context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* This file is licensed to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Xml; using System.Xml.Schema; using Org.XmlUnit.Util; namespace Org.XmlUnit.Diff{ /// <summary> /// Difference engine based on DOM. /// </summary> public sealed class DOMDifferenceEngine : AbstractDifferenceEngine { /// <inheritdoc/> public override void Compare(ISource control, ISource test) { if (control == null) { throw new ArgumentNullException("control"); } if (test == null) { throw new ArgumentNullException("test"); } try { XmlNode controlNode = control.ToNode(); XmlNode testNode = test.ToNode(); CompareNodes(controlNode, XPathContextFor(controlNode), testNode, XPathContextFor(testNode)); } catch (Exception ex) { throw new XMLUnitException("Caught exception during comparison", ex); } } private XPathContext XPathContextFor(XmlNode n) { return new XPathContext(NamespaceContext, n); } /// <summary> /// Recursively compares two XML nodes. /// </summary> /// <remarks> /// Performs comparisons common to all node types, then performs /// the node type specific comparisons and finally recurses into /// the node's child lists. /// /// Stops as soon as any comparison returns ComparisonResult.CRITICAL. /// </remarks> internal ComparisonState CompareNodes(XmlNode control, XPathContext controlContext, XmlNode test, XPathContext testContext) { IEnumerable<XmlNode> allControlChildren = control.ChildNodes.Cast<XmlNode>(); IEnumerable<XmlNode> controlChildren = allControlChildren.Where(n => NodeFilter(n)); IEnumerable<XmlNode> allTestChildren = test.ChildNodes.Cast<XmlNode>(); IEnumerable<XmlNode> testChildren = allTestChildren.Where(n => NodeFilter(n)); return Compare(new Comparison(ComparisonType.NODE_TYPE, control, GetXPath(controlContext), control.NodeType, GetParentXPath(controlContext), test, GetXPath(testContext), test.NodeType, GetParentXPath(testContext))) .AndThen(new Comparison(ComparisonType.NAMESPACE_URI, control, GetXPath(controlContext), control.NamespaceURI, GetParentXPath(controlContext), test, GetXPath(testContext), test.NamespaceURI, GetParentXPath(testContext))) .AndThen(new Comparison(ComparisonType.NAMESPACE_PREFIX, control, GetXPath(controlContext), control.Prefix, GetParentXPath(controlContext), test, GetXPath(testContext), test.Prefix, GetParentXPath(testContext))) .AndIfTrueThen(control.NodeType != XmlNodeType.Attribute, new Comparison(ComparisonType.CHILD_NODELIST_LENGTH, control, GetXPath(controlContext), controlChildren.Count(), GetParentXPath(controlContext), test, GetXPath(testContext), testChildren.Count(), GetParentXPath(testContext))) .AndThen(() => NodeTypeSpecificComparison(control, controlContext, test, testContext)) // and finally recurse into children .AndIfTrueThen(control.NodeType != XmlNodeType.Attribute, CompareChildren(controlContext, allControlChildren, controlChildren, testContext, allTestChildren, testChildren)); } /// <summary> /// Dispatches to the node type specific comparison if one is /// defined for the given combination of nodes. /// </summary> private ComparisonState NodeTypeSpecificComparison(XmlNode control, XPathContext controlContext, XmlNode test, XPathContext testContext) { switch (control.NodeType) { case XmlNodeType.CDATA: case XmlNodeType.Comment: case XmlNodeType.Text: if (test is XmlCharacterData) { return CompareCharacterData((XmlCharacterData) control, controlContext, (XmlCharacterData) test, testContext); } break; case XmlNodeType.Document: if (test is XmlDocument) { return CompareDocuments((XmlDocument) control, controlContext, (XmlDocument) test, testContext); } break; case XmlNodeType.Element: if (test is XmlElement) { return CompareElements((XmlElement) control, controlContext, (XmlElement) test, testContext); } break; case XmlNodeType.ProcessingInstruction: if (test is XmlProcessingInstruction) { return CompareProcessingInstructions((XmlProcessingInstruction) control, controlContext, (XmlProcessingInstruction) test, testContext); } break; case XmlNodeType.DocumentType: if (test is XmlDocumentType) { return CompareDocTypes((XmlDocumentType) control, controlContext, (XmlDocumentType) test, testContext); } break; case XmlNodeType.Attribute: if (test is XmlAttribute) { return CompareAttributes((XmlAttribute) control, controlContext, (XmlAttribute) test, testContext); } break; default: break; } return new OngoingComparisonState(this); } private Func<ComparisonState> CompareChildren(XPathContext controlContext, IEnumerable<XmlNode> allControlChildren, IEnumerable<XmlNode> controlChildren, XPathContext testContext, IEnumerable<XmlNode> allTestChildren, IEnumerable<XmlNode> testChildren) { return () => { controlContext .SetChildren(allControlChildren.Select<XmlNode, XPathContext.INodeInfo> (ElementSelectors.TO_NODE_INFO)); testContext .SetChildren(allTestChildren.Select<XmlNode, XPathContext.INodeInfo> (ElementSelectors.TO_NODE_INFO)); return CompareNodeLists(allControlChildren, controlChildren, controlContext, allTestChildren, testChildren, testContext); }; } /// <summary> /// Compares textual content. /// </summary> private ComparisonState CompareCharacterData(XmlCharacterData control, XPathContext controlContext, XmlCharacterData test, XPathContext testContext) { return Compare(new Comparison(ComparisonType.TEXT_VALUE, control, GetXPath(controlContext), control.Data, GetParentXPath(controlContext), test, GetXPath(testContext), test.Data, GetParentXPath(testContext))); } /// <summary> /// Compares document node, doctype and XML declaration properties /// </summary> private ComparisonState CompareDocuments(XmlDocument control, XPathContext controlContext, XmlDocument test, XPathContext testContext) { XmlDocumentType controlDt = FilterNode(control.DocumentType); XmlDocumentType testDt = FilterNode(test.DocumentType); return Compare(new Comparison(ComparisonType.HAS_DOCTYPE_DECLARATION, control, GetXPath(controlContext), controlDt != null, GetParentXPath(controlContext), test, GetXPath(testContext), testDt != null, GetParentXPath(testContext))) .AndIfTrueThen(controlDt != null && testDt != null, () => CompareNodes(controlDt, controlContext, testDt, testContext)) .AndThen(() => CompareDeclarations(control.FirstChild as XmlDeclaration, controlContext, test.FirstChild as XmlDeclaration, testContext)); } private T FilterNode<T>(T n) where T : XmlNode { return n != null && NodeFilter(n) ? n : null; } /// <summary> /// Compares properties of the doctype declaration. /// </summary> private ComparisonState CompareDocTypes(XmlDocumentType control, XPathContext controlContext, XmlDocumentType test, XPathContext testContext) { return Compare(new Comparison(ComparisonType.DOCTYPE_NAME, control, GetXPath(controlContext), control.Name, GetParentXPath(controlContext), test, GetXPath(testContext), test.Name, GetParentXPath(testContext))) .AndThen(new Comparison(ComparisonType.DOCTYPE_PUBLIC_ID, control, GetXPath(controlContext), control.PublicId, GetParentXPath(controlContext), test, GetXPath(testContext), test.PublicId, GetParentXPath(testContext))) .AndThen(new Comparison(ComparisonType.DOCTYPE_SYSTEM_ID, control, GetXPath(controlContext), control.SystemId, GetParentXPath(controlContext), test, GetXPath(testContext), test.SystemId, GetParentXPath(testContext))); } /// <summary> /// Compares properties of XML declaration. /// </summary> private ComparisonState CompareDeclarations(XmlDeclaration control, XPathContext controlContext, XmlDeclaration test, XPathContext testContext) { string controlVersion = control == null ? "1.0" : control.Version; string testVersion = test == null ? "1.0" : test.Version; string controlStandalone = control == null ? string.Empty : control.Standalone; string testStandalone = test == null ? string.Empty : test.Standalone; string controlEncoding = control != null ? control.Encoding : string.Empty; string testEncoding = test != null ? test.Encoding : string.Empty; return Compare(new Comparison(ComparisonType.XML_VERSION, control, GetXPath(controlContext), controlVersion, GetParentXPath(controlContext), test, GetXPath(testContext), testVersion, GetParentXPath(testContext))) .AndThen(new Comparison(ComparisonType.XML_STANDALONE, control, GetXPath(controlContext), controlStandalone, GetParentXPath(controlContext), test, GetXPath(testContext), testStandalone, GetParentXPath(testContext))) .AndThen(new Comparison(ComparisonType.XML_ENCODING, control, GetXPath(controlContext), controlEncoding, GetParentXPath(controlContext), test, GetXPath(testContext), testEncoding, GetParentXPath(testContext))); } /// <summary> /// Compares element's node properties, in particular the /// element's name and its attributes. /// </summary> private ComparisonState CompareElements(XmlElement control, XPathContext controlContext, XmlElement test, XPathContext testContext) { return Compare(new Comparison(ComparisonType.ELEMENT_TAG_NAME, control, GetXPath(controlContext), Nodes.GetQName(control).Name, GetParentXPath(controlContext), test, GetXPath(testContext), Nodes.GetQName(test).Name, GetParentXPath(testContext))) .AndThen(() => CompareElementAttributes(control, controlContext, test, testContext)); } /// <summary> /// Compares element's attributes. /// </summary> private ComparisonState CompareElementAttributes(XmlElement control, XPathContext controlContext, XmlElement test, XPathContext testContext) { Attributes controlAttributes = SplitAttributes(control.Attributes); controlContext .AddAttributes(controlAttributes.RemainingAttributes .Select<XmlAttribute, XmlQualifiedName>(Nodes.GetQName)); Attributes testAttributes = SplitAttributes(test.Attributes); testContext .AddAttributes(testAttributes.RemainingAttributes .Select<XmlAttribute, XmlQualifiedName>(Nodes.GetQName)); return Compare(new Comparison(ComparisonType.ELEMENT_NUM_ATTRIBUTES, control, GetXPath(controlContext), controlAttributes.RemainingAttributes.Count, GetParentXPath(controlContext), test, GetXPath(testContext), testAttributes.RemainingAttributes.Count, GetParentXPath(testContext))) .AndThen(() => CompareXsiType(controlAttributes.Type, controlContext, testAttributes.Type, testContext)) .AndThen(new Comparison(ComparisonType.SCHEMA_LOCATION, control, GetXPath(controlContext), controlAttributes.SchemaLocation != null ? controlAttributes.SchemaLocation.Value : null, GetParentXPath(controlContext), test, GetXPath(testContext), testAttributes.SchemaLocation != null ? testAttributes.SchemaLocation.Value : null, GetParentXPath(testContext))) .AndThen(new Comparison(ComparisonType.NO_NAMESPACE_SCHEMA_LOCATION, control, GetXPath(controlContext), controlAttributes.NoNamespaceSchemaLocation != null ? controlAttributes.NoNamespaceSchemaLocation.Value : null, GetParentXPath(controlContext), test, GetXPath(testContext), testAttributes.NoNamespaceSchemaLocation != null ? testAttributes.NoNamespaceSchemaLocation.Value : null, GetParentXPath(testContext))) .AndThen(NormalAttributeComparer(control, controlContext, controlAttributes, test, testContext, testAttributes)); } private Func<ComparisonState> NormalAttributeComparer(XmlElement control, XPathContext controlContext, Attributes controlAttributes, XmlElement test, XPathContext testContext, Attributes testAttributes) { return () => { ComparisonState chain = new OngoingComparisonState(this); ICollection<XmlAttribute> foundTestAttributes = new HashSet<XmlAttribute>(); foreach (XmlAttribute controlAttr in controlAttributes.RemainingAttributes) { XmlQualifiedName controlAttrName = controlAttr.GetQName(); XmlAttribute testAttr = FindMatchingAttr(testAttributes.RemainingAttributes, controlAttr); XmlQualifiedName testAttrName = testAttr != null ? testAttr.GetQName() : null; controlContext.NavigateToAttribute(controlAttrName); try { chain = chain.AndThen(new Comparison(ComparisonType.ATTR_NAME_LOOKUP, control, GetXPath(controlContext), controlAttrName, GetParentXPath(controlContext), test, GetXPath(testContext), testAttrName, GetParentXPath(testContext))); if (testAttr != null) { testContext.NavigateToAttribute(testAttrName); try { chain = chain.AndThen(() => CompareNodes(controlAttr, controlContext, testAttr, testContext)); foundTestAttributes.Add(testAttr); } finally { testContext.NavigateToParent(); } } } finally { controlContext.NavigateToParent(); } } return chain.AndThen(() => { ComparisonState secondChain = new OngoingComparisonState(this); foreach (XmlAttribute testAttr in testAttributes.RemainingAttributes) { if (!foundTestAttributes.Contains(testAttr)) { XmlQualifiedName testAttrName = testAttr.GetQName(); testContext.NavigateToAttribute(testAttrName); try { secondChain = secondChain .AndThen(new Comparison(ComparisonType.ATTR_NAME_LOOKUP, control, GetXPath(controlContext), null, GetParentXPath(controlContext), test, GetXPath(testContext), testAttrName, GetParentXPath(testContext))); } finally { testContext.NavigateToParent(); } } } return secondChain; }); }; } /// <summary> /// Compares properties of a processing instruction. /// </summary> private ComparisonState CompareProcessingInstructions(XmlProcessingInstruction control, XPathContext controlContext, XmlProcessingInstruction test, XPathContext testContext) { return Compare(new Comparison(ComparisonType.PROCESSING_INSTRUCTION_TARGET, control, GetXPath(controlContext), control.Target, GetParentXPath(controlContext), test, GetXPath(testContext), test.Target, GetParentXPath(testContext))) .AndThen(new Comparison(ComparisonType.PROCESSING_INSTRUCTION_DATA, control, GetXPath(controlContext), control.Data, GetParentXPath(controlContext), test, GetXPath(testContext), test.Data, GetParentXPath(testContext))); } /// <summary> /// Matches nodes of two node lists and invokes compareNode on /// each pair. /// </summary> /// <remarks> /// Also performs CHILD_LOOKUP comparisons for each node that /// couldn't be matched to one of the "other" list. /// </remarks> private ComparisonState CompareNodeLists(IEnumerable<XmlNode> allControlChildren, IEnumerable<XmlNode> controlSeq, XPathContext controlContext, IEnumerable<XmlNode> allTestChildren, IEnumerable<XmlNode> testSeq, XPathContext testContext) { ComparisonState chain = new OngoingComparisonState(this); IEnumerable<KeyValuePair<XmlNode, XmlNode>> matches = NodeMatcher.Match(controlSeq, testSeq); IList<XmlNode> controlList = new List<XmlNode>(controlSeq); IList<XmlNode> testList = new List<XmlNode>(testSeq); IDictionary<XmlNode, int> controlListForXpathIndex = Index(allControlChildren); IDictionary<XmlNode, int> testListForXpathIndex = Index(allTestChildren); IDictionary<XmlNode, int> controlListIndex = Index(controlList); IDictionary<XmlNode, int> testListIndex = Index(testList); ICollection<XmlNode> seen = new HashSet<XmlNode>(); foreach (KeyValuePair<XmlNode, XmlNode> pair in matches) { XmlNode control = pair.Key; seen.Add(control); XmlNode test = pair.Value; seen.Add(test); int controlIndexForXpath = controlListForXpathIndex[control]; int testIndexForXpath = testListForXpathIndex[test]; int controlIndex = controlListIndex[control]; int testIndex = testListIndex[test]; controlContext.NavigateToChild(controlIndexForXpath); testContext.NavigateToChild(testIndexForXpath); try { chain = chain.AndThen(new Comparison(ComparisonType.CHILD_NODELIST_SEQUENCE, control, GetXPath(controlContext), controlIndex, GetParentXPath(controlContext), test, GetXPath(testContext), testIndex, GetParentXPath(testContext))) .AndThen(() => CompareNodes(control, controlContext, test, testContext)); } finally { testContext.NavigateToParent(); controlContext.NavigateToParent(); } } return chain .AndThen(UnmatchedControlNodes(controlListForXpathIndex, controlList, controlContext, seen, testContext)) .AndThen(UnmatchedTestNodes(testListForXpathIndex, testList, testContext, seen, controlContext)); } private Func<ComparisonState> UnmatchedControlNodes(IDictionary<XmlNode, int> controlListForXpathIndex, IList<XmlNode> controlList, XPathContext controlContext, ICollection<XmlNode> seen, XPathContext testContext) { return () => { ComparisonState chain = new OngoingComparisonState(this); int controlSize = controlList.Count; for (int i = 0; i < controlSize; i++) { if (!seen.Contains(controlList[i])) { controlContext .NavigateToChild(controlListForXpathIndex[controlList[i]]); try { chain = chain .AndThen(new Comparison(ComparisonType.CHILD_LOOKUP, controlList[i], GetXPath(controlContext), controlList[i].GetQName(), GetParentXPath(controlContext), null, null, null, GetXPath(testContext))); } finally { controlContext.NavigateToParent(); } } } return chain; }; } private Func<ComparisonState> UnmatchedTestNodes(IDictionary<XmlNode, int> testListForXpathIndex, IList<XmlNode> testList, XPathContext testContext, ICollection<XmlNode> seen, XPathContext controlContext) { return () => { ComparisonState chain = new OngoingComparisonState(this); int testSize = testList.Count; for (int i = 0; i < testSize; i++) { if (!seen.Contains(testList[i])) { testContext.NavigateToChild(testListForXpathIndex[testList[i]]); try { chain = chain .AndThen(new Comparison(ComparisonType.CHILD_LOOKUP, null, null, null, GetXPath(controlContext), testList[i], GetXPath(testContext), testList[i].GetQName(), GetParentXPath(testContext))); } finally { testContext.NavigateToParent(); } } } return chain; }; } /// <summary> /// Compares xsi:type attribute values /// </summary> private ComparisonState CompareXsiType(XmlAttribute control, XPathContext controlContext, XmlAttribute test, XPathContext testContext) { bool mustChangeControlContext = control != null; bool mustChangeTestContext = test != null; if (!mustChangeControlContext && !mustChangeTestContext) { return new OngoingComparisonState(this); } bool attributePresentOnBothSides = mustChangeControlContext && mustChangeTestContext; try { XmlQualifiedName controlAttrName = null; if (mustChangeControlContext) { controlAttrName = control.GetQName(); controlContext.AddAttribute(controlAttrName); controlContext.NavigateToAttribute(controlAttrName); } XmlQualifiedName testAttrName = null; if (mustChangeTestContext) { testAttrName = test.GetQName(); testContext.AddAttribute(testAttrName); testContext.NavigateToAttribute(testAttrName); } return Compare(new Comparison(ComparisonType.ATTR_NAME_LOOKUP, control, GetXPath(controlContext), controlAttrName, GetParentXPath(controlContext), test, GetXPath(testContext), testAttrName, GetParentXPath(testContext))) .AndIfTrueThen(attributePresentOnBothSides, () => CompareAttributeExplicitness(control, controlContext, test, testContext)) .AndIfTrueThen(attributePresentOnBothSides, new Comparison(ComparisonType.ATTR_VALUE, control, GetXPath(controlContext), ValueAsQName(control), GetParentXPath(controlContext), test, GetXPath(testContext), ValueAsQName(test), GetParentXPath(testContext))); } finally { if (mustChangeControlContext) { controlContext.NavigateToParent(); } if (mustChangeTestContext) { testContext.NavigateToParent(); } } } /// <summary> /// Compares properties of an attribute. /// </summary> private ComparisonState CompareAttributes(XmlAttribute control, XPathContext controlContext, XmlAttribute test, XPathContext testContext) { return CompareAttributeExplicitness(control, controlContext, test, testContext) .AndThen(new Comparison(ComparisonType.ATTR_VALUE, control, GetXPath(controlContext), control.Value, GetParentXPath(controlContext), test, GetXPath(testContext), test.Value, GetParentXPath(testContext))); } /// <summary> /// Compares whether two attributes are specified explicitly. /// </summary> private ComparisonState CompareAttributeExplicitness(XmlAttribute control, XPathContext controlContext, XmlAttribute test, XPathContext testContext) { return Compare(new Comparison(ComparisonType.ATTR_VALUE_EXPLICITLY_SPECIFIED, control, GetXPath(controlContext), control.Specified, GetParentXPath(controlContext), test, GetXPath(testContext), test.Specified, GetParentXPath(testContext))); } /// <summary> /// Separates XML namespace related attributes from "normal" /// attributes. /// </summary> private Attributes SplitAttributes(XmlAttributeCollection map) { XmlAttribute sLoc = map.GetNamedItem("schemaLocation", XmlSchema.InstanceNamespace) as XmlAttribute; XmlAttribute nNsLoc = map.GetNamedItem("noNamespaceSchemaLocation", XmlSchema.InstanceNamespace) as XmlAttribute; XmlAttribute type = map.GetNamedItem("type", XmlSchema.InstanceNamespace) as XmlAttribute; List<XmlAttribute> rest = new List<XmlAttribute>(); foreach (XmlAttribute a in map) { if ("http://www.w3.org/2000/xmlns/" != a.NamespaceURI && a != sLoc && a != nNsLoc && a != type && AttributeFilter(a)) { rest.Add(a); } } return new Attributes(sLoc, nNsLoc, type, rest); } private static XmlQualifiedName ValueAsQName(XmlAttribute attribute) { if (attribute == null) { return null; } // split QName into prefix and local name string[] pieces = attribute.Value.Split(':'); if (pieces.Length < 2) { // unprefixed name pieces = new string[] { string.Empty, pieces[0] }; } else if (pieces.Length > 2) { // actually, this is not a valid QName - be lenient pieces = new string[] { pieces[0], attribute.Value.Substring(pieces[0].Length + 1) }; } return new XmlQualifiedName(pieces[1] ?? string.Empty, attribute .GetNamespaceOfPrefix(pieces[0])); } internal class Attributes { internal readonly XmlAttribute SchemaLocation; internal readonly XmlAttribute NoNamespaceSchemaLocation; internal readonly XmlAttribute Type; internal readonly IList<XmlAttribute> RemainingAttributes; internal Attributes(XmlAttribute schemaLocation, XmlAttribute noNamespaceSchemaLocation, XmlAttribute type, IList<XmlAttribute> remainingAttributes) { this.SchemaLocation = schemaLocation; this.NoNamespaceSchemaLocation = noNamespaceSchemaLocation; this.Type = type; this.RemainingAttributes = remainingAttributes; } } /// <summary> /// Find the attribute with the same namespace and local name /// as a given attribute in a list of attributes. /// </summary> private static XmlAttribute FindMatchingAttr(IList<XmlAttribute> attrs, XmlAttribute attrToMatch) { bool hasNs = !string.IsNullOrEmpty(attrToMatch.NamespaceURI); string nsToMatch = attrToMatch.NamespaceURI; string nameToMatch = hasNs ? attrToMatch.LocalName : attrToMatch.Name; foreach (XmlAttribute a in attrs) { if (((!hasNs && string.IsNullOrEmpty(a.NamespaceURI)) || (hasNs && nsToMatch == a.NamespaceURI)) && ((hasNs && nameToMatch == a.LocalName) || (!hasNs && nameToMatch == a.Name)) ) { return a; } } return null; } private static IDictionary<XmlNode, int> Index(IEnumerable<XmlNode> nodes) { IDictionary<XmlNode, int> indices = new Dictionary<XmlNode, int>(); int idx = 0; foreach (XmlNode n in nodes) { indices[n] = idx++; } return indices; } } }
// 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.AcceptanceTestsHttp { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; /// <summary> /// HttpClientFailure operations. /// </summary> public partial interface IHttpClientFailure { /// <summary> /// Return 400 status code - should be represented in the client as an /// error /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Error>> Head400WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 400 status code - should be represented in the client as an /// error /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Error>> Get400WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 400 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Error>> Put400WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 400 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Error>> Patch400WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 400 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Error>> Post400WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 400 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Error>> Delete400WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 401 status code - should be represented in the client as an /// error /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Error>> Head401WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 402 status code - should be represented in the client as an /// error /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Error>> Get402WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 403 status code - should be represented in the client as an /// error /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Error>> Get403WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 404 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Error>> Put404WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 405 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Error>> Patch405WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 406 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Error>> Post406WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 407 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Error>> Delete407WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 409 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Error>> Put409WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 410 status code - should be represented in the client as an /// error /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Error>> Head410WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 411 status code - should be represented in the client as an /// error /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Error>> Get411WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 412 status code - should be represented in the client as an /// error /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Error>> Get412WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 413 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Error>> Put413WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 414 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Error>> Patch414WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 415 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Error>> Post415WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 416 status code - should be represented in the client as an /// error /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Error>> Get416WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 417 status code - should be represented in the client as an /// error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Error>> Delete417WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 429 status code - should be represented in the client as an /// error /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<Error>> Head429WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
//******************************************************************************************************************************************************************************************// // Public Domain // // // // Written by Peter O. in 2014. // // // // Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ // // // // If you like this, you should donate to Peter O. at: http://peteroupc.github.io/ // //******************************************************************************************************************************************************************************************// using System; using System.Text; namespace Neos.IdentityServer.MultiFactor.WebAuthN.Library.Cbor.Numbers { internal static class EFloatTextString { internal static EFloat FromString( string chars, int offset, int length, EContext ctx, bool throwException) { if (chars == null) { if (!throwException) { return null; } else { throw new ArgumentNullException(nameof(chars)); } } if (offset < 0) { if (!throwException) { return null; } else { throw new FormatException("offset(" + offset + ") is not" + "\u0020greater" + "\u0020or equal to 0"); } } if (offset > chars.Length) { if (!throwException) { return null; } else { throw new FormatException("offset(" + offset + ") is not" + "\u0020less" + "\u0020or" + "\u0020equal to " + chars.Length); } } if (length < 0) { if (!throwException) { return null; } else { throw new FormatException("length(" + length + ") is not" + "\u0020greater or" + "\u0020equal to 0"); } } if (length > chars.Length) { if (!throwException) { return null; } else { throw new FormatException("length(" + length + ") is not" + "\u0020less" + "\u0020or" + "\u0020equal to " + chars.Length); } } if (chars.Length - offset < length) { if (!throwException) { return null; } else { throw new FormatException("str's length minus " + offset + "(" + (chars.Length - offset) + ") is not greater or equal to " + length); } } EContext b64 = EContext.Binary64; if (ctx != null && ctx.HasMaxPrecision && ctx.HasExponentRange && !ctx.IsSimplified && ctx.EMax.CompareTo(b64.EMax) <= 0 && ctx.EMin.CompareTo(b64.EMin) >= 0 && ctx.Precision.CompareTo(b64.Precision) <= 0) { int tmpoffset = offset; int endpos = offset + length; if (length == 0) { if (!throwException) { return null; } else { throw new FormatException(); } } if (chars[tmpoffset] == '-' || chars[tmpoffset] == '+') { ++tmpoffset; } if (tmpoffset < endpos && ((chars[tmpoffset] >= '0' && chars[tmpoffset] <= '9') || chars[tmpoffset] == '.')) { EFloat ef = DoubleEFloatFromString( chars, offset, length, ctx, throwException); if (ef != null) { return ef; } } } return EDecimal.FromString( chars, offset, length, EContext.Unlimited.WithSimplified(ctx != null && ctx.IsSimplified)) .ToEFloat(ctx); } internal static EFloat DoubleEFloatFromString( string chars, int offset, int length, EContext ctx, bool throwException) { int tmpoffset = offset; if (chars == null) { if (!throwException) { return null; } else { throw new ArgumentNullException(nameof(chars)); } } if (length == 0) { if (!throwException) { return null; } else { throw new FormatException(); } } int endStr = tmpoffset + length; var negative = false; var haveDecimalPoint = false; var haveDigits = false; var haveExponent = false; var newScaleInt = 0; var digitStart = 0; int i = tmpoffset; long mantissaLong = 0L; // Ordinary number if (chars[i] == '+' || chars[i] == '-') { if (chars[i] == '-') { negative = true; } ++i; } digitStart = i; int digitEnd = i; int decimalDigitStart = i; var haveNonzeroDigit = false; var decimalPrec = 0; int decimalDigitEnd = i; var nonzeroBeyondMax = false; var lastdigit = -1; // 768 is maximum precision of a decimal // half-ULP in double format var maxDecimalPrec = 768; if (length > 21) { int eminInt = ctx.EMin.ToInt32Checked(); int emaxInt = ctx.EMax.ToInt32Checked(); int precInt = ctx.Precision.ToInt32Checked(); if (eminInt >= -14 && emaxInt <= 15) { maxDecimalPrec = (precInt <= 11) ? 21 : 63; } else if (eminInt >= -126 && emaxInt <= 127) { maxDecimalPrec = (precInt <= 24) ? 113 : 142; } } for (; i < endStr; ++i) { char ch = chars[i]; if (ch >= '0' && ch <= '9') { var thisdigit = (int)(ch - '0'); haveDigits = true; haveNonzeroDigit |= thisdigit != 0; if (decimalPrec > maxDecimalPrec) { if (thisdigit != 0) { nonzeroBeyondMax = true; } if (!haveDecimalPoint) { // NOTE: Absolute value will not be more than // the string portion's length, so will fit comfortably // in an 'int'. newScaleInt = checked(newScaleInt + 1); } continue; } lastdigit = thisdigit; if (haveNonzeroDigit) { ++decimalPrec; } if (haveDecimalPoint) { decimalDigitEnd = i + 1; } else { digitEnd = i + 1; } if (mantissaLong <= 922337203685477580L) { mantissaLong *= 10; mantissaLong += thisdigit; } else { mantissaLong = Int64.MaxValue; } if (haveDecimalPoint) { // NOTE: Absolute value will not be more than // the portion's length, so will fit comfortably // in an 'int'. newScaleInt = checked(newScaleInt - 1); } } else if (ch == '.') { if (haveDecimalPoint) { if (!throwException) { return null; } else { throw new FormatException(); } } haveDecimalPoint = true; decimalDigitStart = i + 1; decimalDigitEnd = i + 1; } else if (ch == 'E' || ch == 'e') { haveExponent = true; ++i; break; } else { if (!throwException) { return null; } else { throw new FormatException(); } } } if (!haveDigits) { if (!throwException) { return null; } else { throw new FormatException(); } } var expInt = 0; var expoffset = 1; var expDigitStart = -1; var expPrec = 0; bool zeroMantissa = !haveNonzeroDigit; haveNonzeroDigit = false; EFloat ef1, ef2; if (haveExponent) { haveDigits = false; if (i == endStr) { if (!throwException) { return null; } else { throw new FormatException(); } } char ch = chars[i]; if (ch == '+' || ch == '-') { if (ch == '-') { expoffset = -1; } ++i; } expDigitStart = i; for (; i < endStr; ++i) { ch = chars[i]; if (ch >= '0' && ch <= '9') { haveDigits = true; var thisdigit = (int)(ch - '0'); haveNonzeroDigit |= thisdigit != 0; if (haveNonzeroDigit) { ++expPrec; } if (expInt <= 214748364) { expInt *= 10; expInt += thisdigit; } else { expInt = Int32.MaxValue; } } else { if (!throwException) { return null; } else { throw new FormatException(); } } } if (!haveDigits) { if (!throwException) { return null; } else { throw new FormatException(); } } expInt *= expoffset; if (expPrec > 12) { // Exponent that can't be compensated by digit // length without remaining beyond Int32 range if (expoffset < 0) { return EFloat.SignalUnderflow(ctx, negative, zeroMantissa); } else { return EFloat.SignalOverflow(ctx, negative, zeroMantissa); } } } if (i != endStr) { if (!throwException) { return null; } else { throw new FormatException(); } } if (expInt != Int32.MaxValue && expInt > -Int32.MaxValue && mantissaLong != Int64.MaxValue && (ctx == null || !ctx.HasFlagsOrTraps)) { if (mantissaLong == 0) { EFloat ef = EFloat.Create( EInteger.Zero, EInteger.FromInt32(expInt)); if (negative) { ef = ef.Negate(); } return ef.RoundToPrecision(ctx); } var finalexp = (long)expInt + (long)newScaleInt; long ml = mantissaLong; if (finalexp >= -22 && finalexp <= 44) { var iexp = (int)finalexp; while (ml <= 900719925474099L && iexp > 22) { ml *= 10; --iexp; } int iabsexp = Math.Abs(iexp); if (ml < 9007199254740992L && iabsexp == 0) { return EFloat.FromInt64(negative ? -mantissaLong : mantissaLong).RoundToPrecision(ctx); } else if (ml < 9007199254740992L && iabsexp <= 22) { EFloat efn = EFloat.FromEInteger(NumberUtility.FindPowerOfTen(iabsexp)); if (negative) { ml = -ml; } EFloat efml = EFloat.FromInt64(ml); if (iexp < 0) { return efml.Divide(efn, ctx); } else { return efml.Multiply(efn, ctx); } } } long adjexpUpperBound = finalexp + (decimalPrec - 1); long adjexpLowerBound = finalexp; if (adjexpUpperBound < -326) { return EFloat.SignalUnderflow(ctx, negative, zeroMantissa); } else if (adjexpLowerBound > 309) { return EFloat.SignalOverflow(ctx, negative, zeroMantissa); } if (negative) { mantissaLong = -mantissaLong; } long absfinalexp = Math.Abs(finalexp); ef1 = EFloat.Create(mantissaLong, (int)0); ef2 = EFloat.FromEInteger(NumberUtility.FindPowerOfTen(absfinalexp)); if (finalexp < 0) { EFloat efret = ef1.Divide(ef2, ctx); /* Console.WriteLine("div " + ef1 + "/" + ef2 + " -> " + (efret)); */ return efret; } else { return ef1.Multiply(ef2, ctx); } } EInteger mant = null; EInteger exp = (!haveExponent) ? EInteger.Zero : EInteger.FromSubstring(chars, expDigitStart, endStr); if (expoffset < 0) { exp = exp.Negate(); } exp = exp.Add(newScaleInt); if (nonzeroBeyondMax) { exp = exp.Subtract(1); ++decimalPrec; } EInteger adjExpUpperBound = exp.Add(decimalPrec).Subtract(1); EInteger adjExpLowerBound = exp; // DebugUtility.Log("exp=" + adjExpLowerBound + "~" + (adjExpUpperBound)); if (adjExpUpperBound.CompareTo(-326) < 0) { return EFloat.SignalUnderflow(ctx, negative, zeroMantissa); } else if (adjExpLowerBound.CompareTo(309) > 0) { return EFloat.SignalOverflow(ctx, negative, zeroMantissa); } if (zeroMantissa) { EFloat ef = EFloat.Create( EInteger.Zero, exp); if (negative) { ef = ef.Negate(); } return ef.RoundToPrecision(ctx); } else if (decimalDigitStart != decimalDigitEnd) { if (digitEnd - digitStart == 1 && chars[digitStart] == '0') { mant = EInteger.FromSubstring( chars, decimalDigitStart, decimalDigitEnd); } else { string ctmpstr = Extras.CharsConcat( chars, digitStart, digitEnd - digitStart, chars, decimalDigitStart, decimalDigitEnd - decimalDigitStart); mant = EInteger.FromString(ctmpstr); } } else { mant = EInteger.FromSubstring(chars, digitStart, digitEnd); } if (nonzeroBeyondMax) { mant = mant.Multiply(10).Add(1); } if (negative) { mant = mant.Negate(); } return EDecimal.Create(mant, exp).ToEFloat(ctx); } } }
using Lucene.Net.Diagnostics; using Lucene.Net.Support; using Lucene.Net.Support.Threading; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; namespace Lucene.Net.Search { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using DefaultSimilarity = Lucene.Net.Search.Similarities.DefaultSimilarity; using Document = Documents.Document; using IndexReader = Lucene.Net.Index.IndexReader; using IndexReaderContext = Lucene.Net.Index.IndexReaderContext; using MultiFields = Lucene.Net.Index.MultiFields; using ReaderUtil = Lucene.Net.Index.ReaderUtil; using Similarity = Lucene.Net.Search.Similarities.Similarity; using StoredFieldVisitor = Lucene.Net.Index.StoredFieldVisitor; using Term = Lucene.Net.Index.Term; using TermContext = Lucene.Net.Index.TermContext; using Terms = Lucene.Net.Index.Terms; /// <summary> /// Implements search over a single <see cref="Index.IndexReader"/>. /// /// <para/>Applications usually need only call the inherited /// <see cref="Search(Query,int)"/> /// or <see cref="Search(Query,Filter,int)"/> methods. For /// performance reasons, if your index is unchanging, you /// should share a single <see cref="IndexSearcher"/> instance across /// multiple searches instead of creating a new one /// per-search. If your index has changed and you wish to /// see the changes reflected in searching, you should /// use <see cref="Index.DirectoryReader.OpenIfChanged(Index.DirectoryReader)"/> /// to obtain a new reader and /// then create a new <see cref="IndexSearcher"/> from that. Also, for /// low-latency turnaround it's best to use a near-real-time /// reader (<see cref="Index.DirectoryReader.Open(Index.IndexWriter,bool)"/>). /// Once you have a new <see cref="Index.IndexReader"/>, it's relatively /// cheap to create a new <see cref="IndexSearcher"/> from it. /// /// <para/><a name="thread-safety"></a><p><b>NOTE</b>: /// <see cref="IndexSearcher"/> instances are completely /// thread safe, meaning multiple threads can call any of its /// methods, concurrently. If your application requires /// external synchronization, you should <b>not</b> /// synchronize on the <see cref="IndexSearcher"/> instance; /// use your own (non-Lucene) objects instead.</p> /// </summary> public class IndexSearcher { internal readonly IndexReader reader; // package private for testing! // NOTE: these members might change in incompatible ways // in the next release protected readonly IndexReaderContext m_readerContext; protected internal readonly IList<AtomicReaderContext> m_leafContexts; /// <summary> /// Used with executor - each slice holds a set of leafs executed within one thread </summary> protected readonly LeafSlice[] m_leafSlices; // These are only used for multi-threaded search private readonly TaskScheduler executor; // the default Similarity private static readonly Similarity defaultSimilarity = new DefaultSimilarity(); /// <summary> /// Expert: returns a default <see cref="Similarities.Similarity"/> instance. /// In general, this method is only called to initialize searchers and writers. /// User code and query implementations should respect /// <see cref="IndexSearcher.Similarity"/>. /// <para/> /// @lucene.internal /// </summary> public static Similarity DefaultSimilarity => defaultSimilarity; /// <summary> /// The <see cref="Similarities.Similarity"/> implementation used by this searcher. </summary> private Similarity similarity = defaultSimilarity; /// <summary> /// Creates a searcher searching the provided index. </summary> public IndexSearcher(IndexReader r) : this(r, null) { } /// <summary> /// Runs searches for each segment separately, using the /// provided <see cref="TaskScheduler"/>. <see cref="IndexSearcher"/> will not /// shutdown/awaitTermination this <see cref="TaskScheduler"/> on /// dispose; you must do so, eventually, on your own. /// <para/> /// @lucene.experimental /// </summary> public IndexSearcher(IndexReader r, TaskScheduler executor) : this(r.Context, executor) { } /// <summary> /// Creates a searcher searching the provided top-level <see cref="IndexReaderContext"/>. /// <para/> /// Given a non-<c>null</c> <see cref="TaskScheduler"/> this method runs /// searches for each segment separately, using the provided <see cref="TaskScheduler"/>. /// <see cref="IndexSearcher"/> will not shutdown/awaitTermination this <see cref="TaskScheduler"/> on /// close; you must do so, eventually, on your own. /// <para/> /// @lucene.experimental /// </summary> /// <seealso cref="IndexReaderContext"/> /// <seealso cref="IndexReader.Context"/> public IndexSearcher(IndexReaderContext context, TaskScheduler executor) { if (Debugging.AssertsEnabled) Debugging.Assert(context.IsTopLevel, () => "IndexSearcher's ReaderContext must be topLevel for reader" + context.Reader); reader = context.Reader; this.executor = executor; this.m_readerContext = context; m_leafContexts = context.Leaves; this.m_leafSlices = executor == null ? null : Slices(m_leafContexts); } /// <summary> /// Creates a searcher searching the provided top-level <see cref="IndexReaderContext"/>. /// <para/> /// @lucene.experimental /// </summary> /// <seealso cref="IndexReaderContext"/> /// <seealso cref="IndexReader.Context"/> public IndexSearcher(IndexReaderContext context) : this(context, null) { } /// <summary> /// Expert: Creates an array of leaf slices each holding a subset of the given leaves. /// Each <see cref="LeafSlice"/> is executed in a single thread. By default there /// will be one <see cref="LeafSlice"/> per leaf (<see cref="AtomicReaderContext"/>). /// </summary> protected virtual LeafSlice[] Slices(IList<AtomicReaderContext> leaves) { LeafSlice[] slices = new LeafSlice[leaves.Count]; for (int i = 0; i < slices.Length; i++) { slices[i] = new LeafSlice(leaves[i]); } return slices; } /// <summary> /// Return the <see cref="Index.IndexReader"/> this searches. </summary> public virtual IndexReader IndexReader => reader; /// <summary> /// Sugar for <code>.IndexReader.Document(docID)</code> </summary> /// <seealso cref="IndexReader.Document(int)"/> public virtual Document Doc(int docID) { return reader.Document(docID); } /// <summary> /// Sugar for <code>.IndexReader.Document(docID, fieldVisitor)</code> </summary> /// <seealso cref="IndexReader.Document(int, StoredFieldVisitor)"/> public virtual void Doc(int docID, StoredFieldVisitor fieldVisitor) { reader.Document(docID, fieldVisitor); } /// <summary> /// Sugar for <code>.IndexReader.Document(docID, fieldsToLoad)</code> </summary> /// <seealso cref="IndexReader.Document(int, ISet{string})"/> public virtual Document Doc(int docID, ISet<string> fieldsToLoad) { return reader.Document(docID, fieldsToLoad); } /// @deprecated Use <see cref="Doc(int, ISet{string})"/> instead. [Obsolete("Use <seealso cref=#doc(int, java.util.Set)/> instead.")] public Document Document(int docID, ISet<string> fieldsToLoad) { return Doc(docID, fieldsToLoad); } /// <summary> /// Expert: Set the <see cref="Similarities.Similarity"/> implementation used by this IndexSearcher. /// </summary> public virtual Similarity Similarity { get => similarity; set => this.similarity = value; } /// <summary> /// @lucene.internal </summary> protected virtual Query WrapFilter(Query query, Filter filter) { return (filter == null) ? query : new FilteredQuery(query, filter); } /// <summary> /// Finds the top <paramref name="n"/> /// hits for top <paramref name="query"/> where all results are after a previous /// result (top <paramref name="after"/>). /// <para/> /// By passing the bottom result from a previous page as <paramref name="after"/>, /// this method can be used for efficient 'deep-paging' across potentially /// large result sets. /// </summary> /// <exception cref="BooleanQuery.TooManyClausesException"> If a query would exceed /// <see cref="BooleanQuery.MaxClauseCount"/> clauses. </exception> public virtual TopDocs SearchAfter(ScoreDoc after, Query query, int n) { return Search(CreateNormalizedWeight(query), after, n); } /// <summary> /// Finds the top <paramref name="n"/> /// hits for <paramref name="query"/>, applying <paramref name="filter"/> if non-null, /// where all results are after a previous result (<paramref name="after"/>). /// <para/> /// By passing the bottom result from a previous page as <paramref name="after"/>, /// this method can be used for efficient 'deep-paging' across potentially /// large result sets. /// </summary> /// <exception cref="BooleanQuery.TooManyClausesException"> If a query would exceed /// <see cref="BooleanQuery.MaxClauseCount"/> clauses. </exception> public virtual TopDocs SearchAfter(ScoreDoc after, Query query, Filter filter, int n) { return Search(CreateNormalizedWeight(WrapFilter(query, filter)), after, n); } /// <summary> /// Finds the top <paramref name="n"/> /// hits for <paramref name="query"/>. /// </summary> /// <exception cref="BooleanQuery.TooManyClausesException"> If a query would exceed /// <see cref="BooleanQuery.MaxClauseCount"/> clauses. </exception> public virtual TopDocs Search(Query query, int n) { return Search(query, null, n); } /// <summary> /// Finds the top <paramref name="n"/> /// hits for <paramref name="query"/>, applying <paramref name="filter"/> if non-null. /// </summary> /// <exception cref="BooleanQuery.TooManyClausesException"> If a query would exceed /// <see cref="BooleanQuery.MaxClauseCount"/> clauses. </exception> public virtual TopDocs Search(Query query, Filter filter, int n) { return Search(CreateNormalizedWeight(WrapFilter(query, filter)), null, n); } /// <summary> /// Lower-level search API. /// /// <para/><see cref="ICollector.Collect(int)"/> is called for every matching /// document. /// </summary> /// <param name="query"> To match documents </param> /// <param name="filter"> Ef non-null, used to permit documents to be collected. </param> /// <param name="results"> To receive hits </param> /// <exception cref="BooleanQuery.TooManyClausesException"> If a query would exceed /// <see cref="BooleanQuery.MaxClauseCount"/> clauses. </exception> public virtual void Search(Query query, Filter filter, ICollector results) { Search(m_leafContexts, CreateNormalizedWeight(WrapFilter(query, filter)), results); } /// <summary> /// Lower-level search API. /// /// <para/><seealso cref="ICollector.Collect(int)"/> is called for every matching document. /// </summary> /// <exception cref="BooleanQuery.TooManyClausesException"> If a query would exceed /// <see cref="BooleanQuery.MaxClauseCount"/> clauses. </exception> public virtual void Search(Query query, ICollector results) { Search(m_leafContexts, CreateNormalizedWeight(query), results); } /// <summary> /// Search implementation with arbitrary sorting. Finds /// the top <paramref name="n"/> hits for <paramref name="query"/>, applying /// <paramref name="filter"/> if non-null, and sorting the hits by the criteria in /// <paramref name="sort"/>. /// /// <para/>NOTE: this does not compute scores by default; use /// <see cref="IndexSearcher.Search(Query,Filter,int,Sort,bool,bool)"/> to /// control scoring. /// </summary> /// <exception cref="BooleanQuery.TooManyClausesException"> If a query would exceed /// <see cref="BooleanQuery.MaxClauseCount"/> clauses. </exception> public virtual TopFieldDocs Search(Query query, Filter filter, int n, Sort sort) { return Search(CreateNormalizedWeight(WrapFilter(query, filter)), n, sort, false, false); } /// <summary> /// Search implementation with arbitrary sorting, plus /// control over whether hit scores and max score /// should be computed. Finds /// the top <paramref name="n"/> hits for <paramref name="query"/>, applying /// <paramref name="filter"/> if non-null, and sorting the hits by the criteria in /// <paramref name="sort"/>. If <paramref name="doDocScores"/> is <c>true</c> /// then the score of each hit will be computed and /// returned. If <paramref name="doMaxScore"/> is /// <c>true</c> then the maximum score over all /// collected hits will be computed. /// </summary> /// <exception cref="BooleanQuery.TooManyClausesException"> If a query would exceed /// <see cref="BooleanQuery.MaxClauseCount"/> clauses. </exception> public virtual TopFieldDocs Search(Query query, Filter filter, int n, Sort sort, bool doDocScores, bool doMaxScore) { return Search(CreateNormalizedWeight(WrapFilter(query, filter)), n, sort, doDocScores, doMaxScore); } /// <summary> /// Finds the top <paramref name="n"/> /// hits for <paramref name="query"/>, applying <paramref name="filter"/> if non-null, /// where all results are after a previous result (<paramref name="after"/>). /// <para/> /// By passing the bottom result from a previous page as <paramref name="after"/>, /// this method can be used for efficient 'deep-paging' across potentially /// large result sets. /// </summary> /// <exception cref="BooleanQuery.TooManyClausesException"> If a query would exceed /// <seealso cref="BooleanQuery.MaxClauseCount"/> clauses. </exception> public virtual TopDocs SearchAfter(ScoreDoc after, Query query, Filter filter, int n, Sort sort) { if (after != null && !(after is FieldDoc)) { // TODO: if we fix type safety of TopFieldDocs we can // remove this throw new ArgumentException("after must be a FieldDoc; got " + after); } return Search(CreateNormalizedWeight(WrapFilter(query, filter)), (FieldDoc)after, n, sort, true, false, false); } /// <summary> /// Search implementation with arbitrary sorting and no filter. </summary> /// <param name="query"> The query to search for </param> /// <param name="n"> Return only the top n results </param> /// <param name="sort"> The <see cref="Lucene.Net.Search.Sort"/> object </param> /// <returns> The top docs, sorted according to the supplied <see cref="Lucene.Net.Search.Sort"/> instance </returns> /// <exception cref="IOException"> if there is a low-level I/O error </exception> public virtual TopFieldDocs Search(Query query, int n, Sort sort) { return Search(CreateNormalizedWeight(query), n, sort, false, false); } /// <summary> /// Finds the top <paramref name="n"/> /// hits for <paramref name="query"/> where all results are after a previous /// result (<paramref name="after"/>). /// <para/> /// By passing the bottom result from a previous page as <paramref name="after"/>, /// this method can be used for efficient 'deep-paging' across potentially /// large result sets. /// </summary> /// <exception cref="BooleanQuery.TooManyClausesException"> If a query would exceed /// <see cref="BooleanQuery.MaxClauseCount"/> clauses. </exception> public virtual TopDocs SearchAfter(ScoreDoc after, Query query, int n, Sort sort) { if (after != null && !(after is FieldDoc)) { // TODO: if we fix type safety of TopFieldDocs we can // remove this throw new ArgumentException("after must be a FieldDoc; got " + after); } return Search(CreateNormalizedWeight(query), (FieldDoc)after, n, sort, true, false, false); } /// <summary> /// Finds the top <paramref name="n"/> /// hits for <paramref name="query"/> where all results are after a previous /// result (<paramref name="after"/>), allowing control over /// whether hit scores and max score should be computed. /// <para/> /// By passing the bottom result from a previous page as <paramref name="after"/>, /// this method can be used for efficient 'deep-paging' across potentially /// large result sets. If <paramref name="doDocScores"/> is <c>true</c> /// then the score of each hit will be computed and /// returned. If <paramref name="doMaxScore"/> is /// <c>true</c> then the maximum score over all /// collected hits will be computed. /// </summary> /// <exception cref="BooleanQuery.TooManyClausesException"> If a query would exceed /// <see cref="BooleanQuery.MaxClauseCount"/> clauses. </exception> public virtual TopDocs SearchAfter(ScoreDoc after, Query query, Filter filter, int n, Sort sort, bool doDocScores, bool doMaxScore) { if (after != null && !(after is FieldDoc)) { // TODO: if we fix type safety of TopFieldDocs we can // remove this throw new ArgumentException("after must be a FieldDoc; got " + after); } return Search(CreateNormalizedWeight(WrapFilter(query, filter)), (FieldDoc)after, n, sort, true, doDocScores, doMaxScore); } /// <summary> /// Expert: Low-level search implementation. Finds the top <paramref name="nDocs"/> /// hits for <c>query</c>, applying <c>filter</c> if non-null. /// /// <para/>Applications should usually call <see cref="IndexSearcher.Search(Query,int)"/> or /// <see cref="IndexSearcher.Search(Query,Filter,int)"/> instead. </summary> /// <exception cref="BooleanQuery.TooManyClausesException"> If a query would exceed /// <see cref="BooleanQuery.MaxClauseCount"/> clauses. </exception> protected virtual TopDocs Search(Weight weight, ScoreDoc after, int nDocs) { int limit = reader.MaxDoc; if (limit == 0) { limit = 1; } if (after != null && after.Doc >= limit) { throw new ArgumentException("after.doc exceeds the number of documents in the reader: after.doc=" + after.Doc + " limit=" + limit); } nDocs = Math.Min(nDocs, limit); if (executor == null) { return Search(m_leafContexts, weight, after, nDocs); } else { HitQueue hq = new HitQueue(nDocs, false); ReentrantLock @lock = new ReentrantLock(); ExecutionHelper<TopDocs> runner = new ExecutionHelper<TopDocs>(executor); for (int i = 0; i < m_leafSlices.Length; i++) // search each sub { runner.Submit(new SearcherCallableNoSort(@lock, this, m_leafSlices[i], weight, after, nDocs, hq)); } int totalHits = 0; float maxScore = float.NegativeInfinity; foreach (TopDocs topDocs in runner) { if (topDocs.TotalHits != 0) { totalHits += topDocs.TotalHits; maxScore = Math.Max(maxScore, topDocs.MaxScore); } } var scoreDocs = new ScoreDoc[hq.Count]; for (int i = hq.Count - 1; i >= 0; i--) // put docs in array { scoreDocs[i] = hq.Pop(); } return new TopDocs(totalHits, scoreDocs, maxScore); } } /// <summary> /// Expert: Low-level search implementation. Finds the top <code>n</code> /// hits for <c>query</c>. /// /// <para/>Applications should usually call <see cref="IndexSearcher.Search(Query,int)"/> or /// <see cref="IndexSearcher.Search(Query,Filter,int)"/> instead. </summary> /// <exception cref="BooleanQuery.TooManyClausesException"> If a query would exceed /// <see cref="BooleanQuery.MaxClauseCount"/> clauses. </exception> protected virtual TopDocs Search(IList<AtomicReaderContext> leaves, Weight weight, ScoreDoc after, int nDocs) { // single thread int limit = reader.MaxDoc; if (limit == 0) { limit = 1; } nDocs = Math.Min(nDocs, limit); TopScoreDocCollector collector = TopScoreDocCollector.Create(nDocs, after, !weight.ScoresDocsOutOfOrder); Search(leaves, weight, collector); return collector.GetTopDocs(); } /// <summary> /// Expert: Low-level search implementation with arbitrary /// sorting and control over whether hit scores and max /// score should be computed. Finds /// the top <paramref name="nDocs"/> hits for <c>query</c> and sorting the hits /// by the criteria in <paramref name="sort"/>. /// /// <para/>Applications should usually call /// <see cref="IndexSearcher.Search(Query,Filter,int,Sort)"/> instead. /// </summary> /// <exception cref="BooleanQuery.TooManyClausesException"> If a query would exceed /// <see cref="BooleanQuery.MaxClauseCount"/> clauses. </exception> protected virtual TopFieldDocs Search(Weight weight, int nDocs, Sort sort, bool doDocScores, bool doMaxScore) { return Search(weight, null, nDocs, sort, true, doDocScores, doMaxScore); } /// <summary> /// Just like <see cref="Search(Weight, int, Sort, bool, bool)"/>, but you choose /// whether or not the fields in the returned <see cref="FieldDoc"/> instances should /// be set by specifying <paramref name="fillFields"/>. /// </summary> protected virtual TopFieldDocs Search(Weight weight, FieldDoc after, int nDocs, Sort sort, bool fillFields, bool doDocScores, bool doMaxScore) { if (sort == null) { throw new ArgumentNullException("Sort must not be null"); } int limit = reader.MaxDoc; if (limit == 0) { limit = 1; } nDocs = Math.Min(nDocs, limit); if (executor == null) { // use all leaves here! return Search(m_leafContexts, weight, after, nDocs, sort, fillFields, doDocScores, doMaxScore); } else { TopFieldCollector topCollector = TopFieldCollector.Create(sort, nDocs, after, fillFields, doDocScores, doMaxScore, false); ReentrantLock @lock = new ReentrantLock(); ExecutionHelper<TopFieldDocs> runner = new ExecutionHelper<TopFieldDocs>(executor); for (int i = 0; i < m_leafSlices.Length; i++) // search each leaf slice { runner.Submit(new SearcherCallableWithSort(@lock, this, m_leafSlices[i], weight, after, nDocs, topCollector, sort, doDocScores, doMaxScore)); } int totalHits = 0; float maxScore = float.NegativeInfinity; foreach (TopFieldDocs topFieldDocs in runner) { if (topFieldDocs.TotalHits != 0) { totalHits += topFieldDocs.TotalHits; maxScore = Math.Max(maxScore, topFieldDocs.MaxScore); } } TopFieldDocs topDocs = (TopFieldDocs)topCollector.GetTopDocs(); return new TopFieldDocs(totalHits, topDocs.ScoreDocs, topDocs.Fields, topDocs.MaxScore); } } /// <summary> /// Just like <see cref="Search(Weight, int, Sort, bool, bool)"/>, but you choose /// whether or not the fields in the returned <see cref="FieldDoc"/> instances should /// be set by specifying <paramref name="fillFields"/>. /// </summary> protected virtual TopFieldDocs Search(IList<AtomicReaderContext> leaves, Weight weight, FieldDoc after, int nDocs, Sort sort, bool fillFields, bool doDocScores, bool doMaxScore) { // single thread int limit = reader.MaxDoc; if (limit == 0) { limit = 1; } nDocs = Math.Min(nDocs, limit); TopFieldCollector collector = TopFieldCollector.Create(sort, nDocs, after, fillFields, doDocScores, doMaxScore, !weight.ScoresDocsOutOfOrder); Search(leaves, weight, collector); return (TopFieldDocs)collector.GetTopDocs(); } /// <summary> /// Lower-level search API. /// /// <para/> /// <seealso cref="ICollector.Collect(int)"/> is called for every document. /// /// <para/> /// NOTE: this method executes the searches on all given leaves exclusively. /// To search across all the searchers leaves use <see cref="m_leafContexts"/>. /// </summary> /// <param name="leaves"> /// The searchers leaves to execute the searches on </param> /// <param name="weight"> /// To match documents </param> /// <param name="collector"> /// To receive hits </param> /// <exception cref="BooleanQuery.TooManyClausesException"> If a query would exceed /// <see cref="BooleanQuery.MaxClauseCount"/> clauses. </exception> protected virtual void Search(IList<AtomicReaderContext> leaves, Weight weight, ICollector collector) { // TODO: should we make this // threaded...? the Collector could be sync'd? // always use single thread: foreach (AtomicReaderContext ctx in leaves) // search each subreader { try { collector.SetNextReader(ctx); } catch (CollectionTerminatedException) { // there is no doc of interest in this reader context // continue with the following leaf continue; } BulkScorer scorer = weight.GetBulkScorer(ctx, !collector.AcceptsDocsOutOfOrder, ctx.AtomicReader.LiveDocs); if (scorer != null) { try { scorer.Score(collector); } catch (CollectionTerminatedException) { // collection was terminated prematurely // continue with the following leaf } } } } /// <summary> /// Expert: called to re-write queries into primitive queries. </summary> /// <exception cref="BooleanQuery.TooManyClausesException"> If a query would exceed /// <see cref="BooleanQuery.MaxClauseCount"/> clauses. </exception> public virtual Query Rewrite(Query original) { Query query = original; for (Query rewrittenQuery = query.Rewrite(reader); rewrittenQuery != query; rewrittenQuery = query.Rewrite(reader)) { query = rewrittenQuery; } return query; } /// <summary> /// Returns an <see cref="Explanation"/> that describes how <paramref name="doc"/> scored against /// <paramref name="query"/>. /// /// <para/>This is intended to be used in developing <see cref="Similarities.Similarity"/> implementations, /// and, for good performance, should not be displayed with every hit. /// Computing an explanation is as expensive as executing the query over the /// entire index. /// </summary> public virtual Explanation Explain(Query query, int doc) { return Explain(CreateNormalizedWeight(query), doc); } /// <summary> /// Expert: low-level implementation method /// Returns an <see cref="Explanation"/> that describes how <paramref name="doc"/> scored against /// <paramref name="weight"/>. /// /// <para/>This is intended to be used in developing <see cref="Similarities.Similarity"/> implementations, /// and, for good performance, should not be displayed with every hit. /// Computing an explanation is as expensive as executing the query over the /// entire index. /// <para/>Applications should call <see cref="IndexSearcher.Explain(Query, int)"/>. </summary> /// <exception cref="BooleanQuery.TooManyClausesException"> If a query would exceed /// <see cref="BooleanQuery.MaxClauseCount"/> clauses. </exception> protected virtual Explanation Explain(Weight weight, int doc) { int n = ReaderUtil.SubIndex(doc, m_leafContexts); AtomicReaderContext ctx = m_leafContexts[n]; int deBasedDoc = doc - ctx.DocBase; return weight.Explain(ctx, deBasedDoc); } /// <summary> /// Creates a normalized weight for a top-level <see cref="Query"/>. /// The query is rewritten by this method and <see cref="Query.CreateWeight(IndexSearcher)"/> called, /// afterwards the <see cref="Weight"/> is normalized. The returned <see cref="Weight"/> /// can then directly be used to get a <see cref="Scorer"/>. /// <para/> /// @lucene.internal /// </summary> public virtual Weight CreateNormalizedWeight(Query query) { query = Rewrite(query); Weight weight = query.CreateWeight(this); float v = weight.GetValueForNormalization(); float norm = Similarity.QueryNorm(v); if (float.IsInfinity(norm) || float.IsNaN(norm)) { norm = 1.0f; } weight.Normalize(norm, 1.0f); return weight; } /// <summary> /// Returns this searchers the top-level <see cref="IndexReaderContext"/>. </summary> /// <seealso cref="IndexReader.Context"/> /* sugar for #getReader().getTopReaderContext() */ public virtual IndexReaderContext TopReaderContext => m_readerContext; /// <summary> /// A thread subclass for searching a single searchable /// </summary> private sealed class SearcherCallableNoSort : ICallable<TopDocs> { private readonly ReentrantLock @lock; private readonly IndexSearcher searcher; private readonly Weight weight; private readonly ScoreDoc after; private readonly int nDocs; private readonly HitQueue hq; private readonly LeafSlice slice; public SearcherCallableNoSort(ReentrantLock @lock, IndexSearcher searcher, LeafSlice slice, Weight weight, ScoreDoc after, int nDocs, HitQueue hq) { this.@lock = @lock; this.searcher = searcher; this.weight = weight; this.after = after; this.nDocs = nDocs; this.hq = hq; this.slice = slice; } public TopDocs Call() { TopDocs docs = searcher.Search(slice.Leaves, weight, after, nDocs); ScoreDoc[] scoreDocs = docs.ScoreDocs; //it would be so nice if we had a thread-safe insert @lock.Lock(); try { for (int j = 0; j < scoreDocs.Length; j++) // merge scoreDocs into hq { ScoreDoc scoreDoc = scoreDocs[j]; if (scoreDoc == hq.InsertWithOverflow(scoreDoc)) { break; } } } finally { @lock.Unlock(); } return docs; } } /// <summary> /// A thread subclass for searching a single searchable /// </summary> private sealed class SearcherCallableWithSort : ICallable<TopFieldDocs> { private readonly ReentrantLock @lock; private readonly IndexSearcher searcher; private readonly Weight weight; private readonly int nDocs; private readonly TopFieldCollector hq; private readonly Sort sort; private readonly LeafSlice slice; private readonly FieldDoc after; private readonly bool doDocScores; private readonly bool doMaxScore; public SearcherCallableWithSort(ReentrantLock @lock, IndexSearcher searcher, LeafSlice slice, Weight weight, FieldDoc after, int nDocs, TopFieldCollector hq, Sort sort, bool doDocScores, bool doMaxScore) { this.@lock = @lock; this.searcher = searcher; this.weight = weight; this.nDocs = nDocs; this.hq = hq; this.sort = sort; this.slice = slice; this.after = after; this.doDocScores = doDocScores; this.doMaxScore = doMaxScore; } private readonly FakeScorer fakeScorer = new FakeScorer(); public TopFieldDocs Call() { if (Debugging.AssertsEnabled) Debugging.Assert(slice.Leaves.Length == 1); TopFieldDocs docs = searcher.Search(slice.Leaves, weight, after, nDocs, sort, true, doDocScores || sort.NeedsScores, doMaxScore); @lock.Lock(); try { AtomicReaderContext ctx = slice.Leaves[0]; int @base = ctx.DocBase; hq.SetNextReader(ctx); hq.SetScorer(fakeScorer); foreach (ScoreDoc scoreDoc in docs.ScoreDocs) { fakeScorer.doc = scoreDoc.Doc - @base; fakeScorer.score = scoreDoc.Score; hq.Collect(scoreDoc.Doc - @base); } // Carry over maxScore from sub: if (doMaxScore && docs.MaxScore > hq.maxScore) { hq.maxScore = docs.MaxScore; } } finally { @lock.Unlock(); } return docs; } } /// <summary> /// A helper class that wraps a <see cref="ICompletionService{T}"/> and provides an /// iterable interface to the completed <see cref="ICallable{V}"/> instances. /// </summary> /// <typeparam name="T">the type of the <see cref="ICallable{V}"/> return value</typeparam> private sealed class ExecutionHelper<T> : IEnumerator<T>, IEnumerable<T> { private readonly ICompletionService<T> service; private int numTasks; private T current; internal ExecutionHelper(TaskScheduler executor) { this.service = new TaskSchedulerCompletionService<T>(executor); } public T Current => current; object IEnumerator.Current => current; public void Dispose() { } public void Submit(ICallable<T> task) { this.service.Submit(task); ++numTasks; } public void Reset() { throw new NotSupportedException(); } public bool MoveNext() { if (numTasks > 0) { try { var awaitable = service.Take(); awaitable.Wait(); current = awaitable.Result; return true; } #if FEATURE_THREAD_INTERRUPT catch (ThreadInterruptedException /*e*/) { //throw new ThreadInterruptedException(e.ToString(), e); throw; // LUCENENET: CA2200: Rethrow to preserve stack details (https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2200-rethrow-to-preserve-stack-details) } #endif catch (Exception e) { // LUCENENET NOTE: We need to re-throw this as Exception to // ensure it is not caught in the wrong place throw new Exception(e.ToString(), e); } finally { --numTasks; } } return false; } // LUCENENET NOTE: Not supported in .NET anyway //public override void Remove() //{ // throw new NotSupportedException(); //} public IEnumerator<T> GetEnumerator() { // use the shortcut here - this is only used in a private context return this; } IEnumerator IEnumerable.GetEnumerator() { return this; } } /// <summary> /// A class holding a subset of the <see cref="IndexSearcher"/>s leaf contexts to be /// executed within a single thread. /// <para/> /// @lucene.experimental /// </summary> public class LeafSlice { internal AtomicReaderContext[] Leaves { get; private set; } public LeafSlice(params AtomicReaderContext[] leaves) { this.Leaves = leaves; } } public override string ToString() { return "IndexSearcher(" + reader + "; executor=" + executor + ")"; } /// <summary> /// Returns <see cref="Search.TermStatistics"/> for a term. /// <para/> /// This can be overridden for example, to return a term's statistics /// across a distributed collection. /// <para/> /// @lucene.experimental /// </summary> public virtual TermStatistics TermStatistics(Term term, TermContext context) { return new TermStatistics(term.Bytes, context.DocFreq, context.TotalTermFreq); } /// <summary> /// Returns <see cref="Search.CollectionStatistics"/> for a field. /// <para/> /// This can be overridden for example, to return a field's statistics /// across a distributed collection. /// <para/> /// @lucene.experimental /// </summary> public virtual CollectionStatistics CollectionStatistics(string field) { int docCount; long sumTotalTermFreq; long sumDocFreq; if (Debugging.AssertsEnabled) Debugging.Assert(field != null); Terms terms = MultiFields.GetTerms(reader, field); if (terms == null) { docCount = 0; sumTotalTermFreq = 0; sumDocFreq = 0; } else { docCount = terms.DocCount; sumTotalTermFreq = terms.SumTotalTermFreq; sumDocFreq = terms.SumDocFreq; } return new CollectionStatistics(field, reader.MaxDoc, docCount, sumTotalTermFreq, sumDocFreq); } } }
// using UnityEngine; using System; using System.Collections; using System.Text; namespace GameAnalyticsSDK { /* Based on the JSON parser from * http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html * * I simplified it so that it doesn't throw exceptions * and can be used in Unity iPhone with maximum code stripping. */ /// <summary> /// This class encodes and decodes JSON strings. /// Spec. details, see http://www.json.org/ /// /// JSON uses Arrays and Objects. These correspond here to the datatypes ArrayList and Hashtable. /// All numbers are parsed to floats. /// </summary> public class GA_MiniJSON { public const int TOKEN_NONE = 0; public const int TOKEN_CURLY_OPEN = 1; public const int TOKEN_CURLY_CLOSE = 2; public const int TOKEN_SQUARED_OPEN = 3; public const int TOKEN_SQUARED_CLOSE = 4; public const int TOKEN_COLON = 5; public const int TOKEN_COMMA = 6; public const int TOKEN_STRING = 7; public const int TOKEN_NUMBER = 8; public const int TOKEN_TRUE = 9; public const int TOKEN_FALSE = 10; public const int TOKEN_NULL = 11; private const int BUILDER_CAPACITY = 2000; protected static GA_MiniJSON instance = new GA_MiniJSON(); /// <summary> /// On decoding, this value holds the position at which the parse failed (-1 = no error). /// </summary> protected int lastErrorIndex = -1; protected string lastDecode = ""; /// <summary> /// Parses the string json into a value /// </summary> /// <param name="json">A JSON string.</param> /// <returns>An ArrayList, a Hashtable, a float, a string, null, true, or false</returns> public static object JsonDecode(string json) { // save the string for debug information GA_MiniJSON.instance.lastDecode = json; if(json != null) { char[] charArray = json.ToCharArray(); int index = 0; bool success = true; object value = GA_MiniJSON.instance.ParseValue(charArray, ref index, ref success); if(success) { GA_MiniJSON.instance.lastErrorIndex = -1; } else { GA_MiniJSON.instance.lastErrorIndex = index; } return value; } else { return null; } } /// <summary> /// Converts a Hashtable / ArrayList object into a JSON string /// </summary> /// <param name="json">A Hashtable / ArrayList</param> /// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns> public static string JsonEncode(object json) { StringBuilder builder = new StringBuilder(BUILDER_CAPACITY); bool success = GA_MiniJSON.instance.SerializeValue(json, builder); return (success ? builder.ToString() : null); } /// <summary> /// On decoding, this function returns the position at which the parse failed (-1 = no error). /// </summary> /// <returns></returns> public static bool LastDecodeSuccessful() { return (GA_MiniJSON.instance.lastErrorIndex == -1); } /// <summary> /// On decoding, this function returns the position at which the parse failed (-1 = no error). /// </summary> /// <returns></returns> public static int GetLastErrorIndex() { return GA_MiniJSON.instance.lastErrorIndex; } /// <summary> /// If a decoding error occurred, this function returns a piece of the JSON string /// at which the error took place. To ease debugging. /// </summary> /// <returns></returns> public static string GetLastErrorSnippet() { if(GA_MiniJSON.instance.lastErrorIndex == -1) { return ""; } else { int startIndex = GA_MiniJSON.instance.lastErrorIndex - 5; int endIndex = GA_MiniJSON.instance.lastErrorIndex + 15; if(startIndex < 0) { startIndex = 0; } if(endIndex >= GA_MiniJSON.instance.lastDecode.Length) { endIndex = GA_MiniJSON.instance.lastDecode.Length - 1; } return GA_MiniJSON.instance.lastDecode.Substring(startIndex, endIndex - startIndex + 1); } } protected Hashtable ParseObject(char[] json, ref int index) { Hashtable table = new Hashtable(); int token; // { NextToken(json, ref index); bool done = false; while(!done) { token = LookAhead(json, index); if(token == GA_MiniJSON.TOKEN_NONE) { return null; } else if(token == GA_MiniJSON.TOKEN_COMMA) { NextToken(json, ref index); } else if(token == GA_MiniJSON.TOKEN_CURLY_CLOSE) { NextToken(json, ref index); return table; } else { // name string name = ParseString(json, ref index); if(name == null) { return null; } // : token = NextToken(json, ref index); if(token != GA_MiniJSON.TOKEN_COLON) { return null; } // value bool success = true; object value = ParseValue(json, ref index, ref success); if(!success) { return null; } table[name] = value; } } return table; } protected ArrayList ParseArray(char[] json, ref int index) { ArrayList array = new ArrayList(); // [ NextToken(json, ref index); bool done = false; while(!done) { int token = LookAhead(json, index); if(token == GA_MiniJSON.TOKEN_NONE) { return null; } else if(token == GA_MiniJSON.TOKEN_COMMA) { NextToken(json, ref index); } else if(token == GA_MiniJSON.TOKEN_SQUARED_CLOSE) { NextToken(json, ref index); break; } else { bool success = true; object value = ParseValue(json, ref index, ref success); if(!success) { return null; } array.Add(value); } } return array; } protected object ParseValue(char[] json, ref int index, ref bool success) { switch(LookAhead(json, index)) { case GA_MiniJSON.TOKEN_STRING: return ParseString(json, ref index); case GA_MiniJSON.TOKEN_NUMBER: return ParseNumber(json, ref index); case GA_MiniJSON.TOKEN_CURLY_OPEN: return ParseObject(json, ref index); case GA_MiniJSON.TOKEN_SQUARED_OPEN: return ParseArray(json, ref index); case GA_MiniJSON.TOKEN_TRUE: NextToken(json, ref index); return Boolean.Parse("TRUE"); case GA_MiniJSON.TOKEN_FALSE: NextToken(json, ref index); return Boolean.Parse("FALSE"); case GA_MiniJSON.TOKEN_NULL: NextToken(json, ref index); return null; case GA_MiniJSON.TOKEN_NONE: break; } success = false; return null; } protected string ParseString(char[] json, ref int index) { string s = ""; char c; EatWhitespace(json, ref index); // " c = json[index]; index++; bool complete = false; while(!complete) { if(index == json.Length) { break; } c = json[index]; index++; if(c == '"') { complete = true; break; } else if(c == '\\') { if(index == json.Length) { break; } c = json[index]; index++; if(c == '"') { s += '"'; } else if(c == '\\') { s += '\\'; } else if(c == '/') { s += '/'; } else if(c == 'b') { s += '\b'; } else if(c == 'f') { s += '\f'; } else if(c == 'n') { s += '\n'; } else if(c == 'r') { s += '\r'; } else if(c == 't') { s += '\t'; } else if(c == 'u') { int remainingLength = json.Length - index; if(remainingLength >= 4) { char[] unicodeCharArray = new char[4]; // Array.Copy(json, index, unicodeCharArray, 0, 4); for(int i = 0; i < 4; i++) { unicodeCharArray[i] = json[index + i]; } // Drop in the HTML markup for the unicode character s += "&#x" + new string(unicodeCharArray) + ";"; /* uint codePoint = UInt32.Parse(new string(unicodeCharArray), NumberStyles.HexNumber); // convert the integer codepoint to a unicode char and add to string s += Char.ConvertFromUtf32((int)codePoint); */ // skip 4 chars index += 4; } else { break; } } } else { s += c.ToString(); } } if(!complete) { return null; } return s; } protected float ParseNumber(char[] json, ref int index) { EatWhitespace(json, ref index); int lastIndex = GetLastIndexOfNumber(json, index); int charLength = (lastIndex - index) + 1; char[] numberCharArray = new char[charLength]; // Array.Copy(json, index, numberCharArray, 0, charLength); for(int i = 0; i < charLength; i++) { numberCharArray[i] = json[index + i]; } index = lastIndex + 1; return Single.Parse(new string(numberCharArray)); // , CultureInfo.InvariantCulture); } protected int GetLastIndexOfNumber(char[] json, int index) { int lastIndex; for(lastIndex = index; lastIndex < json.Length; lastIndex++) { if("0123456789+-.eE".IndexOf(json[lastIndex]) == -1) { break; } } return lastIndex - 1; } protected void EatWhitespace(char[] json, ref int index) { for(; index < json.Length; index++) { if(" \t\n\r".IndexOf(json[index]) == -1) { break; } } } protected int LookAhead(char[] json, int index) { int saveIndex = index; return NextToken(json, ref saveIndex); } protected int NextToken(char[] json, ref int index) { EatWhitespace(json, ref index); if(index == json.Length) { return GA_MiniJSON.TOKEN_NONE; } char c = json[index]; index++; switch(c) { case '{': return GA_MiniJSON.TOKEN_CURLY_OPEN; case '}': return GA_MiniJSON.TOKEN_CURLY_CLOSE; case '[': return GA_MiniJSON.TOKEN_SQUARED_OPEN; case ']': return GA_MiniJSON.TOKEN_SQUARED_CLOSE; case ',': return GA_MiniJSON.TOKEN_COMMA; case '"': return GA_MiniJSON.TOKEN_STRING; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': return GA_MiniJSON.TOKEN_NUMBER; case ':': return GA_MiniJSON.TOKEN_COLON; } index--; int remainingLength = json.Length - index; // false if(remainingLength >= 5) { if(json[index] == 'f' && json[index + 1] == 'a' && json[index + 2] == 'l' && json[index + 3] == 's' && json[index + 4] == 'e') { index += 5; return GA_MiniJSON.TOKEN_FALSE; } } // true if(remainingLength >= 4) { if(json[index] == 't' && json[index + 1] == 'r' && json[index + 2] == 'u' && json[index + 3] == 'e') { index += 4; return GA_MiniJSON.TOKEN_TRUE; } } // null if(remainingLength >= 4) { if(json[index] == 'n' && json[index + 1] == 'u' && json[index + 2] == 'l' && json[index + 3] == 'l') { index += 4; return GA_MiniJSON.TOKEN_NULL; } } return GA_MiniJSON.TOKEN_NONE; } protected bool SerializeObjectOrArray(object objectOrArray, StringBuilder builder) { if(objectOrArray is Hashtable) { return SerializeObject((Hashtable)objectOrArray, builder); } else if(objectOrArray is ArrayList) { return SerializeArray((ArrayList)objectOrArray, builder); } else { return false; } } protected bool SerializeObject(Hashtable anObject, StringBuilder builder) { builder.Append("{"); IDictionaryEnumerator e = anObject.GetEnumerator(); bool first = true; while(e.MoveNext()) { string key = e.Key.ToString(); object value = e.Value; if(!first) { builder.Append(", "); } SerializeString(key, builder); builder.Append(":"); if(!SerializeValue(value, builder)) { return false; } first = false; } builder.Append("}"); return true; } protected bool SerializeArray(ArrayList anArray, StringBuilder builder) { builder.Append("["); bool first = true; for(int i = 0; i < anArray.Count; i++) { object value = anArray[i]; if(!first) { builder.Append(", "); } if(!SerializeValue(value, builder)) { return false; } first = false; } builder.Append("]"); return true; } protected bool SerializeValue(object value, StringBuilder builder) { // Type t = value.GetType(); // Debug.Log("type: " + t.ToString() + " isArray: " + t.IsArray); if(value == null) { builder.Append("null"); } else if(value.GetType().IsArray) { SerializeArray(new ArrayList((ICollection)value), builder); } else if(value is string) { SerializeString((string)value, builder); } else if(value is Char) { SerializeString(value.ToString(), builder); } else if(value is Hashtable) { SerializeObject((Hashtable)value, builder); } else if(value is ArrayList) { SerializeArray((ArrayList)value, builder); } else if((value is Boolean) && ((Boolean)value == true)) { builder.Append("true"); } else if((value is Boolean) && ((Boolean)value == false)) { builder.Append("false"); } // else if (value.GetType().IsPrimitive) { else if(value is Single) { SerializeNumber((Single)value, builder); } else { return false; } return true; } protected void SerializeString(string aString, StringBuilder builder) { builder.Append("\""); char[] charArray = aString.ToCharArray(); for(int i = 0; i < charArray.Length; i++) { char c = charArray[i]; if(c == '"') { builder.Append("\\\""); } else if(c == '\\') { builder.Append("\\\\"); } else if(c == '\b') { builder.Append("\\b"); } else if(c == '\f') { builder.Append("\\f"); } else if(c == '\n') { builder.Append("\\n"); } else if(c == '\r') { builder.Append("\\r"); } else if(c == '\t') { builder.Append("\\t"); } else { int codepoint = (Int32)c; if((codepoint >= 32) && (codepoint <= 126)) { builder.Append(c); } // else // { // builder.Append("\\u" + Convert.ToString(codepoint, 16).PadLeft(4, '0')); // } } } builder.Append("\""); } protected void SerializeNumber(float number, StringBuilder builder) { builder.Append(number.ToString()); // , CultureInfo.InvariantCulture)); } /* /// <summary> /// Determines if a given object is numeric in any way /// (can be integer, float, etc). C# has no pretty way to do this. /// </summary> protected bool IsNumeric(object o) { try { Single.Parse(o.ToString()); } catch (Exception) { return false; } return true; } */ } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.IO; using System.Xml.Serialization; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Interfaces; using OpenMetaverse; namespace OpenSim.Region.Framework.Scenes { /// <summary> /// A new version of the old Channel class, simplified /// </summary> public class TerrainChannel : ITerrainChannel { private readonly bool[,] taint; private double[,] map; private int _revision; public TerrainChannel() { map = new double[Constants.RegionSize, Constants.RegionSize]; taint = new bool[Constants.RegionSize / 16,Constants.RegionSize / 16]; int x; for (x = 0; x < Constants.RegionSize; x++) { int y; for (y = 0; y < Constants.RegionSize; y++) { map[x, y] = TerrainUtil.PerlinNoise2D(x, y, 2, 0.125) * 10; double spherFacA = TerrainUtil.SphericalFactor(x, y, Constants.RegionSize / 2.0, Constants.RegionSize / 2.0, 50) * 0.01; double spherFacB = TerrainUtil.SphericalFactor(x, y, Constants.RegionSize / 2.0, Constants.RegionSize / 2.0, 100) * 0.001; if (map[x, y] < spherFacA) map[x, y] = spherFacA; if (map[x, y] < spherFacB) map[x, y] = spherFacB; } } } public TerrainChannel(double[,] import) { map = import; taint = new bool[import.GetLength(0),import.GetLength(1)]; } public TerrainChannel(double[,] import, int rev) : this(import) { _revision = rev; } public TerrainChannel(bool createMap) { if (createMap) { map = new double[Constants.RegionSize,Constants.RegionSize]; taint = new bool[Constants.RegionSize / 16,Constants.RegionSize / 16]; } } public TerrainChannel(int w, int h) { map = new double[w,h]; taint = new bool[w / 16,h / 16]; } #region ITerrainChannel Members public int Width { get { return map.GetLength(0); } } public int Height { get { return map.GetLength(1); } } public ITerrainChannel MakeCopy() { TerrainChannel copy = new TerrainChannel(false); copy.map = (double[,]) map.Clone(); return copy; } public float[] GetFloatsSerialised() { // Move the member variables into local variables, calling // member variables 256*256 times gets expensive int w = Width; int h = Height; float[] heights = new float[w * h]; int i, j; // map coordinates int idx = 0; // index into serialized array for (i = 0; i < h; i++) { for (j = 0; j < w; j++) { heights[idx++] = (float)map[j, i]; } } return heights; } public double[,] GetDoubles() { return map; } public double this[int x, int y] { get { if (x < map.GetLength(0) && y < map.GetLength(1) && x >= 0 && y >= 0) { return map[x, y]; } else { return 0.0; } } set { // Will "fix" terrain hole problems. Although not fantastically. if (Double.IsNaN(value) || Double.IsInfinity(value)) return; if (map[x, y] != value) { taint[x / 16, y / 16] = true; map[x, y] = value; } } } public int RevisionNumber { get { return _revision; } } public bool Tainted(int x, int y) { if (taint[x / 16, y / 16]) { taint[x / 16, y / 16] = false; return true; } return false; } #endregion public TerrainChannel Copy() { TerrainChannel copy = new TerrainChannel(false); copy.map = (double[,]) map.Clone(); return copy; } public string SaveToXmlString() { XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = Encoding.UTF8; using (StringWriter sw = new StringWriter()) { using (XmlWriter writer = XmlWriter.Create(sw, settings)) { WriteXml(writer); } string output = sw.ToString(); return output; } } private void WriteXml(XmlWriter writer) { writer.WriteStartElement(String.Empty, "TerrainMap", String.Empty); ToXml(writer); writer.WriteEndElement(); } public void LoadFromXmlString(string data) { StringReader sr = new StringReader(data); XmlTextReader reader = new XmlTextReader(sr); reader.Read(); ReadXml(reader); reader.Close(); sr.Close(); } private void ReadXml(XmlReader reader) { reader.ReadStartElement("TerrainMap"); FromXml(reader); } private void ToXml(XmlWriter xmlWriter) { float[] mapData = GetFloatsSerialised(); byte[] buffer = new byte[mapData.Length * 4]; for (int i = 0; i < mapData.Length; i++) { byte[] value = BitConverter.GetBytes(mapData[i]); Array.Copy(value, 0, buffer, (i * 4), 4); } XmlSerializer serializer = new XmlSerializer(typeof(byte[])); serializer.Serialize(xmlWriter, buffer); } private void FromXml(XmlReader xmlReader) { XmlSerializer serializer = new XmlSerializer(typeof(byte[])); byte[] dataArray = (byte[])serializer.Deserialize(xmlReader); int index = 0; for (int y = 0; y < Height; y++) { for (int x = 0; x < Width; x++) { float value; value = BitConverter.ToSingle(dataArray, index); index += 4; this[x, y] = (double)value; } } } /// <summary> /// Get the raw height at the given x/y coordinates on 1m boundary. /// </summary> /// <param name="x">X coordinate</param> /// <param name="y">Y coordinate</param> /// <returns></returns> public float GetRawHeightAt(int x, int y) { return (float)(map[x, y]); } public float GetRawHeightAt(uint x, uint y) { return (float)(map[x, y]); } public double GetRawHeightAt(Vector3 point) { return map[(int)point.X, (int)point.Y]; } /// <summary> /// Get the height of the terrain at given horizontal coordinates. /// </summary> /// <param name="xPos">X coordinate</param> /// <param name="yPos">Y coordinate</param> /// <returns>Height at given coordinates</returns> public float CalculateHeightAt(float xPos, float yPos) { if (!Util.IsValidRegionXY(xPos, yPos)) return 0.0f; int x = (int)xPos; int y = (int)yPos; float xOffset = xPos - (float)x; float yOffset = yPos - (float)y; if ((xOffset == 0.0f) && (yOffset == 0.0f)) return (float)(map[x, y]); // optimize the exact heightmap entry case int xPlusOne = x + 1; int yPlusOne = y + 1; // Check for edge cases (literally) if ((xPlusOne > Constants.RegionSize - 1) || (yPlusOne > Constants.RegionSize - 1)) return (float)map[x, y]; if (xPlusOne > Constants.RegionSize - 1) { if (yPlusOne > Constants.RegionSize - 1) return (float)map[x, y]; // upper right corner // Simpler linear interpolation between 2 points along y (right map edge) return (float)((map[x, yPlusOne] - map[x, y]) * yOffset + map[x, y]); } if (yPlusOne > Constants.RegionSize - 1) { // Simpler linear interpolation between 2 points along x (top map edge) return (float)((map[xPlusOne, y] - map[x, y]) * xOffset + map[x, y]); } // LL terrain triangles are divided like [/] rather than [\] ... // Vertex/triangle layout is: Z2 - Z3 // | / | // Z0 - Z1 float triZ0 = (float)(map[x, y]); float triZ1 = (float)(map[xPlusOne, y]); float triZ2 = (float)(map[x, yPlusOne]); float triZ3 = (float)(map[xPlusOne, yPlusOne]); float height = 0.0f; if ((xOffset + (1.0 - yOffset)) < 1.0f) { // Upper left (NW) triangle // So relative to Z2 corner height = triZ2; height += (triZ3 - triZ2) * xOffset; height += (triZ0 - triZ2) * (1.0f - yOffset); } else { // Lower right (SE) triangle // So relative to Z1 corner height = triZ1; height += (triZ0 - triZ1) * (1.0f - xOffset); height += (triZ3 - triZ1) * yOffset; } return height; } /// <summary> /// Get the height of the terrain at given horizontal coordinates. /// Uses a 4-point bilinear calculation to smooth the terrain based /// on all 4 nearest terrain heightmap vertices. /// </summary> /// <param name="xPos">X coordinate</param> /// <param name="yPos">Y coordinate</param> /// <returns>Height at given coordinates</returns> public float Calculate4PointHeightAt(float xPos, float yPos) { if (!Util.IsValidRegionXY(xPos, yPos)) return 0.0f; int x = (int)xPos; int y = (int)yPos; float xOffset = xPos - (float)x; float yOffset = yPos - (float)y; if ((xOffset == 0.0f) && (yOffset == 0.0f)) return (float)(map[x, y]); // optimize the exact heightmap entry case int xPlusOne = x + 1; int yPlusOne = y + 1; // Check for edge cases (literally) if ((xPlusOne > Constants.RegionSize - 1) || (yPlusOne > Constants.RegionSize - 1)) return (float)map[x, y]; if (xPlusOne > Constants.RegionSize - 1) { if (yPlusOne > Constants.RegionSize - 1) return (float)map[x, y]; // upper right corner // Simpler linear interpolation between 2 points along y (right map edge) return (float)((map[x, yPlusOne] - map[x, y]) * yOffset + map[x, y]); } if (yPlusOne > Constants.RegionSize - 1) { // Simpler linear interpolation between 2 points along x (top map edge) return (float)((map[xPlusOne, y] - map[x, y]) * xOffset + map[x, y]); } // Inside the map square: use 4-point bilinear interpolation // f(x,y) = f(0,0) * (1-x)(1-y) + f(1,0) * x(1-y) + f(0,1) * (1-x)y + f(1,1) * xy float f00 = GetRawHeightAt(x, y); float f01 = GetRawHeightAt(x, yPlusOne); float f10 = GetRawHeightAt(xPlusOne, y); float f11 = GetRawHeightAt(xPlusOne, yPlusOne); float lowest = f00; lowest = Math.Min(lowest, f01); lowest = Math.Min(lowest, f10); lowest = Math.Min(lowest, f11); f00 -= lowest; f01 -= lowest; f10 -= lowest; f11 -= lowest; float z = (float)( f00 * (1.0f - xOffset) * (1.0f - yOffset) + f01 * xOffset * (1.0f - yOffset) + f10 * (1.0f - xOffset) * yOffset + f11 * xOffset * yOffset ); return lowest + z; } // Pass the deltas between point1 and the corner and point2 and the corner private Vector3 TriangleNormal(Vector3 delta1, Vector3 delta2) { Vector3 normal; if (delta1 == Vector3.Zero) normal = new Vector3(0.0f, delta2.Y * -delta1.Z, 1.0f); else if (delta2 == Vector3.Zero) normal = new Vector3(delta1.X * -delta1.Z, 0.0f, 1.0f); else { // The cross product is the slope normal. normal = new Vector3( (delta1.Y * delta2.Z) - (delta1.Z * delta2.Y), (delta1.Z * delta2.X) - (delta1.X * delta2.Z), (delta1.X * delta2.Y) - (delta1.Y * delta2.X) ); } return normal; } public Vector3 NormalToSlope(Vector3 normal) { Vector3 slope = new Vector3(normal); if (slope.Z == 0.0f) slope.Z = 1.0f; else slope.Z = (float)(((normal.X * normal.X) + (normal.Y * normal.Y)) / (-1.0f * normal.Z)); return slope; } // Pass the deltas between point1 and the corner and point2 and the corner private Vector3 TriangleSlope(Vector3 delta1, Vector3 delta2) { return NormalToSlope(TriangleNormal(delta1, delta2)); } public Vector3 CalculateNormalAt(float xPos, float yPos) // 3-point triangle surface normal { if (xPos < 0 || yPos < 0 || xPos >= Constants.RegionSize || yPos >= Constants.RegionSize) return new Vector3(0.00000f, 0.00000f, 1.00000f); List<float> results = new List<float>(3); uint x = (uint)xPos; uint y = (uint)yPos; uint xPlusOne = x + 1; uint yPlusOne = y + 1; if (xPlusOne > Constants.RegionSize - 1) xPlusOne = Constants.RegionSize - 1; if (yPlusOne > Constants.RegionSize - 1) yPlusOne = Constants.RegionSize - 1; Vector3 P0 = new Vector3(x, y, (float)map[x, y]); Vector3 P1 = new Vector3(xPlusOne, y, (float)map[xPlusOne, y]); Vector3 P2 = new Vector3(x, yPlusOne, (float)map[x, yPlusOne]); Vector3 P3 = new Vector3(xPlusOne, yPlusOne, (float)map[xPlusOne, yPlusOne]); float xOffset = xPos - (float)x; float yOffset = yPos - (float)y; Vector3 normal; if ((xOffset + (1.0 - yOffset)) < 1.0f) normal = TriangleNormal(P2 - P3, P0 - P2); // Upper left (NW) triangle else normal = TriangleNormal(P0 - P1, P1 - P3); // Lower right (SE) triangle return normal; } public Vector3 CalculateSlopeAt(float xPos, float yPos) // 3-point triangle slope { return NormalToSlope(CalculateNormalAt(xPos, yPos)); } public Vector3 Calculate4PointNormalAt(float xPos, float yPos) { if (!Util.IsValidRegionXY(xPos, yPos)) return new Vector3(0.00000f, 0.00000f, 1.00000f); List<float> results = new List<float>(3); uint x = (uint)xPos; uint y = (uint)yPos; uint xPlusOne = x + 1; uint yPlusOne = y + 1; if (xPlusOne > Constants.RegionSize - 1) xPlusOne = Constants.RegionSize - 1; if (yPlusOne > Constants.RegionSize - 1) yPlusOne = Constants.RegionSize - 1; Vector3 P0 = new Vector3(x, y, (float)map[x, y]); Vector3 P1 = new Vector3(xPlusOne, y, (float)map[xPlusOne, y]); Vector3 P2 = new Vector3(x, yPlusOne, (float)map[x, yPlusOne]); Vector3 P3 = new Vector3(xPlusOne, yPlusOne, (float)map[xPlusOne, yPlusOne]); // LL terrain triangles are divided like [/] rather than [\] ... // Vertex/triangle layout is: P2 - P3 // | / | // P0 - P1 Vector3 normal0 = TriangleNormal(P2 - P3, P0 - P2); // larger values first, so slope points down Vector3 normal1 = TriangleNormal(P1 - P0, P3 - P1); // and counter-clockwise edge order Vector3 normal = (normal0 + normal1) / 2.0f; if ((normal.X == 0.0f) && (normal.Y == 0.0f)) { // The two triangles are completely symmetric and will result in a vertical slope when averaged. // i.e. the location is on one side of a perfectly balanced ridge or valley. // So use only the triangle the location is in, so that it points into the valley or down the ridge. float xOffset = xPos - x; float yOffset = yPos - y; if ((xOffset + (1.0 - yOffset)) <= 1.0f) { // Upper left (NW) triangle normal = normal0; } else { // Lower right (SE) triangle normal = normal1; } } normal.Normalize(); return normal; } public Vector3 Calculate4PointSlopeAt(float xPos, float yPos) // 3-point triangle slope { return NormalToSlope(Calculate4PointNormalAt(xPos, yPos)); } public int IncrementRevisionNumber() { return ++_revision; } } }
#region license // Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion // // DO NOT EDIT THIS FILE! // // This file was generated automatically by astgen.boo. // namespace Boo.Lang.Compiler.Ast { using System.Collections; using System.Runtime.Serialization; [System.Serializable] public abstract partial class TypeDefinition : TypeMember, INodeWithGenericParameters { protected TypeMemberCollection _members; protected TypeReferenceCollection _baseTypes; protected GenericParameterDeclarationCollection _genericParameters; [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public TypeDefinition CloneNode() { return (TypeDefinition)Clone(); } /// <summary> /// <see cref="Node.CleanClone"/> /// </summary> [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public TypeDefinition CleanClone() { return (TypeDefinition)base.CleanClone(); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Matches(Node node) { if (node == null) return false; if (NodeType != node.NodeType) return false; var other = ( TypeDefinition)node; if (_modifiers != other._modifiers) return NoMatch("TypeDefinition._modifiers"); if (_name != other._name) return NoMatch("TypeDefinition._name"); if (!Node.AllMatch(_attributes, other._attributes)) return NoMatch("TypeDefinition._attributes"); if (!Node.AllMatch(_members, other._members)) return NoMatch("TypeDefinition._members"); if (!Node.AllMatch(_baseTypes, other._baseTypes)) return NoMatch("TypeDefinition._baseTypes"); if (!Node.AllMatch(_genericParameters, other._genericParameters)) return NoMatch("TypeDefinition._genericParameters"); return true; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Replace(Node existing, Node newNode) { if (base.Replace(existing, newNode)) { return true; } if (_attributes != null) { Attribute item = existing as Attribute; if (null != item) { Attribute newItem = (Attribute)newNode; if (_attributes.Replace(item, newItem)) { return true; } } } if (_members != null) { TypeMember item = existing as TypeMember; if (null != item) { TypeMember newItem = (TypeMember)newNode; if (_members.Replace(item, newItem)) { return true; } } } if (_baseTypes != null) { TypeReference item = existing as TypeReference; if (null != item) { TypeReference newItem = (TypeReference)newNode; if (_baseTypes.Replace(item, newItem)) { return true; } } } if (_genericParameters != null) { GenericParameterDeclaration item = existing as GenericParameterDeclaration; if (null != item) { GenericParameterDeclaration newItem = (GenericParameterDeclaration)newNode; if (_genericParameters.Replace(item, newItem)) { return true; } } } return false; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public object Clone() { throw new System.InvalidOperationException("Cannot clone abstract class: TypeDefinition"); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override internal void ClearTypeSystemBindings() { _annotations = null; _entity = null; if (null != _attributes) { _attributes.ClearTypeSystemBindings(); } if (null != _members) { _members.ClearTypeSystemBindings(); } if (null != _baseTypes) { _baseTypes.ClearTypeSystemBindings(); } if (null != _genericParameters) { _genericParameters.ClearTypeSystemBindings(); } } [System.Xml.Serialization.XmlArray] [System.Xml.Serialization.XmlArrayItem(typeof(TypeMember))] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public TypeMemberCollection Members { get { return _members ?? (_members = new TypeMemberCollection(this)); } set { if (_members != value) { _members = value; if (null != _members) { _members.InitializeParent(this); } } } } [System.Xml.Serialization.XmlArray] [System.Xml.Serialization.XmlArrayItem(typeof(TypeReference))] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public TypeReferenceCollection BaseTypes { get { return _baseTypes ?? (_baseTypes = new TypeReferenceCollection(this)); } set { if (_baseTypes != value) { _baseTypes = value; if (null != _baseTypes) { _baseTypes.InitializeParent(this); } } } } [System.Xml.Serialization.XmlArray] [System.Xml.Serialization.XmlArrayItem(typeof(GenericParameterDeclaration))] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public GenericParameterDeclarationCollection GenericParameters { get { return _genericParameters ?? (_genericParameters = new GenericParameterDeclarationCollection(this)); } set { if (_genericParameters != value) { _genericParameters = value; if (null != _genericParameters) { _genericParameters.InitializeParent(this); } } } } } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email info@fyireporting.com or visit the website www.fyiReporting.com. */ // written by GJL & AJM using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using System.Xml; //This NEW class allows the modifying of static series on a chart. GJL & AJM namespace fyiReporting.RdlDesign { public partial class StaticSeriesCtl : UserControl, IProperty { private DesignXmlDraw _Draw; private List<XmlNode> _ReportItems; private SeriesItem si; public bool ShowMe; internal StaticSeriesCtl(DesignXmlDraw dxDraw, List<XmlNode> ris) { _Draw = dxDraw; _ReportItems = ris; InitializeComponent(); InitValues(); } public StaticSeriesCtl() { InitializeComponent(); } public bool IsValid() { return true; } public void Apply() { XmlNode node = _ReportItems[0]; XmlNode ncds = DesignXmlDraw.FindNextInHierarchy(node, "SeriesGroupings", "SeriesGrouping","StaticSeries"); XmlNode ncdc = DesignXmlDraw.FindNextInHierarchy(node, "ChartData"); XmlNode nTyp = DesignXmlDraw.FindNextInHierarchy(node, "Type"); ncds.InnerText = ""; ncdc.InnerText = ""; foreach (SeriesItem si in lbDataSeries.Items) { //Write the staticMember fields ncds.InnerXml += "<StaticMember><Label>" + si.Name + "</Label><Value>" + si.Data.Replace("<","&lt;").Replace(">","&gt;") + "</Value></StaticMember>"; //Write the chartSeries fields //if we have a scatter plot we need to do two datavalues! if (nTyp.InnerXml.Equals("Scatter")) { ncdc.InnerXml += "<ChartSeries><PlotType>" + si.PlotType + "</PlotType><fyi:NoMarker xmlns:fyi=\"http://www.fyireporting.com/schemas\">" + si.NoMarker + "</fyi:NoMarker><fyi:LineSize xmlns:fyi=\"http://www.fyireporting.com/schemas\">" + si.LineSize + "</fyi:LineSize><YAxis>" + si.YAxis + "</YAxis><DataPoints><DataPoint><DataValues><DataValue><Value>" + si.Xplot.Replace("<", "&lt;").Replace(">", "&gt;") + "</Value></DataValue><DataValue><Value>" // 20022008 AJM GJL + si.Data.Replace("<", "&lt;").Replace(">", "&gt;") + "</Value></DataValue></DataValues><DataLabel><Value>" + si.Label.Replace("<", "&lt;").Replace(">", "&gt;") + "</Value><Visible>" + si.ShowLabel.ToString() + "</Visible></DataLabel></DataPoint></DataPoints></ChartSeries>"; } else { ncdc.InnerXml += "<ChartSeries><PlotType>" + si.PlotType + "</PlotType><fyi:NoMarker xmlns:fyi=\"http://www.fyireporting.com/schemas\">" + si.NoMarker + "</fyi:NoMarker><fyi:LineSize xmlns:fyi=\"http://www.fyireporting.com/schemas\">" + si.LineSize + "</fyi:LineSize><YAxis>" + si.YAxis + "</YAxis><DataPoints><DataPoint><DataValues><DataValue><Value>" // 20022008 AJM GJL + si.Data.Replace("<", "&lt;").Replace(">", "&gt;") + "</Value></DataValue></DataValues><DataLabel><Value>" + si.Label.Replace("<", "&lt;").Replace(">", "&gt;") + "</Value><Visible>" + si.ShowLabel.ToString() + "</Visible></DataLabel></DataPoint></DataPoints></ChartSeries>"; } } } private void FunctionButtonClick(Object sender, EventArgs e) { Button myButton = (Button)sender; switch (myButton.Name) { case ("btnSeriesName"): functionBox(txtSeriesName); break; case ("btnDataValue"): functionBox(txtDataValue); break; case ("btnLabelValue"): functionBox(txtLabelValue); break; case ("btnX"): functionBox(txtX); break; } } private void functionBox(TextBox txt) { DialogExprEditor ee = new DialogExprEditor(_Draw, txt.Text,_ReportItems[0] , false); try { if (ee.ShowDialog() == DialogResult.OK) { txt.Text = ee.Expression; } } finally { ee.Dispose(); } return; } private void chkShowLabels_CheckedChanged(object sender, EventArgs e) { txtLabelValue.Enabled = btnLabelValue.Enabled = chkShowLabels.Checked; if (lbDataSeries.SelectedIndex > -1) { si.ShowLabel = chkShowLabels.Checked; } } //GJL private void chkMarker_CheckedChanged(object sender, EventArgs e) { if (lbDataSeries.SelectedIndex > -1) { si.NoMarker = !chkMarker.Checked; } } private void cbLine_SelectedIndexChanged(object sender, EventArgs e) { if (cbLine.SelectedIndex > -1) { si.LineSize = (String)cbLine.Items[cbLine.SelectedIndex]; } } private void InitValues() { XmlNode node = _ReportItems[0]; XmlNode nTyp = DesignXmlDraw.FindNextInHierarchy(node, "Type"); XmlNode ncds = DesignXmlDraw.FindNextInHierarchy(node, "SeriesGroupings","SeriesGrouping","StaticSeries"); ShowMe = ncds != null; txtX.Enabled = btnX.Enabled = nTyp.InnerXml == "Scatter"; if (ShowMe) { XmlNode cd; XmlNode cdo = DesignXmlDraw.FindNextInHierarchy(node, "ChartData"); int i = 0; foreach (XmlNode ncd in ncds.ChildNodes) { cd = cdo.ChildNodes[i]; XmlNode ndv = DesignXmlDraw.FindNextInHierarchy(ncd,"Label"); String nameValue = ndv == null? "": ndv.InnerText; XmlNode ndv2 = DesignXmlDraw.FindNextInHierarchy(ncd,"Value"); String nameStaticValue = ndv2 == null ? "" : ndv2.InnerText; XmlNode pt = DesignXmlDraw.FindNextInHierarchy(cd, "PlotType"); String PlotValue; if (pt == null) { PlotValue = "Auto"; } else { PlotValue = pt.InnerText; } //GJL 14082008 XmlNode Nm = DesignXmlDraw.FindNextInHierarchy(cd, "fyi:NoMarker"); bool NoMarker; if (Nm == null) { NoMarker = false; } else { NoMarker = Boolean.Parse(Nm.InnerText); } XmlNode Ls = DesignXmlDraw.FindNextInHierarchy(cd, "fyi:LineSize"); String LineSize; if (Ls== null) { LineSize = "Regular"; } else { LineSize = Ls.InnerText; } // 20022008 AJM GJL XmlNode ya = DesignXmlDraw.FindNextInHierarchy(cd, "YAxis"); String Yaxis; if (ya == null) { Yaxis = "Left"; } else { Yaxis = ya.InnerText; } XmlNode dv = DesignXmlDraw.FindNextInHierarchy(cd, "DataPoints","DataPoint","DataValues","DataValue","Value"); String dataValue = dv.InnerText; XmlNode lv = DesignXmlDraw.FindNextInHierarchy(cd, "DataPoints","DataPoint","DataLabel","Visible"); bool showLabel = false; if (lv != null) { showLabel = lv.InnerText.ToUpper().Equals("TRUE"); } XmlNode lva = DesignXmlDraw.FindNextInHierarchy(cd, "DataPoints","DataPoint","DataLabel","Value"); String labelValue = ""; if (lva != null) { labelValue = lva.InnerText; } SeriesItem si = new SeriesItem(); si.Name = nameValue; si.Label = labelValue; si.ShowLabel = showLabel; si.Data = nameStaticValue; si.PlotType = PlotValue; si.YAxis = Yaxis;// 20022008 AJM GJL si.Xplot = dataValue; //Only for XY plots si.NoMarker = NoMarker;//0206208 GJL si.LineSize = LineSize; lbDataSeries.Items.Add(si); i++; } } } private void btnDel_Click(object sender, EventArgs e) { if (lbDataSeries.SelectedIndex >= 0) { lbDataSeries.Items.RemoveAt(lbDataSeries.SelectedIndex); txtDataValue.Text = ""; txtLabelValue.Text = ""; txtSeriesName.Text = ""; chkMarker.Checked = true; chkShowLabels.Checked = false; } } private void btnAdd_Click(object sender, EventArgs e) { SeriesItem si = new SeriesItem(); si.Data = ""; si.Name = "<New Series>"; si.ShowLabel = false; si.Label = ""; si.PlotType = "Auto"; si.NoMarker = false; si.LineSize = "Regular"; si.YAxis = "Left";// 20022008 AJM GJL lbDataSeries.Items.Add(si); lbDataSeries.SelectedItem = si; } private class SeriesItem { public String Data; public String Name; public bool ShowLabel; public String Label; public String PlotType; public String YAxis;// 20022008 AJM GJL public String Xplot; //030308 GJL public bool NoMarker;//020608 GJL public String LineSize = "Regular"; //260608 GJL public override String ToString() { return Name; } } private void txtSeriesName_TextChanged(object sender, EventArgs e) { if (lbDataSeries.SelectedIndex > -1) { si.Name = txtSeriesName.Text; int i = lbDataSeries.Items.IndexOf(si); lbDataSeries.Items.Remove(si); lbDataSeries.Items.Insert(i,si); lbDataSeries.SelectedItem = si; } } private void txtDataValue_TextChanged(object sender, EventArgs e) { if (lbDataSeries.SelectedIndex > -1) { si.Data = txtDataValue.Text; } } private void txtLabelValue_TextChanged(object sender, EventArgs e) { if (lbDataSeries.SelectedIndex > -1) { si.Label = txtLabelValue.Text; } } private void lbDataSeries_SelectedIndexChanged(object sender, EventArgs e) { if (lbDataSeries.SelectedIndex > -1) { si = (SeriesItem)lbDataSeries.SelectedItem; txtDataValue.Text = si.Data; txtLabelValue.Text = si.Label; txtSeriesName.Text = si.Name; chkShowLabels.Checked = si.ShowLabel; cbPlotType.Text = si.PlotType; chkMarker.Checked = !si.NoMarker; cbLine.Text = si.LineSize; if (txtX.Enabled) { txtX.Text = si.Xplot; } if (si.YAxis == "Right") { chkRight.Checked = true; } else { chkLeft.Checked = true; } } } private void cbPlotType_SelectedIndexChanged(object sender, EventArgs e) { if (lbDataSeries.SelectedIndex > -1) { si.PlotType = cbPlotType.Text; } } // 20022008 AJM GJL private void chkLeft_CheckedChanged(object sender, EventArgs e) { chkRight.Checked = !chkLeft.Checked; if (lbDataSeries.SelectedIndex > -1) { if (chkRight.Checked) { si.YAxis = "Right"; } else { si.YAxis = "Left"; } } } private void btnDown_Click(object sender, EventArgs e) { int index = lbDataSeries.SelectedIndex; if (index < 0 || index + 1 == lbDataSeries.Items.Count) return; object postname = lbDataSeries.Items[index + 1]; lbDataSeries.Items.RemoveAt(index + 1); lbDataSeries.Items.Insert(index, postname); } private void btnUp_Click(object sender, EventArgs e) { int index = lbDataSeries.SelectedIndex; if (index <= 0) return; object prename = lbDataSeries.Items[index - 1]; lbDataSeries.Items.RemoveAt(index - 1); lbDataSeries.Items.Insert(index, prename); } private void txtX_TextChanged(object sender, EventArgs e) { if (lbDataSeries.SelectedIndex > -1) { si.Xplot = txtX.Text; } } } }
// Copyright (C) 2015-2021 The Neo Project. // // The neo is free software distributed under the MIT software license, // see the accompanying file LICENSE in the main directory of the // project or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without // modifications are permitted. using Neo.IO.Caching; using System; using System.Collections.Generic; using System.IO; using System.Text.Json; namespace Neo.IO.Json { /// <summary> /// Represents a JSON object. /// </summary> public class JObject { /// <summary> /// Represents a <see langword="null"/> object. /// </summary> public static readonly JObject Null = null; private readonly OrderedDictionary<string, JObject> properties = new(); /// <summary> /// Gets or sets the properties of the JSON object. /// </summary> public IDictionary<string, JObject> Properties => properties; /// <summary> /// Gets or sets the properties of the JSON object. /// </summary> /// <param name="name">The name of the property to get or set.</param> /// <returns>The property with the specified name.</returns> public JObject this[string name] { get { if (Properties.TryGetValue(name, out JObject value)) return value; return null; } set { Properties[name] = value; } } /// <summary> /// Gets the property at the specified index. /// </summary> /// <param name="index">The zero-based index of the property to get.</param> /// <returns>The property at the specified index.</returns> public virtual JObject this[int index] { get => properties[index]; set => throw new NotSupportedException(); } /// <summary> /// Converts the current JSON object to a boolean value. /// </summary> /// <returns>The converted value.</returns> public virtual bool AsBoolean() { return true; } /// <summary> /// Converts the current JSON object to a floating point number. /// </summary> /// <returns>The converted value.</returns> public virtual double AsNumber() { return double.NaN; } /// <summary> /// Converts the current JSON object to a <see cref="string"/>. /// </summary> /// <returns>The converted value.</returns> public virtual string AsString() { return ToString(); } /// <summary> /// Determines whether the JSON object contains a property with the specified name. /// </summary> /// <param name="key">The property name to locate in the JSON object.</param> /// <returns><see langword="true"/> if the JSON object contains a property with the name; otherwise, <see langword="false"/>.</returns> public bool ContainsProperty(string key) { return Properties.ContainsKey(key); } /// <summary> /// Converts the current JSON object to a <see cref="JArray"/> object. /// </summary> /// <returns>The converted value.</returns> /// <exception cref="InvalidCastException">The JSON object is not a <see cref="JArray"/>.</exception> public virtual JArray GetArray() => throw new InvalidCastException(); /// <summary> /// Converts the current JSON object to a boolean value. /// </summary> /// <returns>The converted value.</returns> /// <exception cref="InvalidCastException">The JSON object is not a <see cref="JBoolean"/>.</exception> public virtual bool GetBoolean() => throw new InvalidCastException(); /// <summary> /// Converts the current JSON object to a 32-bit signed integer. /// </summary> /// <returns>The converted value.</returns> /// <exception cref="InvalidCastException">The JSON object is not a <see cref="JNumber"/>.</exception> /// <exception cref="InvalidCastException">The JSON object cannot be converted to an integer.</exception> /// <exception cref="OverflowException">The JSON object cannot be converted to a 32-bit signed integer.</exception> public int GetInt32() { double d = GetNumber(); if (d % 1 != 0) throw new InvalidCastException(); return checked((int)d); } /// <summary> /// Converts the current JSON object to a floating point number. /// </summary> /// <returns>The converted value.</returns> /// <exception cref="InvalidCastException">The JSON object is not a <see cref="JNumber"/>.</exception> public virtual double GetNumber() => throw new InvalidCastException(); /// <summary> /// Converts the current JSON object to a <see cref="string"/>. /// </summary> /// <returns>The converted value.</returns> /// <exception cref="InvalidCastException">The JSON object is not a <see cref="JString"/>.</exception> public virtual string GetString() => throw new InvalidCastException(); /// <summary> /// Parses a JSON object from a byte array. /// </summary> /// <param name="value">The byte array that contains the JSON object.</param> /// <param name="max_nest">The maximum nesting depth when parsing the JSON object.</param> /// <returns>The parsed JSON object.</returns> public static JObject Parse(ReadOnlySpan<byte> value, int max_nest = 100) { Utf8JsonReader reader = new(value, new JsonReaderOptions { AllowTrailingCommas = false, CommentHandling = JsonCommentHandling.Skip, MaxDepth = max_nest }); try { JObject json = Read(ref reader); if (reader.Read()) throw new FormatException(); return json; } catch (JsonException ex) { throw new FormatException(ex.Message, ex); } } /// <summary> /// Parses a JSON object from a <see cref="string"/>. /// </summary> /// <param name="value">The <see cref="string"/> that contains the JSON object.</param> /// <param name="max_nest">The maximum nesting depth when parsing the JSON object.</param> /// <returns>The parsed JSON object.</returns> public static JObject Parse(string value, int max_nest = 100) { return Parse(Utility.StrictUTF8.GetBytes(value), max_nest); } private static JObject Read(ref Utf8JsonReader reader, bool skipReading = false) { if (!skipReading && !reader.Read()) throw new FormatException(); return reader.TokenType switch { JsonTokenType.False => false, JsonTokenType.Null => Null, JsonTokenType.Number => reader.GetDouble(), JsonTokenType.StartArray => ReadArray(ref reader), JsonTokenType.StartObject => ReadObject(ref reader), JsonTokenType.String => ReadString(ref reader), JsonTokenType.True => true, _ => throw new FormatException(), }; } private static JArray ReadArray(ref Utf8JsonReader reader) { JArray array = new(); while (reader.Read()) { switch (reader.TokenType) { case JsonTokenType.EndArray: return array; default: array.Add(Read(ref reader, skipReading: true)); break; } } throw new FormatException(); } private static JObject ReadObject(ref Utf8JsonReader reader) { JObject obj = new(); while (reader.Read()) { switch (reader.TokenType) { case JsonTokenType.EndObject: return obj; case JsonTokenType.PropertyName: string name = ReadString(ref reader); if (obj.Properties.ContainsKey(name)) throw new FormatException(); JObject value = Read(ref reader); obj.Properties.Add(name, value); break; default: throw new FormatException(); } } throw new FormatException(); } private static string ReadString(ref Utf8JsonReader reader) { try { return reader.GetString(); } catch (InvalidOperationException ex) { throw new FormatException(ex.Message, ex); } } /// <summary> /// Encode the current JSON object into a byte array. /// </summary> /// <param name="indented">Indicates whether indentation is required.</param> /// <returns>The encoded JSON object.</returns> public byte[] ToByteArray(bool indented) { using MemoryStream ms = new(); using Utf8JsonWriter writer = new(ms, new JsonWriterOptions { Indented = indented, SkipValidation = true }); Write(writer); writer.Flush(); return ms.ToArray(); } /// <summary> /// Encode the current JSON object into a <see cref="string"/>. /// </summary> /// <returns>The encoded JSON object.</returns> public override string ToString() { return ToString(false); } /// <summary> /// Encode the current JSON object into a <see cref="string"/>. /// </summary> /// <param name="indented">Indicates whether indentation is required.</param> /// <returns>The encoded JSON object.</returns> public string ToString(bool indented) { return Utility.StrictUTF8.GetString(ToByteArray(indented)); } /// <summary> /// Converts the current JSON object to an <see cref="Enum"/>. /// </summary> /// <typeparam name="T">The type of the <see cref="Enum"/>.</typeparam> /// <param name="defaultValue">If the current JSON object cannot be converted to type <typeparamref name="T"/>, then the default value is returned.</param> /// <param name="ignoreCase">Indicates whether case should be ignored during conversion.</param> /// <returns>The converted value.</returns> public virtual T TryGetEnum<T>(T defaultValue = default, bool ignoreCase = false) where T : Enum { return defaultValue; } internal virtual void Write(Utf8JsonWriter writer) { writer.WriteStartObject(); foreach (KeyValuePair<string, JObject> pair in Properties) { writer.WritePropertyName(pair.Key); if (pair.Value is null) writer.WriteNullValue(); else pair.Value.Write(writer); } writer.WriteEndObject(); } /// <summary> /// Creates a copy of the current JSON object. /// </summary> /// <returns>A copy of the current JSON object.</returns> public virtual JObject Clone() { var cloned = new JObject(); foreach (KeyValuePair<string, JObject> pair in Properties) { cloned[pair.Key] = pair.Value != null ? pair.Value.Clone() : Null; } return cloned; } public JArray JsonPath(string expr) { JObject[] objects = { this }; if (expr.Length == 0) return objects; Queue<JPathToken> tokens = new(JPathToken.Parse(expr)); JPathToken first = tokens.Dequeue(); if (first.Type != JPathTokenType.Root) throw new FormatException(); JPathToken.ProcessJsonPath(ref objects, tokens); return objects; } public static implicit operator JObject(Enum value) { return (JString)value; } public static implicit operator JObject(JObject[] value) { return (JArray)value; } public static implicit operator JObject(bool value) { return (JBoolean)value; } public static implicit operator JObject(double value) { return (JNumber)value; } public static implicit operator JObject(string value) { return (JString)value; } } }
// 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.ObjectModel; using System.Diagnostics.Contracts; using System.IdentityModel.Policy; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Net; using System.Net.Security; using System.Runtime; using System.Security.Authentication; using System.Security.Principal; using System.ServiceModel; using System.ServiceModel.Description; using System.ServiceModel.Diagnostics.Application; using System.ServiceModel.Security; using System.ServiceModel.Security.Tokens; using System.Threading.Tasks; namespace System.ServiceModel.Channels { class WindowsStreamSecurityUpgradeProvider : StreamSecurityUpgradeProvider { bool _extractGroupsForWindowsAccounts; EndpointIdentity _identity; IdentityVerifier _identityVerifier; ProtectionLevel _protectionLevel; SecurityTokenManager _securityTokenManager; NetworkCredential _serverCredential; string _scheme; bool _isClient; Uri _listenUri; public WindowsStreamSecurityUpgradeProvider(WindowsStreamSecurityBindingElement bindingElement, BindingContext context, bool isClient) : base(context.Binding) { Contract.Assert(isClient, ".NET Core and .NET Native does not support server side"); _extractGroupsForWindowsAccounts = TransportDefaults.ExtractGroupsForWindowsAccounts; _protectionLevel = bindingElement.ProtectionLevel; _scheme = context.Binding.Scheme; _isClient = isClient; _listenUri = TransportSecurityHelpers.GetListenUri(context.ListenUriBaseAddress, context.ListenUriRelativeAddress); SecurityCredentialsManager credentialProvider = context.BindingParameters.Find<SecurityCredentialsManager>(); if (credentialProvider == null) { credentialProvider = ClientCredentials.CreateDefaultCredentials(); } _securityTokenManager = credentialProvider.CreateSecurityTokenManager(); } public string Scheme { get { return _scheme; } } internal bool ExtractGroupsForWindowsAccounts { get { return _extractGroupsForWindowsAccounts; } } public override EndpointIdentity Identity { get { // If the server credential is null, then we have not been opened yet and have no identity to expose. if (_serverCredential != null) { if (_identity == null) { lock (ThisLock) { if (_identity == null) { _identity = SecurityUtils.CreateWindowsIdentity(_serverCredential); } } } } return _identity; } } internal IdentityVerifier IdentityVerifier { get { return _identityVerifier; } } public ProtectionLevel ProtectionLevel { get { return _protectionLevel; } } NetworkCredential ServerCredential { get { return _serverCredential; } } public override StreamUpgradeAcceptor CreateUpgradeAcceptor() { ThrowIfDisposedOrNotOpen(); return new WindowsStreamSecurityUpgradeAcceptor(this); } public override StreamUpgradeInitiator CreateUpgradeInitiator(EndpointAddress remoteAddress, Uri via) { ThrowIfDisposedOrNotOpen(); return new WindowsStreamSecurityUpgradeInitiator(this, remoteAddress, via); } protected override void OnAbort() { } protected override void OnClose(TimeSpan timeout) { } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return new CompletedAsyncResult(callback, state); } protected override void OnEndClose(IAsyncResult result) { CompletedAsyncResult.End(result); } protected override void OnOpen(TimeSpan timeout) { if (!_isClient) { SecurityTokenRequirement sspiTokenRequirement = TransportSecurityHelpers.CreateSspiTokenRequirement(Scheme, _listenUri); _serverCredential = TransportSecurityHelpers.GetSspiCredential(_securityTokenManager, sspiTokenRequirement, timeout, out _extractGroupsForWindowsAccounts); } } protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { OnOpen(timeout); return new CompletedAsyncResult(callback, state); } protected override void OnEndOpen(IAsyncResult result) { CompletedAsyncResult.End(result); } protected override void OnOpened() { base.OnOpened(); if (_identityVerifier == null) { _identityVerifier = IdentityVerifier.CreateDefault(); } if (_serverCredential == null) { _serverCredential = CredentialCache.DefaultNetworkCredentials; } } private class WindowsStreamSecurityUpgradeAcceptor : StreamSecurityUpgradeAcceptorBase { private WindowsStreamSecurityUpgradeProvider _parent; private SecurityMessageProperty _clientSecurity; public WindowsStreamSecurityUpgradeAcceptor(WindowsStreamSecurityUpgradeProvider parent) : base(FramingUpgradeString.Negotiate) { _parent = parent; _clientSecurity = new SecurityMessageProperty(); } protected override Stream OnAcceptUpgrade(Stream stream, out SecurityMessageProperty remoteSecurity) { #if FEATURE_NETNATIVE // NegotiateStream throw ExceptionHelper.PlatformNotSupported("NegotiateStream is not supported on UWP yet"); #else // wrap stream NegotiateStream negotiateStream = new NegotiateStream(stream); // authenticate try { if (TD.WindowsStreamSecurityOnAcceptUpgradeIsEnabled()) { TD.WindowsStreamSecurityOnAcceptUpgrade(EventTraceActivity); } negotiateStream.AuthenticateAsServerAsync(_parent.ServerCredential, _parent.ProtectionLevel, TokenImpersonationLevel.Identification).GetAwaiter().GetResult(); } catch (AuthenticationException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(exception.Message, exception)); } catch (IOException ioException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException( SR.Format(SR.NegotiationFailedIO, ioException.Message), ioException)); } remoteSecurity = CreateClientSecurity(negotiateStream, _parent.ExtractGroupsForWindowsAccounts); return negotiateStream; #endif // FEATURE_NETNATIVE } protected override IAsyncResult OnBeginAcceptUpgrade(Stream stream, AsyncCallback callback, object state) { throw ExceptionHelper.PlatformNotSupported(); } protected override Stream OnEndAcceptUpgrade(IAsyncResult result, out SecurityMessageProperty remoteSecurity) { throw ExceptionHelper.PlatformNotSupported(); } #if !FEATURE_NETNATIVE // NegotiateStream SecurityMessageProperty CreateClientSecurity(NegotiateStream negotiateStream, bool extractGroupsForWindowsAccounts) { WindowsIdentity remoteIdentity = (WindowsIdentity)negotiateStream.RemoteIdentity; SecurityUtils.ValidateAnonymityConstraint(remoteIdentity, false); WindowsSecurityTokenAuthenticator authenticator = new WindowsSecurityTokenAuthenticator(extractGroupsForWindowsAccounts); // When NegotiateStream returns a WindowsIdentity the AuthenticationType is passed in the constructor to WindowsIdentity // by it's internal NegoState class. If this changes, then the call to remoteIdentity.AuthenticationType could fail if the // current process token doesn't have sufficient priviledges. It is a first class exception, and caught by the CLR // null is returned. SecurityToken token = new WindowsSecurityToken(remoteIdentity, SecurityUniqueId.Create().Value, remoteIdentity.AuthenticationType); ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies = authenticator.ValidateToken(token); _clientSecurity = new SecurityMessageProperty(); _clientSecurity.TransportToken = new SecurityTokenSpecification(token, authorizationPolicies); _clientSecurity.ServiceSecurityContext = new ServiceSecurityContext(authorizationPolicies); return _clientSecurity; } #endif // !FEATURE_NETNATIVE public override SecurityMessageProperty GetRemoteSecurity() { if (_clientSecurity.TransportToken != null) { return _clientSecurity; } return base.GetRemoteSecurity(); } } class WindowsStreamSecurityUpgradeInitiator : StreamSecurityUpgradeInitiatorBase { private WindowsStreamSecurityUpgradeProvider _parent; private IdentityVerifier _identityVerifier; private NetworkCredential _credential; private TokenImpersonationLevel _impersonationLevel; private SspiSecurityTokenProvider _clientTokenProvider; private bool _allowNtlm; public WindowsStreamSecurityUpgradeInitiator( WindowsStreamSecurityUpgradeProvider parent, EndpointAddress remoteAddress, Uri via) : base(FramingUpgradeString.Negotiate, remoteAddress, via) { _parent = parent; _clientTokenProvider = TransportSecurityHelpers.GetSspiTokenProvider( parent._securityTokenManager, remoteAddress, via, parent.Scheme, out _identityVerifier); } internal override async Task OpenAsync(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); base.Open(timeoutHelper.RemainingTime()); OutWrapper<TokenImpersonationLevel> impersonationLevelWrapper = new OutWrapper<TokenImpersonationLevel>(); OutWrapper<bool> allowNtlmWrapper = new OutWrapper<bool>(); SecurityUtils.OpenTokenProviderIfRequired(_clientTokenProvider, timeoutHelper.RemainingTime()); _credential = await TransportSecurityHelpers.GetSspiCredentialAsync( _clientTokenProvider, impersonationLevelWrapper, allowNtlmWrapper, timeoutHelper.GetCancellationToken()); _impersonationLevel = impersonationLevelWrapper.Value; _allowNtlm = allowNtlmWrapper; return; } internal override void Open(TimeSpan timeout) { OpenAsync(timeout).GetAwaiter(); } internal override void Close(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); base.Close(timeoutHelper.RemainingTime()); SecurityUtils.CloseTokenProviderIfRequired(_clientTokenProvider, timeoutHelper.RemainingTime()); } #if !FEATURE_NETNATIVE // NegotiateStream static SecurityMessageProperty CreateServerSecurity(NegotiateStream negotiateStream) { GenericIdentity remoteIdentity = (GenericIdentity)negotiateStream.RemoteIdentity; string principalName = remoteIdentity.Name; if ((principalName != null) && (principalName.Length > 0)) { ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies = SecurityUtils.CreatePrincipalNameAuthorizationPolicies(principalName); SecurityMessageProperty result = new SecurityMessageProperty(); result.TransportToken = new SecurityTokenSpecification(null, authorizationPolicies); result.ServiceSecurityContext = new ServiceSecurityContext(authorizationPolicies); return result; } else { return null; } } #endif // !FEATURE_NETNATIVE protected override Stream OnInitiateUpgrade(Stream stream, out SecurityMessageProperty remoteSecurity) { OutWrapper<SecurityMessageProperty> remoteSecurityOut = new OutWrapper<SecurityMessageProperty>(); var retVal = OnInitiateUpgradeAsync(stream, remoteSecurityOut).GetAwaiter().GetResult(); remoteSecurity = remoteSecurityOut.Value; return retVal; } #if FEATURE_NETNATIVE // NegotiateStream protected override Task<Stream> OnInitiateUpgradeAsync(Stream stream, OutWrapper<SecurityMessageProperty> remoteSecurity) { throw ExceptionHelper.PlatformNotSupported("Windows Stream Security is not supported on UWP yet"); } #else protected override async Task<Stream> OnInitiateUpgradeAsync(Stream stream, OutWrapper<SecurityMessageProperty> remoteSecurity) { NegotiateStream negotiateStream; string targetName; EndpointIdentity identity; if (TD.WindowsStreamSecurityOnInitiateUpgradeIsEnabled()) { TD.WindowsStreamSecurityOnInitiateUpgrade(); } // prepare InitiateUpgradePrepare(stream, out negotiateStream, out targetName, out identity); // authenticate try { await negotiateStream.AuthenticateAsClientAsync(_credential, targetName, _parent.ProtectionLevel, _impersonationLevel); } catch (AuthenticationException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(exception.Message, exception)); } catch (IOException ioException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException( SR.Format(SR.NegotiationFailedIO, ioException.Message), ioException)); } remoteSecurity.Value = CreateServerSecurity(negotiateStream); ValidateMutualAuth(identity, negotiateStream, remoteSecurity.Value, _allowNtlm); return negotiateStream; } #endif // FEATURE_NETNATIVE #if !FEATURE_NETNATIVE // NegotiateStream void InitiateUpgradePrepare( Stream stream, out NegotiateStream negotiateStream, out string targetName, out EndpointIdentity identity) { negotiateStream = new NegotiateStream(stream); targetName = string.Empty; identity = null; if (_parent.IdentityVerifier.TryGetIdentity(RemoteAddress, Via, out identity)) { targetName = SecurityUtils.GetSpnFromIdentity(identity, RemoteAddress); } else { targetName = SecurityUtils.GetSpnFromTarget(RemoteAddress); } } void ValidateMutualAuth(EndpointIdentity expectedIdentity, NegotiateStream negotiateStream, SecurityMessageProperty remoteSecurity, bool allowNtlm) { if (negotiateStream.IsMutuallyAuthenticated) { if (expectedIdentity != null) { if (!_parent.IdentityVerifier.CheckAccess(expectedIdentity, remoteSecurity.ServiceSecurityContext.AuthorizationContext)) { string primaryIdentity = SecurityUtils.GetIdentityNamesFromContext(remoteSecurity.ServiceSecurityContext.AuthorizationContext); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(SR.Format( SR.RemoteIdentityFailedVerification, primaryIdentity))); } } } else if (!allowNtlm) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(SR.Format(SR.StreamMutualAuthNotSatisfied))); } } #endif // FEATURE_NETNATIVE } } }
// // ImageWriter.cs // // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2010 Jb Evain // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; #if !READ_ONLY using Mono.Cecil.Cil; using Mono.Cecil.Metadata; using RVA = System.UInt32; namespace Mono.Cecil.PE { sealed class ImageWriter : BinaryStreamWriter { readonly ModuleDefinition module; readonly MetadataBuilder metadata; readonly TextMap text_map; ImageDebugDirectory debug_directory; byte [] debug_data; ByteBuffer win32_resources; const uint pe_header_size = 0x178u; const uint section_header_size = 0x28u; const uint file_alignment = 0x200; const uint section_alignment = 0x2000; const ulong image_base = 0x00400000; internal const RVA text_rva = 0x2000; readonly bool pe64; readonly uint time_stamp; internal Section text; internal Section rsrc; internal Section reloc; ushort sections; ImageWriter (ModuleDefinition module, MetadataBuilder metadata, Stream stream) : base (stream) { this.module = module; this.metadata = metadata; this.GetDebugHeader (); this.GetWin32Resources (); this.text_map = BuildTextMap (); this.sections = 2; // text + reloc this.pe64 = module.Architecture != TargetArchitecture.I386; this.time_stamp = (uint) DateTime.UtcNow.Subtract (new DateTime (1970, 1, 1)).TotalSeconds; } void GetDebugHeader () { var symbol_writer = metadata.symbol_writer; if (symbol_writer == null) return; if (!symbol_writer.GetDebugHeader (out debug_directory, out debug_data)) debug_data = Empty<byte>.Array; } void GetWin32Resources () { var rsrc = GetImageResourceSection (); if (rsrc == null) return; var raw_resources = new byte [rsrc.Data.Length]; Buffer.BlockCopy (rsrc.Data, 0, raw_resources, 0, rsrc.Data.Length); win32_resources = new ByteBuffer (raw_resources); } Section GetImageResourceSection () { if (!module.HasImage) return null; const string rsrc_section = ".rsrc"; return module.Image.GetSection (rsrc_section); } public static ImageWriter CreateWriter (ModuleDefinition module, MetadataBuilder metadata, Stream stream) { var writer = new ImageWriter (module, metadata, stream); writer.BuildSections (); return writer; } void BuildSections () { var has_win32_resources = win32_resources != null; if (has_win32_resources) sections++; text = CreateSection (".text", text_map.GetLength (), null); var previous = text; if (has_win32_resources) { rsrc = CreateSection (".rsrc", (uint) win32_resources.length, previous); PatchWin32Resources (win32_resources); previous = rsrc; } reloc = CreateSection (".reloc", 12u, previous); } Section CreateSection (string name, uint size, Section previous) { return new Section { Name = name, VirtualAddress = previous != null ? previous.VirtualAddress + Align (previous.VirtualSize, section_alignment) : text_rva, VirtualSize = size, PointerToRawData = previous != null ? previous.PointerToRawData + previous.SizeOfRawData : Align (GetHeaderSize (), file_alignment), SizeOfRawData = Align (size, file_alignment) }; } static uint Align (uint value, uint align) { align--; return (value + align) & ~align; } void WriteDOSHeader () { Write (new byte [] { // dos header start 0x4d, 0x5a, 0x90, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // lfanew 0x80, 0x00, 0x00, 0x00, // dos header end 0x0e, 0x1f, 0xba, 0x0e, 0x00, 0xb4, 0x09, 0xcd, 0x21, 0xb8, 0x01, 0x4c, 0xcd, 0x21, 0x54, 0x68, 0x69, 0x73, 0x20, 0x70, 0x72, 0x6f, 0x67, 0x72, 0x61, 0x6d, 0x20, 0x63, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x20, 0x62, 0x65, 0x20, 0x72, 0x75, 0x6e, 0x20, 0x69, 0x6e, 0x20, 0x44, 0x4f, 0x53, 0x20, 0x6d, 0x6f, 0x64, 0x65, 0x2e, 0x0d, 0x0d, 0x0a, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }); } void WritePEFileHeader () { WriteUInt32 (0x00004550); // Magic WriteUInt16 (GetMachine ()); // Machine WriteUInt16 (sections); // NumberOfSections WriteUInt32 (time_stamp); WriteUInt32 (0); // PointerToSymbolTable WriteUInt32 (0); // NumberOfSymbols WriteUInt16 ((ushort) (!pe64 ? 0xe0 : 0xf0)); // SizeOfOptionalHeader // ExecutableImage | (pe64 ? 32BitsMachine : LargeAddressAware) var characteristics = (ushort) (0x0002 | (!pe64 ? 0x0100 : 0x0020)); if (module.Kind == ModuleKind.Dll || module.Kind == ModuleKind.NetModule) characteristics |= 0x2000; WriteUInt16 (characteristics); // Characteristics } ushort GetMachine () { switch (module.Architecture) { case TargetArchitecture.I386: return 0x014c; case TargetArchitecture.AMD64: return 0x8664; case TargetArchitecture.IA64: return 0x0200; } throw new NotSupportedException (); } void WriteOptionalHeaders () { WriteUInt16 ((ushort) (!pe64 ? 0x10b : 0x20b)); // Magic WriteByte (8); // LMajor WriteByte (0); // LMinor WriteUInt32 (text.SizeOfRawData); // CodeSize WriteUInt32 (reloc.SizeOfRawData + (rsrc != null ? rsrc.SizeOfRawData : 0)); // InitializedDataSize WriteUInt32 (0); // UninitializedDataSize var entry_point_rva = text_map.GetRVA (TextSegment.StartupStub); if (module.Architecture == TargetArchitecture.IA64) entry_point_rva += 0x20; WriteUInt32 (entry_point_rva); // EntryPointRVA WriteUInt32 (text_rva); // BaseOfCode if (!pe64) { WriteUInt32 (0); // BaseOfData WriteUInt32 ((uint) image_base); // ImageBase } else { WriteUInt64 (image_base); // ImageBase } WriteUInt32 (section_alignment); // SectionAlignment WriteUInt32 (file_alignment); // FileAlignment WriteUInt16 (4); // OSMajor WriteUInt16 (0); // OSMinor WriteUInt16 (0); // UserMajor WriteUInt16 (0); // UserMinor WriteUInt16 (4); // SubSysMajor WriteUInt16 (0); // SubSysMinor WriteUInt32 (0); // Reserved WriteUInt32 (reloc.VirtualAddress + Align (reloc.VirtualSize, section_alignment)); // ImageSize WriteUInt32 (text.PointerToRawData); // HeaderSize WriteUInt32 (0); // Checksum WriteUInt16 (GetSubSystem ()); // SubSystem WriteUInt16 (0x8540); // DLLFlags const ulong stack_reserve = 0x100000; const ulong stack_commit = 0x1000; const ulong heap_reserve = 0x100000; const ulong heap_commit = 0x1000; if (!pe64) { WriteUInt32 ((uint) stack_reserve); WriteUInt32 ((uint) stack_commit); WriteUInt32 ((uint) heap_reserve); WriteUInt32 ((uint) heap_commit); } else { WriteUInt64 (stack_reserve); WriteUInt64 (stack_commit); WriteUInt64 (heap_reserve); WriteUInt64 (heap_commit); } WriteUInt32 (0); // LoaderFlags WriteUInt32 (16); // NumberOfDataDir WriteZeroDataDirectory (); // ExportTable WriteDataDirectory (text_map.GetDataDirectory (TextSegment.ImportDirectory)); // ImportTable if (rsrc != null) { // ResourceTable WriteUInt32 (rsrc.VirtualAddress); WriteUInt32 (rsrc.VirtualSize); } else WriteZeroDataDirectory (); WriteZeroDataDirectory (); // ExceptionTable WriteZeroDataDirectory (); // CertificateTable WriteUInt32 (reloc.VirtualAddress); // BaseRelocationTable WriteUInt32 (reloc.VirtualSize); if (text_map.GetLength (TextSegment.DebugDirectory) > 0) { WriteUInt32 (text_map.GetRVA (TextSegment.DebugDirectory)); WriteUInt32 (28u); } else WriteZeroDataDirectory (); WriteZeroDataDirectory (); // Copyright WriteZeroDataDirectory (); // GlobalPtr WriteZeroDataDirectory (); // TLSTable WriteZeroDataDirectory (); // LoadConfigTable WriteZeroDataDirectory (); // BoundImport WriteDataDirectory (text_map.GetDataDirectory (TextSegment.ImportAddressTable)); // IAT WriteZeroDataDirectory (); // DelayImportDesc WriteDataDirectory (text_map.GetDataDirectory (TextSegment.CLIHeader)); // CLIHeader WriteZeroDataDirectory (); // Reserved } void WriteZeroDataDirectory () { WriteUInt32 (0); WriteUInt32 (0); } ushort GetSubSystem () { switch (module.Kind) { case ModuleKind.Console: case ModuleKind.Dll: case ModuleKind.NetModule: return 0x3; case ModuleKind.Windows: return 0x2; default: throw new ArgumentOutOfRangeException (); } } void WriteSectionHeaders () { WriteSection (text, 0x60000020); if (rsrc != null) WriteSection (rsrc, 0x40000040); WriteSection (reloc, 0x42000040); } void WriteSection (Section section, uint characteristics) { var name = new byte [8]; var sect_name = section.Name; for (int i = 0; i < sect_name.Length; i++) name [i] = (byte) sect_name [i]; WriteBytes (name); WriteUInt32 (section.VirtualSize); WriteUInt32 (section.VirtualAddress); WriteUInt32 (section.SizeOfRawData); WriteUInt32 (section.PointerToRawData); WriteUInt32 (0); // PointerToRelocations WriteUInt32 (0); // PointerToLineNumbers WriteUInt16 (0); // NumberOfRelocations WriteUInt16 (0); // NumberOfLineNumbers WriteUInt32 (characteristics); } void MoveTo (uint pointer) { BaseStream.Seek (pointer, SeekOrigin.Begin); } void MoveToRVA (Section section, RVA rva) { BaseStream.Seek (section.PointerToRawData + rva - section.VirtualAddress, SeekOrigin.Begin); } void MoveToRVA (TextSegment segment) { MoveToRVA (text, text_map.GetRVA (segment)); } void WriteRVA (RVA rva) { if (!pe64) WriteUInt32 (rva); else WriteUInt64 (rva); } void WriteText () { MoveTo (text.PointerToRawData); // ImportAddressTable WriteRVA (text_map.GetRVA (TextSegment.ImportHintNameTable)); WriteRVA (0); // CLIHeader WriteUInt32 (0x48); WriteUInt16 (2); WriteUInt16 ((ushort) ((module.Runtime <= TargetRuntime.Net_1_1) ? 0 : 5)); WriteUInt32 (text_map.GetRVA (TextSegment.MetadataHeader)); WriteUInt32 (GetMetadataLength ()); WriteUInt32 ((uint) module.Attributes); WriteUInt32 (metadata.entry_point.ToUInt32 ()); WriteDataDirectory (text_map.GetDataDirectory (TextSegment.Resources)); WriteDataDirectory (text_map.GetDataDirectory (TextSegment.StrongNameSignature)); WriteZeroDataDirectory (); // CodeManagerTable WriteZeroDataDirectory (); // VTableFixups WriteZeroDataDirectory (); // ExportAddressTableJumps WriteZeroDataDirectory (); // ManagedNativeHeader // Code MoveToRVA (TextSegment.Code); WriteBuffer (metadata.code); // Resources MoveToRVA (TextSegment.Resources); WriteBuffer (metadata.resources); // Data if (metadata.data.length > 0) { MoveToRVA (TextSegment.Data); WriteBuffer (metadata.data); } // StrongNameSignature // stays blank // MetadataHeader MoveToRVA (TextSegment.MetadataHeader); WriteMetadataHeader (); WriteMetadata (); // DebugDirectory if (text_map.GetLength (TextSegment.DebugDirectory) > 0) { MoveToRVA (TextSegment.DebugDirectory); WriteDebugDirectory (); } // ImportDirectory MoveToRVA (TextSegment.ImportDirectory); WriteImportDirectory (); // StartupStub MoveToRVA (TextSegment.StartupStub); WriteStartupStub (); } uint GetMetadataLength () { return text_map.GetRVA (TextSegment.DebugDirectory) - text_map.GetRVA (TextSegment.MetadataHeader); } void WriteMetadataHeader () { WriteUInt32 (0x424a5342); // Signature WriteUInt16 (1); // MajorVersion WriteUInt16 (1); // MinorVersion WriteUInt32 (0); // Reserved var version = GetZeroTerminatedString (GetVersion ()); WriteUInt32 ((uint) version.Length); WriteBytes (version); WriteUInt16 (0); // Flags WriteUInt16 (GetStreamCount ()); uint offset = text_map.GetRVA (TextSegment.TableHeap) - text_map.GetRVA (TextSegment.MetadataHeader); WriteStreamHeader (ref offset, TextSegment.TableHeap, "#~"); WriteStreamHeader (ref offset, TextSegment.StringHeap, "#Strings"); WriteStreamHeader (ref offset, TextSegment.UserStringHeap, "#US"); WriteStreamHeader (ref offset, TextSegment.GuidHeap, "#GUID"); WriteStreamHeader (ref offset, TextSegment.BlobHeap, "#Blob"); } string GetVersion () { switch (module.Runtime) { case TargetRuntime.Net_1_0: return "v1.0.3705"; case TargetRuntime.Net_1_1: return "v1.1.4322"; case TargetRuntime.Net_2_0: return "v2.0.50727"; case TargetRuntime.Net_4_0: default: return "v4.0.30319"; } } ushort GetStreamCount () { return (ushort) ( 1 // #~ + 1 // #Strings + (metadata.user_string_heap.IsEmpty ? 0 : 1) // #US + 1 // GUID + (metadata.blob_heap.IsEmpty ? 0 : 1)); // #Blob } void WriteStreamHeader (ref uint offset, TextSegment heap, string name) { var length = (uint) text_map.GetLength (heap); if (length == 0) return; WriteUInt32 (offset); WriteUInt32 (length); WriteBytes (GetZeroTerminatedString (name)); offset += length; } static byte [] GetZeroTerminatedString (string @string) { return GetString (@string, (@string.Length + 1 + 3) & ~3); } static byte [] GetSimpleString (string @string) { return GetString (@string, @string.Length); } static byte [] GetString (string @string, int length) { var bytes = new byte [length]; for (int i = 0; i < @string.Length; i++) bytes [i] = (byte) @string [i]; return bytes; } void WriteMetadata () { WriteHeap (TextSegment.TableHeap, metadata.table_heap); WriteHeap (TextSegment.StringHeap, metadata.string_heap); WriteHeap (TextSegment.UserStringHeap, metadata.user_string_heap); WriteGuidHeap (); WriteHeap (TextSegment.BlobHeap, metadata.blob_heap); } void WriteHeap (TextSegment heap, HeapBuffer buffer) { if (buffer.IsEmpty) return; MoveToRVA (heap); WriteBuffer (buffer); } void WriteGuidHeap () { MoveToRVA (TextSegment.GuidHeap); WriteBytes (module.Mvid.ToByteArray ()); } void WriteDebugDirectory () { WriteInt32 (debug_directory.Characteristics); WriteUInt32 (time_stamp); WriteInt16 (debug_directory.MajorVersion); WriteInt16 (debug_directory.MinorVersion); WriteInt32 (debug_directory.Type); WriteInt32 (debug_directory.SizeOfData); WriteInt32 (debug_directory.AddressOfRawData); WriteInt32 ((int) BaseStream.Position + 4); WriteBytes (debug_data); } void WriteImportDirectory () { WriteUInt32 (text_map.GetRVA (TextSegment.ImportDirectory) + 40); // ImportLookupTable WriteUInt32 (0); // DateTimeStamp WriteUInt32 (0); // ForwarderChain WriteUInt32 (text_map.GetRVA (TextSegment.ImportHintNameTable) + 14); WriteUInt32 (text_map.GetRVA (TextSegment.ImportAddressTable)); Advance (20); // ImportLookupTable WriteUInt32 (text_map.GetRVA (TextSegment.ImportHintNameTable)); // ImportHintNameTable MoveToRVA (TextSegment.ImportHintNameTable); WriteUInt16 (0); // Hint WriteBytes (GetRuntimeMain ()); WriteByte (0); WriteBytes (GetSimpleString ("mscoree.dll")); WriteUInt16 (0); } byte [] GetRuntimeMain () { return module.Kind == ModuleKind.Dll || module.Kind == ModuleKind.NetModule ? GetSimpleString ("_CorDllMain") : GetSimpleString ("_CorExeMain"); } void WriteStartupStub () { switch (module.Architecture) { case TargetArchitecture.I386: WriteUInt16 (0x25ff); WriteUInt32 ((uint) image_base + text_map.GetRVA (TextSegment.ImportAddressTable)); return; case TargetArchitecture.AMD64: WriteUInt16 (0xa148); WriteUInt32 ((uint) image_base + text_map.GetRVA (TextSegment.ImportAddressTable)); WriteUInt16 (0xe0ff); return; case TargetArchitecture.IA64: WriteBytes (new byte [] { 0x0b, 0x48, 0x00, 0x02, 0x18, 0x10, 0xa0, 0x40, 0x24, 0x30, 0x28, 0x00, 0x00, 0x00, 0x04, 0x00, 0x10, 0x08, 0x00, 0x12, 0x18, 0x10, 0x60, 0x50, 0x04, 0x80, 0x03, 0x00, 0x60, 0x00, 0x80, 0x00 }); WriteUInt32 ((uint) image_base + text_map.GetRVA (TextSegment.StartupStub)); WriteUInt32 ((uint) image_base + text_rva); return; } } void WriteRsrc () { MoveTo (rsrc.PointerToRawData); WriteBuffer (win32_resources); } void WriteReloc () { MoveTo (reloc.PointerToRawData); var reloc_rva = text_map.GetRVA (TextSegment.StartupStub); reloc_rva += module.Architecture == TargetArchitecture.IA64 ? 0x20u : 2; var page_rva = reloc_rva & ~0xfffu; WriteUInt32 (page_rva); // PageRVA WriteUInt32 (0x000c); // Block Size switch (module.Architecture) { case TargetArchitecture.I386: WriteUInt32 (0x3000 + reloc_rva - page_rva); break; case TargetArchitecture.AMD64: WriteUInt32 (0xa000 + reloc_rva - page_rva); break; case TargetArchitecture.IA64: WriteUInt16 ((ushort) (0xa000 + reloc_rva - page_rva)); WriteUInt16 ((ushort) (0xa000 + reloc_rva - page_rva + 8)); break; } WriteBytes (new byte [file_alignment - reloc.VirtualSize]); } public void WriteImage () { WriteDOSHeader (); WritePEFileHeader (); WriteOptionalHeaders (); WriteSectionHeaders (); WriteText (); if (rsrc != null) WriteRsrc (); WriteReloc (); } TextMap BuildTextMap () { var map = metadata.text_map; map.AddMap (TextSegment.Code, metadata.code.length, !pe64 ? 4 : 16); map.AddMap (TextSegment.Resources, metadata.resources.length, 8); map.AddMap (TextSegment.Data, metadata.data.length, 4); if (metadata.data.length > 0) metadata.table_heap.FixupData (map.GetRVA (TextSegment.Data)); map.AddMap (TextSegment.StrongNameSignature, GetStrongNameLength (), 4); map.AddMap (TextSegment.MetadataHeader, GetMetadataHeaderLength ()); map.AddMap (TextSegment.TableHeap, metadata.table_heap.length, 4); map.AddMap (TextSegment.StringHeap, metadata.string_heap.length, 4); map.AddMap (TextSegment.UserStringHeap, metadata.user_string_heap.IsEmpty ? 0 : metadata.user_string_heap.length, 4); map.AddMap (TextSegment.GuidHeap, 16); map.AddMap (TextSegment.BlobHeap, metadata.blob_heap.IsEmpty ? 0 : metadata.blob_heap.length, 4); int debug_dir_len = 0; if (!debug_data.IsNullOrEmpty ()) { const int debug_dir_header_len = 28; debug_directory.AddressOfRawData = (int) map.GetNextRVA (TextSegment.BlobHeap) + debug_dir_header_len; debug_dir_len = debug_data.Length + debug_dir_header_len; } map.AddMap (TextSegment.DebugDirectory, debug_dir_len, 4); RVA import_dir_rva = map.GetNextRVA (TextSegment.DebugDirectory); RVA import_hnt_rva = import_dir_rva + (!pe64 ? 48u : 52u); import_hnt_rva = (import_hnt_rva + 15u) & ~15u; uint import_dir_len = (import_hnt_rva - import_dir_rva) + 27u; RVA startup_stub_rva = import_dir_rva + import_dir_len; startup_stub_rva = module.Architecture == TargetArchitecture.IA64 ? (startup_stub_rva + 15u) & ~15u : 2 + ((startup_stub_rva + 3u) & ~3u); map.AddMap (TextSegment.ImportDirectory, new Range (import_dir_rva, import_dir_len)); map.AddMap (TextSegment.ImportHintNameTable, new Range (import_hnt_rva, 0)); map.AddMap (TextSegment.StartupStub, new Range (startup_stub_rva, GetStartupStubLength ())); return map; } uint GetStartupStubLength () { switch (module.Architecture) { case TargetArchitecture.I386: return 6; case TargetArchitecture.AMD64: return 12; case TargetArchitecture.IA64: return 48; default: throw new InvalidOperationException (); } } int GetMetadataHeaderLength () { return // MetadataHeader 40 // #~ header + 12 // #Strings header + 20 // #US header + (metadata.user_string_heap.IsEmpty ? 0 : 12) // #GUID header + 16 // #Blob header + (metadata.blob_heap.IsEmpty ? 0 : 16); } int GetStrongNameLength () { if ((module.Attributes & ModuleAttributes.StrongNameSigned) == 0) return 0; if (module.Assembly == null) throw new InvalidOperationException (); var public_key = module.Assembly.Name.PublicKey; if (public_key != null) { // in fx 2.0 the key may be from 384 to 16384 bits // so we must calculate the signature size based on // the size of the public key (minus the 32 byte header) int size = public_key.Length; if (size > 32) return size - 32; // note: size == 16 for the ECMA "key" which is replaced // by the runtime with a 1024 bits key (128 bytes) } return 128; // default strongname signature size } public DataDirectory GetStrongNameSignatureDirectory () { return text_map.GetDataDirectory (TextSegment.StrongNameSignature); } public uint GetHeaderSize () { return pe_header_size + (sections * section_header_size); } void PatchWin32Resources (ByteBuffer resources) { PatchResourceDirectoryTable (resources); } void PatchResourceDirectoryTable (ByteBuffer resources) { resources.Advance (12); var entries = resources.ReadUInt16 () + resources.ReadUInt16 (); for (int i = 0; i < entries; i++) PatchResourceDirectoryEntry (resources); } void PatchResourceDirectoryEntry (ByteBuffer resources) { resources.Advance (4); var child = resources.ReadUInt32 (); var position = resources.position; resources.position = (int) child & 0x7fffffff; if ((child & 0x80000000) != 0) PatchResourceDirectoryTable (resources); else PatchResourceDataEntry (resources); resources.position = position; } void PatchResourceDataEntry (ByteBuffer resources) { var old_rsrc = GetImageResourceSection (); var rva = resources.ReadUInt32 (); resources.position -= 4; resources.WriteUInt32 (rva - old_rsrc.VirtualAddress + rsrc.VirtualAddress); } } } #endif
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /*============================================================ ** ** ** ** Purpose: Convenient wrapper for an array, an offset, and ** a count. Ideally used in streams & collections. ** Net Classes will consume an array of these. ** ** ===========================================================*/ using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Diagnostics.Contracts; namespace System { // Note: users should make sure they copy the fields out of an ArraySegment onto their stack // then validate that the fields describe valid bounds within the array. This must be done // because assignments to value types are not atomic, and also because one thread reading // three fields from an ArraySegment may not see the same ArraySegment from one call to another // (ie, users could assign a new value to the old location). [Serializable] public struct ArraySegment<T> : IList<T>, IReadOnlyList<T> { private T[] _array; private int _offset; private int _count; public ArraySegment(T[] array) { if (array == null) throw new ArgumentNullException("array"); Contract.EndContractBlock(); _array = array; _offset = 0; _count = array.Length; } public ArraySegment(T[] array, int offset, int count) { if (array == null) throw new ArgumentNullException("array"); if (offset < 0) throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (array.Length - offset < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); _array = array; _offset = offset; _count = count; } public T[] Array { get { Contract.Assert( (null == _array && 0 == _offset && 0 == _count) || (null != _array && _offset >= 0 && _count >= 0 && _offset + _count <= _array.Length), "ArraySegment is invalid"); return _array; } } public int Offset { get { // Since copying value types is not atomic & callers cannot atomically // read all three fields, we cannot guarantee that Offset is within // the bounds of Array. That is our intent, but let's not specify // it as a postcondition - force callers to re-verify this themselves // after reading each field out of an ArraySegment into their stack. Contract.Ensures(Contract.Result<int>() >= 0); Contract.Assert( (null == _array && 0 == _offset && 0 == _count) || (null != _array && _offset >= 0 && _count >= 0 && _offset + _count <= _array.Length), "ArraySegment is invalid"); return _offset; } } public int Count { get { // Since copying value types is not atomic & callers cannot atomically // read all three fields, we cannot guarantee that Count is within // the bounds of Array. That's our intent, but let's not specify // it as a postcondition - force callers to re-verify this themselves // after reading each field out of an ArraySegment into their stack. Contract.Ensures(Contract.Result<int>() >= 0); Contract.Assert( (null == _array && 0 == _offset && 0 == _count) || (null != _array && _offset >= 0 && _count >= 0 && _offset + _count <= _array.Length), "ArraySegment is invalid"); return _count; } } public override int GetHashCode() { return null == _array ? 0 : _array.GetHashCode() ^ _offset ^ _count; } public override bool Equals(Object obj) { if (obj is ArraySegment<T>) return Equals((ArraySegment<T>)obj); else return false; } public bool Equals(ArraySegment<T> obj) { return obj._array == _array && obj._offset == _offset && obj._count == _count; } public static bool operator ==(ArraySegment<T> a, ArraySegment<T> b) { return a.Equals(b); } public static bool operator !=(ArraySegment<T> a, ArraySegment<T> b) { return !(a == b); } #region IList<T> T IList<T>.this[int index] { get { if (_array == null) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NullArray")); if (index < 0 || index >= _count) throw new ArgumentOutOfRangeException("index"); Contract.EndContractBlock(); return _array[_offset + index]; } set { if (_array == null) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NullArray")); if (index < 0 || index >= _count) throw new ArgumentOutOfRangeException("index"); Contract.EndContractBlock(); _array[_offset + index] = value; } } int IList<T>.IndexOf(T item) { if (_array == null) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NullArray")); Contract.EndContractBlock(); int index = System.Array.IndexOf<T>(_array, item, _offset, _count); Contract.Assert(index == -1 || (index >= _offset && index < _offset + _count)); return index >= 0 ? index - _offset : -1; } void IList<T>.Insert(int index, T item) { throw new NotSupportedException(); } void IList<T>.RemoveAt(int index) { throw new NotSupportedException(); } #endregion #region IReadOnlyList<T> T IReadOnlyList<T>.this[int index] { get { if (_array == null) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NullArray")); if (index < 0 || index >= _count) throw new ArgumentOutOfRangeException("index"); Contract.EndContractBlock(); return _array[_offset + index]; } } #endregion IReadOnlyList<T> #region ICollection<T> bool ICollection<T>.IsReadOnly { get { // the indexer setter does not throw an exception although IsReadOnly is true. // This is to match the behavior of arrays. return true; } } void ICollection<T>.Add(T item) { throw new NotSupportedException(); } void ICollection<T>.Clear() { throw new NotSupportedException(); } bool ICollection<T>.Contains(T item) { if (_array == null) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NullArray")); Contract.EndContractBlock(); int index = System.Array.IndexOf<T>(_array, item, _offset, _count); Contract.Assert(index == -1 || (index >= _offset && index < _offset + _count)); return index >= 0; } void ICollection<T>.CopyTo(T[] array, int arrayIndex) { if (_array == null) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NullArray")); Contract.EndContractBlock(); System.Array.Copy(_array, _offset, array, arrayIndex, _count); } bool ICollection<T>.Remove(T item) { throw new NotSupportedException(); } #endregion #region IEnumerable<T> IEnumerator<T> IEnumerable<T>.GetEnumerator() { if (_array == null) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NullArray")); Contract.EndContractBlock(); return new ArraySegmentEnumerator(this); } #endregion #region IEnumerable IEnumerator IEnumerable.GetEnumerator() { if (_array == null) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NullArray")); Contract.EndContractBlock(); return new ArraySegmentEnumerator(this); } #endregion [Serializable] private sealed class ArraySegmentEnumerator : IEnumerator<T> { private T[] _array; private int _start; private int _end; private int _current; internal ArraySegmentEnumerator(ArraySegment<T> arraySegment) { Contract.Requires(arraySegment.Array != null); Contract.Requires(arraySegment.Offset >= 0); Contract.Requires(arraySegment.Count >= 0); Contract.Requires(arraySegment.Offset + arraySegment.Count <= arraySegment.Array.Length); _array = arraySegment._array; _start = arraySegment._offset; _end = _start + arraySegment._count; _current = _start - 1; } public bool MoveNext() { if (_current < _end) { _current++; return (_current < _end); } return false; } public T Current { get { if (_current < _start) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted)); if (_current >= _end) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded)); return _array[_current]; } } object IEnumerator.Current { get { return Current; } } void IEnumerator.Reset() { _current = _start - 1; } public void Dispose() { } } } }
/* transpiled with BefunCompile v1.3.0 (c) 2017 */ public static class Program { private static readonly string _g = "AR+LCAAAAAAABADt28tSpDAUgOFXiYIbUow5BBRTVGreYLazoGh22WbFaubdJ9Ci7aV1yrlg6/91VYtJ7IqLJOccmkl9TxSAT+lbsvUcAADA/5QBAAAAAAAAAAAAAAAA"+ "AAAAAIB3b+vnDwBsZ+v9BwAAAAAAAAAAAAAAAAAAAAAAvG7r5w8AnIYp6la3l8E0/UV6c724qO1lt/W8ALyNPx9Hda6LysTzn+N5YU1sXbF/1SZWbTG/mnRlgndn2bST"+ "0tUm9K4x4aJPb2rY+n8A8EZTlLqKYrUEY6NUVTrkW6mOjM67yZVlkDqITePTBac/cLqm413PLu1HFYPdkJVW63HeElIucJcbzJvE8a2hiw/GsocA2/BWgmgrUZm2KoJz"+ "tYT+shdd1Eqi6Lk1mib1K5+60mhrQiWh1GNKBtJ1akntZSnjvns8u21UQ2q9SxMurZ7HjVrbMht29fI5t39LBgG8O8N6Sq8N82l9eFZ71Ui4X+Fpp9Bhv3/UEu0LkQWA"+ "dyHl/03K/aWZawB9Suuj1EX6Wbugi+qg2h9ENfFxU/No0PpJZf9S+A/gffDNEomLLlM4/7Dr8QH+SpjOegdOTVrk++q/WBYw8Mn4Z1J4J/pJa1RrYi86XRXpIo2pJIxr"+ "3EAVDzgxU7RiojXmmb7fjQf8shFE1j9w6rzV4Wq+JXh45y5eLeGAmtMFn+dU9oEPw0uc/LWEUqlsUtPTZ4IOAoHUme+mbOyDtNQLgNN3PZlucMvX97qUxR/e37taWtX9"+ "7T0X5cp1yrdpu/ix9cQB/BFvpBy8W4P9QU273Jn16R61j/4PBizf43NuWfr51pMH8OeGFNGXwVTpfO+8u97X9FuJzkvpRCt1f9Jnc5k/z5fQXzabMIC/6O4ovy3i5z5T"+ "19m8xGOmurwzSj14ZKdPDZr8Hzh9kzFHlvL6BMD6e3/Bmgc+lkkfjeRZ7sAH5527kXhY4NM3Epw1lPiBz8znX/KvW08CwL/xC0UCinQAyAAA"; private static readonly long[] g = System.Array.ConvertAll(zd(System.Convert.FromBase64String(_g)),b=>(long)b); private static byte[]zd(byte[]o){byte[]d=System.Linq.Enumerable.ToArray(System.Linq.Enumerable.Skip(o, 1));for(int i=0;i<o[0];i++)d=zs(d);return d;} private static byte[]zs(byte[]o){using(var c=new System.IO.MemoryStream(o)) using(var z=new System.IO.Compression.GZipStream(c,System.IO.Compression.CompressionMode.Decompress)) using(var r=new System.IO.MemoryStream()){z.CopyTo(r);return r.ToArray();}} private static long gr(long x,long y){return(x>=0&&y>=0&&x<1024&&y<50)?g[y*1024+x]:0;} private static void gw(long x,long y,long v){if(x>=0&&y>=0&&x<1024&&y<50)g[y*1024+x]=v;} private static long td(long a,long b){ return (b==0)?0:(a/b); } private static long tm(long a,long b){ return (b==0)?0:(a%b); } private static System.Collections.Generic.Stack<long> s=new System.Collections.Generic.Stack<long>(); private static long sp(){ return (s.Count==0)?0:s.Pop(); } private static void sa(long v){ s.Push(v); } private static long sr(){ return (s.Count==0)?0:s.Peek(); } static void Main(string[]args) { long t0,t1,t2,t3,t4; gw(2,0,12288); gw(3,0,12000); gw(4,0,281474976710656L); gw(5,0,1024); sa(gr(2,0)); sa(gr(2,0)); _1: if(sp()!=0)goto _32;else goto _2; _2: gw(1,16,2); gw(2,1,2); gw(3,1,gr(3,0)+1); gw(4,1,2); sp(); _3: gw(3,1,gr(3,1)+1); t0=gr(0,16)+1; gw(4,1,(td(gr(4,1),gr(0,16)))*(gr(0,16)+1)); gw(0,16,t0); gw(5,1,0); _4: if(gr(4,1)>(gr(3,1)+(gr(3,0)-gr(2,1))))goto _5;else goto _30; _5: t0=gr(tm(gr(5,1),gr(5,0)),(td(gr(5,1),gr(5,0)))+16); gw(4,1,td(gr(4,1),gr(tm(gr(5,1),gr(5,0)),(td(gr(5,1),gr(5,0)))+16))); t1=gr(3,1); t2=t1-t0; gw(3,1,t2); gw(tm(gr(5,1),gr(5,0)),(td(gr(5,1),gr(5,0)))+16,gr(tm(gr(5,1)+1,gr(5,0)),(td(gr(5,1)+1,gr(5,0)))+16)); t0=gr(tm(gr(5,1),gr(5,0)),(td(gr(5,1),gr(5,0)))+16); gw(4,1,gr(4,1)*gr(tm(gr(5,1),gr(5,0)),(td(gr(5,1),gr(5,0)))+16)); t1=gr(3,1); t2=t1+t0; gw(3,1,t2); gw(5,1,gr(5,1)+1); if((gr(5,1)-(gr(3,0)+1))!=0)goto _6;else goto _8; _6: gw(3,1,gr(3,1)+1); t0=gr(tm(gr(5,1),gr(5,0)),(td(gr(5,1),gr(5,0)))+16); t1=gr(tm(gr(5,1),gr(5,0)),(td(gr(5,1),gr(5,0)))+16); gw(tm(gr(5,1),gr(5,0)),(td(gr(5,1),gr(5,0)))+16,gr(tm(gr(5,1),gr(5,0)),(td(gr(5,1),gr(5,0)))+16)+1); t2=gr(4,1); t3=td(t2,t1); gw(4,1,t3); t0++; t0*=gr(4,1); gw(4,1,t0); if(gr(5,1)>gr(2,1))goto _7;else goto _4; _7: gw(2,1,gr(5,1)); goto _4; _8: gw(0,3,0); gw(1,3,0); gw(7,1,-1); sa(5); sa(0); sa(gr(0,3)); sa(gr(0,3)-gr(7,1)); _9: if(sp()!=0)goto _17;else goto _10; _10: sp(); sa(sr()); sa(0); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(tm(sr(),gr(5,0))); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(td(sp(),gr(5,0))); sa(sp()+3L); {long v0=sp();long v1=sp();gw(v1,v0,sp());} _11: sa(sp()+1L); if((sr()-gr(2,0))!=0)goto _12;else goto _13; _12: sa(sr()); sa(tm(sr(),gr(5,0))); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(td(sp(),gr(5,0))); sa(sp()+3L); {long v0=sp();sa(gr(sp(),v0));} sa(sr()-gr(7,1)); goto _9; _13: gw(9,1,0); t4=gr(0,3); sp(); _14: sa(gr(9,1)); if((gr(9,1)-gr(3,0))!=0)goto _15;else goto _16; _15: sa(sp()+1L); sa(sr()); sa(sr()); gw(9,1,sp()); sa(tm(sp(),gr(5,0))); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(td(sp(),gr(5,0))); sa(sp()+3L); {long v0=sp();t0=gr(sp(),v0);} t4+=t0; goto _14; _16: System.Console.Out.Write(t4+" "); sp(); sp(); return; _17: if(sr()>gr(7,1))goto _18;else goto _20; _18: gw(7,1,sp()); _19: t0=1; goto _11; _20: gw(8,1,sp()); sa(sr()); _21: sa(sp()-1L); if(sr()!=-1)goto _22;else goto _28; _22: sa(sr()); sa(tm(sr(),gr(5,0))); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(td(sp(),gr(5,0))); sa(sp()+3L); {long v0=sp();sa(gr(sp(),v0));} sa(sr()); sa(sr()); if(sp()!=0)goto _23;else goto _29; _23: sa(sp()-gr(8,1)); if(sp()!=0)goto _24;else goto _27; _24: sa((sp()<gr(8,1))?1:0); if(sp()!=0)goto _25;else goto _26; _25: sp(); goto _11; _26: sa(sr()); gw(6,1,sp()); sa(sr()+1); sa(tm(sr(),gr(5,0))); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(td(sp(),gr(5,0))); sa(sp()+3L); {long v0=sp();t0=gr(sp(),v0);} gw(tm(gr(6,1)+1,gr(5,0)),(td(gr(6,1)+1,gr(5,0)))+3,gr(tm(gr(6,1),gr(5,0)),(td(gr(6,1),gr(5,0)))+3)); gw(tm(gr(6,1),gr(5,0)),(td(gr(6,1),gr(5,0)))+3,t0); goto _21; _27: sp(); sa(sp()+1L); sa(0); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(tm(sr(),gr(5,0))); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(td(sp(),gr(5,0))); sa(sp()+3L); {long v0=sp();long v1=sp();gw(v1,v0,sp());} sa(0); _28: sp(); goto _19; _29: t0=3; t1=1; sp(); sp(); goto _26; _30: if((((gr(3,0)-(gr(3,1)-gr(4,1)))>1?1:0)+(gr(4,1)<=gr(3,1)?1:0)+(gr(tm(gr(3,0)-(gr(3,1)-gr(4,1)),gr(5,0)),(td(gr(3,0)-(gr(3,1)-gr(4,1)),gr(5,0)))+3)>gr(4,1)?1L:0L))!=3)goto _3;else goto _31; _31: gw(tm(gr(3,0)-(gr(3,1)-gr(4,1)),gr(5,0)),(td(gr(3,0)-(gr(3,1)-gr(4,1)),gr(5,0)))+3,gr(4,1)); goto _3; _32: sa(sp()-1L); sa(sr()); sa(gr(4,0)); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(tm(sr(),gr(5,0))); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(td(sp(),gr(5,0))); sa(sp()+3L); {long v0=sp();long v1=sp();gw(v1,v0,sp());} sa(sr()); sa(1); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(tm(sr(),gr(5,0))); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(td(sp(),gr(5,0))); sa(sp()+8L); sa(sp()+8L); {long v0=sp();long v1=sp();gw(v1,v0,sp());} sa(sr()); goto _1; } }
// Created by: Jesse Stam. //26-2-2016 using UnityEngine; using System.Collections.Generic; using System.Linq; public class EnemyManager : MonoBehaviour { private static EnemyManager instance; [SerializeField] private EnemyBase[] spawnableBosses; [SerializeField] private Vector3 spawnMin; [SerializeField] private Vector3 spawnMax; [SerializeField] private float spawnRate; [SerializeField, Tooltip("A List of the enemies that can be spawned")] private GameObject[] spawnableEnemies; // was hard to read as one long line [SerializeField, Tooltip("time in seconds")] private float SpawnDelay; private List<EnemyBase> enemyPool; private float timeSinceGameStart; private float spawnTimer; private bool bossActive; protected void Awake () { instance = this; Game_UIControler.onPause += Game_UIControler_onPause; enemyPool = new List<EnemyBase>(); bossActive = false; if (spawnableEnemies == null) { spawnableEnemies = new GameObject[0]; } } private void Game_UIControler_onPause(bool b) { enabled = !b; } protected void Update() { // Enemies respawn at an exponential decay rate (spawn faster depending on how // long you have been playing). if (spawnTimer > 1.5f + (5.0f * Mathf.Exp(-timeSinceGameStart / spawnRate))) { if (spawnableBosses.Length > 0) { if (timeSinceGameStart % 30 == 0) { SpawnBoss(); } } if (spawnableEnemies.Length > 0 && !bossActive) { SpawnEnemies(); } else if (!bossActive) { TestSpawn(); } spawnTimer = 0; } spawnTimer += Time.deltaTime; timeSinceGameStart += Time.deltaTime; } private void TestSpawn() { GameObject g = GameObject.CreatePrimitive(PrimitiveType.Cube); //Destroy(g.GetComponent<BoxCollider>()); g.name = "Test"; PhysicMaterial pm = new PhysicMaterial("BOUNCE"); pm.bounciness = 0.8f; g.GetComponent<BoxCollider>().material = pm; g.transform.SetParent(transform, false); g.transform.localPosition = RandomPos(); Rigidbody r = g.AddComponent<Rigidbody>(); r.velocity = new Vector3(0, 0, -5); r.useGravity = false; g.AddComponent<EnemyBase>(); Destroy(g, 20f); } private void SpawnEnemies() { EnemyBase enemy = GetEnemy(); enemy.Reset(); enemy.Rigidbody.velocity = new Vector3(0, 0, -5); enemy.transform.localPosition = RandomPos(); } public static void HitAllEnemies() { foreach(EnemyBase e in instance.enemyPool) { if (e.IsAlive) { e.isHit(); } } } private EnemyBase SpawnBoss() { EnemyBase SelectedEnemy; GameObject newEnemy = Instantiate(spawnableEnemies[Random.Range(0, spawnableBosses.Length)]); newEnemy.transform.SetParent(transform, false); SelectedEnemy = newEnemy.GetComponent<EnemyBase>(); return SelectedEnemy; } private EnemyBase GetEnemy() { EnemyBase SelectedEnemy; if (enemyPool.Count > 0 && enemyPool.Any(x => x.IsRemoved == true)) { SelectedEnemy = enemyPool.First(x => x.IsRemoved == true); if (SelectedEnemy) { return SelectedEnemy; } } GameObject newEnemy = Instantiate(spawnableEnemies[Random.Range(0, spawnableEnemies.Length)]); newEnemy.transform.SetParent(transform, false); SelectedEnemy = newEnemy.GetComponent<EnemyBase>(); enemyPool.Add(SelectedEnemy); return SelectedEnemy; } private Vector3 RandomPos() { return new Vector3(Random.Range(spawnMin.x, spawnMax.x), Random.Range(spawnMin.y, spawnMax.y), Random.Range(spawnMin.z, spawnMax.z)); } [ContextMenu("Center")] private void Center() { Vector3 startPos = transform.position; transform.position = Vector3.Lerp(spawnMax + transform.position, spawnMin + transform.position, 0.5f); Vector3 diff =transform.position - startPos; spawnMin -= diff; spawnMax -= diff; } #if UNITY_EDITOR public Vector3 SpawnMin { get { return spawnMin; } set { spawnMin = value; } } public Vector3 SpawnMax { get { return spawnMax; } set { spawnMax = value; } } private Vector3 tmpMax; private Vector3 tmpMin; [SerializeField] private Color lineColor; public void OnDrawGizmosSelected() { tmpMax = transform.position + spawnMax; tmpMin = transform.position + spawnMin; Gizmos.color = Color.green; Gizmos.DrawCube(tmpMin, Vector3.one * 0.5f); Gizmos.color = Color.red; Gizmos.DrawCube(tmpMax, Vector3.one * 0.5f); } public void OnDrawGizmos() { Gizmos.color = lineColor; Gizmos.DrawLine(tmpMin, new Vector3(tmpMin.x, tmpMin.y, tmpMax.z)); Gizmos.DrawLine(tmpMin, new Vector3(tmpMin.x, tmpMax.y, tmpMin.z)); Gizmos.DrawLine(tmpMin, new Vector3(tmpMax.x, tmpMin.y, tmpMin.z)); Gizmos.DrawLine(tmpMax, new Vector3(tmpMax.x, tmpMax.y, tmpMin.z)); Gizmos.DrawLine(tmpMax, new Vector3(tmpMax.x, tmpMin.y, tmpMax.z)); Gizmos.DrawLine(tmpMax, new Vector3(tmpMin.x, tmpMax.y, tmpMax.z)); Gizmos.DrawLine(new Vector3(tmpMax.x, tmpMin.y, tmpMax.z), new Vector3(tmpMax.x, tmpMin.y, tmpMin.z)); Gizmos.DrawLine(new Vector3(tmpMax.x, tmpMin.y, tmpMax.z), new Vector3(tmpMin.x, tmpMin.y, tmpMax.z)); Gizmos.DrawLine(new Vector3(tmpMin.x, tmpMax.y, tmpMin.z), new Vector3(tmpMin.x, tmpMax.y, tmpMax.z)); Gizmos.DrawLine(new Vector3(tmpMin.x, tmpMax.y, tmpMin.z), new Vector3(tmpMax.x, tmpMax.y, tmpMin.z)); Gizmos.DrawLine(new Vector3(tmpMin.x, tmpMin.y, tmpMax.z), new Vector3(tmpMin.x, tmpMax.y, tmpMax.z)); Gizmos.DrawLine(new Vector3(tmpMax.x, tmpMax.y, tmpMin.z), new Vector3(tmpMax.x, tmpMin.y, tmpMin.z)); } #endif }
/* * This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson, * the work of Kim Sheffield and the fyiReporting project. * * Prior Copyrights: * _________________________________________________________ * |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others| * | (http://reportfu.org) | * ========================================================= * _________________________________________________________ * |Copyright (C) 2004-2008 fyiReporting Software, LLC | * |For additional information, email info@fyireporting.com | * |or visit the website www.fyiReporting.com. | * ========================================================= * * License: * * 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.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using System.Xml; using System.Text; using System.IO; using Reporting.Rdl; namespace Reporting.RdlDesign { /// <summary> /// Filters specification: used for DataRegions (List, Chart, Table, Matrix), DataSets, group instances /// </summary> internal class SubreportCtl : System.Windows.Forms.UserControl, IProperty { private DesignXmlDraw _Draw; private XmlNode _Subreport; private DataTable _DataTable; private DataGridTextBoxColumn dgtbName; private DataGridTextBoxColumn dgtbValue; private System.Windows.Forms.DataGridTableStyle dgTableStyle; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button bFile; private System.Windows.Forms.TextBox tbReportFile; private System.Windows.Forms.TextBox tbNoRows; private System.Windows.Forms.Label label2; private System.Windows.Forms.CheckBox chkMergeTrans; private System.Windows.Forms.DataGrid dgParms; private System.Windows.Forms.Button bRefreshParms; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; internal SubreportCtl(DesignXmlDraw dxDraw, XmlNode subReport) { _Draw = dxDraw; _Subreport =subReport; // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // Initialize form using the style node values InitValues(); } private void InitValues() { this.tbReportFile.Text = _Draw.GetElementValue(_Subreport, "ReportName", ""); this.tbNoRows.Text = _Draw.GetElementValue(_Subreport, "NoRows", ""); this.chkMergeTrans.Checked = _Draw.GetElementValue(_Subreport, "MergeTransactions", "false").ToLower() == "true"; // Initialize the DataGrid columns dgtbName = new DataGridTextBoxColumn(); dgtbValue = new DataGridTextBoxColumn(); this.dgTableStyle.GridColumnStyles.AddRange(new DataGridColumnStyle[] { this.dgtbName, this.dgtbValue}); // // dgtbFE // dgtbName.HeaderText = "Parameter Name"; dgtbName.MappingName = "ParameterName"; dgtbName.Width = 75; // Get the parent's dataset name // string dataSetName = _Draw.GetDataSetNameValue(_FilterParent); // // string[] fields = _Draw.GetFields(dataSetName, true); // if (fields != null) // dgtbFE.CB.Items.AddRange(fields); // // dgtbValue // this.dgtbValue.HeaderText = "Value"; this.dgtbValue.MappingName = "Value"; this.dgtbValue.Width = 75; // string[] parms = _Draw.GetReportParameters(true); // if (parms != null) // dgtbFV.CB.Items.AddRange(parms); // Initialize the DataTable _DataTable = new DataTable(); _DataTable.Columns.Add(new DataColumn("ParameterName", typeof(string))); _DataTable.Columns.Add(new DataColumn("Value", typeof(string))); string[] rowValues = new string[2]; XmlNode parameters = _Draw.GetNamedChildNode(_Subreport, "Parameters"); if (parameters != null) foreach (XmlNode pNode in parameters.ChildNodes) { if (pNode.NodeType != XmlNodeType.Element || pNode.Name != "Parameter") continue; rowValues[0] = _Draw.GetElementAttribute(pNode, "Name", ""); rowValues[1] = _Draw.GetElementValue(pNode, "Value", ""); _DataTable.Rows.Add(rowValues); } // Don't allow users to add their own rows // DataView dv = new DataView(_DataTable); // bad side effect // dv.AllowNew = false; this.dgParms.DataSource = _DataTable; DataGridTableStyle ts = dgParms.TableStyles[0]; ts.GridColumnStyles[0].Width = 140; ts.GridColumnStyles[0].ReadOnly = true; ts.GridColumnStyles[1].Width = 140; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.dgParms = new System.Windows.Forms.DataGrid(); this.dgTableStyle = new System.Windows.Forms.DataGridTableStyle(); this.label1 = new System.Windows.Forms.Label(); this.tbReportFile = new System.Windows.Forms.TextBox(); this.bFile = new System.Windows.Forms.Button(); this.tbNoRows = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.chkMergeTrans = new System.Windows.Forms.CheckBox(); this.bRefreshParms = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.dgParms)).BeginInit(); this.SuspendLayout(); // // dgParms // this.dgParms.CaptionVisible = false; this.dgParms.DataMember = ""; this.dgParms.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.dgParms.Location = new System.Drawing.Point(8, 112); this.dgParms.Name = "dgParms"; this.dgParms.Size = new System.Drawing.Size(384, 168); this.dgParms.TabIndex = 2; this.dgParms.TableStyles.AddRange(new System.Windows.Forms.DataGridTableStyle[] { this.dgTableStyle}); // // dgTableStyle // this.dgTableStyle.AllowSorting = false; this.dgTableStyle.DataGrid = this.dgParms; this.dgTableStyle.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.dgTableStyle.MappingName = ""; // // label1 // this.label1.Location = new System.Drawing.Point(8, 8); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(88, 23); this.label1.TabIndex = 3; this.label1.Text = "Subreport name"; // // tbReportFile // this.tbReportFile.Location = new System.Drawing.Point(104, 8); this.tbReportFile.Name = "tbReportFile"; this.tbReportFile.Size = new System.Drawing.Size(312, 20); this.tbReportFile.TabIndex = 4; this.tbReportFile.Text = ""; // // bFile // this.bFile.Location = new System.Drawing.Point(424, 8); this.bFile.Name = "bFile"; this.bFile.Size = new System.Drawing.Size(24, 23); this.bFile.TabIndex = 5; this.bFile.Text = "..."; this.bFile.Click += new System.EventHandler(this.bFile_Click); // // tbNoRows // this.tbNoRows.Location = new System.Drawing.Point(104, 40); this.tbNoRows.Name = "tbNoRows"; this.tbNoRows.Size = new System.Drawing.Size(312, 20); this.tbNoRows.TabIndex = 7; this.tbNoRows.Text = ""; // // label2 // this.label2.Location = new System.Drawing.Point(8, 40); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(96, 23); this.label2.TabIndex = 8; this.label2.Text = "No rows message"; // // chkMergeTrans // this.chkMergeTrans.Location = new System.Drawing.Point(8, 72); this.chkMergeTrans.Name = "chkMergeTrans"; this.chkMergeTrans.Size = new System.Drawing.Size(376, 24); this.chkMergeTrans.TabIndex = 9; this.chkMergeTrans.Text = "Use same Data Source connections as parent report when possible"; // // bRefreshParms // this.bRefreshParms.Location = new System.Drawing.Point(392, 120); this.bRefreshParms.Name = "bRefreshParms"; this.bRefreshParms.Size = new System.Drawing.Size(56, 23); this.bRefreshParms.TabIndex = 10; this.bRefreshParms.Text = "Refresh"; this.bRefreshParms.Click += new System.EventHandler(this.bRefreshParms_Click); // // SubreportCtl // this.Controls.Add(this.bRefreshParms); this.Controls.Add(this.chkMergeTrans); this.Controls.Add(this.tbNoRows); this.Controls.Add(this.label2); this.Controls.Add(this.bFile); this.Controls.Add(this.tbReportFile); this.Controls.Add(this.label1); this.Controls.Add(this.dgParms); this.Name = "SubreportCtl"; this.Size = new System.Drawing.Size(464, 304); ((System.ComponentModel.ISupportInitialize)(this.dgParms)).EndInit(); this.ResumeLayout(false); } #endregion public bool IsValid() { if (this.tbReportFile.Text.Length > 0) return true; MessageBox.Show("Subreport file must be specified.", "Subreport"); return false; } public void Apply() { _Draw.SetElement(_Subreport, "ReportName", this.tbReportFile.Text); if (this.tbNoRows.Text.Trim().Length == 0) _Draw.RemoveElement(_Subreport, "NoRows"); else _Draw.SetElement(_Subreport, "NoRows", tbNoRows.Text); _Draw.SetElement(_Subreport, "MergeTransactions", this.chkMergeTrans.Checked? "true": "false"); // Remove the old filters XmlNode parms = _Draw.GetCreateNamedChildNode(_Subreport, "Parameters"); while (parms.FirstChild != null) { parms.RemoveChild(parms.FirstChild); } // Loop thru and add all the filters foreach (DataRow dr in _DataTable.Rows) { if (dr[0] == DBNull.Value || dr[1] == DBNull.Value) continue; string name = (string) dr[0]; string val = (string) dr[1]; if (name.Length <= 0 || val.Length <= 0) continue; XmlNode pNode = _Draw.CreateElement(parms, "Parameter", null); _Draw.SetElementAttribute(pNode, "Name", name); _Draw.SetElement(pNode, "Value", val); } if (!parms.HasChildNodes) _Subreport.RemoveChild(parms); } private void bFile_Click(object sender, System.EventArgs e) { using (OpenFileDialog ofd = new OpenFileDialog()) { ofd.Filter = "Report files (*.rdl)|*.rdl" + "|All files (*.*)|*.*"; ofd.FilterIndex = 1; ofd.FileName = "*.rdl"; ofd.Title = "Specify Report File Name"; ofd.DefaultExt = "rdl"; ofd.AddExtension = true; if (ofd.ShowDialog() == DialogResult.OK) { string file = Path.GetFileNameWithoutExtension(ofd.FileName); tbReportFile.Text = file; } } } private void bRefreshParms_Click(object sender, System.EventArgs e) { // Obtain the source string filename=""; if (tbReportFile.Text.Length > 0) filename = tbReportFile.Text + ".rdl"; string source = this.GetSource(filename); if (source == null) return; // error: message already displayed // Compile the report Report report = this.GetReport(source, filename); if (report == null) return; // error: message already displayed ICollection rps = report.UserReportParameters; string[] rowValues = new string[2]; _DataTable.Rows.Clear(); foreach (UserReportParameter rp in rps) { rowValues[0] = rp.Name; rowValues[1] = ""; _DataTable.Rows.Add(rowValues); } this.dgParms.Refresh(); } private string GetSource(string file) { StreamReader fs=null; string prog=null; try { fs = new StreamReader(file); prog = fs.ReadToEnd(); } catch(Exception e) { prog = null; MessageBox.Show(e.Message, "Error reading report file"); } finally { if (fs != null) fs.Close(); } return prog; } private Report GetReport(string prog, string file) { // Now parse the file RDLParser rdlp; Report r; try { rdlp = new RDLParser(prog); string folder = Path.GetDirectoryName(file); if (folder == "") folder = Environment.CurrentDirectory; rdlp.Folder = folder; r = rdlp.Parse(); if (r.ErrorMaxSeverity > 4) { MessageBox.Show(string.Format("Report {0} has errors and cannot be processed.", "Report")); r = null; // don't return when severe errors } } catch(Exception e) { r = null; MessageBox.Show(e.Message, "Report load failed"); } return r; } } }
using System; using System.Linq; using LinqToDB; using LinqToDB.Mapping; using NUnit.Framework; namespace Tests.Linq { [TestFixture] public class CharTypesTests : TestBase { [Table("ALLTYPES", Configuration = ProviderName.DB2)] [Table("AllTypes")] public class StringTestTable { [Column("ID")] public int Id; [Column("char20DataType")] [Column(Configuration = ProviderName.SqlCe, IsColumn = false)] [Column(Configuration = ProviderName.DB2, IsColumn = false)] [Column(Configuration = ProviderName.PostgreSQL, IsColumn = false)] [Column(Configuration = ProviderName.MySql, IsColumn = false)] [Column(Configuration = ProviderName.MySqlConnector, IsColumn = false)] [Column(Configuration = TestProvName.MySql55, IsColumn = false)] [Column(Configuration = TestProvName.MariaDB, IsColumn = false)] public string? String; [Column("ncharDataType")] [Column("nchar20DataType", Configuration = ProviderName.SapHana)] [Column("CHAR20DATATYPE" , Configuration = ProviderName.DB2)] [Column("char20DataType" , Configuration = ProviderName.PostgreSQL)] [Column("char20DataType" , Configuration = ProviderName.MySql)] [Column("char20DataType" , Configuration = ProviderName.MySqlConnector)] [Column("char20DataType" , Configuration = TestProvName.MySql55)] [Column("char20DataType" , Configuration = TestProvName.MariaDB)] [Column( Configuration = ProviderName.Firebird, IsColumn = false)] public string? NString; } [Table("ALLTYPES", Configuration = ProviderName.DB2)] [Table("AllTypes")] public class CharTestTable { [Column("ID")] public int Id; [Column("char20DataType")] [Column(Configuration = ProviderName.SqlCe, IsColumn = false)] [Column(Configuration = ProviderName.DB2, IsColumn = false)] [Column(Configuration = ProviderName.PostgreSQL, IsColumn = false)] [Column(Configuration = ProviderName.MySql, IsColumn = false)] [Column(Configuration = ProviderName.MySqlConnector, IsColumn = false)] [Column(Configuration = TestProvName.MySql55, IsColumn = false)] [Column(Configuration = TestProvName.MariaDB, IsColumn = false)] public char? Char; [Column("ncharDataType" , DataType = DataType.NChar)] [Column("nchar20DataType", DataType = DataType.NChar, Configuration = ProviderName.SapHana)] [Column("CHAR20DATATYPE" , DataType = DataType.NChar, Configuration = ProviderName.DB2)] [Column("char20DataType" , DataType = DataType.NChar, Configuration = ProviderName.PostgreSQL)] [Column("char20DataType" , DataType = DataType.NChar, Configuration = ProviderName.MySql)] [Column("char20DataType" , DataType = DataType.NChar, Configuration = ProviderName.MySqlConnector)] [Column("char20DataType" , DataType = DataType.NChar, Configuration = TestProvName.MySql55)] [Column("char20DataType" , DataType = DataType.NChar, Configuration = TestProvName.MariaDB)] [Column( Configuration = ProviderName.Firebird, IsColumn = false)] public char? NChar; } // most of ending characters here trimmed by default by .net string TrimX methods // unicode test cases not used for String static readonly StringTestTable[] StringTestData = { new StringTestTable() { String = "test01", NString = "test01" }, new StringTestTable() { String = "test02 ", NString = "test02 " }, new StringTestTable() { String = "test03\x09 ", NString = "test03\x09 " }, new StringTestTable() { String = "test04\x0A ", NString = "test04\x0A " }, new StringTestTable() { String = "test05\x0B ", NString = "test05\x0B " }, new StringTestTable() { String = "test06\x0C ", NString = "test06\x0C " }, new StringTestTable() { String = "test07\x0D ", NString = "test07\x0D " }, new StringTestTable() { String = "test08\xA0 ", NString = "test08\xA0 " }, new StringTestTable() { String = "test09 ", NString = "test09\u2000 " }, new StringTestTable() { String = "test10 ", NString = "test10\u2001 " }, new StringTestTable() { String = "test11 ", NString = "test11\u2002 " }, new StringTestTable() { String = "test12 ", NString = "test12\u2003 " }, new StringTestTable() { String = "test13 ", NString = "test13\u2004 " }, new StringTestTable() { String = "test14 ", NString = "test14\u2005 " }, new StringTestTable() { String = "test15 ", NString = "test15\u2006 " }, new StringTestTable() { String = "test16 ", NString = "test16\u2007 " }, new StringTestTable() { String = "test17 ", NString = "test17\u2008 " }, new StringTestTable() { String = "test18 ", NString = "test18\u2009 " }, new StringTestTable() { String = "test19 ", NString = "test19\u200A " }, new StringTestTable() { String = "test20 ", NString = "test20\u3000 " }, new StringTestTable() { String = "test21\0 ", NString = "test21\0 " }, new StringTestTable() }; // need to configure sybase docker image to use utf8 character set [ActiveIssue(Configuration = TestProvName.AllSybase)] [Test] public void StringTrimming([DataSources(TestProvName.AllInformix)] string context) { using (var db = GetDataContext(context)) { var lastId = db.GetTable<StringTestTable>().Select(_ => _.Id).Max(); try { var testData = GetStringData(context); foreach (var record in testData) { var query = db.GetTable<StringTestTable>().Value(_ => _.NString, record.NString); if (!SkipChar(context)) query = query.Value(_ => _.String, record.String); if ( context == ProviderName.Firebird || context == ProviderName.Firebird + ".LinqService" || context == TestProvName.Firebird3 || context == TestProvName.Firebird3 + ".LinqService") query = db.GetTable<StringTestTable>().Value(_ => _.String, record.String); query.Insert(); } var records = db.GetTable<StringTestTable>().Where(_ => _.Id > lastId).OrderBy(_ => _.Id).ToArray(); Assert.AreEqual(testData.Length, records.Length); for (var i = 0; i < records.Length; i++) { if (!SkipChar(context)) { if (context.Contains("Sybase")) Assert.AreEqual(testData[i].String?.TrimEnd(' ')?.TrimEnd('\0'), records[i].String); else Assert.AreEqual(testData[i].String?.TrimEnd(' '), records[i].String); } if (context != ProviderName.Firebird && context != ProviderName.Firebird + ".LinqService" && context != TestProvName.Firebird3 && context != TestProvName.Firebird3 + ".LinqService") { if (context.Contains("Sybase")) Assert.AreEqual(testData[i].NString?.TrimEnd(' ')?.TrimEnd('\0'), records[i].NString); else Assert.AreEqual(testData[i].NString?.TrimEnd(' '), records[i].NString); } } } finally { db.GetTable<StringTestTable>().Where(_ => _.Id > lastId).Delete(); } } } private CharTestTable[] GetCharData([DataSources] string context) { var provider = GetProviderName(context, out var _); // filter out null-character test cases for servers/providers without support if ( context.Contains(ProviderName.PostgreSQL) || provider == ProviderName.DB2 || provider == ProviderName.SqlCe || context.Contains(ProviderName.SapHana)) return CharTestData.Where(_ => _.NChar != '\0').ToArray(); // I wonder why if (context.Contains(ProviderName.Firebird)) return CharTestData.Where(_ => _.NChar != '\xA0').ToArray(); // also strange if (context.Contains(TestProvName.AllInformix)) return CharTestData.Where(_ => _.NChar != '\0' && (_.NChar ?? 0) < byte.MaxValue).ToArray(); return CharTestData; } private StringTestTable[] GetStringData([DataSources] string context) { var provider = GetProviderName(context, out var _); // filter out null-character test cases for servers/providers without support if (context.Contains(ProviderName.PostgreSQL) || provider == ProviderName.DB2 || context == ProviderName.DB2 + ".LinqService" || context.Contains("SQLite") || provider == ProviderName.SqlCe || context.Contains(ProviderName.SapHana)) return StringTestData.Where(_ => !(_.NString ?? string.Empty).Contains("\0")).ToArray(); // I wonder why if (context.Contains(ProviderName.Firebird)) return StringTestData.Where(_ => !(_.NString ?? string.Empty).Contains("\xA0")).ToArray(); // also strange if (context.Contains(TestProvName.AllInformix)) return StringTestData.Where(_ => !(_.NString ?? string.Empty).Contains("\0") && !(_.NString ?? string.Empty).Any(c => (int)c > byte.MaxValue)).ToArray(); return StringTestData; } static readonly CharTestTable[] CharTestData = { new CharTestTable() { Char = ' ', NChar = ' ' }, new CharTestTable() { Char = '\x09', NChar = '\x09' }, new CharTestTable() { Char = '\x0A', NChar = '\x0A' }, new CharTestTable() { Char = '\x0B', NChar = '\x0B' }, new CharTestTable() { Char = '\x0C', NChar = '\x0C' }, new CharTestTable() { Char = '\x0D', NChar = '\x0D' }, new CharTestTable() { Char = '\xA0', NChar = '\xA0' }, new CharTestTable() { Char = ' ', NChar = '\u2000' }, new CharTestTable() { Char = ' ', NChar = '\u2001' }, new CharTestTable() { Char = ' ', NChar = '\u2002' }, new CharTestTable() { Char = ' ', NChar = '\u2003' }, new CharTestTable() { Char = ' ', NChar = '\u2004' }, new CharTestTable() { Char = ' ', NChar = '\u2005' }, new CharTestTable() { Char = ' ', NChar = '\u2006' }, new CharTestTable() { Char = ' ', NChar = '\u2007' }, new CharTestTable() { Char = ' ', NChar = '\u2008' }, new CharTestTable() { Char = ' ', NChar = '\u2009' }, new CharTestTable() { Char = ' ', NChar = '\u200A' }, new CharTestTable() { Char = ' ', NChar = '\u3000' }, new CharTestTable() { Char = '\0', NChar = '\0' }, new CharTestTable() }; // need to configure sybase docker image to use utf8 character set #if AZURE [ActiveIssue(Configuration = TestProvName.AllSybase)] #endif [Test] public void CharTrimming([DataSources(TestProvName.AllInformix)] string context) { using (var db = GetDataContext(context)) { var lastId = db.GetTable<CharTestTable>().Select(_ => _.Id).Max(); try { var testData = GetCharData(context); foreach (var record in testData) { var query = db.GetTable<CharTestTable>().Value(_ => _.NChar, record.NChar); if (!SkipChar(context)) query = query.Value(_ => _.Char, record.Char); if (context.Contains(ProviderName.Firebird)) query = db.GetTable<CharTestTable>().Value(_ => _.Char, record.Char); query.Insert(); } var records = db.GetTable<CharTestTable>().Where(_ => _.Id > lastId).OrderBy(_ => _.Id).ToArray(); Assert.AreEqual(testData.Length, records.Length); for (var i = 0; i < records.Length; i++) { if (context.StartsWith(ProviderName.SapHana)) { // SAP or provider trims space and we return default value, which is \0 for char // or we insert it incorrectly? if (testData[i].Char == ' ') Assert.AreEqual('\0', records[i].Char); else Assert.AreEqual(testData[i].Char, records[i].Char); if (testData[i].NChar == ' ') Assert.AreEqual('\0', records[i].NChar); else Assert.AreEqual(testData[i].NChar, records[i].NChar); continue; } if (!SkipChar(context)) { if (context.Contains("Sybase")) Assert.AreEqual(testData[i].Char == '\0' ? ' ' : testData[i].Char, records[i].Char); else Assert.AreEqual(testData[i].Char, records[i].Char); } if (context == ProviderName.MySql || context == ProviderName.MySql + ".LinqService" || context == ProviderName.MySqlConnector || context == ProviderName.MySqlConnector + ".LinqService" || context == TestProvName.MySql55 || context == TestProvName.MySql55 + ".LinqService" || context == TestProvName.MariaDB || context == TestProvName.MariaDB + ".LinqService") // for some reason mysql doesn't insert space Assert.AreEqual(testData[i].NChar == ' ' ? '\0' : testData[i].NChar, records[i].NChar); else if (!context.Contains(ProviderName.Firebird)) { if (context.Contains("Sybase")) Assert.AreEqual(testData[i].NChar == '\0' ? ' ' : testData[i].NChar, records[i].NChar); else Assert.AreEqual(testData[i].NChar, records[i].NChar); } } } finally { db.GetTable<CharTestTable>().Where(_ => _.Id > lastId).Delete(); } } } private static bool SkipChar([DataSources] string context) { return context == ProviderName.SqlCe || context == ProviderName.SqlCe + ".LinqService" || context == ProviderName.DB2 || context == ProviderName.DB2 + ".LinqService" || context.Contains(ProviderName.PostgreSQL) || context == ProviderName.MySql || context == ProviderName.MySql + ".LinqService" || context == ProviderName.MySqlConnector || context == ProviderName.MySqlConnector + ".LinqService" || context == TestProvName.MySql55 || context == TestProvName.MySql55 + ".LinqService" || context == TestProvName.MariaDB || context == TestProvName.MariaDB + ".LinqService"; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Xml; using Lighthouse.Common.SilverlightUnitTestingAbstractions; using LighthouseDesktop.Core.ExtensionMethods; using LighthouseDesktop.Core.Infrastructure.TestExecution; using LighthouseDesktop.Core.Infrastructure.XapManagement; namespace LighthouseDesktop.Core.Infrastructure.TestResultsConverters { public interface INUnitXmlResultsFileCreator { string CreateFile(RemoteTestExecutionResults outcome); } public class NUnitXmlResultsFileCreator : INUnitXmlResultsFileCreator { public string OutputFilePath { get; set; } private XmlTextWriter xmlWriter; private MemoryStream memoryStream; public NUnitXmlResultsFileCreator() { } public string CreateFile(RemoteTestExecutionResults results) { this.memoryStream = new MemoryStream(); this.xmlWriter = new XmlTextWriter(new StreamWriter(memoryStream, System.Text.Encoding.UTF8)); InitializeXmlFile(results); var outcome = results.UnitTestOutcome; var groupedByAssembly = outcome.TestResults.GroupBy(r => r.TestClass.Assembly.Name); foreach (var assembly in groupedByAssembly) { WriteAssemblyTestSuiteElement(new ComposedUnitTestOutcome() { TestResults = assembly.ToList() }); } return TerminateXmlFile(); } private void StartTestSuiteElement(string testSuiteName, string testSuiteTypeText, bool executed, bool succeeded, double time, int assertsCount) { xmlWriter.WriteStartElement("test-suite"); if (!string.IsNullOrEmpty(testSuiteTypeText)) { xmlWriter.WriteAttributeString("type", testSuiteTypeText); } xmlWriter.WriteAttributeString("name", testSuiteName); xmlWriter.WriteAttributeString("executed", executed.ToString()); xmlWriter.WriteAttributeString("result", succeeded ? "Success" : "Failure"); if (executed) { xmlWriter.WriteAttributeString("success", succeeded ? "True" : "False"); xmlWriter.WriteAttributeString("time", time.ToString("#####0.000", NumberFormatInfo.InvariantInfo)); xmlWriter.WriteAttributeString("asserts", assertsCount.ToString()); } } private void WriteAssemblyTestSuiteElement(IComposedUnitTestOutcome results) { var assemblyName = results.TestResults.FirstOrDefault().TestClass.Assembly.Name; StartTestSuiteElement(assemblyName, "Assembly", results.TotalNumberOfTestsExecuted() > 0, results.Succeeded(), results.ExecutionTimeInMiliseconds(), 0); xmlWriter.WriteStartElement("results"); var groupedByNamespace = results.TestResults.GroupBy(r => r.TestClass.Namespace); foreach (var namespaceData in groupedByNamespace) { WriteNamespaceTestSuiteElement(new ComposedUnitTestOutcome() { TestResults = namespaceData.ToList() }); } xmlWriter.WriteEndElement(); // results xmlWriter.WriteEndElement(); // test suite element } private void WriteNamespaceTestSuiteElement(IComposedUnitTestOutcome results) { var namespaceName = results.TestResults.FirstOrDefault().TestClass.Namespace; StartTestSuiteElement(namespaceName, "Namespace", results.TotalNumberOfTestsExecuted() > 0, results.Succeeded(), results.ExecutionTimeInMiliseconds(), 0); xmlWriter.WriteStartElement("results"); WriteTestFixtureTestSuiteElement(results); xmlWriter.WriteEndElement(); // results xmlWriter.WriteEndElement(); // test suite element } private void WriteTestFixtureTestSuiteElement(IComposedUnitTestOutcome results) { var testSuiteRealName = results.TestResults.FirstOrDefault().TestClass.Name; StartTestSuiteElement(testSuiteRealName, "TestFixture", results.TotalNumberOfTestsExecuted() > 0, results.Succeeded(), results.ExecutionTimeInMiliseconds(), 0); xmlWriter.WriteStartElement("results"); if (results.TestResults.Any()) WriteChildResults(results.TestResults); xmlWriter.WriteEndElement(); // results xmlWriter.WriteEndElement(); // test suite element } private void WriteChildResults(IList<IUnitTestScenarioResult> results) { foreach (var childResult in results) WriteResultElement(childResult); } private void WriteResultElement(IUnitTestScenarioResult result) { xmlWriter.WriteStartElement("test-case"); xmlWriter.WriteAttributeString("name", result.TestMethod.Name); xmlWriter.WriteAttributeString("executed", (result.Result != UnitTestOutcome.NotExecuted).ToString()); xmlWriter.WriteAttributeString("result", result.Result == UnitTestOutcome.Passed ? "Success" : "Error"); /* if (result.Result == UnitTestOutcome.Passed) { */ xmlWriter.WriteAttributeString("success", (result.Result == UnitTestOutcome.Passed).ToString()); xmlWriter.WriteAttributeString("time", (result.Finished-result.Started).TotalSeconds.ToString("#####0.000", NumberFormatInfo.InvariantInfo)); xmlWriter.WriteAttributeString("asserts", "0"); /* } */ switch (result.Result) { case UnitTestOutcome.Failed: case UnitTestOutcome.Error: case UnitTestOutcome.Timeout: WriteFailureElement(result); break; } xmlWriter.WriteEndElement(); // test element } private void WriteFailureElement(IUnitTestScenarioResult result) { xmlWriter.WriteStartElement("failure"); xmlWriter.WriteStartElement("message"); string errorMsg = "Unknown"; string stackTrace = "Unknown"; if (result.Exception != null) { if (result.Exception.Message != null) { errorMsg = result.Exception.Message; } if (result.Exception.StackTrace != null) { stackTrace = result.Exception.StackTrace; } } WriteCData(errorMsg); xmlWriter.WriteEndElement(); xmlWriter.WriteStartElement("stack-trace"); WriteCData(StackTraceFilter.Filter(stackTrace)); xmlWriter.WriteEndElement(); xmlWriter.WriteEndElement(); } private string TerminateXmlFile() { var result = string.Empty; try { xmlWriter.WriteEndElement(); // test-results xmlWriter.WriteEndDocument(); xmlWriter.Flush(); if (memoryStream != null) { memoryStream.Position = 0; using (var rdr = new StreamReader(memoryStream)) { result = rdr.ReadToEnd(); } } xmlWriter.Close(); } finally { //writer.Close(); } return result; } private void WriteEnvironment() { xmlWriter.WriteStartElement("environment"); xmlWriter.WriteAttributeString("nunit-version", "2.5.9"); xmlWriter.WriteAttributeString("clr-version", Environment.Version.ToString()); xmlWriter.WriteAttributeString("os-version", Environment.OSVersion.ToString()); xmlWriter.WriteAttributeString("platform", Environment.OSVersion.Platform.ToString()); xmlWriter.WriteAttributeString("cwd", Environment.CurrentDirectory); xmlWriter.WriteAttributeString("machine-name", Environment.MachineName); xmlWriter.WriteAttributeString("user", Environment.UserName); xmlWriter.WriteAttributeString("user-domain", Environment.UserDomainName); xmlWriter.WriteEndElement(); } private void WriteCultureInfo() { xmlWriter.WriteStartElement("culture-info"); xmlWriter.WriteAttributeString("current-culture", CultureInfo.CurrentCulture.ToString()); xmlWriter.WriteAttributeString("current-uiculture", CultureInfo.CurrentUICulture.ToString()); xmlWriter.WriteEndElement(); } private void InitializeXmlFile(RemoteTestExecutionResults executionResults) { xmlWriter.Formatting = Formatting.Indented; xmlWriter.WriteStartDocument(false); xmlWriter.WriteComment("This file represents the results of running a test suite"); xmlWriter.WriteStartElement("test-results"); var outcome = executionResults.UnitTestOutcome; var errors = outcome.TestResults.Where(p => p.Result == UnitTestOutcome.Error); string name; if (executionResults.XapBuildResult is XapSourcedXapBuildResult) { name = (executionResults.XapBuildResult as XapSourcedXapBuildResult).SourceXapFullPath; } else { name = executionResults.XapBuildResult.ResultingXapFullPath; } xmlWriter.WriteAttributeString("name", name); xmlWriter.WriteAttributeString("total", outcome.TotalNumberOfTestsExecuted().ToString()); xmlWriter.WriteAttributeString("errors", outcome.NumberOfErrors().ToString()); xmlWriter.WriteAttributeString("failures", outcome.NumberOfFailures().ToString()); xmlWriter.WriteAttributeString("not-run", outcome.NumberOfNotExecuted().ToString()); xmlWriter.WriteAttributeString("inconclusive", outcome.NumberOfInconclusive().ToString()); xmlWriter.WriteAttributeString("ignored", "0"); xmlWriter.WriteAttributeString("skipped", "0"); xmlWriter.WriteAttributeString("invalid", "0"); DateTime now = DateTime.Now; xmlWriter.WriteAttributeString("date", XmlConvert.ToString(now, "yyyy-MM-dd")); xmlWriter.WriteAttributeString("time", XmlConvert.ToString(now, "HH:mm:ss")); WriteEnvironment(); WriteCultureInfo(); } #region Output Helpers /// <summary> /// Makes string safe for xml parsing, replacing control chars with '?' /// </summary> /// <param name="encodedString">string to make safe</param> /// <returns>xml safe string</returns> private static string CharacterSafeString(string encodedString) { /*The default code page for the system will be used. Since all code pages use the same lower 128 bytes, this should be sufficient for finding uprintable control characters that make the xslt processor error. We use characters encoded by the default code page to avoid mistaking bytes as individual characters on non-latin code pages.*/ char[] encodedChars = System.Text.Encoding.Default.GetChars(System.Text.Encoding.Default.GetBytes(encodedString)); System.Collections.ArrayList pos = new System.Collections.ArrayList(); for (int x = 0; x < encodedChars.Length; x++) { char currentChar = encodedChars[x]; //unprintable characters are below 0x20 in Unicode tables //some control characters are acceptable. (carriage return 0x0D, line feed 0x0A, horizontal tab 0x09) if (currentChar < 32 && (currentChar != 9 && currentChar != 10 && currentChar != 13)) { //save the array index for later replacement. pos.Add(x); } } foreach (int index in pos) { encodedChars[index] = '?';//replace unprintable control characters with ?(3F) } return System.Text.Encoding.Default.GetString(System.Text.Encoding.Default.GetBytes(encodedChars)); } private void WriteCData(string text) { int start = 0; while (true) { int illegal = text.IndexOf("]]>", start); if (illegal < 0) break; xmlWriter.WriteCData(text.Substring(start, illegal - start + 2)); start = illegal + 2; if (start >= text.Length) return; } if (start > 0) xmlWriter.WriteCData(text.Substring(start)); else xmlWriter.WriteCData(text); } #endregion } public class StackTraceFilter { public static string Filter(string stack) { if (stack == null) return null; StringWriter sw = new StringWriter(); StringReader sr = new StringReader(stack); try { string line; while ((line = sr.ReadLine()) != null) { if (!FilterLine(line)) sw.WriteLine(line.Trim()); } } catch (Exception) { return stack; } return sw.ToString(); } static bool FilterLine(string line) { string[] patterns = new string[] { "NUnit.Core.TestCase", "NUnit.Core.ExpectedExceptionTestCase", "NUnit.Core.TemplateTestCase", "NUnit.Core.TestResult", "NUnit.Core.TestSuite", "NUnit.Framework.Assertion", "NUnit.Framework.Assert", "System.Reflection.MonoMethod" }; for (int i = 0; i < patterns.Length; i++) { if (line.IndexOf(patterns[i]) > 0) return true; } return false; } } }
using System; using System.Linq; using System.Collections.Generic; using System.Drawing; using System.Threading; using System.Threading.Tasks; #if __UNIFIED__ using Foundation; using CoreFoundation; using AVFoundation; using CoreGraphics; using CoreMedia; using CoreVideo; using ObjCRuntime; using UIKit; #else using MonoTouch.AVFoundation; using MonoTouch.CoreFoundation; using MonoTouch.CoreGraphics; using MonoTouch.CoreMedia; using MonoTouch.CoreVideo; using MonoTouch.Foundation; using MonoTouch.ObjCRuntime; using MonoTouch.UIKit; using CGRect = global::System.Drawing.RectangleF; using CGPoint = global::System.Drawing.PointF; #endif using ZXing.Common; using ZXing.Mobile; namespace ZXing.Mobile { public class ZXingScannerView : UIView, IZXingScanner<UIView> { public delegate void ScannerSetupCompleteDelegate(); public event ScannerSetupCompleteDelegate OnScannerSetupComplete; public ZXingScannerView() { } public ZXingScannerView(IntPtr handle) : base(handle) { } public ZXingScannerView (CGRect frame) : base(frame) { } AVCaptureSession session; AVCaptureVideoPreviewLayer previewLayer; AVCaptureVideoDataOutput output; OutputRecorder outputRecorder; DispatchQueue queue; Action<ZXing.Result> resultCallback; volatile bool stopped = true; //BarcodeReader barcodeReader; UIView layerView; UIView overlayView = null; public string CancelButtonText { get;set; } public string FlashButtonText { get;set; } MobileBarcodeScanningOptions options = new MobileBarcodeScanningOptions(); void Setup(CGRect frame) { var started = DateTime.UtcNow; if (overlayView != null) overlayView.RemoveFromSuperview (); if (UseCustomOverlayView && CustomOverlayView != null) overlayView = CustomOverlayView; else overlayView = new ZXingDefaultOverlayView (new CGRect(0, 0, this.Frame.Width, this.Frame.Height), TopText, BottomText, CancelButtonText, FlashButtonText, () => { StopScanning (); resultCallback (null); }, ToggleTorch); if (overlayView != null) { /*UITapGestureRecognizer tapGestureRecognizer = new UITapGestureRecognizer (); tapGestureRecognizer.AddTarget (() => { var pt = tapGestureRecognizer.LocationInView(overlayView); Focus(pt); Console.WriteLine("OVERLAY TOUCH: " + pt.X + ", " + pt.Y); }); tapGestureRecognizer.CancelsTouchesInView = false; tapGestureRecognizer.NumberOfTapsRequired = 1; tapGestureRecognizer.NumberOfTouchesRequired = 1; overlayView.AddGestureRecognizer (tapGestureRecognizer);*/ overlayView.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height); overlayView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight; } var total = DateTime.UtcNow - started; Console.WriteLine ("ZXingScannerView.Setup() took {0} ms.", total.TotalMilliseconds); } bool torch = false; bool analyzing = true; bool SetupCaptureSession () { var started = DateTime.UtcNow; var availableResolutions = new List<CameraResolution> (); var consideredResolutions = new Dictionary<NSString, CameraResolution> { { AVCaptureSession.Preset352x288, new CameraResolution { Width = 352, Height = 288 } }, { AVCaptureSession.PresetMedium, new CameraResolution { Width = 480, Height = 360 } }, //480x360 { AVCaptureSession.Preset640x480, new CameraResolution { Width = 640, Height = 480 } }, { AVCaptureSession.Preset1280x720, new CameraResolution { Width = 1280, Height = 720 } }, { AVCaptureSession.Preset1920x1080, new CameraResolution { Width = 1920, Height = 1080 } } }; // configure the capture session for low resolution, change this if your code // can cope with more data or volume session = new AVCaptureSession () { SessionPreset = AVCaptureSession.Preset640x480 }; // create a device input and attach it to the session // var captureDevice = AVCaptureDevice.DefaultDeviceWithMediaType (AVMediaType.Video); AVCaptureDevice captureDevice = null; var devices = AVCaptureDevice.DevicesWithMediaType(AVMediaType.Video); foreach (var device in devices) { captureDevice = device; if (options.UseFrontCameraIfAvailable.HasValue && options.UseFrontCameraIfAvailable.Value && device.Position == AVCaptureDevicePosition.Front) break; //Front camera successfully set else if (device.Position == AVCaptureDevicePosition.Back && (!options.UseFrontCameraIfAvailable.HasValue || !options.UseFrontCameraIfAvailable.Value)) break; //Back camera succesfully set } if (captureDevice == null){ Console.WriteLine ("No captureDevice - this won't work on the simulator, try a physical device"); if (overlayView != null) { this.AddSubview (overlayView); this.BringSubviewToFront (overlayView); } return false; } CameraResolution resolution = null; // Find resolution // Go through the resolutions we can even consider foreach (var cr in consideredResolutions) { // Now check to make sure our selected device supports the resolution // so we can add it to the list to pick from if (captureDevice.SupportsAVCaptureSessionPreset (cr.Key)) availableResolutions.Add (cr.Value); } resolution = options.GetResolution (availableResolutions); // See if the user selected a resolution if (resolution != null) { // Now get the preset string from the resolution chosen var preset = (from c in consideredResolutions where c.Value.Width == resolution.Width && c.Value.Height == resolution.Height select c.Key).FirstOrDefault (); // If we found a matching preset, let's set it on the session if (!string.IsNullOrEmpty(preset)) session.SessionPreset = preset; } var input = AVCaptureDeviceInput.FromDevice (captureDevice); if (input == null){ Console.WriteLine ("No input - this won't work on the simulator, try a physical device"); if (overlayView != null) { this.AddSubview (overlayView); this.BringSubviewToFront (overlayView); } return false; } else session.AddInput (input); var startedAVPreviewLayerAlloc = DateTime.UtcNow; previewLayer = new AVCaptureVideoPreviewLayer(session); var totalAVPreviewLayerAlloc = DateTime.UtcNow - startedAVPreviewLayerAlloc; Console.WriteLine ("PERF: Alloc AVCaptureVideoPreviewLayer took {0} ms.", totalAVPreviewLayerAlloc.TotalMilliseconds); //Framerate set here (15 fps) if (UIDevice.CurrentDevice.CheckSystemVersion (7, 0)) { var perf1 = PerformanceCounter.Start (); NSError lockForConfigErr = null; captureDevice.LockForConfiguration (out lockForConfigErr); if (lockForConfigErr == null) { captureDevice.ActiveVideoMinFrameDuration = new CMTime (1, 10); captureDevice.UnlockForConfiguration (); } PerformanceCounter.Stop (perf1, "PERF: ActiveVideoMinFrameDuration Took {0} ms"); } else previewLayer.Connection.VideoMinFrameDuration = new CMTime(1, 10); var perf2 = PerformanceCounter.Start (); #if __UNIFIED__ previewLayer.VideoGravity = AVLayerVideoGravity.ResizeAspectFill; #else previewLayer.LayerVideoGravity = AVLayerVideoGravity.ResizeAspectFill; #endif previewLayer.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height); previewLayer.Position = new CGPoint(this.Layer.Bounds.Width / 2, (this.Layer.Bounds.Height / 2)); layerView = new UIView(new CGRect(0, 0, this.Frame.Width, this.Frame.Height)); layerView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight; layerView.Layer.AddSublayer(previewLayer); this.AddSubview(layerView); ResizePreview(UIApplication.SharedApplication.StatusBarOrientation); if (overlayView != null) { this.AddSubview (overlayView); this.BringSubviewToFront (overlayView); //overlayView.LayoutSubviews (); } PerformanceCounter.Stop (perf2, "PERF: Setting up layers took {0} ms"); var perf3 = PerformanceCounter.Start (); session.StartRunning (); PerformanceCounter.Stop (perf3, "PERF: session.StartRunning() took {0} ms"); var perf4 = PerformanceCounter.Start (); var videoSettings = NSDictionary.FromObjectAndKey (new NSNumber ((int) CVPixelFormatType.CV32BGRA), CVPixelBuffer.PixelFormatTypeKey); // create a VideoDataOutput and add it to the sesion output = new AVCaptureVideoDataOutput { WeakVideoSettings = videoSettings }; // configure the output queue = new DispatchQueue("ZxingScannerView"); // (Guid.NewGuid().ToString()); var barcodeReader = new BarcodeReader(null, (img) => { var src = new RGBLuminanceSource(img); //, bmp.Width, bmp.Height); //Don't try and rotate properly if we're autorotating anyway if (ScanningOptions.AutoRotate.HasValue && ScanningOptions.AutoRotate.Value) return src; var tmpInterfaceOrientation = UIInterfaceOrientation.Portrait; InvokeOnMainThread(() => tmpInterfaceOrientation = UIApplication.SharedApplication.StatusBarOrientation); switch (tmpInterfaceOrientation) { case UIInterfaceOrientation.Portrait: return src.rotateCounterClockwise().rotateCounterClockwise().rotateCounterClockwise(); case UIInterfaceOrientation.PortraitUpsideDown: return src.rotateCounterClockwise().rotateCounterClockwise().rotateCounterClockwise(); case UIInterfaceOrientation.LandscapeLeft: return src; case UIInterfaceOrientation.LandscapeRight: return src; } return src; }, null, null); //(p, w, h, f) => new RGBLuminanceSource(p, w, h, RGBLuminanceSource.BitmapFormat.Unknown)); if (ScanningOptions.TryHarder.HasValue) { Console.WriteLine("TRY_HARDER: " + ScanningOptions.TryHarder.Value); barcodeReader.Options.TryHarder = ScanningOptions.TryHarder.Value; } if (ScanningOptions.PureBarcode.HasValue) barcodeReader.Options.PureBarcode = ScanningOptions.PureBarcode.Value; if (ScanningOptions.AutoRotate.HasValue) { Console.WriteLine("AUTO_ROTATE: " + ScanningOptions.AutoRotate.Value); barcodeReader.AutoRotate = ScanningOptions.AutoRotate.Value; } if (!string.IsNullOrEmpty (ScanningOptions.CharacterSet)) barcodeReader.Options.CharacterSet = ScanningOptions.CharacterSet; if (ScanningOptions.TryInverted.HasValue) barcodeReader.TryInverted = ScanningOptions.TryInverted.Value; if (ScanningOptions.PossibleFormats != null && ScanningOptions.PossibleFormats.Count > 0) { barcodeReader.Options.PossibleFormats = new List<BarcodeFormat>(); foreach (var pf in ScanningOptions.PossibleFormats) barcodeReader.Options.PossibleFormats.Add(pf); } outputRecorder = new OutputRecorder (ScanningOptions, img => { if (!IsAnalyzing) return; try { //var sw = new System.Diagnostics.Stopwatch(); //sw.Start(); var rs = barcodeReader.Decode(img); //sw.Stop(); //Console.WriteLine("Decode Time: {0} ms", sw.ElapsedMilliseconds); if (rs != null) resultCallback(rs); } catch (Exception ex) { Console.WriteLine("DECODE FAILED: " + ex); } }); output.AlwaysDiscardsLateVideoFrames = true; output.SetSampleBufferDelegate (outputRecorder, queue); PerformanceCounter.Stop(perf4, "PERF: SetupCamera Finished. Took {0} ms."); session.AddOutput (output); //session.StartRunning (); var perf5 = PerformanceCounter.Start (); NSError err = null; if (captureDevice.LockForConfiguration(out err)) { if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.ContinuousAutoFocus)) captureDevice.FocusMode = AVCaptureFocusMode.ContinuousAutoFocus; else if (captureDevice.IsFocusModeSupported(AVCaptureFocusMode.AutoFocus)) captureDevice.FocusMode = AVCaptureFocusMode.AutoFocus; if (captureDevice.IsExposureModeSupported (AVCaptureExposureMode.ContinuousAutoExposure)) captureDevice.ExposureMode = AVCaptureExposureMode.ContinuousAutoExposure; else if (captureDevice.IsExposureModeSupported(AVCaptureExposureMode.AutoExpose)) captureDevice.ExposureMode = AVCaptureExposureMode.AutoExpose; if (captureDevice.IsWhiteBalanceModeSupported (AVCaptureWhiteBalanceMode.ContinuousAutoWhiteBalance)) captureDevice.WhiteBalanceMode = AVCaptureWhiteBalanceMode.ContinuousAutoWhiteBalance; else if (captureDevice.IsWhiteBalanceModeSupported (AVCaptureWhiteBalanceMode.AutoWhiteBalance)) captureDevice.WhiteBalanceMode = AVCaptureWhiteBalanceMode.AutoWhiteBalance; if (UIDevice.CurrentDevice.CheckSystemVersion (7, 0) && captureDevice.AutoFocusRangeRestrictionSupported) captureDevice.AutoFocusRangeRestriction = AVCaptureAutoFocusRangeRestriction.Near; if (captureDevice.FocusPointOfInterestSupported) captureDevice.FocusPointOfInterest = new PointF(0.5f, 0.5f); if (captureDevice.ExposurePointOfInterestSupported) captureDevice.ExposurePointOfInterest = new PointF (0.5f, 0.5f); captureDevice.UnlockForConfiguration(); } else Console.WriteLine("Failed to Lock for Config: " + err.Description); PerformanceCounter.Stop (perf5, "PERF: Setup Focus in {0} ms."); return true; } public void DidRotate(UIInterfaceOrientation orientation) { ResizePreview (orientation); this.LayoutSubviews (); // if (overlayView != null) // overlayView.LayoutSubviews (); } public void ResizePreview (UIInterfaceOrientation orientation) { if (previewLayer == null) return; previewLayer.Frame = new CGRect (0, 0, this.Frame.Width, this.Frame.Height); if (previewLayer.RespondsToSelector (new Selector ("connection"))) { switch (orientation) { case UIInterfaceOrientation.LandscapeLeft: previewLayer.Connection.VideoOrientation = AVCaptureVideoOrientation.LandscapeLeft; break; case UIInterfaceOrientation.LandscapeRight: previewLayer.Connection.VideoOrientation = AVCaptureVideoOrientation.LandscapeRight; break; case UIInterfaceOrientation.Portrait: previewLayer.Connection.VideoOrientation = AVCaptureVideoOrientation.Portrait; break; case UIInterfaceOrientation.PortraitUpsideDown: previewLayer.Connection.VideoOrientation = AVCaptureVideoOrientation.PortraitUpsideDown; break; } } } public void Focus(PointF pointOfInterest) { //Get the device if (AVMediaType.Video == null) return; var device = AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Video); if (device == null) return; //See if it supports focusing on a point if (device.FocusPointOfInterestSupported && !device.AdjustingFocus) { NSError err = null; //Lock device to config if (device.LockForConfiguration(out err)) { Console.WriteLine("Focusing at point: " + pointOfInterest.X + ", " + pointOfInterest.Y); //Focus at the point touched device.FocusPointOfInterest = pointOfInterest; device.FocusMode = AVCaptureFocusMode.ContinuousAutoFocus; device.UnlockForConfiguration(); } } } public class OutputRecorder : AVCaptureVideoDataOutputSampleBufferDelegate { public OutputRecorder(MobileBarcodeScanningOptions options, Action<UIImage> handleImage) : base() { HandleImage = handleImage; this.options = options; } MobileBarcodeScanningOptions options; Action<UIImage> HandleImage; DateTime lastAnalysis = DateTime.MinValue; volatile bool working = false; [Export ("captureOutput:didDropSampleBuffer:fromConnection:")] public void DidDropSampleBuffer(AVCaptureOutput captureOutput, CMSampleBuffer sampleBuffer, AVCaptureConnection connection) { //Console.WriteLine("DROPPED"); } public CancellationTokenSource CancelTokenSource = new CancellationTokenSource(); public override void DidOutputSampleBuffer (AVCaptureOutput captureOutput, CMSampleBuffer sampleBuffer, AVCaptureConnection connection) { if ((DateTime.UtcNow - lastAnalysis).TotalMilliseconds < options.DelayBetweenAnalyzingFrames || working || CancelTokenSource.IsCancellationRequested) { if (sampleBuffer != null) { sampleBuffer.Dispose (); sampleBuffer = null; } return; } working = true; //Console.WriteLine("SAMPLE"); lastAnalysis = DateTime.UtcNow; try { using (var image = ImageFromSampleBuffer (sampleBuffer)) HandleImage(image); // // Although this looks innocent "Oh, he is just optimizing this case away" // this is incredibly important to call on this callback, because the AVFoundation // has a fixed number of buffers and if it runs out of free buffers, it will stop // delivering frames. // sampleBuffer.Dispose (); sampleBuffer = null; } catch (Exception e){ Console.WriteLine (e); } working = false; } UIImage ImageFromSampleBuffer (CMSampleBuffer sampleBuffer) { UIImage img = null; // Get the CoreVideo image using (var pixelBuffer = sampleBuffer.GetImageBuffer () as CVPixelBuffer) { // Lock the base address pixelBuffer.Lock (0); // Get the number of bytes per row for the pixel buffer var baseAddress = pixelBuffer.BaseAddress; var bytesPerRow = pixelBuffer.BytesPerRow; var width = pixelBuffer.Width; var height = pixelBuffer.Height; var flags = CGBitmapFlags.PremultipliedFirst | CGBitmapFlags.ByteOrder32Little; // Create a CGImage on the RGB colorspace from the configured parameter above using (var cs = CGColorSpace.CreateDeviceRGB ()) using (var context = new CGBitmapContext (baseAddress, (int)width, (int)height, 8, (int)bytesPerRow, cs, (CGImageAlphaInfo) flags)) using (var cgImage = context.ToImage ()) { pixelBuffer.Unlock (0); img = new UIImage(cgImage); } } return img; } } #region IZXingScanner implementation public void StartScanning (MobileBarcodeScanningOptions options, Action<Result> callback) { if (!stopped) return; stopped = false; var perf = PerformanceCounter.Start (); Setup (this.Frame); this.options = options; this.resultCallback = callback; Console.WriteLine("StartScanning"); this.InvokeOnMainThread(() => { if (!SetupCaptureSession()) { //Setup 'simulated' view: Console.WriteLine("Capture Session FAILED"); } if (Runtime.Arch == Arch.SIMULATOR) { var simView = new UIView(new CGRect(0, 0, this.Frame.Width, this.Frame.Height)); simView.BackgroundColor = UIColor.LightGray; simView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight; this.InsertSubview(simView, 0); } }); if (!analyzing) analyzing = true; PerformanceCounter.Stop(perf, "PERF: StartScanning() Took {0} ms."); var evt = this.OnScannerSetupComplete; if (evt != null) evt (); } public void StartScanning (Action<Result> callback) { StartScanning (new MobileBarcodeScanningOptions (), callback); } public void StopScanning() { if (overlayView != null) { if (overlayView is ZXingDefaultOverlayView) (overlayView as ZXingDefaultOverlayView).Destroy (); overlayView = null; } if (stopped) return; Console.WriteLine("Stopping..."); if (outputRecorder != null) outputRecorder.CancelTokenSource.Cancel(); //Try removing all existing outputs prior to closing the session try { while (session.Outputs.Length > 0) session.RemoveOutput (session.Outputs [0]); } catch { } //Try to remove all existing inputs prior to closing the session try { while (session.Inputs.Length > 0) session.RemoveInput (session.Inputs [0]); } catch { } if (session.Running) session.StopRunning(); stopped = true; } public void PauseAnalysis () { analyzing = false; } public void ResumeAnalysis () { analyzing = true; } public void SetTorch (bool on) { try { NSError err; var device = AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Video); device.LockForConfiguration(out err); if (on) { device.TorchMode = AVCaptureTorchMode.On; device.FlashMode = AVCaptureFlashMode.On; } else { device.TorchMode = AVCaptureTorchMode.Off; device.FlashMode = AVCaptureFlashMode.Off; } device.UnlockForConfiguration(); device = null; torch = on; } catch { } } public void ToggleTorch() { SetTorch(!IsTorchOn); } public void AutoFocus () { //Doesn't do much on iOS :( } public string TopText { get;set; } public string BottomText { get;set; } public UIView CustomOverlayView { get; set; } public bool UseCustomOverlayView { get; set; } public MobileBarcodeScanningOptions ScanningOptions { get { return options; } } public bool IsAnalyzing { get { return analyzing; } } public bool IsTorchOn { get { return torch; } } #endregion } }
//----------------------------------------------------------------------- // <copyright file="FixedBufferSpec.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using Akka.Streams.Implementation; using Akka.Streams.TestKit.Tests; using FluentAssertions; using Xunit; using Buffer = Akka.Streams.Implementation.Buffer; namespace Akka.Streams.Tests.Implementation { public class FixedBufferSpec : AkkaSpec { [Theory] [MemberData("Sizes")] public void FixedSizeBuffer_must_start_as_empty(int size) { var buf = FixedSizeBuffer.Create<NotUsed>(size); buf.IsEmpty.Should().BeTrue(); buf.IsFull.Should().BeFalse(); } [Theory] [MemberData("Sizes")] public void FixedSizeBuffer_must_become_nonempty_after_enqueueing(int size) { var buf = FixedSizeBuffer.Create<string>(size); buf.Enqueue("test"); buf.IsEmpty.Should().BeFalse(); buf.IsFull.Should().Be(size == 1); } [Theory] [MemberData("Sizes")] public void FixedSizeBuffer_must_become_full_after_size_elements_are_enqueued(int size) { var buf = FixedSizeBuffer.Create<string>(size); for (var i = 0; i < size; i++) buf.Enqueue("test"); buf.IsEmpty.Should().BeFalse(); buf.IsFull.Should().BeTrue(); } [Theory] [MemberData("Sizes")] public void FixedSizeBuffer_must_become_empty_after_enqueueing_and_tail_drop(int size) { var buf = FixedSizeBuffer.Create<string>(size); buf.Enqueue("test"); buf.DropTail(); buf.IsEmpty.Should().BeTrue(); buf.IsFull.Should().BeFalse(); } [Theory] [MemberData("Sizes")] public void FixedSizeBuffer_must_become_empty_after_enqueueing_and_head_drop(int size) { var buf = FixedSizeBuffer.Create<string>(size); buf.Enqueue("test"); buf.DropHead(); buf.IsEmpty.Should().BeTrue(); buf.IsFull.Should().BeFalse(); } [Theory] [MemberData("Sizes")] public void FixedSizeBuffer_must_drop_head_properly(int size) { var buf = FixedSizeBuffer.Create<int>(size); for (var elem = 1; elem <= size; elem++) buf.Enqueue(elem); buf.DropHead(); for (var elem = 2; elem <= size; elem++) buf.Dequeue().Should().Be(elem); } [Theory] [MemberData("Sizes")] public void FixedSizeBuffer_must_drop_tail_properly(int size) { var buf = FixedSizeBuffer.Create<int>(size); for (var elem = 1; elem <= size; elem++) buf.Enqueue(elem); buf.DropTail(); for (var elem = 1; elem <= size - 1; elem++) buf.Dequeue().Should().Be(elem); } [Theory] [MemberData("Sizes")] public void FixedSizeBuffer_must_become_non_full_after_tail_dropped_from_full_buffer(int size) { var buf = FixedSizeBuffer.Create<string>(size); for (var elem = 1; elem <= size; elem++) buf.Enqueue("test"); buf.DropTail(); buf.IsEmpty.Should().Be(size == 1); buf.IsFull.Should().BeFalse(); } [Theory] [MemberData("Sizes")] public void FixedSizeBuffer_must_become_non_full_after_head_dropped_from_full_buffer(int size) { var buf = FixedSizeBuffer.Create<string>(size); for (var elem = 1; elem <= size; elem++) buf.Enqueue("test"); buf.DropHead(); buf.IsEmpty.Should().Be(size == 1); buf.IsFull.Should().BeFalse(); } [Theory] [MemberData("Sizes")] public void FixedSizeBuffer_must_work_properly_with_full_range_filling_draining_cycles(int size) { var buf = FixedSizeBuffer.Create<int>(size); for (var i = 0; i < 10; i++) { buf.IsEmpty.Should().BeTrue(); buf.IsFull.Should().BeFalse(); for (var elem = 1; elem <= size; elem++) buf.Enqueue(elem); buf.IsEmpty.Should().BeFalse(); buf.IsFull.Should().BeTrue(); for (var elem = 1; elem <= size; elem++) buf.Dequeue().Should().Be(elem); } } [Theory] [MemberData("Sizes")] public void FixedSizeBuffer_must_work_when_indexes_wrap_around_at_Int_MaxValue(int size) { IBuffer<int> buf; if (((size - 1) & size) == 0) buf= new CheatPowerOfTwoFixedSizeBuffer(size); else buf = new CheatModuloFixedSizeBuffer(size); for (var i = 0; i < 10; i++) { buf.IsEmpty.Should().BeTrue(); buf.IsFull.Should().BeFalse(); for (var elem = 1; elem <= size; elem++) buf.Enqueue(elem); buf.IsEmpty.Should().BeFalse(); buf.IsFull.Should().BeTrue(); for (var elem = 1; elem <= size; elem++) buf.Dequeue().Should().Be(elem); } } private class CheatPowerOfTwoFixedSizeBuffer : PowerOfTwoFixedSizeBuffer<int> { public CheatPowerOfTwoFixedSizeBuffer(int size) : base(size) { ReadIndex = Int32.MaxValue; WriteIndex = Int32.MaxValue; } } private class CheatModuloFixedSizeBuffer : ModuloFixedSizeBuffer<int> { public CheatModuloFixedSizeBuffer(int size) : base(size) { ReadIndex = Int32.MaxValue; WriteIndex = Int32.MaxValue; } } public static IEnumerable<object[]> Sizes { get { yield return new object[] { 1 }; yield return new object[] { 3 }; yield return new object[] { 4 }; } } private ActorMaterializerSettings Default => ActorMaterializerSettings.Create(Sys); [Fact] public void Buffer_factory_must_set_default_to_one_billion_for_MaxFixedBufferSize() { Default.MaxFixedBufferSize.Should().Be(1000000000); } [Fact] public void Buffer_factory_must_produce_BoundedBuffers_when_capacity_greather_than_MaxFixedBufferSize() { Buffer.Create<int>(Int32.MaxValue, Default).Should().BeOfType<BoundedBuffer<int>>(); } [Fact] public void Buffer_factory_must_produce_FixedSizeBuffers_when_capacity_lower_than_MaxFixedBufferSize() { Buffer.Create<int>(1000, Default).Should().BeOfType<ModuloFixedSizeBuffer<int>>(); Buffer.Create<int>(1024, Default).Should().BeOfType<PowerOfTwoFixedSizeBuffer<int>>(); } [Fact] public void Buffer_factory_must_produce_FixedSizeBuffers_when_MaxFixedBufferSize_lower_than_BoundedBufferSize() { var settings = Default.WithMaxFixedBufferSize(9); Buffer.Create<int>(5, settings).Should().BeOfType<ModuloFixedSizeBuffer<int>>(); Buffer.Create<int>(10, settings).Should().BeOfType<ModuloFixedSizeBuffer<int>>(); Buffer.Create<int>(16, settings).Should().BeOfType<PowerOfTwoFixedSizeBuffer<int>>(); } } }
namespace com.qetrix.apps.quly { using System; using System.Collections.Generic; using System.Reflection; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; using UnityStandardAssets.CrossPlatformInput; using libs; public class GameManager : MonoBehaviour { public static GameManager instance; public GameObject busyIndicator; Text clock; Sun daytime; public static Scene scene; public string sceneName; bool isSaved = false; bool _joystick = false; GameObject quleUI; public static bool gameControls = true; /// Game controls are active (false = menu, modal dialog or anything but the game itself) public static bool worldClock = true; /// Showing world clock (false = race time, quest timer or anything but the world time itself) public List<Player> players = new List<Player>(); Dictionary<string, libs.Material> _materials = new Dictionary<string, libs.Material>(); Dictionary<string, Item> _items = new Dictionary<string, Item>(); Dictionary<string, Recipe> _recipes = new Dictionary<string, Recipe>(); void Awake() { instance = this; Application.targetFrameRate = 30; sceneName = "Scene001"; string[] sfx = { "bounce", "crash", "pickup", "noenergy", "jump", "laser", "teleport", "boom", "modwinopen", "modwinclose" }; Util.initSfx(sfx); } void Start() { /// UI setup busyIndicator = GameObject.Find("BusyIndicator"); showLoading(); /// Data setup loadMaterials(); loadItems(); loadRecipes(); /// Environment setup clock = GameObject.Find("Clock").GetComponent<Text>(); daytime = GameObject.Find("Sun").GetComponent<Sun>(); /// Scene setup Type t = Type.GetType("com.qetrix.apps.quly." + sceneName); scene = (Scene) Activator.CreateInstance(t); MethodInfo method = t.GetMethod("init", BindingFlags.Instance | BindingFlags.Public); if (method != null) method.Invoke(scene, null); /// Player setup var cam = GameObject.Find(players[0].name() + "/QulyCam").GetComponent<QulyCam>(); cam.player(players[1]); /// Qules setup foreach (Qule q in scene.qules) { Vector3 pos = q.transform().position(); if (pos.y == -1) { pos = new Vector3(pos.x, Terrain.activeTerrain.SampleHeight(pos) + 2, pos.z); Debug.Log("New pos:" + pos + " for " + q.name()); } QuleMB qq = (Instantiate(Resources.Load("Prefabs/Qule"), pos, q.transform().rotation()) as GameObject).GetComponent<QuleMB>(); qq.q(q); qq.tag = (cam.playerFamily() == q.family() ? "Family" : "Neutral"); // TODO!!!! if (q.npc() != null) { qq.gameObject.AddComponent(Type.GetType("com.qetrix.apps.quly." + q.npc(), true, true)); qq.gameObject.AddComponent<EnergyManager>().scriptCalled = q.npc(); qq.tag = "Neutral"; qq.GetComponent<Rigidbody>().sleepThreshold = 1f; } qq = null; } hideLoading(); } public void setClock(string time) { clock.text = time; } void loadMaterials() { TextAsset txt = (TextAsset)Resources.Load("Data/materials", typeof(TextAsset)); Util.parseData(txt.text, material); Debug.Log("Loaded " + _materials.Count + " materials"); } bool material(Dictionary<string, string> data) { var mat = new libs.Material(data); _materials.Add(mat.name().Trim().ToLower(), mat); return true; } public libs.Material material(string name) { name = name.Trim().ToLower(); if (!_materials.ContainsKey(name)) { Debug.Log("Material " + name + " not loaded (" + _materials.Count + " materials loaded)"); return null; } return _materials[name]; } void loadItems() { TextAsset txt = (TextAsset)Resources.Load("Data/items", typeof(TextAsset)); Util.parseData(txt.text, item); Debug.Log("Loaded " + _items.Count + " items"); } bool item(Dictionary<string, string> data) { var itm = new Item(data); _items.Add(itm.name().Trim().ToLower(), itm); return true; } public Item item(string name) { name = name.Trim().ToLower(); if (!_items.ContainsKey(name)) { Debug.Log("Item " + name + " not loaded (" + _items.Count + " items loaded)"); return null; } return _items[name]; } void loadRecipes() { TextAsset txt = (TextAsset)Resources.Load("Data/recipes", typeof(TextAsset)); string[] content = txt.text.Replace("\r", "").Split('\n'); Debug.Log("Loaded " + content.Length + " recipes"); } bool recipe(Dictionary<string, string> data) { var rcp = new Recipe(data); _recipes.Add(rcp.name().Trim().ToLower(), rcp); return true; } public Recipe recipe(string name) { name = name.Trim().ToLower(); if (!_recipes.ContainsKey(name)) { Debug.Log("Recipe " + name + " not loaded (" + _recipes.Count + " recipes loaded)"); return null; } return _recipes[name]; } void Update() { if (worldClock) { float minutes = daytime.currentTimeOfDay * 1440; setClock(Mathf.Floor(minutes / 60f).ToString("00") + ":" + Mathf.Floor(minutes % 60f).ToString("00")); if (minutes % 60f < 0.5f) { if (!isSaved) { scene.save(); isSaved = true; } } else isSaved = false; } if (gameControls && CrossPlatformInputManager.GetButtonDown("GameMenu")) { transform.FindChild("GameMenu").gameObject.SetActive(true); EventSystem.current.SetSelectedGameObject(GameObject.Find("ContinueButton")); } if (Input.GetKey (KeyCode.JoystickButton0)) _joystick = true; } /*public static AudioSource playClipAtPoint(AudioClip clip, Vector3 pos) { return playClipAtPoint(clip, pos, true); } public static AudioSource playClipAtPoint(AudioClip clip, Vector3 pos, bool mySound) { GameObject tempGO = new GameObject("TempAudio_" + clip.name); tempGO.transform.position = pos; AudioSource aSource = tempGO.AddComponent<AudioSource>(); if (!mySound) aSource.spatialBlend = 1; aSource.clip = clip; aSource.Play(); Destroy(tempGO, clip.length); return aSource; }*/ public enum materialCategory { gas, liquid, loose, solid, bulk } public enum itemCategory { item, herb, rock, meal, potion, weapon, container } public enum recipeCategory { crafting, herbalism, blacksmithing, alchemy } public bool joystick() { return _joystick; } public void showLoading() { busyIndicator.SetActive(true); } public void hideLoading() { busyIndicator.SetActive(false); } public void deadQule(Qule q) { var p = players[q.family()]; scene.qules.Remove(q); } } }
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !SILVERLIGHT #define DEBUG namespace NLog.UnitTests { using System; using System.Globalization; using System.Threading; using System.Diagnostics; using Xunit; public class NLogTraceListenerTests : NLogTestBase, IDisposable { private readonly CultureInfo previousCultureInfo; public NLogTraceListenerTests() { this.previousCultureInfo = Thread.CurrentThread.CurrentCulture; // set the culture info with the decimal separator (comma) different from InvariantCulture separator (point) Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR"); } public void Dispose() { // restore previous culture info Thread.CurrentThread.CurrentCulture = this.previousCultureInfo; } [Fact] public void TraceWriteTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Debug.Listeners.Clear(); Debug.Listeners.Add(new NLogTraceListener { Name = "Logger1" }); Debug.Write("Hello"); AssertDebugLastMessage("debug", "Logger1 Debug Hello"); Debug.Write("Hello", "Cat1"); AssertDebugLastMessage("debug", "Logger1 Debug Cat1: Hello"); Debug.Write(3.1415); AssertDebugLastMessage("debug", string.Format("Logger1 Debug {0}", 3.1415)); Debug.Write(3.1415, "Cat2"); AssertDebugLastMessage("debug", string.Format("Logger1 Debug Cat2: {0}", 3.1415)); } [Fact] public void TraceWriteLineTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Debug.Listeners.Clear(); Debug.Listeners.Add(new NLogTraceListener { Name = "Logger1" }); Debug.WriteLine("Hello"); AssertDebugLastMessage("debug", "Logger1 Debug Hello"); Debug.WriteLine("Hello", "Cat1"); AssertDebugLastMessage("debug", "Logger1 Debug Cat1: Hello"); Debug.WriteLine(3.1415); AssertDebugLastMessage("debug", string.Format("Logger1 Debug {0}", 3.1415)); Debug.WriteLine(3.1415, "Cat2"); AssertDebugLastMessage("debug", string.Format("Logger1 Debug Cat2: {0}", 3.1415)); } [Fact] public void TraceWriteNonDefaultLevelTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets> <rules> <logger name='*' minlevel='Trace' writeTo='debug' /> </rules> </nlog>"); Debug.Listeners.Clear(); Debug.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace }); Debug.Write("Hello"); AssertDebugLastMessage("debug", "Logger1 Trace Hello"); } [Fact] public void TraceConfiguration() { var listener = new NLogTraceListener(); listener.Attributes.Add("defaultLogLevel", "Warn"); listener.Attributes.Add("forceLogLevel", "Error"); listener.Attributes.Add("autoLoggerName", "1"); Assert.Equal(LogLevel.Warn, listener.DefaultLogLevel); Assert.Equal(LogLevel.Error, listener.ForceLogLevel); Assert.True(listener.AutoLoggerName); } [Fact] public void TraceFailTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Debug.Listeners.Clear(); Debug.Listeners.Add(new NLogTraceListener { Name = "Logger1" }); Debug.Fail("Message"); AssertDebugLastMessage("debug", "Logger1 Error Message"); Debug.Fail("Message", "Detailed Message"); AssertDebugLastMessage("debug", "Logger1 Error Message Detailed Message"); } [Fact] public void AutoLoggerNameTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Debug.Listeners.Clear(); Debug.Listeners.Add(new NLogTraceListener { Name = "Logger1", AutoLoggerName = true }); Debug.Write("Hello"); AssertDebugLastMessage("debug", this.GetType().FullName + " Debug Hello"); } [Fact] public void TraceDataTests() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets> <rules> <logger name='*' minlevel='Trace' writeTo='debug' /> </rules> </nlog>"); TraceSource ts = CreateTraceSource(); ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace }); ts.TraceData(TraceEventType.Critical, 123, 42); AssertDebugLastMessage("debug", "MySource1 Fatal 42 123"); ts.TraceData(TraceEventType.Critical, 145, 42, 3.14, "foo"); AssertDebugLastMessage("debug", string.Format("MySource1 Fatal 42, {0}, foo 145", 3.14.ToString(System.Globalization.CultureInfo.CurrentCulture))); } #if MONO [Fact(Skip="Not working under MONO - not sure if unit test is wrong, or the code")] #else [Fact] #endif public void LogInformationTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets> <rules> <logger name='*' minlevel='Trace' writeTo='debug' /> </rules> </nlog>"); TraceSource ts = CreateTraceSource(); ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace }); ts.TraceInformation("Quick brown fox"); AssertDebugLastMessage("debug", "MySource1 Info Quick brown fox 0"); ts.TraceInformation("Mary had {0} lamb", "a little"); AssertDebugLastMessage("debug", "MySource1 Info Mary had a little lamb 0"); } [Fact] public void TraceEventTests() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets> <rules> <logger name='*' minlevel='Trace' writeTo='debug' /> </rules> </nlog>"); TraceSource ts = CreateTraceSource(); ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace }); ts.TraceEvent(TraceEventType.Information, 123, "Quick brown {0} jumps over the lazy {1}.", "fox", "dog"); AssertDebugLastMessage("debug", "MySource1 Info Quick brown fox jumps over the lazy dog. 123"); ts.TraceEvent(TraceEventType.Information, 123); AssertDebugLastMessage("debug", "MySource1 Info 123"); ts.TraceEvent(TraceEventType.Verbose, 145, "Bar"); AssertDebugLastMessage("debug", "MySource1 Trace Bar 145"); ts.TraceEvent(TraceEventType.Error, 145, "Foo"); AssertDebugLastMessage("debug", "MySource1 Error Foo 145"); ts.TraceEvent(TraceEventType.Suspend, 145, "Bar"); AssertDebugLastMessage("debug", "MySource1 Debug Bar 145"); ts.TraceEvent(TraceEventType.Resume, 145, "Foo"); AssertDebugLastMessage("debug", "MySource1 Debug Foo 145"); ts.TraceEvent(TraceEventType.Warning, 145, "Bar"); AssertDebugLastMessage("debug", "MySource1 Warn Bar 145"); ts.TraceEvent(TraceEventType.Critical, 145, "Foo"); AssertDebugLastMessage("debug", "MySource1 Fatal Foo 145"); } #if MONO [Fact(Skip="Not working under MONO - not sure if unit test is wrong, or the code")] #else [Fact] #endif public void ForceLogLevelTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets> <rules> <logger name='*' minlevel='Trace' writeTo='debug' /> </rules> </nlog>"); TraceSource ts = CreateTraceSource(); ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace, ForceLogLevel = LogLevel.Warn }); // force all logs to be Warn, DefaultLogLevel has no effect on TraceSource ts.TraceInformation("Quick brown fox"); AssertDebugLastMessage("debug", "MySource1 Warn Quick brown fox 0"); ts.TraceInformation("Mary had {0} lamb", "a little"); AssertDebugLastMessage("debug", "MySource1 Warn Mary had a little lamb 0"); } private static TraceSource CreateTraceSource() { var ts = new TraceSource("MySource1", SourceLevels.All); #if MONO // for some reason needed on Mono ts.Switch = new SourceSwitch("MySource1", "Verbose"); ts.Switch.Level = SourceLevels.All; #endif return ts; } } } #endif
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; using System.Configuration; using System.IO; using System.ComponentModel; using System.Collections.Generic; using Csla.Validation; namespace Northwind.CSLA.Library { /// <summary> /// Product Generated by MyGeneration using the CSLA Object Mapping template /// </summary> [Serializable()] [TypeConverter(typeof(ProductConverter))] public partial class Product : BusinessBase<Product>, IDisposable, IVEHasBrokenRules { #region Refresh private List<Product> _RefreshProducts = new List<Product>(); private List<ProductOrderDetail> _RefreshProductOrderDetails = new List<ProductOrderDetail>(); private void AddToRefreshList(List<Product> refreshProducts, List<ProductOrderDetail> refreshProductOrderDetails) { if (IsDirty) refreshProducts.Add(this); if (_ProductOrderDetails != null && _ProductOrderDetails.IsDirty) { foreach (ProductOrderDetail tmp in _ProductOrderDetails) { if(tmp.IsDirty)refreshProductOrderDetails.Add(tmp); } } } private void BuildRefreshList() { _RefreshProducts = new List<Product>(); _RefreshProductOrderDetails = new List<ProductOrderDetail>(); AddToRefreshList(_RefreshProducts, _RefreshProductOrderDetails); } private void ProcessRefreshList() { foreach (Product tmp in _RefreshProducts) { ProductInfo.Refresh(tmp); if(tmp._MyCategory != null) CategoryInfo.Refresh(tmp._MyCategory); if(tmp._MySupplier != null) SupplierInfo.Refresh(tmp._MySupplier); } foreach (ProductOrderDetail tmp in _RefreshProductOrderDetails) { OrderDetailInfo.Refresh(this, tmp); } } #endregion #region Collection protected static List<Product> _AllList = new List<Product>(); private static Dictionary<string, Product> _AllByPrimaryKey = new Dictionary<string, Product>(); private static void ConvertListToDictionary() { List<Product> remove = new List<Product>(); foreach (Product tmp in _AllList) { _AllByPrimaryKey[tmp.ProductID.ToString()]=tmp; // Primary Key remove.Add(tmp); } foreach (Product tmp in remove) _AllList.Remove(tmp); } public static Product GetExistingByPrimaryKey(int productID) { ConvertListToDictionary(); string key = productID.ToString(); if (_AllByPrimaryKey.ContainsKey(key)) return _AllByPrimaryKey[key]; return null; } #endregion #region Business Methods private string _ErrorMessage = string.Empty; public string ErrorMessage { get { return _ErrorMessage; } } private static int _nextProductID = -1; public static int NextProductID { get { return _nextProductID--; } } private int _ProductID; [System.ComponentModel.DataObjectField(true, true)] public int ProductID { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _ProductID; } } private string _ProductName = string.Empty; public string ProductName { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _ProductName; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { CanWriteProperty(true); if (value == null) value = string.Empty; if (_ProductName != value) { _ProductName = value; PropertyHasChanged(); } } } private int? _SupplierID; public int? SupplierID { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); if (_MySupplier != null) _SupplierID = _MySupplier.SupplierID; return _SupplierID; } } private Supplier _MySupplier; public Supplier MySupplier { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); if (_MySupplier == null && _SupplierID != null) _MySupplier = Supplier.Get((int)_SupplierID); return _MySupplier; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { CanWriteProperty(true); if (_MySupplier != value) { _MySupplier = value; _SupplierID = (value == null ? null : (int?) value.SupplierID); PropertyHasChanged(); } } } private int? _CategoryID; public int? CategoryID { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); if (_MyCategory != null) _CategoryID = _MyCategory.CategoryID; return _CategoryID; } } private Category _MyCategory; public Category MyCategory { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); if (_MyCategory == null && _CategoryID != null) _MyCategory = Category.Get((int)_CategoryID); return _MyCategory; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { CanWriteProperty(true); if (_MyCategory != value) { _MyCategory = value; _CategoryID = (value == null ? null : (int?) value.CategoryID); PropertyHasChanged(); } } } private string _QuantityPerUnit = string.Empty; public string QuantityPerUnit { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _QuantityPerUnit; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { CanWriteProperty(true); if (value == null) value = string.Empty; if (_QuantityPerUnit != value) { _QuantityPerUnit = value; PropertyHasChanged(); } } } private decimal? _UnitPrice; public decimal? UnitPrice { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _UnitPrice; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { CanWriteProperty(true); if (_UnitPrice != value) { _UnitPrice = value; PropertyHasChanged(); } } } private Int16? _UnitsInStock; public Int16? UnitsInStock { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _UnitsInStock; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { CanWriteProperty(true); if (_UnitsInStock != value) { _UnitsInStock = value; PropertyHasChanged(); } } } private Int16? _UnitsOnOrder; public Int16? UnitsOnOrder { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _UnitsOnOrder; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { CanWriteProperty(true); if (_UnitsOnOrder != value) { _UnitsOnOrder = value; PropertyHasChanged(); } } } private Int16? _ReorderLevel; public Int16? ReorderLevel { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _ReorderLevel; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { CanWriteProperty(true); if (_ReorderLevel != value) { _ReorderLevel = value; PropertyHasChanged(); } } } private bool _Discontinued; public bool Discontinued { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _Discontinued; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { CanWriteProperty(true); if (_Discontinued != value) { _Discontinued = value; PropertyHasChanged(); } } } private int _ProductOrderDetailCount = 0; /// <summary> /// Count of ProductOrderDetails for this Product /// </summary> public int ProductOrderDetailCount { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _ProductOrderDetailCount; } } private ProductOrderDetails _ProductOrderDetails = null; /// <summary> /// Related Field /// </summary> [TypeConverter(typeof(ProductOrderDetailsConverter))] public ProductOrderDetails ProductOrderDetails { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); if(_ProductOrderDetailCount > 0 && _ProductOrderDetails == null) _ProductOrderDetails = ProductOrderDetails.GetByProductID(ProductID); else if(_ProductOrderDetails == null) _ProductOrderDetails = ProductOrderDetails.New(); return _ProductOrderDetails; } } public override bool IsDirty { get { return base.IsDirty || (_ProductOrderDetails == null? false : _ProductOrderDetails.IsDirty) || (_MyCategory == null? false : _MyCategory.IsDirty) || (_MySupplier == null? false : _MySupplier.IsDirty); } } public override bool IsValid { get { return (IsNew && !IsDirty ? true : base.IsValid) && (_ProductOrderDetails == null? true : _ProductOrderDetails.IsValid) && (_MyCategory == null? true : _MyCategory.IsValid) && (_MySupplier == null? true : _MySupplier.IsValid); } } // TODO: Replace base Product.ToString function as necessary /// <summary> /// Overrides Base ToString /// </summary> /// <returns>A string representation of current Product</returns> //public override string ToString() //{ // return base.ToString(); //} // TODO: Check Product.GetIdValue to assure that the ID returned is unique /// <summary> /// Overrides Base GetIdValue - Used internally by CSLA to determine equality /// </summary> /// <returns>A Unique ID for the current Product</returns> protected override object GetIdValue() { return _ProductID; } #endregion #region ValidationRules [NonSerialized] private bool _CheckingBrokenRules=false; public IVEHasBrokenRules HasBrokenRules { get { if(_CheckingBrokenRules)return null; if ((IsDirty || !IsNew) && BrokenRulesCollection.Count > 0) return this; try { _CheckingBrokenRules=true; IVEHasBrokenRules hasBrokenRules = null; if (_ProductOrderDetails != null && (hasBrokenRules = _ProductOrderDetails.HasBrokenRules) != null) return hasBrokenRules; if (_MySupplier != null && (hasBrokenRules = _MySupplier.HasBrokenRules) != null) return hasBrokenRules; if (_MyCategory != null && (hasBrokenRules = _MyCategory.HasBrokenRules) != null) return hasBrokenRules; return hasBrokenRules; } finally { _CheckingBrokenRules=false; } } } public BrokenRulesCollection BrokenRules { get { IVEHasBrokenRules hasBrokenRules = HasBrokenRules; if (this.Equals(hasBrokenRules)) return BrokenRulesCollection; return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null); } } protected override void AddBusinessRules() { ValidationRules.AddRule( Csla.Validation.CommonRules.StringRequired, "ProductName"); ValidationRules.AddRule( Csla.Validation.CommonRules.StringMaxLength, new Csla.Validation.CommonRules.MaxLengthRuleArgs("ProductName", 40)); ValidationRules.AddRule( Csla.Validation.CommonRules.StringMaxLength, new Csla.Validation.CommonRules.MaxLengthRuleArgs("QuantityPerUnit", 20)); //ValidationRules.AddDependantProperty("x", "y"); _ProductExtension.AddValidationRules(ValidationRules); // TODO: Add other validation rules } protected override void AddInstanceBusinessRules() { _ProductExtension.AddInstanceValidationRules(ValidationRules); // TODO: Add other validation rules } // Sample data comparison validation rule //private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e) //{ // if (_started > _ended) // { // e.Description = "Start date can't be after end date"; // return false; // } // else // return true; //} #endregion #region Authorization Rules protected override void AddAuthorizationRules() { //TODO: Who can read/write which fields //AuthorizationRules.AllowRead(ProductID, "<Role(s)>"); //AuthorizationRules.AllowRead(ProductName, "<Role(s)>"); //AuthorizationRules.AllowRead(SupplierID, "<Role(s)>"); //AuthorizationRules.AllowRead(CategoryID, "<Role(s)>"); //AuthorizationRules.AllowRead(QuantityPerUnit, "<Role(s)>"); //AuthorizationRules.AllowRead(UnitPrice, "<Role(s)>"); //AuthorizationRules.AllowRead(UnitsInStock, "<Role(s)>"); //AuthorizationRules.AllowRead(UnitsOnOrder, "<Role(s)>"); //AuthorizationRules.AllowRead(ReorderLevel, "<Role(s)>"); //AuthorizationRules.AllowRead(Discontinued, "<Role(s)>"); //AuthorizationRules.AllowWrite(ProductName, "<Role(s)>"); //AuthorizationRules.AllowWrite(SupplierID, "<Role(s)>"); //AuthorizationRules.AllowWrite(CategoryID, "<Role(s)>"); //AuthorizationRules.AllowWrite(QuantityPerUnit, "<Role(s)>"); //AuthorizationRules.AllowWrite(UnitPrice, "<Role(s)>"); //AuthorizationRules.AllowWrite(UnitsInStock, "<Role(s)>"); //AuthorizationRules.AllowWrite(UnitsOnOrder, "<Role(s)>"); //AuthorizationRules.AllowWrite(ReorderLevel, "<Role(s)>"); //AuthorizationRules.AllowWrite(Discontinued, "<Role(s)>"); _ProductExtension.AddAuthorizationRules(AuthorizationRules); } protected override void AddInstanceAuthorizationRules() { //TODO: Who can read/write which fields _ProductExtension.AddInstanceAuthorizationRules(AuthorizationRules); } public static bool CanAddObject() { // TODO: Can Add Authorization //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); return true; } public static bool CanGetObject() { // TODO: CanGet Authorization return true; } public static bool CanDeleteObject() { // TODO: CanDelete Authorization //bool result = false; //if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true; //if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true; //return result; return true; } public static bool CanEditObject() { // TODO: CanEdit Authorization //return Csla.ApplicationContext.User.IsInRole("ProjectManager"); return true; } #endregion #region Factory Methods public int CurrentEditLevel { get { return EditLevel; } } protected Product() {/* require use of factory methods */ _AllList.Add(this); } public void Dispose() { _AllList.Remove(this); _AllByPrimaryKey.Remove(ProductID.ToString()); } public static Product New() { if (!CanAddObject()) throw new System.Security.SecurityException("User not authorized to add a Product"); try { return DataPortal.Create<Product>(); } catch (Exception ex) { throw new DbCslaException("Error on Product.New", ex); } } public static Product New(string productName) { Product tmp = Product.New(); tmp.ProductName = productName; return tmp; } public static Product New(string productName, Supplier mySupplier, Category myCategory, string quantityPerUnit, decimal? unitPrice, Int16? unitsInStock, Int16? unitsOnOrder, Int16? reorderLevel, bool discontinued) { Product tmp = Product.New(); tmp.ProductName = productName; tmp.MySupplier = mySupplier; tmp.MyCategory = myCategory; tmp.QuantityPerUnit = quantityPerUnit; tmp.UnitPrice = unitPrice; tmp.UnitsInStock = unitsInStock; tmp.UnitsOnOrder = unitsOnOrder; tmp.ReorderLevel = reorderLevel; tmp.Discontinued = discontinued; return tmp; } public static Product MakeProduct(string productName, Supplier mySupplier, Category myCategory, string quantityPerUnit, decimal? unitPrice, Int16? unitsInStock, Int16? unitsOnOrder, Int16? reorderLevel, bool discontinued) { Product tmp = Product.New(productName, mySupplier, myCategory, quantityPerUnit, unitPrice, unitsInStock, unitsOnOrder, reorderLevel, discontinued); if (tmp.IsSavable) tmp = tmp.Save(); else { Csla.Validation.BrokenRulesCollection brc = tmp.ValidationRules.GetBrokenRules(); tmp._ErrorMessage = "Failed Validation:"; foreach (Csla.Validation.BrokenRule br in brc) { tmp._ErrorMessage += "\r\n\tFailure: " + br.RuleName; } } return tmp; } public static Product New(string productName, Supplier mySupplier, Category myCategory, string quantityPerUnit) { Product tmp = Product.New(); tmp.ProductName = productName; tmp.MySupplier = mySupplier; tmp.MyCategory = myCategory; tmp.QuantityPerUnit = quantityPerUnit; return tmp; } public static Product MakeProduct(string productName, Supplier mySupplier, Category myCategory, string quantityPerUnit) { Product tmp = Product.New(productName, mySupplier, myCategory, quantityPerUnit); if (tmp.IsSavable) tmp = tmp.Save(); else { Csla.Validation.BrokenRulesCollection brc = tmp.ValidationRules.GetBrokenRules(); tmp._ErrorMessage = "Failed Validation:"; foreach (Csla.Validation.BrokenRule br in brc) { tmp._ErrorMessage += "\r\n\tFailure: " + br.RuleName; } } return tmp; } public static Product Get(int productID) { if (!CanGetObject()) throw new System.Security.SecurityException("User not authorized to view a Product"); try { Product tmp = GetExistingByPrimaryKey(productID); if (tmp == null) { tmp = DataPortal.Fetch<Product>(new PKCriteria(productID)); _AllList.Add(tmp); } if (tmp.ErrorMessage == "No Record Found") tmp = null; return tmp; } catch (Exception ex) { throw new DbCslaException("Error on Product.Get", ex); } } public static Product Get(SafeDataReader dr) { if (dr.Read()) return new Product(dr); return null; } internal Product(SafeDataReader dr) { ReadData(dr); } public static void Delete(int productID) { if (!CanDeleteObject()) throw new System.Security.SecurityException("User not authorized to remove a Product"); try { DataPortal.Delete(new PKCriteria(productID)); } catch (Exception ex) { throw new DbCslaException("Error on Product.Delete", ex); } } public override Product Save() { if (IsDeleted && !CanDeleteObject()) throw new System.Security.SecurityException("User not authorized to remove a Product"); else if (IsNew && !CanAddObject()) throw new System.Security.SecurityException("User not authorized to add a Product"); else if (!CanEditObject()) throw new System.Security.SecurityException("User not authorized to update a Product"); try { BuildRefreshList(); Product product = base.Save(); _AllList.Add(product);//Refresh the item in AllList ProcessRefreshList(); return product; } catch (Exception ex) { throw new DbCslaException("Error on CSLA Save", ex); } } #endregion #region Data Access Portal [Serializable()] protected class PKCriteria { private int _ProductID; public int ProductID { get { return _ProductID; } } public PKCriteria(int productID) { _ProductID = productID; } } // TODO: If Create needs to access DB - It should not be marked RunLocal [RunLocal()] private new void DataPortal_Create() { _ProductID = NextProductID; // Database Defaults _UnitPrice = _ProductExtension.DefaultUnitPrice; _UnitsInStock = _ProductExtension.DefaultUnitsInStock; _UnitsOnOrder = _ProductExtension.DefaultUnitsOnOrder; _ReorderLevel = _ProductExtension.DefaultReorderLevel; _Discontinued = _ProductExtension.DefaultDiscontinued; // TODO: Add any defaults that are necessary ValidationRules.CheckRules(); } private void ReadData(SafeDataReader dr) { Database.LogInfo("Product.ReadData", GetHashCode()); try { _ProductID = dr.GetInt32("ProductID"); _ProductName = dr.GetString("ProductName"); _SupplierID = (int?)dr.GetValue("SupplierID"); _CategoryID = (int?)dr.GetValue("CategoryID"); _QuantityPerUnit = dr.GetString("QuantityPerUnit"); _UnitPrice = (decimal?)dr.GetValue("UnitPrice"); _UnitsInStock = (Int16?)dr.GetValue("UnitsInStock"); _UnitsOnOrder = (Int16?)dr.GetValue("UnitsOnOrder"); _ReorderLevel = (Int16?)dr.GetValue("ReorderLevel"); _Discontinued = dr.GetBoolean("Discontinued"); _ProductOrderDetailCount = dr.GetInt32("OrderDetailCount"); MarkOld(); } catch (Exception ex) { Database.LogException("Product.ReadData", ex); _ErrorMessage = ex.Message; throw new DbCslaException("Product.ReadData", ex); } } private void DataPortal_Fetch(PKCriteria criteria) { Database.LogInfo("Product.DataPortal_Fetch", GetHashCode()); try { using (SqlConnection cn = Database.Northwind_SqlConnection) { ApplicationContext.LocalContext["cn"] = cn; using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "getProduct"; cm.Parameters.AddWithValue("@ProductID", criteria.ProductID); using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader())) { if (!dr.Read()) { _ErrorMessage = "No Record Found"; return; } ReadData(dr); // load child objects dr.NextResult(); _ProductOrderDetails = ProductOrderDetails.Get(dr); } } // removing of item only needed for local data portal if (ApplicationContext.ExecutionLocation == ApplicationContext.ExecutionLocations.Client) ApplicationContext.LocalContext.Remove("cn"); } } catch (Exception ex) { Database.LogException("Product.DataPortal_Fetch", ex); _ErrorMessage = ex.Message; throw new DbCslaException("Product.DataPortal_Fetch", ex); } } [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Insert() { try { using (SqlConnection cn = Database.Northwind_SqlConnection) { ApplicationContext.LocalContext["cn"] = cn; SQLInsert(); // removing of item only needed for local data portal if (ApplicationContext.ExecutionLocation == ApplicationContext.ExecutionLocations.Client) ApplicationContext.LocalContext.Remove("cn"); } } catch (Exception ex) { Database.LogException("Product.DataPortal_Insert", ex); _ErrorMessage = ex.Message; throw new DbCslaException("Product.DataPortal_Insert", ex); } finally { Database.LogInfo("Product.DataPortal_Insert", GetHashCode()); } } [Transactional(TransactionalTypes.TransactionScope)] internal void SQLInsert() { if (!this.IsDirty) return; try { if(_MyCategory != null) _MyCategory.Update(); if(_MySupplier != null) _MySupplier.Update(); SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "addProduct"; // Input All Fields - Except Calculated Columns cm.Parameters.AddWithValue("@ProductName", _ProductName); cm.Parameters.AddWithValue("@SupplierID", SupplierID); cm.Parameters.AddWithValue("@CategoryID", CategoryID); cm.Parameters.AddWithValue("@QuantityPerUnit", _QuantityPerUnit); cm.Parameters.AddWithValue("@UnitPrice", _UnitPrice); cm.Parameters.AddWithValue("@UnitsInStock", _UnitsInStock); cm.Parameters.AddWithValue("@UnitsOnOrder", _UnitsOnOrder); cm.Parameters.AddWithValue("@ReorderLevel", _ReorderLevel); cm.Parameters.AddWithValue("@Discontinued", _Discontinued); // Output Calculated Columns SqlParameter param_ProductID = new SqlParameter("@newProductID", SqlDbType.Int); param_ProductID.Direction = ParameterDirection.Output; cm.Parameters.Add(param_ProductID); // TODO: Define any additional output parameters cm.ExecuteNonQuery(); // Save all values being returned from the Procedure _ProductID = (int)cm.Parameters["@newProductID"].Value; } MarkOld(); // update child objects if (_ProductOrderDetails != null) _ProductOrderDetails.Update(this); Database.LogInfo("Product.SQLInsert", GetHashCode()); } catch (Exception ex) { Database.LogException("Product.SQLInsert", ex); _ErrorMessage = ex.Message; throw new DbCslaException("Product.SQLInsert", ex); } } [Transactional(TransactionalTypes.TransactionScope)] public static void Add(SqlConnection cn, ref int productID, string productName, Supplier mySupplier, Category myCategory, string quantityPerUnit, decimal? unitPrice, Int16? unitsInStock, Int16? unitsOnOrder, Int16? reorderLevel, bool discontinued) { Database.LogInfo("Product.Add", 0); try { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "addProduct"; // Input All Fields - Except Calculated Columns cm.Parameters.AddWithValue("@ProductName", productName); if(mySupplier != null)cm.Parameters.AddWithValue("@SupplierID", mySupplier.SupplierID); if(myCategory != null)cm.Parameters.AddWithValue("@CategoryID", myCategory.CategoryID); cm.Parameters.AddWithValue("@QuantityPerUnit", quantityPerUnit); cm.Parameters.AddWithValue("@UnitPrice", unitPrice); cm.Parameters.AddWithValue("@UnitsInStock", unitsInStock); cm.Parameters.AddWithValue("@UnitsOnOrder", unitsOnOrder); cm.Parameters.AddWithValue("@ReorderLevel", reorderLevel); cm.Parameters.AddWithValue("@Discontinued", discontinued); // Output Calculated Columns SqlParameter param_ProductID = new SqlParameter("@newProductID", SqlDbType.Int); param_ProductID.Direction = ParameterDirection.Output; cm.Parameters.Add(param_ProductID); // TODO: Define any additional output parameters cm.ExecuteNonQuery(); // Save all values being returned from the Procedure productID = (int)cm.Parameters["@newProductID"].Value; // No Timestamp value to return } } catch (Exception ex) { Database.LogException("Product.Add", ex); throw new DbCslaException("Product.Add", ex); } } [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Update() { if (!IsDirty) return; // If not dirty - nothing to do Database.LogInfo("Product.DataPortal_Update", GetHashCode()); try { using (SqlConnection cn = Database.Northwind_SqlConnection) { ApplicationContext.LocalContext["cn"] = cn; SQLUpdate(); // removing of item only needed for local data portal if (ApplicationContext.ExecutionLocation == ApplicationContext.ExecutionLocations.Client) ApplicationContext.LocalContext.Remove("cn"); } } catch (Exception ex) { Database.LogException("Product.DataPortal_Update", ex); _ErrorMessage = ex.Message; if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } [Transactional(TransactionalTypes.TransactionScope)] internal void SQLUpdate() { if (!IsDirty) return; // If not dirty - nothing to do Database.LogInfo("Product.SQLUpdate", GetHashCode()); try { if(_MyCategory != null) _MyCategory.Update(); if(_MySupplier != null) _MySupplier.Update(); SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; if (base.IsDirty) { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "updateProduct"; // All Fields including Calculated Fields cm.Parameters.AddWithValue("@ProductID", _ProductID); cm.Parameters.AddWithValue("@ProductName", _ProductName); cm.Parameters.AddWithValue("@SupplierID", SupplierID); cm.Parameters.AddWithValue("@CategoryID", CategoryID); cm.Parameters.AddWithValue("@QuantityPerUnit", _QuantityPerUnit); cm.Parameters.AddWithValue("@UnitPrice", _UnitPrice); cm.Parameters.AddWithValue("@UnitsInStock", _UnitsInStock); cm.Parameters.AddWithValue("@UnitsOnOrder", _UnitsOnOrder); cm.Parameters.AddWithValue("@ReorderLevel", _ReorderLevel); cm.Parameters.AddWithValue("@Discontinued", _Discontinued); // Output Calculated Columns // TODO: Define any additional output parameters cm.ExecuteNonQuery(); // Save all values being returned from the Procedure } } MarkOld(); // use the open connection to update child objects if (_ProductOrderDetails != null) _ProductOrderDetails.Update(this); } catch (Exception ex) { Database.LogException("Product.SQLUpdate", ex); _ErrorMessage = ex.Message; if (!ex.Message.EndsWith("has been edited by another user.")) throw ex; } } internal void Update() { if (!this.IsDirty) return; if (base.IsDirty) { SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"]; if (IsNew) Product.Add(cn, ref _ProductID, _ProductName, _MySupplier, _MyCategory, _QuantityPerUnit, _UnitPrice, _UnitsInStock, _UnitsOnOrder, _ReorderLevel, _Discontinued); else Product.Update(cn, ref _ProductID, _ProductName, _MySupplier, _MyCategory, _QuantityPerUnit, _UnitPrice, _UnitsInStock, _UnitsOnOrder, _ReorderLevel, _Discontinued); MarkOld(); } if (_ProductOrderDetails != null) _ProductOrderDetails.Update(this); } [Transactional(TransactionalTypes.TransactionScope)] public static void Update(SqlConnection cn, ref int productID, string productName, Supplier mySupplier, Category myCategory, string quantityPerUnit, decimal? unitPrice, Int16? unitsInStock, Int16? unitsOnOrder, Int16? reorderLevel, bool discontinued) { Database.LogInfo("Product.Update", 0); try { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "updateProduct"; // Input All Fields - Except Calculated Columns cm.Parameters.AddWithValue("@ProductID", productID); cm.Parameters.AddWithValue("@ProductName", productName); if(mySupplier != null)cm.Parameters.AddWithValue("@SupplierID", mySupplier.SupplierID); if(myCategory != null)cm.Parameters.AddWithValue("@CategoryID", myCategory.CategoryID); cm.Parameters.AddWithValue("@QuantityPerUnit", quantityPerUnit); cm.Parameters.AddWithValue("@UnitPrice", unitPrice); cm.Parameters.AddWithValue("@UnitsInStock", unitsInStock); cm.Parameters.AddWithValue("@UnitsOnOrder", unitsOnOrder); cm.Parameters.AddWithValue("@ReorderLevel", reorderLevel); cm.Parameters.AddWithValue("@Discontinued", discontinued); // Output Calculated Columns // TODO: Define any additional output parameters cm.ExecuteNonQuery(); // Save all values being returned from the Procedure // No Timestamp value to return } } catch (Exception ex) { Database.LogException("Product.Update", ex); throw new DbCslaException("Product.Update", ex); } } [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_DeleteSelf() { DataPortal_Delete(new PKCriteria(_ProductID)); } [Transactional(TransactionalTypes.TransactionScope)] private void DataPortal_Delete(PKCriteria criteria) { Database.LogInfo("Product.DataPortal_Delete", GetHashCode()); try { using (SqlConnection cn = Database.Northwind_SqlConnection) { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "deleteProduct"; cm.Parameters.AddWithValue("@ProductID", criteria.ProductID); cm.ExecuteNonQuery(); } } } catch (Exception ex) { Database.LogException("Product.DataPortal_Delete", ex); _ErrorMessage = ex.Message; throw new DbCslaException("Product.DataPortal_Delete", ex); } } [Transactional(TransactionalTypes.TransactionScope)] public static void Remove(SqlConnection cn, int productID) { Database.LogInfo("Product.Remove", 0); try { using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "deleteProduct"; // Input PK Fields cm.Parameters.AddWithValue("@ProductID", productID); // TODO: Define any additional output parameters cm.ExecuteNonQuery(); } } catch (Exception ex) { Database.LogException("Product.Remove", ex); throw new DbCslaException("Product.Remove", ex); } } #endregion #region Exists public static bool Exists(int productID) { ExistsCommand result; try { result = DataPortal.Execute<ExistsCommand>(new ExistsCommand(productID)); return result.Exists; } catch (Exception ex) { throw new DbCslaException("Error on Product.Exists", ex); } } [Serializable()] private class ExistsCommand : CommandBase { private int _ProductID; private bool _exists; public bool Exists { get { return _exists; } } public ExistsCommand(int productID) { _ProductID = productID; } protected override void DataPortal_Execute() { Database.LogInfo("Product.DataPortal_Execute", GetHashCode()); try { using (SqlConnection cn = Database.Northwind_SqlConnection) { cn.Open(); using (SqlCommand cm = cn.CreateCommand()) { cm.CommandType = CommandType.StoredProcedure; cm.CommandText = "existsProduct"; cm.Parameters.AddWithValue("@ProductID", _ProductID); int count = (int)cm.ExecuteScalar(); _exists = (count > 0); } } } catch (Exception ex) { Database.LogException("Product.DataPortal_Execute", ex); throw new DbCslaException("Product.DataPortal_Execute", ex); } } } #endregion // Standard Default Code #region extension ProductExtension _ProductExtension = new ProductExtension(); [Serializable()] partial class ProductExtension : extensionBase { } [Serializable()] class extensionBase { // Default Values public virtual decimal? DefaultUnitPrice { get { return 0; } } public virtual Int16? DefaultUnitsInStock { get { return 0; } } public virtual Int16? DefaultUnitsOnOrder { get { return 0; } } public virtual Int16? DefaultReorderLevel { get { return 0; } } public virtual bool DefaultDiscontinued { get { return Convert.ToBoolean(0); } } // Authorization Rules public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) { // Needs to be overriden to add new authorization rules } // Instance Authorization Rules public virtual void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) { // Needs to be overriden to add new authorization rules } // Validation Rules public virtual void AddValidationRules(Csla.Validation.ValidationRules rules) { // Needs to be overriden to add new validation rules } // InstanceValidation Rules public virtual void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) { // Needs to be overriden to add new validation rules } } #endregion } // Class #region Converter internal class ProductConverter : ExpandableObjectConverter { public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType) { if (destType == typeof(string) && value is Product) { // Return the ToString value return ((Product)value).ToString(); } return base.ConvertTo(context, culture, value, destType); } } #endregion } // Namespace //// The following is a sample Extension File. You can use it to create ProductExt.cs //using System; //using System.Collections.Generic; //using System.Text; //using Csla; //namespace Northwind.CSLA.Library //{ // public partial class Product // { // partial class ProductExtension : extensionBase // { // // TODO: Override automatic defaults // public virtual decimal? DefaultUnitPrice // { // get { return 0; } // } // public virtual Int16? DefaultUnitsInStock // { // get { return 0; } // } // public virtual Int16? DefaultUnitsOnOrder // { // get { return 0; } // } // public virtual Int16? DefaultReorderLevel // { // get { return 0; } // } // public virtual bool DefaultDiscontinued // { // get { return 0; } // } // public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules) // { // //rules.AllowRead(Dbid, "<Role(s)>"); // } // public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules) // { // //rules.AllowInstanceRead(Dbid, "<Role(s)>"); // } // public new void AddValidationRules(Csla.Validation.ValidationRules rules) // { // rules.AddRule( // Csla.Validation.CommonRules.StringMaxLength, // new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100)); // } // public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules) // { // rules.AddInstanceRule(/* Instance Validation Rule */); // } // } // } //}
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; namespace LibGit2Sharp.Core { internal class HistoryRewriter { private readonly IRepository repo; private readonly HashSet<Commit> targetedCommits; private readonly Dictionary<GitObject, GitObject> objectMap = new Dictionary<GitObject, GitObject>(); private readonly Dictionary<Reference, Reference> refMap = new Dictionary<Reference, Reference>(); private readonly Queue<Action> rollbackActions = new Queue<Action>(); private readonly string backupRefsNamespace; private readonly RewriteHistoryOptions options; public HistoryRewriter( IRepository repo, IEnumerable<Commit> commitsToRewrite, RewriteHistoryOptions options) { this.repo = repo; this.options = options; targetedCommits = new HashSet<Commit>(commitsToRewrite); backupRefsNamespace = this.options.BackupRefsNamespace; if (!backupRefsNamespace.EndsWith("/", StringComparison.Ordinal)) { backupRefsNamespace += "/"; } } public void Execute() { var success = false; try { // Find out which refs lead to at least one the commits var refsToRewrite = repo.Refs.ReachableFrom(targetedCommits).ToList(); var filter = new CommitFilter { Since = refsToRewrite, SortBy = CommitSortStrategies.Reverse | CommitSortStrategies.Topological }; var commits = repo.Commits.QueryBy(filter); foreach (var commit in commits) { RewriteCommit(commit); } // Ordering matters. In the case of `A -> B -> commit`, we need to make sure B is rewritten // before A. foreach (var reference in refsToRewrite.OrderBy(ReferenceDepth)) { // TODO: Rewrite refs/notes/* properly if (reference.CanonicalName.StartsWith("refs/notes/")) { continue; } RewriteReference(reference); } success = true; if (options.OnSucceeding != null) { options.OnSucceeding(); } } catch (Exception ex) { try { if (!success && options.OnError != null) { options.OnError(ex); } } finally { foreach (var action in rollbackActions) { action(); } } throw; } finally { rollbackActions.Clear(); } } private Reference RewriteReference(Reference reference) { // Has this target already been rewritten? if (refMap.ContainsKey(reference)) { return refMap[reference]; } var sref = reference as SymbolicReference; if (sref != null) { return RewriteReference(sref, old => old.Target, RewriteReference, (refs, old, target, logMessage) => refs.UpdateTarget(old, target, logMessage)); } var dref = reference as DirectReference; if (dref != null) { return RewriteReference(dref, old => old.Target, RewriteTarget, (refs, old, target, logMessage) => refs.UpdateTarget(old, target.Id, logMessage)); } return reference; } private delegate Reference ReferenceUpdater<in TRef, in TTarget>( ReferenceCollection refs, TRef origRef, TTarget origTarget, string logMessage) where TRef : Reference where TTarget : class; private Reference RewriteReference<TRef, TTarget>( TRef oldRef, Func<TRef, TTarget> selectTarget, Func<TTarget, TTarget> rewriteTarget, ReferenceUpdater<TRef, TTarget> updateTarget) where TRef : Reference where TTarget : class { var oldRefTarget = selectTarget(oldRef); string newRefName = oldRef.CanonicalName; if (oldRef.IsTag && options.TagNameRewriter != null) { newRefName = Reference.TagPrefix + options.TagNameRewriter(oldRef.CanonicalName.Substring(Reference.TagPrefix.Length), false, oldRef.TargetIdentifier); } var newTarget = rewriteTarget(oldRefTarget); if (oldRefTarget.Equals(newTarget) && oldRef.CanonicalName == newRefName) { // The reference isn't rewritten return oldRef; } string backupName = backupRefsNamespace + oldRef.CanonicalName.Substring("refs/".Length); if (repo.Refs.Resolve<Reference>(backupName) != null) { throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "Can't back up reference '{0}' - '{1}' already exists", oldRef.CanonicalName, backupName)); } repo.Refs.Add(backupName, oldRef.TargetIdentifier, "filter-branch: backup"); rollbackActions.Enqueue(() => repo.Refs.Remove(backupName)); if (newTarget == null) { repo.Refs.Remove(oldRef); rollbackActions.Enqueue(() => repo.Refs.Add(oldRef.CanonicalName, oldRef, "filter-branch: abort", true)); return refMap[oldRef] = null; } Reference newRef = updateTarget(repo.Refs, oldRef, newTarget, "filter-branch: rewrite"); rollbackActions.Enqueue(() => updateTarget(repo.Refs, oldRef, oldRefTarget, "filter-branch: abort")); if (newRef.CanonicalName == newRefName) { return refMap[oldRef] = newRef; } var movedRef = repo.Refs.Rename(newRef, newRefName, false); rollbackActions.Enqueue(() => repo.Refs.Rename(newRef, oldRef.CanonicalName, false)); return refMap[oldRef] = movedRef; } private void RewriteCommit(Commit commit) { var newHeader = CommitRewriteInfo.From(commit); var newTree = commit.Tree; // Find the new parents var newParents = commit.Parents; if (targetedCommits.Contains(commit)) { // Get the new commit header if (options.CommitHeaderRewriter != null) { newHeader = options.CommitHeaderRewriter(commit) ?? newHeader; } if (options.CommitTreeRewriter != null) { // Get the new commit tree var newTreeDefinition = options.CommitTreeRewriter(commit); newTree = repo.ObjectDatabase.CreateTree(newTreeDefinition); } // Retrieve new parents if (options.CommitParentsRewriter != null) { newParents = options.CommitParentsRewriter(commit); } } // Create the new commit var mappedNewParents = newParents .Select(oldParent => objectMap.ContainsKey(oldParent) ? objectMap[oldParent] as Commit : oldParent) .Where(newParent => newParent != null) .ToList(); if (options.PruneEmptyCommits && TryPruneEmptyCommit(commit, mappedNewParents, newTree)) { return; } var newCommit = repo.ObjectDatabase.CreateCommit(newHeader.Author, newHeader.Committer, newHeader.Message, newTree, mappedNewParents, true); // Record the rewrite objectMap[commit] = newCommit; } private bool TryPruneEmptyCommit(Commit commit, IList<Commit> mappedNewParents, Tree newTree) { var parent = mappedNewParents.Count > 0 ? mappedNewParents[0] : null; if (parent == null) { if (newTree.Count == 0) { objectMap[commit] = null; return true; } } else if (parent.Tree == newTree) { objectMap[commit] = parent; return true; } return false; } private GitObject RewriteTarget(GitObject oldTarget) { // Has this target already been rewritten? if (objectMap.ContainsKey(oldTarget)) { return objectMap[oldTarget]; } Debug.Assert((oldTarget as Commit) == null); var annotation = oldTarget as TagAnnotation; if (annotation == null) { //TODO: Probably a Tree or a Blob. This is not covered by any test return oldTarget; } // Recursively rewrite annotations if necessary var newTarget = RewriteTarget(annotation.Target); string newName = annotation.Name; if (options.TagNameRewriter != null) { newName = options.TagNameRewriter(annotation.Name, true, annotation.Target.Sha); } var newAnnotation = repo.ObjectDatabase.CreateTagAnnotation(newName, newTarget, annotation.Tagger, annotation.Message); objectMap[annotation] = newAnnotation; return newAnnotation; } private int ReferenceDepth(Reference reference) { var dref = reference as DirectReference; return dref == null ? 1 + ReferenceDepth(((SymbolicReference)reference).Target) : 1; } } }
// 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.ServiceModel; using System.Reflection; namespace System.Collections.Generic { [Runtime.InteropServices.ComVisible(false)] public class SynchronizedCollection<T> : IList<T>, IList { private object _sync; public SynchronizedCollection() { Items = new List<T>(); _sync = new Object(); } public SynchronizedCollection(object syncRoot) { Items = new List<T>(); _sync = syncRoot ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(syncRoot))); } public SynchronizedCollection(object syncRoot, IEnumerable<T> list) { if (list == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(list))); } Items = new List<T>(list); _sync = syncRoot ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(syncRoot))); } public SynchronizedCollection(object syncRoot, params T[] list) { if (list == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(list))); } Items = new List<T>(list.Length); for (int i = 0; i < list.Length; i++) { Items.Add(list[i]); } _sync = syncRoot ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(syncRoot))); } public int Count { get { lock (_sync) { return Items.Count; } } } protected List<T> Items { get; } public object SyncRoot { get { return _sync; } } public T this[int index] { get { lock (_sync) { return Items[index]; } } set { lock (_sync) { if (index < 0 || index >= Items.Count) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(index), index, SR.Format(SR.ValueMustBeInRange, 0, Items.Count - 1))); } SetItem(index, value); } } } public void Add(T item) { lock (_sync) { int index = Items.Count; InsertItem(index, item); } } public void Clear() { lock (_sync) { ClearItems(); } } public void CopyTo(T[] array, int index) { lock (_sync) { Items.CopyTo(array, index); } } public bool Contains(T item) { lock (_sync) { return Items.Contains(item); } } public IEnumerator<T> GetEnumerator() { lock (_sync) { return Items.GetEnumerator(); } } public int IndexOf(T item) { lock (_sync) { return InternalIndexOf(item); } } public void Insert(int index, T item) { lock (_sync) { if (index < 0 || index > Items.Count) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(index), index, SR.Format(SR.ValueMustBeInRange, 0, Items.Count))); } InsertItem(index, item); } } private int InternalIndexOf(T item) { int count = Items.Count; for (int i = 0; i < count; i++) { if (object.Equals(Items[i], item)) { return i; } } return -1; } public bool Remove(T item) { lock (_sync) { int index = InternalIndexOf(item); if (index < 0) { return false; } RemoveItem(index); return true; } } public void RemoveAt(int index) { lock (_sync) { if (index < 0 || index >= Items.Count) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(index), index, SR.Format(SR.ValueMustBeInRange, 0, Items.Count - 1))); } RemoveItem(index); } } protected virtual void ClearItems() { Items.Clear(); } protected virtual void InsertItem(int index, T item) { Items.Insert(index, item); } protected virtual void RemoveItem(int index) { Items.RemoveAt(index); } protected virtual void SetItem(int index, T item) { Items[index] = item; } bool ICollection<T>.IsReadOnly { get { return false; } } IEnumerator IEnumerable.GetEnumerator() { return ((IList)Items).GetEnumerator(); } bool ICollection.IsSynchronized { get { return true; } } object ICollection.SyncRoot { get { return _sync; } } void ICollection.CopyTo(Array array, int index) { lock (_sync) { ((IList)Items).CopyTo(array, index); } } object IList.this[int index] { get { return this[index]; } set { VerifyValueType(value); this[index] = (T)value; } } bool IList.IsReadOnly { get { return false; } } bool IList.IsFixedSize { get { return false; } } int IList.Add(object value) { VerifyValueType(value); lock (_sync) { Add((T)value); return Count - 1; } } bool IList.Contains(object value) { VerifyValueType(value); return Contains((T)value); } int IList.IndexOf(object value) { VerifyValueType(value); return IndexOf((T)value); } void IList.Insert(int index, object value) { VerifyValueType(value); Insert(index, (T)value); } void IList.Remove(object value) { VerifyValueType(value); Remove((T)value); } private static void VerifyValueType(object value) { if (value == null) { if (typeof(T).GetTypeInfo().IsValueType) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.SynchronizedCollectionWrongTypeNull)); } } else if (!(value is T)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.SynchronizedCollectionWrongType1, value.GetType().FullName))); } } } }
using System; using System.Linq; using System.Collections.Generic; using Blueprint41; using Blueprint41.Core; using Blueprint41.Query; using Blueprint41.DatastoreTemplates; using q = Domain.Data.Query; namespace Domain.Data.Manipulation { public interface IPurchaseOrderHeaderOriginalData : ISchemaBaseOriginalData { string RevisionNumber { get; } string Status { get; } System.DateTime OrderDate { get; } System.DateTime ShipDate { get; } double SubTotal { get; } double TaxAmt { get; } string Freight { get; } double TotalDue { get; } Vendor Vendor { get; } ShipMethod ShipMethod { get; } } public partial class PurchaseOrderHeader : OGM<PurchaseOrderHeader, PurchaseOrderHeader.PurchaseOrderHeaderData, System.String>, ISchemaBase, INeo4jBase, IPurchaseOrderHeaderOriginalData { #region Initialize static PurchaseOrderHeader() { Register.Types(); } protected override void RegisterGeneratedStoredQueries() { #region LoadByKeys RegisterQuery(nameof(LoadByKeys), (query, alias) => query. Where(alias.Uid.In(Parameter.New<System.String>(Param0)))); #endregion AdditionalGeneratedStoredQueries(); } partial void AdditionalGeneratedStoredQueries(); public static Dictionary<System.String, PurchaseOrderHeader> LoadByKeys(IEnumerable<System.String> uids) { return FromQuery(nameof(LoadByKeys), new Parameter(Param0, uids.ToArray(), typeof(System.String))).ToDictionary(item=> item.Uid, item => item); } protected static void RegisterQuery(string name, Func<IMatchQuery, q.PurchaseOrderHeaderAlias, IWhereQuery> query) { q.PurchaseOrderHeaderAlias alias; IMatchQuery matchQuery = Blueprint41.Transaction.CompiledQuery.Match(q.Node.PurchaseOrderHeader.Alias(out alias)); IWhereQuery partial = query.Invoke(matchQuery, alias); ICompiled compiled = partial.Return(alias).Compile(); RegisterQuery(name, compiled); } public override string ToString() { return $"PurchaseOrderHeader => RevisionNumber : {this.RevisionNumber}, Status : {this.Status}, OrderDate : {this.OrderDate}, ShipDate : {this.ShipDate}, SubTotal : {this.SubTotal}, TaxAmt : {this.TaxAmt}, Freight : {this.Freight}, TotalDue : {this.TotalDue}, ModifiedDate : {this.ModifiedDate}, Uid : {this.Uid}"; } public override int GetHashCode() { return base.GetHashCode(); } protected override void LazySet() { base.LazySet(); if (PersistenceState == PersistenceState.NewAndChanged || PersistenceState == PersistenceState.LoadedAndChanged) { if ((object)InnerData == (object)OriginalData) OriginalData = new PurchaseOrderHeaderData(InnerData); } } #endregion #region Validations protected override void ValidateSave() { bool isUpdate = (PersistenceState != PersistenceState.New && PersistenceState != PersistenceState.NewAndChanged); #pragma warning disable CS0472 if (InnerData.RevisionNumber == null) throw new PersistenceException(string.Format("Cannot save PurchaseOrderHeader with key '{0}' because the RevisionNumber cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.Status == null) throw new PersistenceException(string.Format("Cannot save PurchaseOrderHeader with key '{0}' because the Status cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.OrderDate == null) throw new PersistenceException(string.Format("Cannot save PurchaseOrderHeader with key '{0}' because the OrderDate cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.ShipDate == null) throw new PersistenceException(string.Format("Cannot save PurchaseOrderHeader with key '{0}' because the ShipDate cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.SubTotal == null) throw new PersistenceException(string.Format("Cannot save PurchaseOrderHeader with key '{0}' because the SubTotal cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.TaxAmt == null) throw new PersistenceException(string.Format("Cannot save PurchaseOrderHeader with key '{0}' because the TaxAmt cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.Freight == null) throw new PersistenceException(string.Format("Cannot save PurchaseOrderHeader with key '{0}' because the Freight cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.TotalDue == null) throw new PersistenceException(string.Format("Cannot save PurchaseOrderHeader with key '{0}' because the TotalDue cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.ModifiedDate == null) throw new PersistenceException(string.Format("Cannot save PurchaseOrderHeader with key '{0}' because the ModifiedDate cannot be null.", this.Uid?.ToString() ?? "<null>")); #pragma warning restore CS0472 } protected override void ValidateDelete() { } #endregion #region Inner Data public class PurchaseOrderHeaderData : Data<System.String> { public PurchaseOrderHeaderData() { } public PurchaseOrderHeaderData(PurchaseOrderHeaderData data) { RevisionNumber = data.RevisionNumber; Status = data.Status; OrderDate = data.OrderDate; ShipDate = data.ShipDate; SubTotal = data.SubTotal; TaxAmt = data.TaxAmt; Freight = data.Freight; TotalDue = data.TotalDue; Vendor = data.Vendor; ShipMethod = data.ShipMethod; ModifiedDate = data.ModifiedDate; Uid = data.Uid; } #region Initialize Collections protected override void InitializeCollections() { NodeType = "PurchaseOrderHeader"; Vendor = new EntityCollection<Vendor>(Wrapper, Members.Vendor); ShipMethod = new EntityCollection<ShipMethod>(Wrapper, Members.ShipMethod); } public string NodeType { get; private set; } sealed public override System.String GetKey() { return Entity.Parent.PersistenceProvider.ConvertFromStoredType<System.String>(Uid); } sealed protected override void SetKey(System.String key) { Uid = (string)Entity.Parent.PersistenceProvider.ConvertToStoredType<System.String>(key); base.SetKey(Uid); } #endregion #region Map Data sealed public override IDictionary<string, object> MapTo() { IDictionary<string, object> dictionary = new Dictionary<string, object>(); dictionary.Add("RevisionNumber", RevisionNumber); dictionary.Add("Status", Status); dictionary.Add("OrderDate", Conversion<System.DateTime, long>.Convert(OrderDate)); dictionary.Add("ShipDate", Conversion<System.DateTime, long>.Convert(ShipDate)); dictionary.Add("SubTotal", SubTotal); dictionary.Add("TaxAmt", TaxAmt); dictionary.Add("Freight", Freight); dictionary.Add("TotalDue", TotalDue); dictionary.Add("ModifiedDate", Conversion<System.DateTime, long>.Convert(ModifiedDate)); dictionary.Add("Uid", Uid); return dictionary; } sealed public override void MapFrom(IReadOnlyDictionary<string, object> properties) { object value; if (properties.TryGetValue("RevisionNumber", out value)) RevisionNumber = (string)value; if (properties.TryGetValue("Status", out value)) Status = (string)value; if (properties.TryGetValue("OrderDate", out value)) OrderDate = Conversion<long, System.DateTime>.Convert((long)value); if (properties.TryGetValue("ShipDate", out value)) ShipDate = Conversion<long, System.DateTime>.Convert((long)value); if (properties.TryGetValue("SubTotal", out value)) SubTotal = (double)value; if (properties.TryGetValue("TaxAmt", out value)) TaxAmt = (double)value; if (properties.TryGetValue("Freight", out value)) Freight = (string)value; if (properties.TryGetValue("TotalDue", out value)) TotalDue = (double)value; if (properties.TryGetValue("ModifiedDate", out value)) ModifiedDate = Conversion<long, System.DateTime>.Convert((long)value); if (properties.TryGetValue("Uid", out value)) Uid = (string)value; } #endregion #region Members for interface IPurchaseOrderHeader public string RevisionNumber { get; set; } public string Status { get; set; } public System.DateTime OrderDate { get; set; } public System.DateTime ShipDate { get; set; } public double SubTotal { get; set; } public double TaxAmt { get; set; } public string Freight { get; set; } public double TotalDue { get; set; } public EntityCollection<Vendor> Vendor { get; private set; } public EntityCollection<ShipMethod> ShipMethod { get; private set; } #endregion #region Members for interface ISchemaBase public System.DateTime ModifiedDate { get; set; } #endregion #region Members for interface INeo4jBase public string Uid { get; set; } #endregion } #endregion #region Outer Data #region Members for interface IPurchaseOrderHeader public string RevisionNumber { get { LazyGet(); return InnerData.RevisionNumber; } set { if (LazySet(Members.RevisionNumber, InnerData.RevisionNumber, value)) InnerData.RevisionNumber = value; } } public string Status { get { LazyGet(); return InnerData.Status; } set { if (LazySet(Members.Status, InnerData.Status, value)) InnerData.Status = value; } } public System.DateTime OrderDate { get { LazyGet(); return InnerData.OrderDate; } set { if (LazySet(Members.OrderDate, InnerData.OrderDate, value)) InnerData.OrderDate = value; } } public System.DateTime ShipDate { get { LazyGet(); return InnerData.ShipDate; } set { if (LazySet(Members.ShipDate, InnerData.ShipDate, value)) InnerData.ShipDate = value; } } public double SubTotal { get { LazyGet(); return InnerData.SubTotal; } set { if (LazySet(Members.SubTotal, InnerData.SubTotal, value)) InnerData.SubTotal = value; } } public double TaxAmt { get { LazyGet(); return InnerData.TaxAmt; } set { if (LazySet(Members.TaxAmt, InnerData.TaxAmt, value)) InnerData.TaxAmt = value; } } public string Freight { get { LazyGet(); return InnerData.Freight; } set { if (LazySet(Members.Freight, InnerData.Freight, value)) InnerData.Freight = value; } } public double TotalDue { get { LazyGet(); return InnerData.TotalDue; } set { if (LazySet(Members.TotalDue, InnerData.TotalDue, value)) InnerData.TotalDue = value; } } public Vendor Vendor { get { return ((ILookupHelper<Vendor>)InnerData.Vendor).GetItem(null); } set { if (LazySet(Members.Vendor, ((ILookupHelper<Vendor>)InnerData.Vendor).GetItem(null), value)) ((ILookupHelper<Vendor>)InnerData.Vendor).SetItem(value, null); } } public ShipMethod ShipMethod { get { return ((ILookupHelper<ShipMethod>)InnerData.ShipMethod).GetItem(null); } set { if (LazySet(Members.ShipMethod, ((ILookupHelper<ShipMethod>)InnerData.ShipMethod).GetItem(null), value)) ((ILookupHelper<ShipMethod>)InnerData.ShipMethod).SetItem(value, null); } } #endregion #region Members for interface ISchemaBase public System.DateTime ModifiedDate { get { LazyGet(); return InnerData.ModifiedDate; } set { if (LazySet(Members.ModifiedDate, InnerData.ModifiedDate, value)) InnerData.ModifiedDate = value; } } #endregion #region Members for interface INeo4jBase public string Uid { get { return InnerData.Uid; } set { KeySet(() => InnerData.Uid = value); } } #endregion #region Virtual Node Type public string NodeType { get { return InnerData.NodeType; } } #endregion #endregion #region Reflection private static PurchaseOrderHeaderMembers members = null; public static PurchaseOrderHeaderMembers Members { get { if (members == null) { lock (typeof(PurchaseOrderHeader)) { if (members == null) members = new PurchaseOrderHeaderMembers(); } } return members; } } public class PurchaseOrderHeaderMembers { internal PurchaseOrderHeaderMembers() { } #region Members for interface IPurchaseOrderHeader public Property RevisionNumber { get; } = Datastore.AdventureWorks.Model.Entities["PurchaseOrderHeader"].Properties["RevisionNumber"]; public Property Status { get; } = Datastore.AdventureWorks.Model.Entities["PurchaseOrderHeader"].Properties["Status"]; public Property OrderDate { get; } = Datastore.AdventureWorks.Model.Entities["PurchaseOrderHeader"].Properties["OrderDate"]; public Property ShipDate { get; } = Datastore.AdventureWorks.Model.Entities["PurchaseOrderHeader"].Properties["ShipDate"]; public Property SubTotal { get; } = Datastore.AdventureWorks.Model.Entities["PurchaseOrderHeader"].Properties["SubTotal"]; public Property TaxAmt { get; } = Datastore.AdventureWorks.Model.Entities["PurchaseOrderHeader"].Properties["TaxAmt"]; public Property Freight { get; } = Datastore.AdventureWorks.Model.Entities["PurchaseOrderHeader"].Properties["Freight"]; public Property TotalDue { get; } = Datastore.AdventureWorks.Model.Entities["PurchaseOrderHeader"].Properties["TotalDue"]; public Property Vendor { get; } = Datastore.AdventureWorks.Model.Entities["PurchaseOrderHeader"].Properties["Vendor"]; public Property ShipMethod { get; } = Datastore.AdventureWorks.Model.Entities["PurchaseOrderHeader"].Properties["ShipMethod"]; #endregion #region Members for interface ISchemaBase public Property ModifiedDate { get; } = Datastore.AdventureWorks.Model.Entities["SchemaBase"].Properties["ModifiedDate"]; #endregion #region Members for interface INeo4jBase public Property Uid { get; } = Datastore.AdventureWorks.Model.Entities["Neo4jBase"].Properties["Uid"]; #endregion } private static PurchaseOrderHeaderFullTextMembers fullTextMembers = null; public static PurchaseOrderHeaderFullTextMembers FullTextMembers { get { if (fullTextMembers == null) { lock (typeof(PurchaseOrderHeader)) { if (fullTextMembers == null) fullTextMembers = new PurchaseOrderHeaderFullTextMembers(); } } return fullTextMembers; } } public class PurchaseOrderHeaderFullTextMembers { internal PurchaseOrderHeaderFullTextMembers() { } } sealed public override Entity GetEntity() { if (entity == null) { lock (typeof(PurchaseOrderHeader)) { if (entity == null) entity = Datastore.AdventureWorks.Model.Entities["PurchaseOrderHeader"]; } } return entity; } private static PurchaseOrderHeaderEvents events = null; public static PurchaseOrderHeaderEvents Events { get { if (events == null) { lock (typeof(PurchaseOrderHeader)) { if (events == null) events = new PurchaseOrderHeaderEvents(); } } return events; } } public class PurchaseOrderHeaderEvents { #region OnNew private bool onNewIsRegistered = false; private EventHandler<PurchaseOrderHeader, EntityEventArgs> onNew; public event EventHandler<PurchaseOrderHeader, EntityEventArgs> OnNew { add { lock (this) { if (!onNewIsRegistered) { Entity.Events.OnNew -= onNewProxy; Entity.Events.OnNew += onNewProxy; onNewIsRegistered = true; } onNew += value; } } remove { lock (this) { onNew -= value; if (onNew == null && onNewIsRegistered) { Entity.Events.OnNew -= onNewProxy; onNewIsRegistered = false; } } } } private void onNewProxy(object sender, EntityEventArgs args) { EventHandler<PurchaseOrderHeader, EntityEventArgs> handler = onNew; if ((object)handler != null) handler.Invoke((PurchaseOrderHeader)sender, args); } #endregion #region OnDelete private bool onDeleteIsRegistered = false; private EventHandler<PurchaseOrderHeader, EntityEventArgs> onDelete; public event EventHandler<PurchaseOrderHeader, EntityEventArgs> OnDelete { add { lock (this) { if (!onDeleteIsRegistered) { Entity.Events.OnDelete -= onDeleteProxy; Entity.Events.OnDelete += onDeleteProxy; onDeleteIsRegistered = true; } onDelete += value; } } remove { lock (this) { onDelete -= value; if (onDelete == null && onDeleteIsRegistered) { Entity.Events.OnDelete -= onDeleteProxy; onDeleteIsRegistered = false; } } } } private void onDeleteProxy(object sender, EntityEventArgs args) { EventHandler<PurchaseOrderHeader, EntityEventArgs> handler = onDelete; if ((object)handler != null) handler.Invoke((PurchaseOrderHeader)sender, args); } #endregion #region OnSave private bool onSaveIsRegistered = false; private EventHandler<PurchaseOrderHeader, EntityEventArgs> onSave; public event EventHandler<PurchaseOrderHeader, EntityEventArgs> OnSave { add { lock (this) { if (!onSaveIsRegistered) { Entity.Events.OnSave -= onSaveProxy; Entity.Events.OnSave += onSaveProxy; onSaveIsRegistered = true; } onSave += value; } } remove { lock (this) { onSave -= value; if (onSave == null && onSaveIsRegistered) { Entity.Events.OnSave -= onSaveProxy; onSaveIsRegistered = false; } } } } private void onSaveProxy(object sender, EntityEventArgs args) { EventHandler<PurchaseOrderHeader, EntityEventArgs> handler = onSave; if ((object)handler != null) handler.Invoke((PurchaseOrderHeader)sender, args); } #endregion #region OnPropertyChange public static class OnPropertyChange { #region OnRevisionNumber private static bool onRevisionNumberIsRegistered = false; private static EventHandler<PurchaseOrderHeader, PropertyEventArgs> onRevisionNumber; public static event EventHandler<PurchaseOrderHeader, PropertyEventArgs> OnRevisionNumber { add { lock (typeof(OnPropertyChange)) { if (!onRevisionNumberIsRegistered) { Members.RevisionNumber.Events.OnChange -= onRevisionNumberProxy; Members.RevisionNumber.Events.OnChange += onRevisionNumberProxy; onRevisionNumberIsRegistered = true; } onRevisionNumber += value; } } remove { lock (typeof(OnPropertyChange)) { onRevisionNumber -= value; if (onRevisionNumber == null && onRevisionNumberIsRegistered) { Members.RevisionNumber.Events.OnChange -= onRevisionNumberProxy; onRevisionNumberIsRegistered = false; } } } } private static void onRevisionNumberProxy(object sender, PropertyEventArgs args) { EventHandler<PurchaseOrderHeader, PropertyEventArgs> handler = onRevisionNumber; if ((object)handler != null) handler.Invoke((PurchaseOrderHeader)sender, args); } #endregion #region OnStatus private static bool onStatusIsRegistered = false; private static EventHandler<PurchaseOrderHeader, PropertyEventArgs> onStatus; public static event EventHandler<PurchaseOrderHeader, PropertyEventArgs> OnStatus { add { lock (typeof(OnPropertyChange)) { if (!onStatusIsRegistered) { Members.Status.Events.OnChange -= onStatusProxy; Members.Status.Events.OnChange += onStatusProxy; onStatusIsRegistered = true; } onStatus += value; } } remove { lock (typeof(OnPropertyChange)) { onStatus -= value; if (onStatus == null && onStatusIsRegistered) { Members.Status.Events.OnChange -= onStatusProxy; onStatusIsRegistered = false; } } } } private static void onStatusProxy(object sender, PropertyEventArgs args) { EventHandler<PurchaseOrderHeader, PropertyEventArgs> handler = onStatus; if ((object)handler != null) handler.Invoke((PurchaseOrderHeader)sender, args); } #endregion #region OnOrderDate private static bool onOrderDateIsRegistered = false; private static EventHandler<PurchaseOrderHeader, PropertyEventArgs> onOrderDate; public static event EventHandler<PurchaseOrderHeader, PropertyEventArgs> OnOrderDate { add { lock (typeof(OnPropertyChange)) { if (!onOrderDateIsRegistered) { Members.OrderDate.Events.OnChange -= onOrderDateProxy; Members.OrderDate.Events.OnChange += onOrderDateProxy; onOrderDateIsRegistered = true; } onOrderDate += value; } } remove { lock (typeof(OnPropertyChange)) { onOrderDate -= value; if (onOrderDate == null && onOrderDateIsRegistered) { Members.OrderDate.Events.OnChange -= onOrderDateProxy; onOrderDateIsRegistered = false; } } } } private static void onOrderDateProxy(object sender, PropertyEventArgs args) { EventHandler<PurchaseOrderHeader, PropertyEventArgs> handler = onOrderDate; if ((object)handler != null) handler.Invoke((PurchaseOrderHeader)sender, args); } #endregion #region OnShipDate private static bool onShipDateIsRegistered = false; private static EventHandler<PurchaseOrderHeader, PropertyEventArgs> onShipDate; public static event EventHandler<PurchaseOrderHeader, PropertyEventArgs> OnShipDate { add { lock (typeof(OnPropertyChange)) { if (!onShipDateIsRegistered) { Members.ShipDate.Events.OnChange -= onShipDateProxy; Members.ShipDate.Events.OnChange += onShipDateProxy; onShipDateIsRegistered = true; } onShipDate += value; } } remove { lock (typeof(OnPropertyChange)) { onShipDate -= value; if (onShipDate == null && onShipDateIsRegistered) { Members.ShipDate.Events.OnChange -= onShipDateProxy; onShipDateIsRegistered = false; } } } } private static void onShipDateProxy(object sender, PropertyEventArgs args) { EventHandler<PurchaseOrderHeader, PropertyEventArgs> handler = onShipDate; if ((object)handler != null) handler.Invoke((PurchaseOrderHeader)sender, args); } #endregion #region OnSubTotal private static bool onSubTotalIsRegistered = false; private static EventHandler<PurchaseOrderHeader, PropertyEventArgs> onSubTotal; public static event EventHandler<PurchaseOrderHeader, PropertyEventArgs> OnSubTotal { add { lock (typeof(OnPropertyChange)) { if (!onSubTotalIsRegistered) { Members.SubTotal.Events.OnChange -= onSubTotalProxy; Members.SubTotal.Events.OnChange += onSubTotalProxy; onSubTotalIsRegistered = true; } onSubTotal += value; } } remove { lock (typeof(OnPropertyChange)) { onSubTotal -= value; if (onSubTotal == null && onSubTotalIsRegistered) { Members.SubTotal.Events.OnChange -= onSubTotalProxy; onSubTotalIsRegistered = false; } } } } private static void onSubTotalProxy(object sender, PropertyEventArgs args) { EventHandler<PurchaseOrderHeader, PropertyEventArgs> handler = onSubTotal; if ((object)handler != null) handler.Invoke((PurchaseOrderHeader)sender, args); } #endregion #region OnTaxAmt private static bool onTaxAmtIsRegistered = false; private static EventHandler<PurchaseOrderHeader, PropertyEventArgs> onTaxAmt; public static event EventHandler<PurchaseOrderHeader, PropertyEventArgs> OnTaxAmt { add { lock (typeof(OnPropertyChange)) { if (!onTaxAmtIsRegistered) { Members.TaxAmt.Events.OnChange -= onTaxAmtProxy; Members.TaxAmt.Events.OnChange += onTaxAmtProxy; onTaxAmtIsRegistered = true; } onTaxAmt += value; } } remove { lock (typeof(OnPropertyChange)) { onTaxAmt -= value; if (onTaxAmt == null && onTaxAmtIsRegistered) { Members.TaxAmt.Events.OnChange -= onTaxAmtProxy; onTaxAmtIsRegistered = false; } } } } private static void onTaxAmtProxy(object sender, PropertyEventArgs args) { EventHandler<PurchaseOrderHeader, PropertyEventArgs> handler = onTaxAmt; if ((object)handler != null) handler.Invoke((PurchaseOrderHeader)sender, args); } #endregion #region OnFreight private static bool onFreightIsRegistered = false; private static EventHandler<PurchaseOrderHeader, PropertyEventArgs> onFreight; public static event EventHandler<PurchaseOrderHeader, PropertyEventArgs> OnFreight { add { lock (typeof(OnPropertyChange)) { if (!onFreightIsRegistered) { Members.Freight.Events.OnChange -= onFreightProxy; Members.Freight.Events.OnChange += onFreightProxy; onFreightIsRegistered = true; } onFreight += value; } } remove { lock (typeof(OnPropertyChange)) { onFreight -= value; if (onFreight == null && onFreightIsRegistered) { Members.Freight.Events.OnChange -= onFreightProxy; onFreightIsRegistered = false; } } } } private static void onFreightProxy(object sender, PropertyEventArgs args) { EventHandler<PurchaseOrderHeader, PropertyEventArgs> handler = onFreight; if ((object)handler != null) handler.Invoke((PurchaseOrderHeader)sender, args); } #endregion #region OnTotalDue private static bool onTotalDueIsRegistered = false; private static EventHandler<PurchaseOrderHeader, PropertyEventArgs> onTotalDue; public static event EventHandler<PurchaseOrderHeader, PropertyEventArgs> OnTotalDue { add { lock (typeof(OnPropertyChange)) { if (!onTotalDueIsRegistered) { Members.TotalDue.Events.OnChange -= onTotalDueProxy; Members.TotalDue.Events.OnChange += onTotalDueProxy; onTotalDueIsRegistered = true; } onTotalDue += value; } } remove { lock (typeof(OnPropertyChange)) { onTotalDue -= value; if (onTotalDue == null && onTotalDueIsRegistered) { Members.TotalDue.Events.OnChange -= onTotalDueProxy; onTotalDueIsRegistered = false; } } } } private static void onTotalDueProxy(object sender, PropertyEventArgs args) { EventHandler<PurchaseOrderHeader, PropertyEventArgs> handler = onTotalDue; if ((object)handler != null) handler.Invoke((PurchaseOrderHeader)sender, args); } #endregion #region OnVendor private static bool onVendorIsRegistered = false; private static EventHandler<PurchaseOrderHeader, PropertyEventArgs> onVendor; public static event EventHandler<PurchaseOrderHeader, PropertyEventArgs> OnVendor { add { lock (typeof(OnPropertyChange)) { if (!onVendorIsRegistered) { Members.Vendor.Events.OnChange -= onVendorProxy; Members.Vendor.Events.OnChange += onVendorProxy; onVendorIsRegistered = true; } onVendor += value; } } remove { lock (typeof(OnPropertyChange)) { onVendor -= value; if (onVendor == null && onVendorIsRegistered) { Members.Vendor.Events.OnChange -= onVendorProxy; onVendorIsRegistered = false; } } } } private static void onVendorProxy(object sender, PropertyEventArgs args) { EventHandler<PurchaseOrderHeader, PropertyEventArgs> handler = onVendor; if ((object)handler != null) handler.Invoke((PurchaseOrderHeader)sender, args); } #endregion #region OnShipMethod private static bool onShipMethodIsRegistered = false; private static EventHandler<PurchaseOrderHeader, PropertyEventArgs> onShipMethod; public static event EventHandler<PurchaseOrderHeader, PropertyEventArgs> OnShipMethod { add { lock (typeof(OnPropertyChange)) { if (!onShipMethodIsRegistered) { Members.ShipMethod.Events.OnChange -= onShipMethodProxy; Members.ShipMethod.Events.OnChange += onShipMethodProxy; onShipMethodIsRegistered = true; } onShipMethod += value; } } remove { lock (typeof(OnPropertyChange)) { onShipMethod -= value; if (onShipMethod == null && onShipMethodIsRegistered) { Members.ShipMethod.Events.OnChange -= onShipMethodProxy; onShipMethodIsRegistered = false; } } } } private static void onShipMethodProxy(object sender, PropertyEventArgs args) { EventHandler<PurchaseOrderHeader, PropertyEventArgs> handler = onShipMethod; if ((object)handler != null) handler.Invoke((PurchaseOrderHeader)sender, args); } #endregion #region OnModifiedDate private static bool onModifiedDateIsRegistered = false; private static EventHandler<PurchaseOrderHeader, PropertyEventArgs> onModifiedDate; public static event EventHandler<PurchaseOrderHeader, PropertyEventArgs> OnModifiedDate { add { lock (typeof(OnPropertyChange)) { if (!onModifiedDateIsRegistered) { Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy; Members.ModifiedDate.Events.OnChange += onModifiedDateProxy; onModifiedDateIsRegistered = true; } onModifiedDate += value; } } remove { lock (typeof(OnPropertyChange)) { onModifiedDate -= value; if (onModifiedDate == null && onModifiedDateIsRegistered) { Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy; onModifiedDateIsRegistered = false; } } } } private static void onModifiedDateProxy(object sender, PropertyEventArgs args) { EventHandler<PurchaseOrderHeader, PropertyEventArgs> handler = onModifiedDate; if ((object)handler != null) handler.Invoke((PurchaseOrderHeader)sender, args); } #endregion #region OnUid private static bool onUidIsRegistered = false; private static EventHandler<PurchaseOrderHeader, PropertyEventArgs> onUid; public static event EventHandler<PurchaseOrderHeader, PropertyEventArgs> OnUid { add { lock (typeof(OnPropertyChange)) { if (!onUidIsRegistered) { Members.Uid.Events.OnChange -= onUidProxy; Members.Uid.Events.OnChange += onUidProxy; onUidIsRegistered = true; } onUid += value; } } remove { lock (typeof(OnPropertyChange)) { onUid -= value; if (onUid == null && onUidIsRegistered) { Members.Uid.Events.OnChange -= onUidProxy; onUidIsRegistered = false; } } } } private static void onUidProxy(object sender, PropertyEventArgs args) { EventHandler<PurchaseOrderHeader, PropertyEventArgs> handler = onUid; if ((object)handler != null) handler.Invoke((PurchaseOrderHeader)sender, args); } #endregion } #endregion } #endregion #region IPurchaseOrderHeaderOriginalData public IPurchaseOrderHeaderOriginalData OriginalVersion { get { return this; } } #region Members for interface IPurchaseOrderHeader string IPurchaseOrderHeaderOriginalData.RevisionNumber { get { return OriginalData.RevisionNumber; } } string IPurchaseOrderHeaderOriginalData.Status { get { return OriginalData.Status; } } System.DateTime IPurchaseOrderHeaderOriginalData.OrderDate { get { return OriginalData.OrderDate; } } System.DateTime IPurchaseOrderHeaderOriginalData.ShipDate { get { return OriginalData.ShipDate; } } double IPurchaseOrderHeaderOriginalData.SubTotal { get { return OriginalData.SubTotal; } } double IPurchaseOrderHeaderOriginalData.TaxAmt { get { return OriginalData.TaxAmt; } } string IPurchaseOrderHeaderOriginalData.Freight { get { return OriginalData.Freight; } } double IPurchaseOrderHeaderOriginalData.TotalDue { get { return OriginalData.TotalDue; } } Vendor IPurchaseOrderHeaderOriginalData.Vendor { get { return ((ILookupHelper<Vendor>)OriginalData.Vendor).GetOriginalItem(null); } } ShipMethod IPurchaseOrderHeaderOriginalData.ShipMethod { get { return ((ILookupHelper<ShipMethod>)OriginalData.ShipMethod).GetOriginalItem(null); } } #endregion #region Members for interface ISchemaBase ISchemaBaseOriginalData ISchemaBase.OriginalVersion { get { return this; } } System.DateTime ISchemaBaseOriginalData.ModifiedDate { get { return OriginalData.ModifiedDate; } } #endregion #region Members for interface INeo4jBase INeo4jBaseOriginalData INeo4jBase.OriginalVersion { get { return this; } } string INeo4jBaseOriginalData.Uid { get { return OriginalData.Uid; } } #endregion #endregion } }
using System; using System.Linq.Expressions; using System.Threading.Tasks; using GraphQL.Builders; using GraphQL.Resolvers; using GraphQL.Subscription; using GraphQL.Types.Relay; using GraphQL.Utilities; namespace GraphQL.Types { /// <summary> /// Represents an interface for all complex (that is, having their own properties) input and output graph types. /// </summary> public interface IComplexGraphType : IGraphType { /// <summary> /// Returns a list of the fields configured for this graph type. /// </summary> TypeFields Fields { get; } /// <summary> /// Adds a field to this graph type. /// </summary> FieldType AddField(FieldType fieldType); /// <summary> /// Returns <see langword="true"/> when a field matching the specified name is configured for this graph type. /// </summary> bool HasField(string name); /// <summary> /// Returns the <see cref="FieldType"/> for the field matching the specified name that /// is configured for this graph type, or <see langword="null"/> if none is found. /// </summary> FieldType? GetField(string name); } /// <summary> /// Represents a default base class for all complex (that is, having their own properties) input and output graph types. /// </summary> public abstract class ComplexGraphType<TSourceType> : GraphType, IComplexGraphType { internal const string ORIGINAL_EXPRESSION_PROPERTY_NAME = nameof(ORIGINAL_EXPRESSION_PROPERTY_NAME); /// <inheritdoc/> protected ComplexGraphType() { Description ??= typeof(TSourceType).Description(); DeprecationReason ??= typeof(TSourceType).ObsoleteMessage(); } /// <inheritdoc/> public TypeFields Fields { get; } = new TypeFields(); /// <inheritdoc/> public bool HasField(string name) { if (string.IsNullOrWhiteSpace(name)) return false; // DO NOT USE LINQ ON HOT PATH foreach (var field in Fields.List) { if (string.Equals(field.Name, name, StringComparison.Ordinal)) return true; } return false; } /// <inheritdoc/> public FieldType? GetField(string name) { // DO NOT USE LINQ ON HOT PATH if (!string.IsNullOrWhiteSpace(name)) { foreach (var field in Fields.List) { if (string.Equals(field.Name, name, StringComparison.Ordinal)) return field; } } return null; } /// <inheritdoc/> public virtual FieldType AddField(FieldType fieldType) { if (fieldType == null) throw new ArgumentNullException(nameof(fieldType)); NameValidator.ValidateNameNotNull(fieldType.Name, NamedElement.Field); if (!fieldType.ResolvedType.IsGraphQLTypeReference()) { if (this is IInputObjectGraphType) { if (fieldType.ResolvedType != null ? fieldType.ResolvedType.IsInputType() == false : fieldType.Type?.IsInputType() == false) throw new ArgumentOutOfRangeException(nameof(fieldType), $"Input type '{Name ?? GetType().GetFriendlyName()}' can have fields only of input types: ScalarGraphType, EnumerationGraphType or IInputObjectGraphType. Field '{fieldType.Name}' has an output type."); } else { if (fieldType.ResolvedType != null ? fieldType.ResolvedType.IsOutputType() == false : fieldType.Type?.IsOutputType() == false) throw new ArgumentOutOfRangeException(nameof(fieldType), $"Output type '{Name ?? GetType().GetFriendlyName()}' can have fields only of output types: ScalarGraphType, ObjectGraphType, InterfaceGraphType, UnionGraphType or EnumerationGraphType. Field '{fieldType.Name}' has an input type."); } } if (HasField(fieldType.Name)) { throw new ArgumentOutOfRangeException(nameof(fieldType), $"A field with the name '{fieldType.Name}' is already registered for GraphType '{Name ?? GetType().Name}'"); } if (fieldType.ResolvedType == null) { if (fieldType.Type == null) { throw new ArgumentOutOfRangeException(nameof(fieldType), $"The declared field '{fieldType.Name ?? fieldType.GetType().GetFriendlyName()}' on '{Name ?? GetType().GetFriendlyName()}' requires a field '{nameof(fieldType.Type)}' when no '{nameof(fieldType.ResolvedType)}' is provided."); } else if (!fieldType.Type.IsGraphType()) { throw new ArgumentOutOfRangeException(nameof(fieldType), $"The declared Field type '{fieldType.Type.Name}' should derive from GraphType."); } } Fields.Add(fieldType); return fieldType; } /// <summary> /// Adds a field with the specified properties to this graph type. /// </summary> /// <param name="type">The .NET type of the graph type of this field.</param> /// <param name="name">The name of the field.</param> /// <param name="description">The description of the field.</param> /// <param name="arguments">A list of arguments for the field.</param> /// <param name="resolve">A field resolver delegate. Only applicable to fields of output graph types. If not specified, <see cref="NameFieldResolver"/> will be used.</param> /// <param name="deprecationReason">The deprecation reason for the field. Applicable only for output graph types.</param> /// <returns>The newly added <see cref="FieldType"/> instance.</returns> public FieldType Field( Type type, string name, string? description = null, QueryArguments? arguments = null, Func<IResolveFieldContext<TSourceType>, object?>? resolve = null, string? deprecationReason = null) { return AddField(new FieldType { Name = name, Description = description, DeprecationReason = deprecationReason, Type = type, Arguments = arguments, Resolver = resolve != null ? new FuncFieldResolver<TSourceType, object>(resolve) : null }); } /// <summary> /// Adds a field with the specified properties to this graph type. /// </summary> /// <typeparam name="TGraphType">The .NET type of the graph type of this field.</typeparam> /// <param name="name">The name of the field.</param> /// <param name="description">The description of the field.</param> /// <param name="arguments">A list of arguments for the field.</param> /// <param name="resolve">A field resolver delegate. Only applicable to fields of output graph types. If not specified, <see cref="NameFieldResolver"/> will be used.</param> /// <param name="deprecationReason">The deprecation reason for the field. Applicable only for output graph types.</param> /// <returns>The newly added <see cref="FieldType"/> instance.</returns> public FieldType Field<TGraphType>( string name, string? description = null, QueryArguments? arguments = null, Func<IResolveFieldContext<TSourceType>, object?>? resolve = null, string? deprecationReason = null) where TGraphType : IGraphType { return AddField(new FieldType { Name = name, Description = description, DeprecationReason = deprecationReason, Type = typeof(TGraphType), Arguments = arguments, Resolver = resolve != null ? new FuncFieldResolver<TSourceType, object>(resolve) : null }); } /// <summary> /// Adds a field with the specified properties to this graph type. /// </summary> /// <typeparam name="TGraphType">The .NET type of the graph type of this field.</typeparam> /// <param name="name">The name of the field.</param> /// <param name="description">The description of the field.</param> /// <param name="arguments">A list of arguments for the field.</param> /// <param name="resolve">A field resolver delegate. Only applicable to fields of output graph types. If not specified, <see cref="NameFieldResolver"/> will be used.</param> /// <param name="deprecationReason">The deprecation reason for the field. Applicable only for output graph types.</param> /// <returns>The newly added <see cref="FieldType"/> instance.</returns> public FieldType FieldDelegate<TGraphType>( string name, string? description = null, QueryArguments? arguments = null, Delegate? resolve = null, string? deprecationReason = null) where TGraphType : IGraphType { return AddField(new FieldType { Name = name, Description = description, DeprecationReason = deprecationReason, Type = typeof(TGraphType), Arguments = arguments, Resolver = resolve != null ? new DelegateFieldModelBinderResolver(resolve) : null }); } /// <summary> /// Adds a field with the specified properties to this graph type. /// </summary> /// <param name="type">The .NET type of the graph type of this field.</param> /// <param name="name">The name of the field.</param> /// <param name="description">The description of the field.</param> /// <param name="arguments">A list of arguments for the field.</param> /// <param name="resolve">A field resolver delegate. Only applicable to fields of output graph types. If not specified, <see cref="NameFieldResolver"/> will be used.</param> /// <param name="deprecationReason">The deprecation reason for the field. Applicable only for output graph types.</param> /// <returns>The newly added <see cref="FieldType"/> instance.</returns> public FieldType FieldAsync( Type type, string name, string? description = null, QueryArguments? arguments = null, Func<IResolveFieldContext<TSourceType>, Task<object?>>? resolve = null, string? deprecationReason = null) { return AddField(new FieldType { Name = name, Description = description, DeprecationReason = deprecationReason, Type = type, Arguments = arguments, Resolver = resolve != null ? new AsyncFieldResolver<TSourceType, object>(resolve) : null }); } /// <summary> /// Adds a field with the specified properties to this graph type. /// </summary> /// <typeparam name="TGraphType">The .NET type of the graph type of this field.</typeparam> /// <param name="name">The name of the field.</param> /// <param name="description">The description of the field.</param> /// <param name="arguments">A list of arguments for the field.</param> /// <param name="resolve">A field resolver delegate. Only applicable to fields of output graph types. If not specified, <see cref="NameFieldResolver"/> will be used.</param> /// <param name="deprecationReason">The deprecation reason for the field. Applicable only for output graph types.</param> /// <returns>The newly added <see cref="FieldType"/> instance.</returns> public FieldType FieldAsync<TGraphType>( string name, string? description = null, QueryArguments? arguments = null, Func<IResolveFieldContext<TSourceType>, Task<object?>>? resolve = null, string? deprecationReason = null) where TGraphType : IGraphType { return AddField(new FieldType { Name = name, Description = description, DeprecationReason = deprecationReason, Type = typeof(TGraphType), Arguments = arguments, Resolver = resolve != null ? new AsyncFieldResolver<TSourceType, object>(resolve) : null }); } /// <summary> /// Adds a field with the specified properties to this graph type. /// </summary> /// <typeparam name="TGraphType">The .NET type of the graph type of this field.</typeparam> /// <typeparam name="TReturnType">The type of the return value of the field resolver delegate.</typeparam> /// <param name="name">The name of the field.</param> /// <param name="description">The description of the field.</param> /// <param name="arguments">A list of arguments for the field.</param> /// <param name="resolve">A field resolver delegate. Only applicable to fields of output graph types. If not specified, <see cref="NameFieldResolver"/> will be used.</param> /// <param name="deprecationReason">The deprecation reason for the field. Applicable only for output graph types.</param> /// <returns>The newly added <see cref="FieldType"/> instance.</returns> public FieldType FieldAsync<TGraphType, TReturnType>( string name, string? description = null, QueryArguments? arguments = null, Func<IResolveFieldContext<TSourceType>, Task<TReturnType?>>? resolve = null, string? deprecationReason = null) where TGraphType : IGraphType { return AddField(new FieldType { Name = name, Description = description, DeprecationReason = deprecationReason, Type = typeof(TGraphType), Arguments = arguments, Resolver = resolve != null ? new AsyncFieldResolver<TSourceType, TReturnType>(resolve) : null }); } public FieldType FieldSubscribe<TGraphType>( string name, string? description = null, QueryArguments? arguments = null, Func<IResolveFieldContext<TSourceType>, object?>? resolve = null, Func<IResolveEventStreamContext, IObservable<object?>>? subscribe = null, string? deprecationReason = null) where TGraphType : IGraphType { return AddField(new EventStreamFieldType { Name = name, Description = description, DeprecationReason = deprecationReason, Type = typeof(TGraphType), Arguments = arguments, Resolver = resolve != null ? new FuncFieldResolver<TSourceType, object>(resolve) : null, Subscriber = subscribe != null ? new EventStreamResolver<object>(subscribe) : null }); } public FieldType FieldSubscribeAsync<TGraphType>( string name, string? description = null, QueryArguments? arguments = null, Func<IResolveFieldContext<TSourceType>, object?>? resolve = null, Func<IResolveEventStreamContext, Task<IObservable<object?>>>? subscribeAsync = null, string? deprecationReason = null) where TGraphType : IGraphType { return AddField(new EventStreamFieldType { Name = name, Description = description, DeprecationReason = deprecationReason, Type = typeof(TGraphType), Arguments = arguments, Resolver = resolve != null ? new FuncFieldResolver<TSourceType, object>(resolve) : null, AsyncSubscriber = subscribeAsync != null ? new AsyncEventStreamResolver<object>(subscribeAsync) : null }); } /// <summary> /// Adds a new field to the complex graph type and returns a builder for this newly added field. /// </summary> /// <typeparam name="TGraphType">The .NET type of the graph type of this field.</typeparam> /// <typeparam name="TReturnType">The return type of the field resolver.</typeparam> /// <param name="name">The name of the field.</param> public virtual FieldBuilder<TSourceType, TReturnType> Field<TGraphType, TReturnType>(string name = "default") where TGraphType : IGraphType { var builder = FieldBuilder.Create<TSourceType, TReturnType>(typeof(TGraphType)) .Name(name); AddField(builder.FieldType); return builder; } /// <summary> /// Adds a new field to the complex graph type and returns a builder for this newly added field. /// </summary> /// <typeparam name="TGraphType">The .NET type of the graph type of this field.</typeparam> public virtual FieldBuilder<TSourceType, object> Field<TGraphType>() where TGraphType : IGraphType => Field<TGraphType, object>(); /// <summary> /// Adds a new field to the complex graph type and returns a builder for this newly added field that is linked to a property of the source object. /// <br/><br/> /// Note: this method uses dynamic compilation and therefore allocates a relatively large amount of /// memory in managed heap, ~1KB. Do not use this method in cases with limited memory requirements. /// </summary> /// <typeparam name="TProperty">The return type of the field.</typeparam> /// <param name="name">The name of this field.</param> /// <param name="expression">The property of the source object represented within an expression.</param> /// <param name="nullable">Indicates if this field should be nullable or not. Ignored when <paramref name="type"/> is specified.</param> /// <param name="type">The graph type of the field; if <see langword="null"/> then will be inferred from the specified expression via registered schema mappings.</param> public virtual FieldBuilder<TSourceType, TProperty> Field<TProperty>( string name, Expression<Func<TSourceType, TProperty>> expression, bool nullable = false, Type? type = null) { try { if (type == null) type = typeof(TProperty).GetGraphTypeFromType(nullable, this is IInputObjectGraphType ? TypeMappingMode.InputType : TypeMappingMode.OutputType); } catch (ArgumentOutOfRangeException exp) { throw new ArgumentException($"The GraphQL type for field '{Name ?? GetType().Name}.{name}' could not be derived implicitly from expression '{expression}'.", exp); } var builder = FieldBuilder.Create<TSourceType, TProperty>(type) .Name(name) .Resolve(new ExpressionFieldResolver<TSourceType, TProperty>(expression)) .Description(expression.DescriptionOf()) .DeprecationReason(expression.DeprecationReasonOf()) .DefaultValue(expression.DefaultValueOf()); if (expression.Body is MemberExpression expr) { builder.FieldType.Metadata[ORIGINAL_EXPRESSION_PROPERTY_NAME] = expr.Member.Name; } AddField(builder.FieldType); return builder; } /// <summary> /// Adds a new field to the complex graph type and returns a builder for this newly added field that is linked to a property of the source object. /// The default name of this field is inferred by the property represented within the expression. /// <br/><br/> /// Note: this method uses dynamic compilation and therefore allocates a relatively large amount of /// memory in managed heap, ~1KB. Do not use this method in cases with limited memory requirements. /// </summary> /// <typeparam name="TProperty">The return type of the field.</typeparam> /// <param name="expression">The property of the source object represented within an expression.</param> /// <param name="nullable">Indicates if this field should be nullable or not. Ignored when <paramref name="type"/> is specified.</param> /// <param name="type">The graph type of the field; if <see langword="null"/> then will be inferred from the specified expression via registered schema mappings.</param> public virtual FieldBuilder<TSourceType, TProperty> Field<TProperty>( Expression<Func<TSourceType, TProperty>> expression, bool nullable = false, Type? type = null) { string name; try { name = expression.NameOf(); } catch { throw new ArgumentException( $"Cannot infer a Field name from the expression: '{expression.Body}' " + $"on parent GraphQL type: '{Name ?? GetType().Name}'."); } return Field(name, expression, nullable, type); } /// <inheritdoc cref="ConnectionBuilder{TSourceType}.Create{TNodeType}(string)"/> public ConnectionBuilder<TSourceType> Connection<TNodeType>() where TNodeType : IGraphType { var builder = ConnectionBuilder.Create<TNodeType, TSourceType>(); AddField(builder.FieldType); return builder; } /// <inheritdoc cref="ConnectionBuilder{TSourceType}.Create{TNodeType, TEdgeType}(string)"/> public ConnectionBuilder<TSourceType> Connection<TNodeType, TEdgeType>() where TNodeType : IGraphType where TEdgeType : EdgeType<TNodeType> { var builder = ConnectionBuilder.Create<TNodeType, TEdgeType, TSourceType>(); AddField(builder.FieldType); return builder; } /// <inheritdoc cref="ConnectionBuilder{TSourceType}.Create{TNodeType, TEdgeType, TConnectionType}(string)"/> public ConnectionBuilder<TSourceType> Connection<TNodeType, TEdgeType, TConnectionType>() where TNodeType : IGraphType where TEdgeType : EdgeType<TNodeType> where TConnectionType : ConnectionType<TNodeType, TEdgeType> { var builder = ConnectionBuilder.Create<TNodeType, TEdgeType, TConnectionType, TSourceType>(); AddField(builder.FieldType); return builder; } } }
// Copyright (C) 2014 dot42 // // Original filename: List.cs // // 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.Collections.ObjectModel; using Dot42; using Dot42.Collections; using Java.Lang; using Java.Util; namespace System.Collections.Generic { public class List<T> : IList<T>, IList { private readonly ArrayList<T> list; /// <summary> /// Default ctor /// </summary> public List() { list = new ArrayList<T>(); } /// <summary> /// Copy ctor /// </summary> public List(IEnumerable<T> source) { var colSource = source as Java.Util.ICollection<T>; if (colSource != null) { list = new ArrayList<T>(colSource); } else { list = new ArrayList<T>(); foreach (var item in source) { list.Add(item); } } } /// <summary> /// Copy ctor /// </summary> public List(IIterable<T> source) { var colSource = source as Java.Util.ICollection<T>; if (colSource != null) { list = new ArrayList<T>(colSource); } else { list = new ArrayList<T>(); foreach (var item in source.AsEnumerable()) { list.Add(item); } } } /// <summary> /// Initialize a new list with initial capacity /// </summary> public List(int capacity) { list = new ArrayList<T>(capacity); } /// <summary> /// Gets an enummerator to enumerate over all elements in this sequence. /// </summary> /// <returns></returns> public IEnumerator<T> GetEnumerator() { return new Enumerator<T>(list); } /// <summary> /// Gets an enummerator to enumerate over all elements in this sequence. /// </summary> /// <returns></returns> IEnumerator<T> IEnumerable<T>.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Gets an enummerator to enumerate over all elements in this sequence. /// </summary> /// <returns></returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Gets number of elements in this collection. /// </summary> public int Count { get { return list.Size(); } } /// <summary> /// Is this collection thread safe. /// </summary> public bool IsSynchronized { get { return false; } } /// <summary> /// Gets the object used to synchronize access to this collection. /// </summary> public object SyncRoot { get { return list; } } /// <summary> /// Copy all my elements to the given array starting at the given index. /// </summary> /// <param name="array">Array to copy my elements into.</param> /// <param name="index">Position in <see cref="array"/> where the first element will be copied to.</param> public void CopyTo(Array array, int index) { Dot42.Collections.Collections.CopyTo(list, array, index); } /// <summary> /// Does this list have a fixed size? /// </summary> public bool IsFixedSize { get { return false; } } /// <summary> /// Is this list read-only. /// </summary> public bool IsReadOnly { get { return false; } } /// <summary> /// Gets/sets an item in this list at the given index. /// </summary> public T this[int index] { get { return list.Get(index); } set { list.Set(index, value); } } /// <summary> /// Gets/sets an item in this list at the given index. /// </summary> object IList.this[int index] { get { return list.Get(index); } set { list.Set(index, (T) value); } } /// <summary> /// Add ths given element to the end of this list. /// </summary> /// <returns>The index at which the element was added or -1 if the element was not added.</returns> public int Add(object element) { var rc = list.Size(); list.Add((T) element); return rc; } /// <summary> /// Add the given item to this collection. /// </summary> public void Add(T item) { list.Add(item); } int IList<T>.Add(T element) { var rc = list.Size(); list.Add(element); return rc; } /// <summary> /// Adds the elements of the specified collection to the end of this List. /// </summary> public void AddRange(IEnumerable<T> collection) { foreach (var element in collection) { list.Add(element); } } /// <summary> /// Is the given element contained in this list? /// </summary> public bool Contains(T element) { return list.Contains(element); } bool ICollection<T>.Remove(T item) { return list.Remove(item); } /// <summary> /// Removes the first occurrance of the given element from this list. /// </summary> public bool Remove(T element) { return list.Remove(element); } /// <summary> /// Removes the first occurrance of the given element from this list. /// </summary> void IList<T>.Remove(T element) { list.Remove(element); } public int IndexOf(T element) { return list.IndexOf(element); } public void Insert(int index, T element) { list.Add(index, element); } public void Clear() { list.Clear(); } public void CopyTo(T[] array, int index) { Dot42.Collections.Collections.CopyTo(list, array, index); } public bool Contains(object element) { return list.Contains(element); } public int IndexOf(object element) { return list.IndexOf(element); } public void Insert(int index, object element) { list.Add(index, (T) element); } public void Remove(object element) { list.Remove(element); } public void RemoveAt(int index) { list.Remove(list.Get(index)); } /// <summary> /// Copy all elements into a new array. /// </summary> public T[] ToArray() { var result = new T[list.Count]; return list.ToArray(result); } /// <summary> /// Return this list as readonly. /// </summary> /// <returns></returns> public ReadOnlyCollection<T> AsReadOnly() { return new ReadOnlyCollection<T>(this); } public class Enumerator<T> : IteratorWrapper<T> { public Enumerator(IIterable<T> iterable) : base(iterable) { } } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace ParentLoad.Business.ERCLevel { /// <summary> /// B08_Region (editable child object).<br/> /// This is a generated base class of <see cref="B08_Region"/> business object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="B09_CityObjects"/> of type <see cref="B09_CityColl"/> (1:M relation to <see cref="B10_City"/>)<br/> /// This class is an item of <see cref="B07_RegionColl"/> collection. /// </remarks> [Serializable] public partial class B08_Region : BusinessBase<B08_Region> { #region Static Fields private static int _lastID; #endregion #region State Fields [NotUndoable] [NonSerialized] internal int parent_Country_ID = 0; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Region_ID"/> property. /// </summary> public static readonly PropertyInfo<int> Region_IDProperty = RegisterProperty<int>(p => p.Region_ID, "Region ID"); /// <summary> /// Gets the Region ID. /// </summary> /// <value>The Region ID.</value> public int Region_ID { get { return GetProperty(Region_IDProperty); } } /// <summary> /// Maintains metadata about <see cref="Region_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Region_NameProperty = RegisterProperty<string>(p => p.Region_Name, "Region Name"); /// <summary> /// Gets or sets the Region Name. /// </summary> /// <value>The Region Name.</value> public string Region_Name { get { return GetProperty(Region_NameProperty); } set { SetProperty(Region_NameProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="B09_Region_SingleObject"/> property. /// </summary> public static readonly PropertyInfo<B09_Region_Child> B09_Region_SingleObjectProperty = RegisterProperty<B09_Region_Child>(p => p.B09_Region_SingleObject, "B09 Region Single Object", RelationshipTypes.Child); /// <summary> /// Gets the B09 Region Single Object ("parent load" child property). /// </summary> /// <value>The B09 Region Single Object.</value> public B09_Region_Child B09_Region_SingleObject { get { return GetProperty(B09_Region_SingleObjectProperty); } private set { LoadProperty(B09_Region_SingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="B09_Region_ASingleObject"/> property. /// </summary> public static readonly PropertyInfo<B09_Region_ReChild> B09_Region_ASingleObjectProperty = RegisterProperty<B09_Region_ReChild>(p => p.B09_Region_ASingleObject, "B09 Region ASingle Object", RelationshipTypes.Child); /// <summary> /// Gets the B09 Region ASingle Object ("parent load" child property). /// </summary> /// <value>The B09 Region ASingle Object.</value> public B09_Region_ReChild B09_Region_ASingleObject { get { return GetProperty(B09_Region_ASingleObjectProperty); } private set { LoadProperty(B09_Region_ASingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="B09_CityObjects"/> property. /// </summary> public static readonly PropertyInfo<B09_CityColl> B09_CityObjectsProperty = RegisterProperty<B09_CityColl>(p => p.B09_CityObjects, "B09 City Objects", RelationshipTypes.Child); /// <summary> /// Gets the B09 City Objects ("parent load" child property). /// </summary> /// <value>The B09 City Objects.</value> public B09_CityColl B09_CityObjects { get { return GetProperty(B09_CityObjectsProperty); } private set { LoadProperty(B09_CityObjectsProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="B08_Region"/> object. /// </summary> /// <returns>A reference to the created <see cref="B08_Region"/> object.</returns> internal static B08_Region NewB08_Region() { return DataPortal.CreateChild<B08_Region>(); } /// <summary> /// Factory method. Loads a <see cref="B08_Region"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="B08_Region"/> object.</returns> internal static B08_Region GetB08_Region(SafeDataReader dr) { B08_Region obj = new B08_Region(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); obj.LoadProperty(B09_CityObjectsProperty, B09_CityColl.NewB09_CityColl()); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="B08_Region"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public B08_Region() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="B08_Region"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { LoadProperty(Region_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID)); LoadProperty(B09_Region_SingleObjectProperty, DataPortal.CreateChild<B09_Region_Child>()); LoadProperty(B09_Region_ASingleObjectProperty, DataPortal.CreateChild<B09_Region_ReChild>()); LoadProperty(B09_CityObjectsProperty, DataPortal.CreateChild<B09_CityColl>()); var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="B08_Region"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Region_IDProperty, dr.GetInt32("Region_ID")); LoadProperty(Region_NameProperty, dr.GetString("Region_Name")); // parent properties parent_Country_ID = dr.GetInt32("Parent_Country_ID"); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Loads child <see cref="B09_Region_Child"/> object. /// </summary> /// <param name="child">The child object to load.</param> internal void LoadChild(B09_Region_Child child) { LoadProperty(B09_Region_SingleObjectProperty, child); } /// <summary> /// Loads child <see cref="B09_Region_ReChild"/> object. /// </summary> /// <param name="child">The child object to load.</param> internal void LoadChild(B09_Region_ReChild child) { LoadProperty(B09_Region_ASingleObjectProperty, child); } /// <summary> /// Inserts a new <see cref="B08_Region"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(B06_Country parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddB08_Region", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Parent_Country_ID", parent.Country_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Region_ID", ReadProperty(Region_IDProperty)).Direction = ParameterDirection.Output; cmd.Parameters.AddWithValue("@Region_Name", ReadProperty(Region_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); LoadProperty(Region_IDProperty, (int) cmd.Parameters["@Region_ID"].Value); } // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Updates in the database all changes made to the <see cref="B08_Region"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update() { if (!IsDirty) return; using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateB08_Region", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Region_ID", ReadProperty(Region_IDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Region_Name", ReadProperty(Region_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Self deletes the <see cref="B08_Region"/> object from database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf() { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { // flushes all pending data operations FieldManager.UpdateChildren(this); using (var cmd = new SqlCommand("DeleteB08_Region", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Region_ID", ReadProperty(Region_IDProperty)).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } // removes all previous references to children LoadProperty(B09_Region_SingleObjectProperty, DataPortal.CreateChild<B09_Region_Child>()); LoadProperty(B09_Region_ASingleObjectProperty, DataPortal.CreateChild<B09_Region_ReChild>()); LoadProperty(B09_CityObjectsProperty, DataPortal.CreateChild<B09_CityColl>()); } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
using FluentMvc.Conventions; namespace FluentMvc.Spec.Unit.ConfigurationDsl { using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Web.Mvc; using Configuration; using Constraints; using FluentMvc; using FluentMvc.ActionResultFactories; using NUnit.Framework; using Rhino.Mocks; using Utils; [TestFixture] public class When_no_settings_have_been_set : DslSpecBase { public override void Because() { Configuration = FluentMvcConfiguration.Create(); } [Test] public void Should_have_default_conventions() { Configuration.Convention.ShouldBeOfType(typeof(FluentMvcConvention)); } } [TestFixture] public class when_registering_an_instance_of_a_filter_with_no_contraints : DslSpecBase { private ActionFilterRegistry actionFilterRegistry; private IActionFilter filterInstance; public override void Because() { actionFilterRegistry = new ActionFilterRegistry(CreateStub<IFluentMvcObjectFactory>()); filterInstance = CreateStub<IActionFilter>(); FluentMvcConfiguration.Create(CreateStub<IFluentMvcResolver>(), actionFilterRegistry, CreateStub<IActionResultRegistry>(), CreateStub<IFilterConventionCollection>()) .WithFilter(filterInstance).BuildFilterProvider(); } [Test] public void should_be_registered_using_the_supplied_type() { actionFilterRegistry.Registrations.First().Create<IActionFilter>(CreateStub<IFluentMvcObjectFactory>()).ShouldEqual(filterInstance); } } [TestFixture] public class When_adding_two_action_result_factories : DslSpecBase { private IActionResultFactory Child1; private IActionResultFactory Child2; public override void Given() { Configuration = FluentMvcConfiguration.Create(); Child1 = CreateStub<IActionResultFactory>(); Child2 = CreateStub<IActionResultFactory>(); } public override void Because() { Configuration .WithResultFactory(Child1) .WithResultFactory(Child2); } [Test] public void Should_set_inner_conventions_factories() { Configuration.Convention.Factories.ToArray()[0].ShouldBeTheSameAs(Child1); Configuration.Convention.Factories.ToArray()[1].ShouldBeTheSameAs(Child2); } } [TestFixture] public class When_adding_one_action_result_factory_generically : DslSpecBase { public override void Given() { Configuration = FluentMvcConfiguration.Create(); } public override void Because() { Configuration .WithResultFactory<TestActionResultFactory>(); } [Test] public void Should_set_inner_conventions_factories() { Configuration.Convention.Factories.ToArray()[0].ShouldBe(typeof (TestActionResultFactory)); } } [TestFixture] public class When_adding_one_action_result_factories_with_a_constraint : DslSpecBase { private IActionResultFactory resultFactory; public override void Given() { resultFactory = CreateStub<IActionResultFactory>(); Configuration = FluentMvcConfiguration.Create(); } public override void Because() { Configuration .WithResultFactory(resultFactory, Apply.When<ExpectsJson>()); } [Test] public void should_override_factory_constraint() { resultFactory.AssertWasCalled(x => x.SetConstraints(Arg<IEnumerable<IConstraint>>.Is.Anything)); } } [TestFixture] public class When_adding_one_action_result_factories_with_a_controller_speicific_constraint : DslSpecBase { private IActionResultFactory resultFactory; public override void Given() { resultFactory = CreateStub<AbstractActionResultFactory>(); Configuration = FluentMvcConfiguration.Create(); } public override void Because() { Configuration .WithResultFactory(resultFactory, Apply.For<TestController>()); } [Test] public void should_set_the_correct_controller_type_contraint() { resultFactory.Constraints.First().ShouldBe(typeof(ControllerTypeConstraint<TestController>)); } } [TestFixture] public class When_adding_one_action_result_factories_with_an_action_speicific_constraint : DslSpecBase { private IActionResultFactory resultFactory; public override void Given() { resultFactory = CreateStub<AbstractActionResultFactory>(); Configuration = FluentMvcConfiguration.Create(); } public override void Because() { Configuration .WithResultFactory(resultFactory, Apply.For<TestController>(x => x.ReturnNull())); } [Test] public void should_set_the_correct_controller_type_contraint() { resultFactory.Constraints.First().ShouldBe(typeof(ControllerActionConstraint)); } } [TestFixture] public class When_overriding_the_convention : DslSpecBase { private FluentMvcConvention ExpectedConvention; public override void Given() { Configuration = FluentMvcConfiguration.Create(); ExpectedConvention = CreateStub<FluentMvcConvention>(); } public override void Because() { Configuration.WithConvention(ExpectedConvention); } [Test] public void Should_set_the_inner_convention() { Configuration.Convention.ShouldBeTheSameAs(ExpectedConvention); } } [TestFixture] public class When_editing_convention : DslSpecBase { private bool WasCalled; public override void Given() { Configuration = FluentMvcConfiguration.Create(); } public override void Because() { Configuration.WithConvention(convention => { WasCalled = true; }); } [Test] public void Should_invoke_action() { WasCalled.ShouldBeTrue(); } } [TestFixture] public class When_setting_the_default_factory : DslSpecBase { private IActionResultFactory ExpectedDefaultFactory; public override void Given() { ExpectedDefaultFactory = CreateStub<IActionResultFactory>(); Configuration = FluentMvcConfiguration.Create(); } public override void Because() { Configuration.WithResultFactory(ExpectedDefaultFactory, true); } [Test] public void Should_set_the_inner_convention() { Configuration.Convention.DefaultFactory.ShouldBeTheSameAs(ExpectedDefaultFactory); } } [TestFixture] public class When_setting_the_default_factory_generically : DslSpecBase { private IActionResultFactory ExpectedDefaultFactory; public override void Given() { ExpectedDefaultFactory = CreateStub<IActionResultFactory>(); Configuration = FluentMvcConfiguration.Create(); } public override void Because() { Configuration.WithResultFactory<TestActionResultFactory>(true); } [Test] public void Should_set_the_inner_convention() { Configuration.Convention.DefaultFactory.ShouldBe(typeof(TestActionResultFactory)); } } [TestFixture] public class when_building_controller_factory : DslSpecBase { private IFluentMvcResolver fluentMvcResolver; private IActionFilterRegistry actionFilterRegistry; private IActionResultRegistry actionResultRegistry; private IFilterConventionCollection filterConventionCollection; public override void Given() { fluentMvcResolver = CreateStub<IFluentMvcResolver>(); actionFilterRegistry = CreateStub<IActionFilterRegistry>(); actionResultRegistry = CreateStub<IActionResultRegistry>(); filterConventionCollection = CreateStub<IFilterConventionCollection>(); Configuration = FluentMvcConfiguration .Create(fluentMvcResolver, actionFilterRegistry, actionResultRegistry, filterConventionCollection); } public override void Because() { Configuration.BuildFilterProvider(); } [Test] public void should_set_resolvers_action_result_registry() { fluentMvcResolver .AssertWasCalled(arr => arr.SetActionResultRegistry(Arg<IActionResultRegistry>.Is.Anything)); } [Test] public void should_set_resolvers_action_filter_registry() { fluentMvcResolver .AssertWasCalled(arr => arr.SetActionFilterRegistry(Arg<IActionFilterRegistry>.Is.Anything)); } [Test] public void should_set_resolvers_action_result_pipeline() { fluentMvcResolver .AssertWasCalled(arr => arr.RegisterActionResultPipeline(Arg<IActionResultPipeline>.Is.Anything)); } [Test] public void should_load_filter_conventions() { filterConventionCollection .AssertWasCalled(x => x.ApplyConventions(Arg<IFilterRegistration>.Is.Anything)); } } [TestFixture] public class when_registering_an_result_factory_with_a_constraint_that_is_satified : DslSpecBase { private IActionResultRegistry actionResultRegistry; public override void Given() { actionResultRegistry = new ActionResultRegistry(); Configuration = FluentMvcConfiguration.Create(CreateStub<IFluentMvcResolver>(), CreateStub<IActionFilterRegistry>(), actionResultRegistry, CreateStub<IFilterConventionCollection>()) .WithResultFactory<JsonResultFactory>(Apply.When<TrueReturningConstraint>()); } public override void Because() { Configuration.BuildFilterProvider(); } [Test] public void should_register_with_constraint() { actionResultRegistry.Registrations.Length.ShouldEqual(1); } [Test] public void should_be_returned() { actionResultRegistry.FindForSelector(new ActionResultSelector()).First().Type.ShouldEqual(typeof (JsonResultFactory)); } } }
// // StringUtil.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2006-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Linq; using System.Collections.Generic; using System.IO; using System.Text; using System.Globalization; using System.Text.RegularExpressions; namespace Hyena { public static class StringUtil { private static CompareOptions compare_options = CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth; public static int RelaxedIndexOf (string haystack, string needle) { return ApplicationContext.CurrentCulture.CompareInfo.IndexOf (haystack, needle, compare_options); } public static int RelaxedCompare (string a, string b) { if (a == null && b == null) { return 0; } else if (a != null && b == null) { return 1; } else if (a == null && b != null) { return -1; } int a_offset = a.StartsWith ("the ") ? 4 : 0; int b_offset = b.StartsWith ("the ") ? 4 : 0; return ApplicationContext.CurrentCulture.CompareInfo.Compare (a, a_offset, a.Length - a_offset, b, b_offset, b.Length - b_offset, compare_options); } public static string CamelCaseToUnderCase (string s) { return CamelCaseToUnderCase (s, '_'); } private static Regex camelcase = new Regex ("([A-Z]{1}[a-z]+)", RegexOptions.Compiled); public static string CamelCaseToUnderCase (string s, char underscore) { if (String.IsNullOrEmpty (s)) { return null; } StringBuilder undercase = new StringBuilder (); string [] tokens = camelcase.Split (s); for (int i = 0; i < tokens.Length; i++) { if (tokens[i] == String.Empty) { continue; } undercase.Append (tokens[i].ToLower (System.Globalization.CultureInfo.InvariantCulture)); if (i < tokens.Length - 2) { undercase.Append (underscore); } } return undercase.ToString (); } public static string UnderCaseToCamelCase (string s) { if (String.IsNullOrEmpty (s)) { return null; } StringBuilder builder = new StringBuilder (); for (int i = 0, n = s.Length, b = -1; i < n; i++) { if (b < 0 && s[i] != '_') { builder.Append (Char.ToUpper (s[i])); b = i; } else if (s[i] == '_' && i + 1 < n && s[i + 1] != '_') { if (builder.Length > 0 && Char.IsUpper (builder[builder.Length - 1])) { builder.Append (Char.ToLower (s[i + 1])); } else { builder.Append (Char.ToUpper (s[i + 1])); } i++; b = i; } else if (s[i] != '_') { builder.Append (Char.ToLower (s[i])); b = i; } } return builder.ToString (); } public static string RemoveNewlines (string input) { if (input != null) { return input.Replace ("\r\n", String.Empty).Replace ("\n", String.Empty); } return null; } private static Regex tags = new Regex ("<[^>]+>", RegexOptions.Compiled | RegexOptions.Multiline); public static string RemoveHtml (string input) { if (input == null) { return input; } return tags.Replace (input, String.Empty); } public static string DoubleToTenthsPrecision (double num) { return DoubleToTenthsPrecision (num, false); } public static string DoubleToTenthsPrecision (double num, bool always_decimal) { return DoubleToTenthsPrecision (num, always_decimal, NumberFormatInfo.CurrentInfo); } public static string DoubleToTenthsPrecision (double num, bool always_decimal, IFormatProvider provider) { num = Math.Round (num, 1, MidpointRounding.ToEven); return String.Format (provider, !always_decimal && num == (int)num ? "{0:N0}" : "{0:N1}", num); } // This method helps us pluralize doubles. Probably a horrible i18n idea. public static int DoubleToPluralInt (double num) { if (num == (int)num) return (int)num; else return (int)num + 1; } // A mapping of non-Latin characters to be considered the same as // a Latin equivalent. private static Dictionary<char, char> BuildSpecialCases () { Dictionary<char, char> dict = new Dictionary<char, char> (); dict['\u00f8'] = 'o'; dict['\u0142'] = 'l'; return dict; } private static Dictionary<char, char> searchkey_special_cases = BuildSpecialCases (); // Removes accents from Latin characters, and some kinds of punctuation. public static string SearchKey (string val) { if (String.IsNullOrEmpty (val)) { return val; } val = val.ToLower (); StringBuilder sb = new StringBuilder (); UnicodeCategory category; bool previous_was_letter = false; bool got_space = false; // Normalizing to KD splits into (base, combining) so we can check for letters // and then strip off any NonSpacingMarks following them foreach (char orig_c in val.TrimStart ().Normalize (NormalizationForm.FormKD)) { // Check for a special case *before* whitespace. This way, if // a special case is ever added that maps to ' ' or '\t', it // won't cause a run of whitespace in the result. char c = orig_c; if (searchkey_special_cases.ContainsKey (c)) { c = searchkey_special_cases[c]; } if (c == ' ' || c == '\t') { got_space = true; continue; } category = Char.GetUnicodeCategory (c); if (category == UnicodeCategory.OtherPunctuation) { // Skip punctuation } else if (!(previous_was_letter && category == UnicodeCategory.NonSpacingMark)) { if (got_space) { sb.Append (" "); got_space = false; } sb.Append (c); } // Can ignore A-Z because we've already lowercased the char previous_was_letter = Char.IsLetter (c); } string result = sb.ToString (); try { result = result.Normalize (NormalizationForm.FormKC); } catch { // FIXME: work-around, see http://bugzilla.gnome.org/show_bug.cgi?id=590478 } return result; } private static Regex invalid_path_regex = BuildInvalidPathRegex (); private static Regex BuildInvalidPathRegex () { char [] invalid_path_characters = new char [] { // Control characters: there's no reason to ever have one of these in a track name anyway, // and they're invalid in all Windows filesystems. '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07', '\x08', '\x09', '\x0A', '\x0B', '\x0C', '\x0D', '\x0E', '\x0F', '\x10', '\x11', '\x12', '\x13', '\x14', '\x15', '\x16', '\x17', '\x18', '\x19', '\x1A', '\x1B', '\x1C', '\x1D', '\x1E', '\x1F', // Invalid in FAT32 / NTFS: " \ / : * | ? < > // Invalid in HFS : // Invalid in ext3 / '"', '\\', '/', ':', '*', '|', '?', '<', '>' }; string regex_str = "["; for (int i = 0; i < invalid_path_characters.Length; i++) { regex_str += "\\" + invalid_path_characters[i]; } regex_str += "]+"; return new Regex (regex_str, RegexOptions.Compiled); } private static CompareInfo culture_compare_info = ApplicationContext.CurrentCulture.CompareInfo; public static byte[] SortKey (string orig) { if (orig == null) { return null; } return culture_compare_info.GetSortKey (orig, CompareOptions.IgnoreCase).KeyData; } private static readonly char[] escape_path_trim_chars = new char[] {'.', '\x20'}; public static string EscapeFilename (string input) { if (input == null) return ""; // Remove leading and trailing dots and spaces. input = input.Trim (escape_path_trim_chars); return invalid_path_regex.Replace (input, "_"); } public static string EscapePath (string input) { if (input == null) return ""; // This method should be called before the full path is constructed. if (Path.IsPathRooted (input)) { return input; } StringBuilder builder = new StringBuilder (); foreach (string name in input.Split (Path.DirectorySeparatorChar)) { // Escape the directory or the file name. string escaped = EscapeFilename (name); // Skip empty names. if (escaped.Length > 0) { builder.Append (escaped); builder.Append (Path.DirectorySeparatorChar); } } // Chop off the last character. if (builder.Length > 0) { builder.Length--; } return builder.ToString (); } public static string MaybeFallback (string input, string fallback) { string trimmed = input == null ? null : input.Trim (); return String.IsNullOrEmpty (trimmed) ? fallback : trimmed; } public static uint SubstringCount (string haystack, string needle) { if (String.IsNullOrEmpty (haystack) || String.IsNullOrEmpty (needle)) { return 0; } int position = 0; uint count = 0; while (true) { int index = haystack.IndexOf (needle, position); if (index < 0) { return count; } count++; position = index + 1; } } public static string SubstringBetween (this string input, string start, string end) { int s = input.IndexOf (start); if (s == -1) return null; s += start.Length; int l = Math.Min (input.Length - 1, input.IndexOf (end, s)) - s; if (l > 0 && s + l < input.Length) { return input.Substring (s, l); } else { return null; } } private static readonly char[] escaped_like_chars = new char[] {'\\', '%', '_'}; public static string EscapeLike (string s) { if (s.IndexOfAny (escaped_like_chars) != -1) { return s.Replace (@"\", @"\\").Replace ("%", @"\%").Replace ("_", @"\_"); } return s; } public static string Join (this IEnumerable<string> strings, string sep) { var sb = new StringBuilder (); foreach (var str in strings) { sb.Append (str); sb.Append (sep); } if (sb.Length > 0 && sep != null) { sb.Length -= sep.Length; } return sb.ToString (); } public static IEnumerable<object> FormatInterleaved (string format, params object [] objects) { var indices = new Dictionary<object, int> (); for (int i = 0; i < objects.Length; i++) { int j = format.IndexOf ("{" + i + "}"); if (j == -1) { Hyena.Log.ErrorFormat ("Translated string {0} should contain {{1}} in which to place object {2}", format, i, objects[i]); } indices[objects[i]] = j; } int str_pos = 0; foreach (var obj in objects.OrderBy (w => indices[w])) { int widget_i = indices[obj]; if (widget_i > str_pos) { var str = format.Substring (str_pos, widget_i - str_pos).Trim (); if (str != "") yield return str; } yield return obj; str_pos = widget_i + 2 + Array.IndexOf (objects, obj).ToString ().Length; } if (str_pos < format.Length - 1) { var str = format.Substring (str_pos, format.Length - str_pos).Trim (); if (str != "") yield return str; } } } }
// #define EnableTokensOutput // Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. See license.txt file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using DotLiquid.Tests.Tags; using Newtonsoft.Json.Linq; using NUnit.Framework; using Scriban.Helpers; using Scriban.Parsing; using Scriban.Runtime; using Scriban.Syntax; using static Scriban.Tests.TestFilesHelper; namespace Scriban.Tests { [TestFixture] public class TestParser { private const string BuiltinMarkdownDocFile = @"..\..\..\..\..\doc\builtins.md"; [Test] public void TestRoundtrip() { var text = "This is a text {{ code # With some comment }} and a text"; AssertRoundtrip(text); } [Test] public void TestScribanIfElseFunction() { var template = Template.Parse(@" func testIfElse if $0 < 0 ret 1 else ret 0 end ret -1 end testIfElse testValue ", lexerOptions: new LexerOptions { KeepTrivia = false, Mode = ScriptMode.ScriptOnly }); var templateContext = new TemplateContext { LoopLimit = int.MaxValue, }; templateContext.BuiltinObject.SetValue("testValue", -1, true); var result = template.Evaluate(templateContext); Assert.AreEqual(1, result); templateContext.BuiltinObject.SetValue("testValue", 1, true); result = template.Evaluate(templateContext); Assert.AreEqual(0, result); // returns null } [Test] public void TestRoundtrip1() { var text = "This is a text {{ code | pipe a b c | a + b }} and a text"; AssertRoundtrip(text); } [Test] public void TestLiquidMissingClosingBrace() { var template = Template.ParseLiquid("{%endunless"); Assert.True(template.HasErrors); Assert.AreEqual(1, template.Messages.Count); Assert.AreEqual("<input>(1,3) : error : Unable to find a pending `unless` for this `endunless`", template.Messages[0].ToString()); } [Test] public void TestScientificWithFunctionExpression() { var context = new TemplateContext(); context.BuiltinObject.SetValue("clear", DelegateCustomFunction.CreateFunc<ScriptExpression, string>(FunctionClear), false); context.BuiltinObject.SetValue("history", DelegateCustomFunction.Create<object>(FunctionHistory), false); var template = Template.Parse("clear history", lexerOptions: new LexerOptions() { Lang = ScriptLang.Scientific, Mode = ScriptMode.ScriptOnly }); var test = template.Render(context); Assert.AreEqual("history", test); template = Template.Parse("clear history * 5", lexerOptions: new LexerOptions() { Lang = ScriptLang.Scientific, Mode = ScriptMode.ScriptOnly }); test = template.Render(context); Assert.AreEqual("history*5", test); } private static string FunctionClear(ScriptExpression what = null) { return what?.ToString(); } private static void FunctionHistory(object line = null) { } [Test] public void TestLiquidInvalidStringEscape() { var template = Template.ParseLiquid(@"{%""\u"""); Assert.True(template.HasErrors); } [TestCase("1-2", -1, "1 - 2")] [TestCase("abs 5", 5, "abs(5)")] [TestCase("2 abs 5", 10, "2 * abs(5)")] [TestCase("abs 5^2", 25, "abs(5 ^ 2)")] [TestCase("abs 5^2*3", 75, "abs((5 ^ 2) * 3)")] [TestCase("abs 5^2*3 - 1", 74, "abs((5 ^ 2) * 3) - 1")] [TestCase("abs 5^2*3 + 1", 76, "abs((5 ^ 2) * 3) + 1")] [TestCase("2 abs 5^2*3 + 1", 151, "2 * abs((5 ^ 2) * 3) + 1")] [TestCase("abs 4 abs 3 abs 2", 24, "abs(4) * abs(3) * abs(2)")] [TestCase("abs 4 * abs 3 * abs 2", 24, "abs(4) * abs(3) * abs(2)")] [TestCase("abs 4 + abs 3 * abs 2", 10, "abs(4) + abs(3) * abs(2)")] [TestCase("abs 4 * abs 3 + abs 2", 14, "abs(4) * abs(3) + abs(2)")] [TestCase("1 + abs 4 * abs 3", 13, "1 + abs(4) * abs(3)")] [TestCase("abs 4 * abs 3 + 1", 13, "abs(4) * abs(3) + 1")] [TestCase("abs 10 / abs 2 + 1", 6, "(abs(10) / abs(2)) + 1")] [TestCase("-5|>math.abs", 5, "-5 |> math.abs")] [TestCase("-5*2|>math.abs", 10, "-5 * 2 |> math.abs")] [TestCase("2x", 2, "2 * x")] [TestCase("10x/2", 5.0, "(10 * x) / 2")] [TestCase("10x y + y", 22, "10 * x * y + y")] [TestCase("10x * y + 3y + 1 + 2", 29, "10 * x * y + 3 * y + 1 + 2")] [TestCase("2 y math.abs z * 5 // 2 + 1 + z", 91, "2 * y * math.abs((z * 5) // 2) + 1 + z")] // 2 * 2 * abs(-10) * 5 / 2 + 1 + (-10) = 91 [TestCase("2 y math.abs z * 5 // 2 + 1 * 3 + z + 17", 110, "2 * y * math.abs((z * 5) // 2) + 1 * 3 + z + 17")] // 2 * 2 * abs(-10) * 5 / 2 + 3 + (-10) + 17 = 110 [TestCase("2^11 - 2^5 + 2^2", 2020, "(2 ^ 11) - (2 ^ 5) + (2 ^ 2)")] [TestCase("2^3^4", 4096, "(2 ^ 3) ^ 4")] [TestCase("3y^2 + 3x", 15, "3 * (y ^ 2) + 3 * x")] [TestCase("1 + 2 + 3x + 4y + z", 4, "1 + 2 + 3 * x + 4 * y + z")] [TestCase("y^5 * 2 + 1", 65, "(y ^ 5) * 2 + 1")] [TestCase("y^5 // 2 + 1", 17, "((y ^ 5) // 2) + 1")] [TestCase("f(x)= x*2 +1* 50; f(10* 2)", 90, "f(x) = x * 2 + 1 * 50; f(10 * 2)")] [TestCase("f(x)= x*2 +1* 50; 10* 2|>f", 90, "f(x) = x * 2 + 1 * 50; 10 * 2 |> f")] // int binaries [TestCase("1 << 2", 4, "1 << 2")] [TestCase("8 >> 2", 2, "8 >> 2")] [TestCase("1 | 2", 3, "1 | 2")] [TestCase("3 & 2", 2, "3 & 2")] // long [TestCase("10000000000 + 1", (long)10000000000 + 1, "10000000000 + 1")] [TestCase("10000000000 - 1", (long)10000000000 - 1, "10000000000 - 1")] [TestCase("10000000000 * 3", (long)10000000000 * 3, "10000000000 * 3")] [TestCase("10000000000 / 3", (double)10000000000 / 3, "10000000000 / 3")] [TestCase("10000000000 // 3", (long)10000000000 / 3, "10000000000 // 3")] [TestCase("10000000000 << 2", (long)10000000000 << 2, "10000000000 << 2")] [TestCase("10000000000 >> 2", (long)10000000000 >> 2, "10000000000 >> 2")] [TestCase("10000000001 | 2", (long)10000000001 | 2, "10000000001 | 2")] [TestCase("10000000003 & 2", (long)10000000003 & 2, "10000000003 & 2")] [TestCase("10000000003 % 7", (long)10000000003 % 7, "10000000003 % 7")] [TestCase("10000000003 == 7", 10000000003 == 7, "10000000003 == 7")] [TestCase("10000000003 != 7", 10000000003 != 7, "10000000003 != 7")] [TestCase("10000000003 < 7", 10000000003 < 7, "10000000003 < 7")] [TestCase("10000000003 > 7", 10000000003 > 7, "10000000003 > 7")] [TestCase("10000000003 <= 7", 10000000003 <= 7, "10000000003 <= 7")] [TestCase("10000000003 >= 7", 10000000003 >= 7, "10000000003 >= 7")] // float [TestCase("1.0f + 2.0f", 1.0f + 2.0f, "1.0f + 2.0f")] [TestCase("1.0f - 2.0f", 1.0f - 2.0f, "1.0f - 2.0f")] [TestCase("2.0f * 3.0f", 2.0f * 3.0f, "2.0f * 3.0f")] [TestCase("2.0f / 3.0f", 2.0f / 3.0f, "2.0f / 3.0f")] [TestCase("4.0f // 3.0f", (float)(int)(4.0f / 3.0f), "4.0f // 3.0f")] [TestCase("4.0f ^ 2.0f", (float)16.0, "4.0f ^ 2.0f")] [TestCase("4.0f << 1", (float)4.0f * 2.0f, "4.0f << 1")] [TestCase("4.0f >> 1", (float)4.0f / 2.0f, "4.0f >> 1")] [TestCase("4.0f % 3.0f", (float)4.0f % 3.0f, "4.0f % 3.0f")] [TestCase("4.0f == 3.0f", 4.0f == 3.0f, "4.0f == 3.0f")] [TestCase("4.0f != 3.0f", 4.0f != 3.0f, "4.0f != 3.0f")] [TestCase("4.0f < 3.0f", 4.0f < 3.0f, "4.0f < 3.0f")] [TestCase("4.0f > 3.0f", 4.0f > 3.0f, "4.0f > 3.0f")] [TestCase("4.0f <= 3.0f", 4.0f <= 3.0f, "4.0f <= 3.0f")] [TestCase("4.0f >= 3.0f", 4.0f >= 3.0f, "4.0f >= 3.0f")] // double [TestCase("4.0 // 3.0", (double)(int)(4.0f / 3.0), "4.0 // 3.0")] [TestCase("4.0 ^ 2.0", (double)16.0, "4.0 ^ 2.0")] [TestCase("4.0 << 1", (double)4.0 * 2.0, "4.0 << 1")] [TestCase("4.0 >> 1", (double)4.0 / 2.0, "4.0 >> 1")] [TestCase("4.0d", 4.0, "4.0")] [TestCase("4.0D", 4.0, "4.0")] // decimal [TestCase("4.0m", 4.0, "4.0m")] [TestCase("4.0M", 4.0, "4.0m")] [TestCase("4.0m + 2.0m", 6.0, "4.0m + 2.0m")] [TestCase("4.0m - 2.0m", 2.0, "4.0m - 2.0m")] [TestCase("4.0m * 2.0m", 8.0, "4.0m * 2.0m")] [TestCase("8.0m / 2.0m", 4.0, "8.0m / 2.0m")] [TestCase("5.0m // 2.0m", 2.0, "5.0m // 2.0m")] [TestCase("2.0m ^ 3.0m", 8.0, "2.0m ^ 3.0m")] [TestCase("2.0m << 1", 4.0, "2.0m << 1")] [TestCase("4.0m >> 1", 2.0, "4.0m >> 1")] [TestCase("4.0m % 3.0m", 1.0, "4.0m % 3.0m")] [TestCase("4.0m == 3.0m", 4.0m == 3.0m, "4.0m == 3.0m")] [TestCase("4.0m != 3.0m", 4.0m != 3.0m, "4.0m != 3.0m")] [TestCase("4.0m < 3.0m", 4.0m < 3.0m, "4.0m < 3.0m")] [TestCase("4.0m > 3.0m", 4.0m > 3.0m, "4.0m > 3.0m")] [TestCase("4.0m <= 3.0m", 4.0m <= 3.0m, "4.0m <= 3.0m")] [TestCase("4.0m >= 3.0m", 4.0m >= 3.0m, "4.0m >= 3.0m")] [TestCase("3.0ff", 12.0, "3.0 * ff")] public void TestScientific(string script, object value, string scriptReformat) { var template = Template.Parse(script, lexerOptions: new LexerOptions() {Mode = ScriptMode.ScriptOnly, Lang = ScriptLang.Scientific}); Assert.False(template.HasErrors, $"Template has errors: {template.Messages}"); var context = new TemplateContext(); context.CurrentGlobal.SetValue("x", 1, false); context.CurrentGlobal.SetValue("y", 2, false); context.CurrentGlobal.SetValue("z", -10, false); context.CurrentGlobal.SetValue("ff", 4, false); context.CurrentGlobal.SetValue("abs", ((ScriptObject)context.BuiltinObject["math"])["abs"], false); var result = template.Evaluate(context); Assert.AreEqual(value, result); var resultAsync = template.EvaluateAsync(context).Result; Assert.AreEqual(value, resultAsync, "Invalid async result"); var reformat = template.Page.Format(new ScriptFormatterOptions(context, ScriptLang.Scientific, ScriptFormatterFlags.ExplicitClean)); var exprAsString = reformat.ToString(); Assert.AreEqual(scriptReformat, exprAsString, "Format string don't match"); } [Test] public void RoundtripFunction() { var text = @"{{ func inc ret $0 + 1 end }}"; AssertRoundtrip(text); } [Test] public void RoundtripFunction2() { var text = @"{{ func inc ret $0 + 1 end xxx 1 }}"; AssertRoundtrip(text); } [Test] public void RoundtripIf() { var text = @"{{ if true ""yes"" end }} raw "; AssertRoundtrip(text); } [Test] public void RoundtripIfElse() { var text = @"{{ if true ""yes"" else ""no"" end }} raw "; AssertRoundtrip(text); } [Test] public void RoundtripIfElseIf() { var text = @"{{ if true ""yes"" else if yo ""no"" end y }} raw "; AssertRoundtrip(text); } [Test] public void RoundtripCapture() { var text = @" {{ capture variable -}} This is a capture {{- end -}} {{ variable }}"; AssertRoundtrip(text); } [Test] public void RoundtripRaw() { var text = @"This is a raw {{~ x ~}} end"; AssertRoundtrip(text); } /// <summary> /// Regression test for issue-295 /// </summary> [Test] public void ShouldNotThrowWithTrailingColon() { //this particular input string is required to tickle the original bug var text = @"{{T ""m"" b:"; var context = new TemplateContext(); context.PushGlobal(new ScriptObject()); Assert.DoesNotThrow(() => Template.Parse(text)); } [Test] public void TestDateNow() { // default is dd MM yyyy var dateNow = DateTime.Now.ToString("dd MMM yyyy", CultureInfo.InvariantCulture); var template = ParseTemplate(@"{{ date.now }}"); var result = template.Render(); Assert.AreEqual(dateNow, result); template = ParseTemplate(@"{{ date.format = '%Y'; date.now }}"); result = template.Render(); Assert.AreEqual(DateTime.Now.ToString("yyyy", CultureInfo.InvariantCulture), result); template = ParseTemplate(@"{{ date.format = '%Y'; date.now | date.add_years 1 }}"); result = template.Render(); Assert.AreEqual(DateTime.Now.AddYears(1).ToString("yyyy", CultureInfo.InvariantCulture), result); } [Test] public void TestHelloWorld() { var template = ParseTemplate(@"This is a {{ text }} World from scriban!"); var result = template.Render(new { text = "Hello" }); Assert.AreEqual("This is a Hello World from scriban!", result); } [Test] public void TestFrontMatter() { var options = new LexerOptions() {Mode = ScriptMode.FrontMatterAndContent}; var input = @"+++ variable = 1 name = 'yes' +++ This is after the frontmatter: {{ name }} {{ variable + 1 }}"; input = input.Replace("\r\n", "\n"); var template = ParseTemplate(input, options); // Make sure that we have a front matter Assert.NotNull(template.Page.FrontMatter); var context = new TemplateContext(); // Evaluate front-matter var frontResult = context.Evaluate(template.Page.FrontMatter); Assert.Null(frontResult); // Evaluate page-content context.Evaluate(template.Page); var pageResult = context.Output.ToString(); TextAssert.AreEqual("This is after the frontmatter: yes\n2", pageResult); } [Test] public void TestFrontMatterOnly() { var options = new ParserOptions(); var input = @"+++ variable = 1 name = 'yes' +++ This is after the frontmatter: {{ name }} {{ variable + 1 }}"; input = input.Replace("\r\n", "\n"); var lexer = new Lexer(input, null, new LexerOptions() { Mode = ScriptMode.FrontMatterOnly }); var parser = new Parser(lexer, options); var page = parser.Run(); foreach (var message in parser.Messages) { Console.WriteLine(message); } Assert.False(parser.HasErrors); // Check that the parser finished parsing on the first code exit }} // and hasn't tried to run the lexer on the remaining text Assert.AreEqual(new TextPosition(34, 4, 0), parser.CurrentSpan.Start); var startPositionAfterFrontMatter = page.FrontMatter.TextPositionAfterEndMarker; // Make sure that we have a front matter Assert.NotNull(page.FrontMatter); Assert.Null(page.Body); var context = new TemplateContext(); // Evaluate front-matter var frontResult = context.Evaluate(page.FrontMatter); Assert.Null(frontResult); lexer = new Lexer(input, null, new LexerOptions() { StartPosition = startPositionAfterFrontMatter }); parser = new Parser(lexer); page = parser.Run(); foreach (var message in parser.Messages) { Console.WriteLine(message); } Assert.False(parser.HasErrors); context.Evaluate(page); var pageResult = context.Output.ToString(); TextAssert.AreEqual("This is after the frontmatter: yes\n2", pageResult); } [Test] public void TestScriptOnly() { var options = new LexerOptions() { Mode = ScriptMode.ScriptOnly }; var template = ParseTemplate(@" variable = 1 name = 'yes' ", options); var context = new TemplateContext(); template.Render(context); var outputStr = context.Output.ToString(); Assert.AreEqual(string.Empty, outputStr); var global = context.CurrentGlobal; object value; Assert.True(global.TryGetValue("name", out value)); Assert.AreEqual("yes", value); Assert.True(global.TryGetValue("variable", out value)); Assert.AreEqual(1, value); } private static Template ParseTemplate(string text, LexerOptions? lexerOptions = null, ParserOptions? parserOptions = null) { var template = Template.Parse(text, "text", parserOptions, lexerOptions); foreach (var message in template.Messages) { Console.WriteLine(message); } Assert.False(template.HasErrors); return template; } [Test] public void TestFunctionCallInExpression() { var lexer = new Lexer(@"{{ with math round pi end }}"); var parser = new Parser(lexer); var scriptPage = parser.Run(); foreach (var message in parser.Messages) { Console.WriteLine(message); } Assert.False(parser.HasErrors); Assert.NotNull(scriptPage); var rootObject = new ScriptObject(); rootObject.SetValue("math", ScriptObject.From(typeof(MathObject)), true); var context = new TemplateContext(); context.PushGlobal(rootObject); context.Evaluate(scriptPage); context.PopGlobal(); // Result var result = context.Output.ToString(); Console.WriteLine(result); } [TestCaseSource("ListTestFiles", new object[] { "000-basic" })] public static void A000_basic(string inputName) { TestFile(inputName); } [TestCaseSource("ListTestFiles", new object[] { "010-literals" })] public static void A010_literals(string inputName) { TestFile(inputName); } [TestCaseSource("ListTestFiles", new object[] { "100-expressions" })] public static void A100_expressions(string inputName) { TestFile(inputName); } [TestCaseSource("ListTestFiles", new object[] { "200-statements" })] public static void A200_statements(string inputName) { TestFile(inputName); } [TestCaseSource("ListTestFiles", new object[] { "300-functions" })] public static void A300_functions(string inputName) { TestFile(inputName); } [TestCaseSource("ListTestFiles", new object[] { "400-builtins" })] public static void A400_builtins(string inputName) { TestFile(inputName); } [TestCaseSource("ListTestFiles", new object[] { "500-liquid" })] public static void A500_liquid(string inputName) { TestFile(inputName); } [TestCaseSource("ListBuiltinFunctionTests", new object[] { "array" })] public static void Doc_array(string inputName, string input, string output) { AssertTemplate(output, input); } [TestCaseSource("ListBuiltinFunctionTests", new object[] { "date" })] public static void Doc_date(string inputName, string input, string output) { AssertTemplate(output, input); } [TestCaseSource("ListBuiltinFunctionTests", new object[] { "html" })] public static void Doc_html(string inputName, string input, string output) { AssertTemplate(output, input); } [TestCaseSource("ListBuiltinFunctionTests", new object[] { "math" })] public static void Doc_math(string inputName, string input, string output) { // Skip these functions, since their output not deterministic if (input.Contains("math.uuid") || input.Contains("math.random")) { return; } AssertTemplate(output, input); } [TestCaseSource("ListBuiltinFunctionTests", new object[] { "object" })] public static void Doc_object(string inputName, string input, string output) { AssertTemplate(output, input); } [TestCaseSource("ListBuiltinFunctionTests", new object[] { "regex" })] public static void Doc_regex(string inputName, string input, string output) { AssertTemplate(output, input); } [TestCaseSource("ListBuiltinFunctionTests", new object[] { "string" })] public static void Doc_string(string inputName, string input, string output) { AssertTemplate(output, input); } [TestCaseSource("ListBuiltinFunctionTests", new object[] { "timespan" })] public static void Doc_timespan(string inputName, string input, string output) { AssertTemplate(output, input); } [Test] public void TestArrayFilter() { var script = @"{{[1, 200 , 3,400] | array.filter @(do;ret $0 >=100; end)}}"; var template = Template.Parse(script); var result = template.Render(); Assert.AreEqual(result.Trim(), @"[200, 400]"); } [Test] public void EnsureThatItemWithIndexePropertyDoesNotThrow() { var obj = JObject.Parse("{\"name\":\"steve\"}"); var template = Template.Parse("Hi {{name}}"); Assert.DoesNotThrow(()=>template.Render(obj)); } [Test] public void EnsureMalformedFunctionDoesNotThrow() { Assert.DoesNotThrow(() =>Template.Parse("{{ func (t(")); } [Test] public void TestEvaluateProcessing() { { var result = Template.Parse("{{['', '200', '','400'] | array.filter @string.strip}}").Evaluate(new TemplateContext()); Assert.AreEqual(new[] { "", "200", "", "400" }, result); } { var result = Template.Parse("{{['', '200', '','400'] | array.filter @string.empty}}").Evaluate(new TemplateContext()); Assert.AreEqual(new[] { "", "" }, result); } } private static void TestFile(string inputName) { var filename = Path.GetFileName(inputName); var isSupportingExactRoundtrip = !NotSupportingExactRoundtrip.Contains(filename); var inputText = LoadTestFile(inputName); var expectedOutputName = Path.ChangeExtension(inputName, OutputEndFileExtension); var expectedOutputText = LoadTestFile(expectedOutputName); Assert.NotNull(expectedOutputText, $"Expecting output result file `{expectedOutputName}` for input file `{inputName}`"); var lang = ScriptLang.Default; if (inputName.Contains("liquid")) { lang = ScriptLang.Liquid; } else if (inputName.Contains("scientific")) { lang = ScriptLang.Scientific; } AssertTemplate(expectedOutputText, inputText, lang, false, isSupportingExactRoundtrip, expectParsingErrorForRountrip: filename == "513-liquid-statement-for.variables.txt"); } private void AssertRoundtrip(string inputText, bool isLiquid = false) { inputText = inputText.Replace("\r\n", "\n"); AssertTemplate(inputText, inputText, isLiquid ? ScriptLang.Liquid : ScriptLang.Default, true); } /// <summary> /// Lists of the tests that don't support exact byte-to-byte roundtrip (due to reformatting...etc.) /// </summary> private static readonly HashSet<string> NotSupportingExactRoundtrip = new HashSet<string>() { "003-whitespaces.txt", "010-literals.txt", "205-case-when-statement2.txt", "230-capture-statement2.txt", "470-html.txt" }; public static void AssertTemplate(string expected, string input, ScriptLang lang = ScriptLang.Default, bool isRoundtripTest = false, bool supportExactRoundtrip = true, object model = null, bool specialLiquid = false, bool expectParsingErrorForRountrip = false, bool supportRoundTrip = true) { bool isLiquid = lang == ScriptLang.Liquid; var parserOptions = new ParserOptions() { LiquidFunctionsToScriban = isLiquid, }; var lexerOptions = new LexerOptions() { Lang = lang }; if (isRoundtripTest) { lexerOptions.KeepTrivia = true; } if (specialLiquid) { parserOptions.ExpressionDepthLimit = 500; } #if EnableTokensOutput { Console.WriteLine("Tokens"); Console.WriteLine("======================================"); var lexer = new Lexer(input, options: lexerOptions); foreach (var token in lexer) { Console.WriteLine($"{token.Type}: {token.GetText(input)}"); } Console.WriteLine(); } #endif string roundtripText = null; // We loop first on input text, then on roundtrip while (true) { bool isRoundtrip = roundtripText != null; bool hasErrors = false; bool hasException = false; if (isRoundtrip) { Console.WriteLine("Roundtrip"); Console.WriteLine("======================================"); Console.WriteLine(roundtripText); lexerOptions.Lang = lang == ScriptLang.Scientific ? lang : ScriptLang.Default; if (!isLiquid && supportExactRoundtrip) { Console.WriteLine("Checking Exact Roundtrip - Input"); Console.WriteLine("======================================"); TextAssert.AreEqual(input, roundtripText); } input = roundtripText; } else { Console.WriteLine("Input"); Console.WriteLine("======================================"); Console.WriteLine(input); } var template = Template.Parse(input, "text", parserOptions, lexerOptions); var result = string.Empty; var resultAsync = string.Empty; if (template.HasErrors) { hasErrors = true; for (int i = 0; i < template.Messages.Count; i++) { var message = template.Messages[i]; if (i > 0) { result += "\n"; } result += message; } if (specialLiquid && !isRoundtrip) { throw new InvalidOperationException("Parser errors: " + result); } } else { if (isRoundtripTest) { result = template.ToText(); } else { Assert.NotNull(template.Page); if (!isRoundtrip) { // Dumps the roundtrip version var lexerOptionsForTrivia = lexerOptions; lexerOptionsForTrivia.KeepTrivia = true; var templateWithTrivia = Template.Parse(input, "input", parserOptions, lexerOptionsForTrivia); roundtripText = templateWithTrivia.ToText(); } try { // Setup a default model context for the tests if (model == null) { var scriptObj = new ScriptObject { ["page"] = new ScriptObject {["title"] = "This is a title"}, ["user"] = new ScriptObject {["name"] = "John"}, ["product"] = new ScriptObject {["title"] = "Orange", ["type"] = "fruit"}, ["products"] = new ScriptArray() { new ScriptObject {["title"] = "Orange", ["type"] = "fruit"}, new ScriptObject {["title"] = "Banana", ["type"] = "fruit"}, new ScriptObject {["title"] = "Apple", ["type"] = "fruit"}, new ScriptObject {["title"] = "Computer", ["type"] = "electronics"}, new ScriptObject {["title"] = "Mobile Phone", ["type"] = "electronics"}, new ScriptObject {["title"] = "Table", ["type"] = "furniture"}, new ScriptObject {["title"] = "Sofa", ["type"] = "furniture"}, } }; scriptObj.Import(typeof(SpecialFunctionProvider)); model = scriptObj; } // Render sync { var context = NewTemplateContext(lang); context.PushOutput(new TextWriterOutput(new StringWriter() {NewLine = "\n"})); var contextObj = new ScriptObject(); contextObj.Import(model); context.PushGlobal(contextObj); result = template.Render(context); } // Render async { var asyncContext = NewTemplateContext(lang); asyncContext.PushOutput(new TextWriterOutput(new StringWriter() {NewLine = "\n"})); var contextObj = new ScriptObject(); contextObj.Import(model); asyncContext.PushGlobal(contextObj); resultAsync = template.RenderAsync(asyncContext).Result; } } catch (Exception exception) { hasException = true; if (specialLiquid) { throw; } else { result = GetReason(exception); } } } } var testContext = isRoundtrip ? "Roundtrip - " : String.Empty; Console.WriteLine($"{testContext}Result"); Console.WriteLine("======================================"); Console.WriteLine(result); Console.WriteLine($"{testContext}Expected"); Console.WriteLine("======================================"); Console.WriteLine(expected); if (isRoundtrip && expectParsingErrorForRountrip) { Assert.True(hasErrors, "The roundtrip test is expecting an error"); Assert.AreNotEqual(expected, result); } else { TextAssert.AreEqual(expected, result); } if (!isRoundtrip && !isRoundtripTest && !hasErrors && !hasException) { Console.WriteLine("Checking async"); Console.WriteLine("======================================"); TextAssert.AreEqual(expected, resultAsync); } if (!supportRoundTrip || isRoundtripTest || isRoundtrip || hasErrors) { break; } } } private static TemplateContext NewTemplateContext(ScriptLang lang) { var isLiquid = lang == ScriptLang.Liquid; var context = isLiquid ? new LiquidTemplateContext() { TemplateLoader = new LiquidCustomTemplateLoader() } : new TemplateContext() { TemplateLoader = new CustomTemplateLoader() }; if (lang == ScriptLang.Scientific) { context.UseScientific = true; } // We use a custom output to make sure that all output is using the "\n" context.NewLine = "\n"; return context; } private static string GetReason(Exception ex) { var text = new StringBuilder(); while (ex != null) { text.Append(ex); if (ex.InnerException != null) { text.Append(". Reason: "); } ex = ex.InnerException; } return text.ToString(); } public static IEnumerable ListBuiltinFunctionTests(string functionObject) { var builtinDocFile = Path.GetFullPath(Path.Combine(BaseDirectory, BuiltinMarkdownDocFile)); var lines = File.ReadAllLines(builtinDocFile); var matchFunctionSection = new Regex($@"^###\s+`({functionObject}\.\w+)`"); var tests = new List<TestCaseData>(); string nextFunctionName = null; int processState = 0; // states: // - 0 function section or wait for ```scriban-html (input) // - 2 parse input (wait for ```) // - 3 wait for ```html (output) // - 4 parse input (wait for ```) var input = new StringBuilder(); var output = new StringBuilder(); foreach (var line in lines) { // Match first: //### `array.add_range` switch (processState) { case 0: var match = matchFunctionSection.Match(line); if (match.Success) { nextFunctionName = match.Groups[1].Value; } // We have reached another object section, we can exit if (line.StartsWith("## ") && nextFunctionName != null) { return tests; } if (nextFunctionName != null && line.StartsWith("```scriban-html")) { processState = 1; input = new StringBuilder(); output = new StringBuilder(); } break; case 1: if (line.Equals("```")) { processState = 2; } else { input.AppendLine(line); } break; case 2: if (line.StartsWith("```html")) { processState = 3; } break; case 3: if (line.Equals("```")) { tests.Add(new TestCaseData(nextFunctionName, input.ToString(), output.ToString())); processState = 0; } else { output.AppendLine(line); } break; } } return tests; } public static IEnumerable ListTestFiles(string folder) { return ListTestFilesInFolder(folder); } } }
//============================================================================= // The Custom Channel - Knowledge Base // (C) Copyright 2003, Roman Kiss (rkiss@pathcom.com) // All rights reserved. // The code and information is provided "as-is" without waranty of any kind, // either expresed or implied. // //----------------------------------------------------------------------------- // History: // 06/05/2003 Roman Kiss Initial Revision //============================================================================= // #region references using System; using System.Diagnostics; using System.Threading; using System.Collections; using System.Configuration; using System.IO; using System.Runtime.Remoting; #endregion namespace RKiss.CustomChannel { public class KnowledgeBase: MarshalByRefObject, IKnowledgeBaseControl { #region private members private ObjRef m_thisObjRef = null; // reference to the endpoint private bool m_AllowToUpdate = true; // allow to update the KB remotely private Hashtable m_KB = Hashtable.Synchronized(new Hashtable()); #endregion #region properties public Hashtable KB { get { return m_KB; }} public bool AllowToUpdate { get { return m_AllowToUpdate; } set { m_AllowToUpdate = value; }} #endregion #region constructor public KnowledgeBase() { } #endregion #region control methods public void Publish(string endpoint) { // publish this object m_thisObjRef = RemotingServices.Marshal(this, endpoint); } #endregion #region virtual handlers public virtual bool OnBeforeChangeKnowledgeBase(string name, string val) { return true; } public virtual void OnChangedKnowledgeBase(string name, string val) {} public virtual bool OnBeforeClearKnowledgeBase(string name) { return true; } public virtual void OnClearKnowledgeBase(string name) {} public virtual void OnLoadKnowledgeBase() {} #endregion #region IKnowledgeBaseControl public virtual void Save(string filename) { throw new NotSupportedException(); } public virtual void Load(string filename) { if(AllowToUpdate == false) throw new Exception("The Knowledge Base is locked"); // fire event OnLoadKnowledgeBase(); throw new NotSupportedException(); } public virtual void Store(string name, string val, bool bOverwrite) { // validation if(AllowToUpdate == false) throw new Exception("The Knowledge Base is locked"); if(KB.Contains(name) == true && bOverwrite == false) throw new Exception(string.Format("The logical name '{0}' already exist", name)); // fire event if(OnBeforeChangeKnowledgeBase(name, val) == false) return; // update/add value in the KB KB[name] = val; // fire event OnChangedKnowledgeBase(name, val); } public virtual void Store(string strLURL, bool bOverwrite) { string[] lurl = strLURL.Split(','); foreach(string s in lurl) { string[] nv = s.Split(new char[]{'='}, 2); if(nv.Length != 2) throw new Exception(string.Format("The logical name '{0}' doesn't have a value", s)); Store(nv[0].Trim(), nv[1].Trim(), bOverwrite); } } public virtual void Update(string name, string val) { // validation if(AllowToUpdate == false) throw new Exception("The Knowledge Base is locked"); if(KB.Contains(name) == false) throw new Exception(string.Format("The logical name '{0}' doesn't exist", name)); // fire event if(OnBeforeChangeKnowledgeBase(name, val) == false) return; // update value in the KB KB[name] = val; // fire event OnChangedKnowledgeBase(name, val); } public virtual void Update(string strLURL) { string[] lurl = strLURL.Split(','); foreach(string s in lurl) { string[] nv = s.Split(new char[]{'='}, 2); if(nv.Length != 2) throw new Exception(string.Format("The logical name '{0}' doesn't have a value", s)); Update(nv[0].Trim(), nv[1].Trim()); } } public virtual void RemoveAll() { if(AllowToUpdate == false) throw new Exception("The Knowledge Base is locked"); // fire event if(OnBeforeClearKnowledgeBase(null) == false) return; // clear KB KB.Clear(); // fire event OnClearKnowledgeBase(null); } public virtual void Remove(string name) { // validation if(AllowToUpdate == false) throw new Exception("The Knowledge Base is locked"); if(KB.Contains(name) == false) throw new Exception(string.Format("The logical name '{0}' doesn't exist", name)); // fire event if(OnBeforeClearKnowledgeBase(name) == false) return; // remove name from the KB KB.Remove(name); // fire event OnClearKnowledgeBase(name); } public virtual object GetAll() { return KB.Clone(); } public virtual string Get(string name) { // validation if(KB.Contains(name) == false) throw new Exception(string.Format("The logical name '{0}' doesn't exist", name)); return Convert.ToString(KB[name]); } public virtual string Mapping(string name) { return KB.Contains(name) == true ? Convert.ToString(KB[name]) : name; } public virtual bool Exists(string name) { return KB.Contains(name); } public virtual bool CanBeUpdated() { return AllowToUpdate; } #endregion #region InitializeLifetimeService public override object InitializeLifetimeService() { // infinite lifetime of the remoting access return null; } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // A simple coordination data structure that we use for fork/join style parallelism. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; namespace System.Threading { /// <summary> /// Represents a synchronization primitive that is signaled when its count reaches zero. /// </summary> /// <remarks> /// All public and protected members of <see cref="CountdownEvent"/> are thread-safe and may be used /// concurrently from multiple threads, with the exception of Dispose, which /// must only be used when all other operations on the <see cref="CountdownEvent"/> have /// completed, and Reset, which should only be used when no other threads are /// accessing the event. /// </remarks> [ComVisible(false)] [DebuggerDisplay("Initial Count={InitialCount}, Current Count={CurrentCount}")] public class CountdownEvent : IDisposable { // CountdownEvent is a simple synchronization primitive used for fork/join parallelism. We create a // latch with a count of N; threads then signal the latch, which decrements N by 1; other threads can // wait on the latch at any point; when the latch count reaches 0, all threads are woken and // subsequent waiters return without waiting. The implementation internally lazily creates a true // Win32 event as needed. We also use some amount of spinning on MP machines before falling back to a // wait. private int _initialCount; // The original # of signals the latch was instantiated with. private volatile int _currentCount; // The # of outstanding signals before the latch transitions to a signaled state. private ManualResetEventSlim _event; // An event used to manage blocking and signaling. private volatile bool _disposed; // Whether the latch has been disposed. /// <summary> /// Initializes a new instance of <see cref="T:System.Threading.CountdownEvent"/> class with the /// specified count. /// </summary> /// <param name="initialCount">The number of signals required to set the <see /// cref="T:System.Threading.CountdownEvent"/>.</param> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="initialCount"/> is less /// than 0.</exception> public CountdownEvent(int initialCount) { if (initialCount < 0) { throw new ArgumentOutOfRangeException("initialCount"); } _initialCount = initialCount; _currentCount = initialCount; // Allocate a thin event, which internally defers creation of an actual Win32 event. _event = new ManualResetEventSlim(); // If the latch was created with a count of 0, then it's already in the signaled state. if (initialCount == 0) { _event.Set(); } } /// <summary> /// Gets the number of remaining signals required to set the event. /// </summary> /// <value> /// The number of remaining signals required to set the event. /// </value> public int CurrentCount { get { int observedCount = _currentCount; return observedCount < 0 ? 0 : observedCount; } } /// <summary> /// Gets the numbers of signals initially required to set the event. /// </summary> /// <value> /// The number of signals initially required to set the event. /// </value> public int InitialCount { get { return _initialCount; } } /// <summary> /// Determines whether the event is set. /// </summary> /// <value>true if the event is set; otherwise, false.</value> public bool IsSet { get { // The latch is "completed" if its current count has reached 0. Note that this is NOT // the same thing is checking the event's IsCompleted property. There is a tiny window // of time, after the final decrement of the current count to 0 and before setting the // event, where the two values are out of sync. return (_currentCount <= 0); } } /// <summary> /// Gets a <see cref="T:System.Threading.WaitHandle"/> that is used to wait for the event to be set. /// </summary> /// <value>A <see cref="T:System.Threading.WaitHandle"/> that is used to wait for the event to be set.</value> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been disposed.</exception> /// <remarks> /// <see cref="WaitHandle"/> should only be used if it's needed for integration with code bases /// that rely on having a WaitHandle. If all that's needed is to wait for the <see cref="CountdownEvent"/> /// to be set, the <see cref="Wait()"/> method should be preferred. /// </remarks> public WaitHandle WaitHandle { get { ThrowIfDisposed(); return _event.WaitHandle; } } /// <summary> /// Releases all resources used by the current instance of <see cref="T:System.Threading.CountdownEvent"/>. /// </summary> /// <remarks> /// Unlike most of the members of <see cref="CountdownEvent"/>, <see cref="Dispose()"/> is not /// thread-safe and may not be used concurrently with other members of this instance. /// </remarks> public void Dispose() { // Gets rid of this latch's associated resources. This can consist of a Win32 event // which is (lazily) allocated by the underlying thin event. This method is not safe to // call concurrently -- i.e. a caller must coordinate to ensure only one thread is using // the latch at the time of the call to Dispose. Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// When overridden in a derived class, releases the unmanaged resources used by the /// <see cref="T:System.Threading.CountdownEvent"/>, and optionally releases the managed resources. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release /// only unmanaged resources.</param> /// <remarks> /// Unlike most of the members of <see cref="CountdownEvent"/>, <see cref="Dispose()"/> is not /// thread-safe and may not be used concurrently with other members of this instance. /// </remarks> protected virtual void Dispose(bool disposing) { if (disposing) { _event.Dispose(); _disposed = true; } } /// <summary> /// Registers a signal with the <see cref="T:System.Threading.CountdownEvent"/>, decrementing its /// count. /// </summary> /// <returns>true if the signal caused the count to reach zero and the event was set; otherwise, /// false.</returns> /// <exception cref="T:System.InvalidOperationException">The current instance is already set. /// </exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public bool Signal() { ThrowIfDisposed(); Debug.Assert(_event != null); if (_currentCount <= 0) { throw new InvalidOperationException(SR.CountdownEvent_Decrement_BelowZero); } #pragma warning disable 0420 int newCount = Interlocked.Decrement(ref _currentCount); #pragma warning restore 0420 if (newCount == 0) { _event.Set(); return true; } else if (newCount < 0) { //if the count is decremented below zero, then throw, it's OK to keep the count negative, and we shouldn't set the event here //because there was a thread already which decremented it to zero and set the event throw new InvalidOperationException(SR.CountdownEvent_Decrement_BelowZero); } return false; } /// <summary> /// Registers multiple signals with the <see cref="T:System.Threading.CountdownEvent"/>, /// decrementing its count by the specified amount. /// </summary> /// <param name="signalCount">The number of signals to register.</param> /// <returns>true if the signals caused the count to reach zero and the event was set; otherwise, /// false.</returns> /// <exception cref="T:System.InvalidOperationException"> /// The current instance is already set. -or- Or <paramref name="signalCount"/> is greater than <see /// cref="CurrentCount"/>. /// </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="signalCount"/> is less /// than 1.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public bool Signal(int signalCount) { if (signalCount <= 0) { throw new ArgumentOutOfRangeException("signalCount"); } ThrowIfDisposed(); Debug.Assert(_event != null); int observedCount; SpinWait spin = new SpinWait(); while (true) { observedCount = _currentCount; // If the latch is already signaled, we will fail. if (observedCount < signalCount) { throw new InvalidOperationException(SR.CountdownEvent_Decrement_BelowZero); } // This disables the "CS0420: a reference to a volatile field will not be treated as volatile" warning // for this statement. This warning is clearly senseless for Interlocked operations. #pragma warning disable 0420 if (Interlocked.CompareExchange(ref _currentCount, observedCount - signalCount, observedCount) == observedCount) #pragma warning restore 0420 { break; } // The CAS failed. Spin briefly and try again. spin.SpinOnce(); } // If we were the last to signal, set the event. if (observedCount == signalCount) { _event.Set(); return true; } Debug.Assert(_currentCount >= 0, "latch was decremented below zero"); return false; } /// <summary> /// Increments the <see cref="T:System.Threading.CountdownEvent"/>'s current count by one. /// </summary> /// <exception cref="T:System.InvalidOperationException">The current instance is already /// set.</exception> /// <exception cref="T:System.InvalidOperationException"><see cref="CurrentCount"/> is equal to <see /// cref="T:System.Int32.MaxValue"/>.</exception> /// <exception cref="T:System.ObjectDisposedException"> /// The current instance has already been disposed. /// </exception> public void AddCount() { AddCount(1); } /// <summary> /// Attempts to increment the <see cref="T:System.Threading.CountdownEvent"/>'s current count by one. /// </summary> /// <returns>true if the increment succeeded; otherwise, false. If <see cref="CurrentCount"/> is /// already at zero. this will return false.</returns> /// <exception cref="T:System.InvalidOperationException"><see cref="CurrentCount"/> is equal to <see /// cref="T:System.Int32.MaxValue"/>.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public bool TryAddCount() { return TryAddCount(1); } /// <summary> /// Increments the <see cref="T:System.Threading.CountdownEvent"/>'s current count by a specified /// value. /// </summary> /// <param name="signalCount">The value by which to increase <see cref="CurrentCount"/>.</param> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="signalCount"/> is less than /// 0.</exception> /// <exception cref="T:System.InvalidOperationException">The current instance is already /// set.</exception> /// <exception cref="T:System.InvalidOperationException"><see cref="CurrentCount"/> is equal to <see /// cref="T:System.Int32.MaxValue"/>.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public void AddCount(int signalCount) { if (!TryAddCount(signalCount)) { throw new InvalidOperationException(SR.CountdownEvent_Increment_AlreadyZero); } } /// <summary> /// Attempts to increment the <see cref="T:System.Threading.CountdownEvent"/>'s current count by a /// specified value. /// </summary> /// <param name="signalCount">The value by which to increase <see cref="CurrentCount"/>.</param> /// <returns>true if the increment succeeded; otherwise, false. If <see cref="CurrentCount"/> is /// already at zero this will return false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="signalCount"/> is less /// than 0.</exception> /// <exception cref="T:System.InvalidOperationException">The current instance is already /// set.</exception> /// <exception cref="T:System.InvalidOperationException"><see cref="CurrentCount"/> is equal to <see /// cref="T:System.Int32.MaxValue"/>.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public bool TryAddCount(int signalCount) { if (signalCount <= 0) { throw new ArgumentOutOfRangeException("signalCount"); } ThrowIfDisposed(); // Loop around until we successfully increment the count. int observedCount; SpinWait spin = new SpinWait(); while (true) { observedCount = _currentCount; if (observedCount <= 0) { return false; } else if (observedCount > (Int32.MaxValue - signalCount)) { throw new InvalidOperationException(SR.CountdownEvent_Increment_AlreadyMax); } // This disables the "CS0420: a reference to a volatile field will not be treated as volatile" warning // for this statement. This warning is clearly senseless for Interlocked operations. #pragma warning disable 0420 if (Interlocked.CompareExchange(ref _currentCount, observedCount + signalCount, observedCount) == observedCount) #pragma warning restore 0420 { break; } // The CAS failed. Spin briefly and try again. spin.SpinOnce(); } return true; } /// <summary> /// Resets the <see cref="CurrentCount"/> to the value of <see cref="InitialCount"/>. /// </summary> /// <remarks> /// Unlike most of the members of <see cref="CountdownEvent"/>, Reset is not /// thread-safe and may not be used concurrently with other members of this instance. /// </remarks> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed..</exception> public void Reset() { Reset(_initialCount); } /// <summary> /// Resets the <see cref="CurrentCount"/> to a specified value. /// </summary> /// <param name="count">The number of signals required to set the <see /// cref="T:System.Threading.CountdownEvent"/>.</param> /// <remarks> /// Unlike most of the members of <see cref="CountdownEvent"/>, Reset is not /// thread-safe and may not be used concurrently with other members of this instance. /// </remarks> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="count"/> is /// less than 0.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has alread been disposed.</exception> public void Reset(int count) { ThrowIfDisposed(); if (count < 0) { throw new ArgumentOutOfRangeException("count"); } _currentCount = count; _initialCount = count; if (count == 0) { _event.Set(); } else { _event.Reset(); } } /// <summary> /// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set. /// </summary> /// <remarks> /// The caller of this method blocks indefinitely until the current instance is set. The caller will /// return immediately if the event is currently in a set state. /// </remarks> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public void Wait() { Wait(Timeout.Infinite, new CancellationToken()); } /// <summary> /// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set, while /// observing a <see cref="T:System.Threading.CancellationToken"/>. /// </summary> /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to /// observe.</param> /// <remarks> /// The caller of this method blocks indefinitely until the current instance is set. The caller will /// return immediately if the event is currently in a set state. If the /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> being observed /// is canceled during the wait operation, an <see cref="T:System.OperationCanceledException"/> /// will be thrown. /// </remarks> /// <exception cref="T:System.OperationCanceledException"><paramref name="cancellationToken"/> has been /// canceled.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public void Wait(CancellationToken cancellationToken) { Wait(Timeout.Infinite, cancellationToken); } /// <summary> /// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set, using a /// <see cref="T:System.TimeSpan"/> to measure the time interval. /// </summary> /// <param name="timeout">A <see cref="T:System.TimeSpan"/> that represents the number of /// milliseconds to wait, or a <see cref="T:System.TimeSpan"/> that represents -1 milliseconds to /// wait indefinitely.</param> /// <returns>true if the <see cref="System.Threading.CountdownEvent"/> was set; otherwise, /// false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative /// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater /// than <see cref="System.Int32.MaxValue"/>.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public bool Wait(TimeSpan timeout) { long totalMilliseconds = (long)timeout.TotalMilliseconds; if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new ArgumentOutOfRangeException("timeout"); } return Wait((int)totalMilliseconds, new CancellationToken()); } /// <summary> /// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set, using /// a <see cref="T:System.TimeSpan"/> to measure the time interval, while observing a /// <see cref="T:System.Threading.CancellationToken"/>. /// </summary> /// <param name="timeout">A <see cref="T:System.TimeSpan"/> that represents the number of /// milliseconds to wait, or a <see cref="T:System.TimeSpan"/> that represents -1 milliseconds to /// wait indefinitely.</param> /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to /// observe.</param> /// <returns>true if the <see cref="System.Threading.CountdownEvent"/> was set; otherwise, /// false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative /// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater /// than <see cref="System.Int32.MaxValue"/>.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> /// <exception cref="T:System.OperationCanceledException"><paramref name="cancellationToken"/> has /// been canceled.</exception> public bool Wait(TimeSpan timeout, CancellationToken cancellationToken) { long totalMilliseconds = (long)timeout.TotalMilliseconds; if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new ArgumentOutOfRangeException("timeout"); } return Wait((int)totalMilliseconds, cancellationToken); } /// <summary> /// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set, using a /// 32-bit signed integer to measure the time interval. /// </summary> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see /// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param> /// <returns>true if the <see cref="System.Threading.CountdownEvent"/> was set; otherwise, /// false.</returns> /// <exception cref="ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a /// negative number other than -1, which represents an infinite time-out.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public bool Wait(int millisecondsTimeout) { return Wait(millisecondsTimeout, new CancellationToken()); } /// <summary> /// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set, using a /// 32-bit signed integer to measure the time interval, while observing a /// <see cref="T:System.Threading.CancellationToken"/>. /// </summary> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see /// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param> /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to /// observe.</param> /// <returns>true if the <see cref="System.Threading.CountdownEvent"/> was set; otherwise, /// false.</returns> /// <exception cref="ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a /// negative number other than -1, which represents an infinite time-out.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> /// <exception cref="T:System.OperationCanceledException"><paramref name="cancellationToken"/> has /// been canceled.</exception> public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken) { if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException("millisecondsTimeout"); } ThrowIfDisposed(); cancellationToken.ThrowIfCancellationRequested(); bool returnValue = IsSet; // If not completed yet, wait on the event. if (!returnValue) { // ** the actual wait returnValue = _event.Wait(millisecondsTimeout, cancellationToken); //the Wait will throw OCE itself if the token is canceled. } return returnValue; } // -------------------------------------- // Private methods /// <summary> /// Throws an exception if the latch has been disposed. /// </summary> private void ThrowIfDisposed() { if (_disposed) { throw new ObjectDisposedException("CountdownEvent"); } } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ /* ================================================================ * About NPOI * Author: Tony Qu * Author's email: tonyqus (at) gmail.com * Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn) * HomePage: http://www.codeplex.com/npoi * Contributors: * * ==============================================================*/ using System; using System.Collections; using System.IO; using NUnit.Framework; using NStorage.FileSystem; using NStorage.Utility; using NStorage.Storage; using NStorage.Properties; namespace NStorage.Test.POIFS.FileSystem { /** * Class to Test POIFSDocumentPath functionality * * @author Marc Johnson */ [TestFixture] public class TestPOIFSDocumentPath { /** * Constructor TestPOIFSDocumentPath * * @param name */ public TestPOIFSDocumentPath() { } /** * Test default constructor */ [Test] public void TestDefaultConstructor() { POIFSDocumentPath path = new POIFSDocumentPath(); Assert.AreEqual(0, path.Length); } /** * Test full path constructor */ [Test] public void TestFullPathConstructor() { string[] components = { "foo", "bar", "foobar", "fubar" }; for (int j = 0; j < components.Length; j++) { string[] pms = new string[j]; for (int k = 0; k < j; k++) { pms[k] = components[k]; } POIFSDocumentPath path = new POIFSDocumentPath(pms); Assert.AreEqual(j, path.Length); for (int k = 0; k < j; k++) { Assert.AreEqual(components[k], path.GetComponent(k)); } if (j == 0) Assert.IsNull(path.Parent); else { POIFSDocumentPath parent = path.Parent; Assert.IsNotNull(parent); Assert.AreEqual(j - 1, parent.Length); for (int k = 0; k < j - 1; k++) Assert.AreEqual(components[k], parent.GetComponent(k)); } } // Test weird variants Assert.AreEqual(0, new POIFSDocumentPath(null).Length); try { new POIFSDocumentPath(new string[] { "fu", "" }); Assert.Fail("Should have caught IllegalArgumentException"); } catch (ArgumentException) { } try { new POIFSDocumentPath(new string[] { "fu", null }); Assert.Fail("Should have caught IllegalArgumentException"); } catch (ArgumentException) { } } /** * Test relative path constructor */ [Test] public void TestRelativePathConstructor() { string[] initialComponents = { "a", "b", "c" }; for (int n = 0; n < initialComponents.Length; n++) { String[] initialParams = new String[n]; for (int k = 0; k < n; k++) initialParams[k] = initialComponents[k]; POIFSDocumentPath b = new POIFSDocumentPath(initialParams); string[] components = { "foo", "bar", "foobar", "fubar" }; for (int j = 0; j < components.Length; j++) { String[] params1 = new String[j]; for (int k = 0; k < j; k++) { params1[k] = components[k]; } POIFSDocumentPath path = new POIFSDocumentPath(b, params1); Assert.AreEqual(j + n, path.Length); for (int k = 0; k < n; k++) { Assert.AreEqual(initialComponents[k], path.GetComponent(k)); } for (int k = 0; k < j; k++) { Assert.AreEqual(components[k], path.GetComponent(k + n)); } if ((j + n) == 0) { Assert.IsNull(path.Parent); } else { POIFSDocumentPath parent = path.Parent; Assert.IsNotNull(parent); Assert.AreEqual(j + n - 1, parent.Length); for (int k = 0; k < (j + n - 1); k++) { Assert.AreEqual(path.GetComponent(k), parent.GetComponent(k)); } } } Assert.AreEqual(n, new POIFSDocumentPath(b, null).Length); //this one is allowed. new POIFSDocumentPath(b, new string[] { "fu", "" }); //this one is allowed too new POIFSDocumentPath(b, new string[] { "", "fu" }); //this one is not allowed. try { new POIFSDocumentPath(b, new string[] { "fu", null }); Assert.Fail("should have caught ArgumentException"); } catch (ArgumentException) { } try { new POIFSDocumentPath(b, new string[] { "fu", null }); Assert.Fail("should have caught ArgumentException"); } catch (ArgumentException) { } } } /** * Test equality */ [Test] public void TestEquality() { POIFSDocumentPath a1 = new POIFSDocumentPath(); POIFSDocumentPath a2 = new POIFSDocumentPath(null); POIFSDocumentPath a3 = new POIFSDocumentPath(new String[0]); POIFSDocumentPath a4 = new POIFSDocumentPath(a1, null); POIFSDocumentPath a5 = new POIFSDocumentPath(a1, new string[0]); POIFSDocumentPath[] paths = { a1, a2, a3, a4, a5 }; for (int j = 0; j < paths.Length; j++) { for (int k = 0; k < paths.Length; k++) Assert.AreEqual(paths[j], paths[k], j + "<>" + k); } a2 = new POIFSDocumentPath(a1, new string[] { "foo" }); a3 = new POIFSDocumentPath(a2, new string[] { "bar" }); a4 = new POIFSDocumentPath(a3, new string[] { "fubar" }); a5 = new POIFSDocumentPath(a4, new string[] { "foobar" }); POIFSDocumentPath[] builtUpPaths = { a1, a2, a3, a4, a5 }; POIFSDocumentPath[] fullPaths = { new POIFSDocumentPath(), new POIFSDocumentPath(new string[]{"foo"}), new POIFSDocumentPath(new string[]{"foo", "bar"}), new POIFSDocumentPath(new string[]{"foo", "bar", "fubar"}), new POIFSDocumentPath(new string[]{"foo", "bar", "fubar", "foobar"}) }; for (int k = 0; k < builtUpPaths.Length; k++) { for (int j = 0; j < fullPaths.Length; j++) { if (k == j) Assert.AreEqual(fullPaths[j], builtUpPaths[k], j + "<>" + k); else Assert.IsTrue(!(fullPaths[j].Equals(builtUpPaths[k])), j + "<>" + k); } } POIFSDocumentPath[] badPaths = { new POIFSDocumentPath(new string[]{"_foo"}), new POIFSDocumentPath(new string[]{"foo", "_bar"}), new POIFSDocumentPath(new string[]{"foo", "bar", "_fubar"}), new POIFSDocumentPath(new string[]{"foo", "bar", "fubar", "_foobar"}) }; for (int k = 0; k < builtUpPaths.Length; k++) { for (int j = 0; j < badPaths.Length; j++) Assert.IsTrue(!(fullPaths[k].Equals(badPaths[j])), j + "<>" + k); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; namespace System.Net.Sockets { // The Task-based APIs are currently wrappers over either the APM APIs (e.g. BeginConnect) // or the SocketAsyncEventArgs APIs (e.g. ReceiveAsync(SocketAsyncEventArgs)). The latter // are much more efficient when the SocketAsyncEventArg instances can be reused; as such, // at present we use them for ReceiveAsync and SendAsync, caching an instance for each. // In the future we could potentially maintain a global cache of instances used for accepts // and connects, and potentially separate per-socket instances for Receive{Message}FromAsync, // which would need different instances from ReceiveAsync due to having different results // and thus different Completed logic. We also currently fall back to APM implementations // when the single cached instance for each of send/receive is otherwise in use; we could // potentially also employ a global pool from which to pull in such situations. public partial class Socket { /// <summary>Handler for completed AcceptAsync operations.</summary> private static readonly EventHandler<SocketAsyncEventArgs> AcceptCompletedHandler = (s, e) => CompleteAccept((Socket)s, (TaskSocketAsyncEventArgs<Socket>)e); /// <summary>Handler for completed ReceiveAsync operations.</summary> private static readonly EventHandler<SocketAsyncEventArgs> ReceiveCompletedHandler = (s, e) => CompleteSendReceive((Socket)s, (Int32TaskSocketAsyncEventArgs)e, isReceive: true); /// <summary>Handler for completed SendAsync operations.</summary> private static readonly EventHandler<SocketAsyncEventArgs> SendCompletedHandler = (s, e) => CompleteSendReceive((Socket)s, (Int32TaskSocketAsyncEventArgs)e, isReceive: false); /// <summary> /// Sentinel that can be stored into one of the Socket cached fields to indicate that an instance /// was previously created but is currently being used by another concurrent operation. /// </summary> private static readonly TaskSocketAsyncEventArgs<Socket> s_rentedSocketSentinel = new TaskSocketAsyncEventArgs<Socket>(); /// <summary> /// Sentinel that can be stored into one of the Int32 fields to indicate that an instance /// was previously created but is currently being used by another concurrent operation. /// </summary> private static readonly Int32TaskSocketAsyncEventArgs s_rentedInt32Sentinel = new Int32TaskSocketAsyncEventArgs(); /// <summary>Cached task with a 0 value.</summary> private static readonly Task<int> s_zeroTask = Task.FromResult(0); /// <summary>Cached event args used with Task-based async operations.</summary> private CachedTaskEventArgs _cachedTaskEventArgs; internal Task<Socket> AcceptAsync(Socket acceptSocket) { // Get any cached SocketAsyncEventArg we may have. TaskSocketAsyncEventArgs<Socket> saea = Interlocked.Exchange(ref LazyInitializer.EnsureInitialized(ref _cachedTaskEventArgs).Accept, s_rentedSocketSentinel); if (saea == s_rentedSocketSentinel) { // An instance was once created (or is currently being created elsewhere), but some other // concurrent operation is using it. Since we can store at most one, and since an individual // APM operation is less expensive than creating a new SAEA and using it only once, we simply // fall back to using an APM implementation. return AcceptAsyncApm(acceptSocket); } else if (saea == null) { // No instance has been created yet, so create one. saea = new TaskSocketAsyncEventArgs<Socket>(); saea.Completed += AcceptCompletedHandler; } // Configure the SAEA. saea.AcceptSocket = acceptSocket; // Initiate the accept operation. Task<Socket> t; if (AcceptAsync(saea)) { // The operation is completing asynchronously (it may have already completed). // Get the task for the operation, with appropriate synchronization to coordinate // with the async callback that'll be completing the task. bool responsibleForReturningToPool; t = saea.GetCompletionResponsibility(out responsibleForReturningToPool).Task; if (responsibleForReturningToPool) { // We're responsible for returning it only if the callback has already been invoked // and gotten what it needs from the SAEA; otherwise, the callback will return it. ReturnSocketAsyncEventArgs(saea); } } else { // The operation completed synchronously. Get a task for it. t = saea.SocketError == SocketError.Success ? Task.FromResult(saea.AcceptSocket) : Task.FromException<Socket>(GetException(saea.SocketError)); // There won't be a callback, and we're done with the SAEA, so return it to the pool. ReturnSocketAsyncEventArgs(saea); } return t; } /// <summary>Implements Task-returning AcceptAsync on top of Begin/EndAsync.</summary> private Task<Socket> AcceptAsyncApm(Socket acceptSocket) { var tcs = new TaskCompletionSource<Socket>(this); BeginAccept(acceptSocket, 0, iar => { var innerTcs = (TaskCompletionSource<Socket>)iar.AsyncState; try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState).EndAccept(iar)); } catch (Exception e) { innerTcs.TrySetException(e); } }, tcs); return tcs.Task; } internal Task ConnectAsync(EndPoint remoteEP) { var tcs = new TaskCompletionSource<bool>(this); BeginConnect(remoteEP, iar => { var innerTcs = (TaskCompletionSource<bool>)iar.AsyncState; try { ((Socket)innerTcs.Task.AsyncState).EndConnect(iar); innerTcs.TrySetResult(true); } catch (Exception e) { innerTcs.TrySetException(e); } }, tcs); return tcs.Task; } internal Task ConnectAsync(IPAddress address, int port) { var tcs = new TaskCompletionSource<bool>(this); BeginConnect(address, port, iar => { var innerTcs = (TaskCompletionSource<bool>)iar.AsyncState; try { ((Socket)innerTcs.Task.AsyncState).EndConnect(iar); innerTcs.TrySetResult(true); } catch (Exception e) { innerTcs.TrySetException(e); } }, tcs); return tcs.Task; } internal Task ConnectAsync(IPAddress[] addresses, int port) { var tcs = new TaskCompletionSource<bool>(this); BeginConnect(addresses, port, iar => { var innerTcs = (TaskCompletionSource<bool>)iar.AsyncState; try { ((Socket)innerTcs.Task.AsyncState).EndConnect(iar); innerTcs.TrySetResult(true); } catch (Exception e) { innerTcs.TrySetException(e); } }, tcs); return tcs.Task; } internal Task ConnectAsync(string host, int port) { var tcs = new TaskCompletionSource<bool>(this); BeginConnect(host, port, iar => { var innerTcs = (TaskCompletionSource<bool>)iar.AsyncState; try { ((Socket)innerTcs.Task.AsyncState).EndConnect(iar); innerTcs.TrySetResult(true); } catch (Exception e) { innerTcs.TrySetException(e); } }, tcs); return tcs.Task; } internal Task<int> ReceiveAsync(ArraySegment<byte> buffer, SocketFlags socketFlags, bool fromNetworkStream) { // Validate the arguments. ValidateBuffer(buffer); Int32TaskSocketAsyncEventArgs saea = RentSocketAsyncEventArgs(isReceive: true); if (saea != null) { // We got a cached instance. Configure the buffer and initate the operation. ConfigureBuffer(saea, buffer, socketFlags, wrapExceptionsInIOExceptions: fromNetworkStream); return GetTaskForSendReceive(ReceiveAsync(saea), saea, fromNetworkStream, isReceive: true); } else { // We couldn't get a cached instance, due to a concurrent receive operation on the socket. // Fall back to wrapping APM. return ReceiveAsyncApm(buffer, socketFlags); } } internal ValueTask<int> ReceiveAsync(Memory<byte> buffer, SocketFlags socketFlags, bool fromNetworkStream, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return new ValueTask<int>(Task.FromCanceled<int>(cancellationToken)); } // TODO https://github.com/dotnet/corefx/issues/24430: // Fully plumb cancellation down into socket operations. Int32TaskSocketAsyncEventArgs saea = RentSocketAsyncEventArgs(isReceive: true); if (saea != null) { // We got a cached instance. Configure the buffer and initate the operation. ConfigureBuffer(saea, buffer, socketFlags, wrapExceptionsInIOExceptions: fromNetworkStream); return GetValueTaskForSendReceive(ReceiveAsync(saea), saea, fromNetworkStream, isReceive: true); } else { // We couldn't get a cached instance, due to a concurrent receive operation on the socket. // Fall back to wrapping APM. return new ValueTask<int>(ReceiveAsyncApm(buffer, socketFlags)); } } /// <summary>Implements Task-returning ReceiveAsync on top of Begin/EndReceive.</summary> private Task<int> ReceiveAsyncApm(Memory<byte> buffer, SocketFlags socketFlags) { if (buffer.TryGetArray(out ArraySegment<byte> bufferArray)) { // We were able to extract the underlying byte[] from the Memory<byte>. Use it. var tcs = new TaskCompletionSource<int>(this); BeginReceive(bufferArray.Array, bufferArray.Offset, bufferArray.Count, socketFlags, iar => { var innerTcs = (TaskCompletionSource<int>)iar.AsyncState; try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState).EndReceive(iar)); } catch (Exception e) { innerTcs.TrySetException(e); } }, tcs); return tcs.Task; } else { // We weren't able to extract an underlying byte[] from the Memory<byte>. // Instead read into an ArrayPool array, then copy from that into the memory. byte[] poolArray = ArrayPool<byte>.Shared.Rent(buffer.Length); var tcs = new TaskCompletionSource<int>(this); BeginReceive(poolArray, 0, buffer.Length, socketFlags, iar => { var state = (Tuple<TaskCompletionSource<int>, Memory<byte>, byte[]>)iar.AsyncState; try { int bytesCopied = ((Socket)state.Item1.Task.AsyncState).EndReceive(iar); new ReadOnlyMemory<byte>(state.Item3, 0, bytesCopied).Span.CopyTo(state.Item2.Span); state.Item1.TrySetResult(bytesCopied); } catch (Exception e) { state.Item1.TrySetException(e); } finally { ArrayPool<byte>.Shared.Return(state.Item3); } }, Tuple.Create(tcs, buffer, poolArray)); return tcs.Task; } } internal Task<int> ReceiveAsync(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags) { // Validate the arguments. ValidateBuffersList(buffers); Int32TaskSocketAsyncEventArgs saea = RentSocketAsyncEventArgs(isReceive: true); if (saea != null) { // We got a cached instance. Configure the buffer list and initate the operation. ConfigureBufferList(saea, buffers, socketFlags); return GetTaskForSendReceive(ReceiveAsync(saea), saea, fromNetworkStream: false, isReceive: true); } else { // We couldn't get a cached instance, due to a concurrent receive operation on the socket. // Fall back to wrapping APM. return ReceiveAsyncApm(buffers, socketFlags); } } /// <summary>Implements Task-returning ReceiveAsync on top of Begin/EndReceive.</summary> private Task<int> ReceiveAsyncApm(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags) { var tcs = new TaskCompletionSource<int>(this); BeginReceive(buffers, socketFlags, iar => { var innerTcs = (TaskCompletionSource<int>)iar.AsyncState; try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState).EndReceive(iar)); } catch (Exception e) { innerTcs.TrySetException(e); } }, tcs); return tcs.Task; } internal Task<SocketReceiveFromResult> ReceiveFromAsync(ArraySegment<byte> buffer, SocketFlags socketFlags, EndPoint remoteEndPoint) { var tcs = new StateTaskCompletionSource<EndPoint, SocketReceiveFromResult>(this) { _field1 = remoteEndPoint }; BeginReceiveFrom(buffer.Array, buffer.Offset, buffer.Count, socketFlags, ref tcs._field1, iar => { var innerTcs = (StateTaskCompletionSource<EndPoint, SocketReceiveFromResult>)iar.AsyncState; try { int receivedBytes = ((Socket)innerTcs.Task.AsyncState).EndReceiveFrom(iar, ref innerTcs._field1); innerTcs.TrySetResult(new SocketReceiveFromResult { ReceivedBytes = receivedBytes, RemoteEndPoint = innerTcs._field1 }); } catch (Exception e) { innerTcs.TrySetException(e); } }, tcs); return tcs.Task; } internal Task<SocketReceiveMessageFromResult> ReceiveMessageFromAsync(ArraySegment<byte> buffer, SocketFlags socketFlags, EndPoint remoteEndPoint) { var tcs = new StateTaskCompletionSource<SocketFlags, EndPoint, SocketReceiveMessageFromResult>(this) { _field1 = socketFlags, _field2 = remoteEndPoint }; BeginReceiveMessageFrom(buffer.Array, buffer.Offset, buffer.Count, socketFlags, ref tcs._field2, iar => { var innerTcs = (StateTaskCompletionSource<SocketFlags, EndPoint, SocketReceiveMessageFromResult>)iar.AsyncState; try { IPPacketInformation ipPacketInformation; int receivedBytes = ((Socket)innerTcs.Task.AsyncState).EndReceiveMessageFrom(iar, ref innerTcs._field1, ref innerTcs._field2, out ipPacketInformation); innerTcs.TrySetResult(new SocketReceiveMessageFromResult { ReceivedBytes = receivedBytes, RemoteEndPoint = innerTcs._field2, SocketFlags = innerTcs._field1, PacketInformation = ipPacketInformation }); } catch (Exception e) { innerTcs.TrySetException(e); } }, tcs); return tcs.Task; } internal Task<int> SendAsync(ArraySegment<byte> buffer, SocketFlags socketFlags, bool fromNetworkStream) { // Validate the arguments. ValidateBuffer(buffer); Int32TaskSocketAsyncEventArgs saea = RentSocketAsyncEventArgs(isReceive: false); if (saea != null) { // We got a cached instance. Configure the buffer and initate the operation. ConfigureBuffer(saea, buffer, socketFlags, wrapExceptionsInIOExceptions: fromNetworkStream); return GetTaskForSendReceive(SendAsync(saea), saea, fromNetworkStream, isReceive: false); } else { // We couldn't get a cached instance, due to a concurrent send operation on the socket. // Fall back to wrapping APM. return SendAsyncApm(buffer, socketFlags); } } internal ValueTask<int> SendAsync(ReadOnlyMemory<byte> buffer, SocketFlags socketFlags, bool fromNetworkStream, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return new ValueTask<int>(Task.FromCanceled<int>(cancellationToken)); } // TODO https://github.com/dotnet/corefx/issues/24430: // Fully plumb cancellation down into socket operations. Int32TaskSocketAsyncEventArgs saea = RentSocketAsyncEventArgs(isReceive: false); if (saea != null) { // We got a cached instance. Configure the buffer and initate the operation. ConfigureBuffer(saea, Unsafe.As<ReadOnlyMemory<byte>,Memory<byte>>(ref buffer), socketFlags, wrapExceptionsInIOExceptions: fromNetworkStream); return GetValueTaskForSendReceive(SendAsync(saea), saea, fromNetworkStream, isReceive: false); } else { // We couldn't get a cached instance, due to a concurrent send operation on the socket. // Fall back to wrapping APM. return new ValueTask<int>(SendAsyncApm(buffer, socketFlags)); } } /// <summary>Implements Task-returning SendAsync on top of Begin/EndSend.</summary> private Task<int> SendAsyncApm(ReadOnlyMemory<byte> buffer, SocketFlags socketFlags) { if (buffer.DangerousTryGetArray(out ArraySegment<byte> bufferArray)) { var tcs = new TaskCompletionSource<int>(this); BeginSend(bufferArray.Array, bufferArray.Offset, bufferArray.Count, socketFlags, iar => { var innerTcs = (TaskCompletionSource<int>)iar.AsyncState; try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState).EndSend(iar)); } catch (Exception e) { innerTcs.TrySetException(e); } }, tcs); return tcs.Task; } else { // We weren't able to extract an underlying byte[] from the Memory<byte>. // Instead read into an ArrayPool array, then copy from that into the memory. byte[] poolArray = ArrayPool<byte>.Shared.Rent(buffer.Length); buffer.Span.CopyTo(poolArray); var tcs = new TaskCompletionSource<int>(this); BeginSend(poolArray, 0, buffer.Length, socketFlags, iar => { var state = (Tuple<TaskCompletionSource<int>, byte[]>)iar.AsyncState; try { state.Item1.TrySetResult(((Socket)state.Item1.Task.AsyncState).EndSend(iar)); } catch (Exception e) { state.Item1.TrySetException(e); } finally { ArrayPool<byte>.Shared.Return(state.Item2); } }, Tuple.Create(tcs, poolArray)); return tcs.Task; } } internal Task<int> SendAsync(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags) { // Validate the arguments. ValidateBuffersList(buffers); Int32TaskSocketAsyncEventArgs saea = RentSocketAsyncEventArgs(isReceive: false); if (saea != null) { // We got a cached instance. Configure the buffer list and initate the operation. ConfigureBufferList(saea, buffers, socketFlags); return GetTaskForSendReceive(SendAsync(saea), saea, fromNetworkStream: false, isReceive: false); } else { // We couldn't get a cached instance, due to a concurrent send operation on the socket. // Fall back to wrapping APM. return SendAsyncApm(buffers, socketFlags); } } /// <summary>Implements Task-returning SendAsync on top of Begin/EndSend.</summary> private Task<int> SendAsyncApm(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags) { var tcs = new TaskCompletionSource<int>(this); BeginSend(buffers, socketFlags, iar => { var innerTcs = (TaskCompletionSource<int>)iar.AsyncState; try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState).EndSend(iar)); } catch (Exception e) { innerTcs.TrySetException(e); } }, tcs); return tcs.Task; } internal Task<int> SendToAsync(ArraySegment<byte> buffer, SocketFlags socketFlags, EndPoint remoteEP) { var tcs = new TaskCompletionSource<int>(this); BeginSendTo(buffer.Array, buffer.Offset, buffer.Count, socketFlags, remoteEP, iar => { var innerTcs = (TaskCompletionSource<int>)iar.AsyncState; try { innerTcs.TrySetResult(((Socket)innerTcs.Task.AsyncState).EndSendTo(iar)); } catch (Exception e) { innerTcs.TrySetException(e); } }, tcs); return tcs.Task; } /// <summary>Validates the supplied array segment, throwing if its array or indices are null or out-of-bounds, respectively.</summary> private static void ValidateBuffer(ArraySegment<byte> buffer) { if (buffer.Array == null) { throw new ArgumentNullException(nameof(buffer.Array)); } if (buffer.Offset < 0 || buffer.Offset > buffer.Array.Length) { throw new ArgumentOutOfRangeException(nameof(buffer.Offset)); } if (buffer.Count < 0 || buffer.Count > buffer.Array.Length - buffer.Offset) { throw new ArgumentOutOfRangeException(nameof(buffer.Count)); } } /// <summary>Validates the supplied buffer list, throwing if it's null or empty.</summary> private static void ValidateBuffersList(IList<ArraySegment<byte>> buffers) { if (buffers == null) { throw new ArgumentNullException(nameof(buffers)); } if (buffers.Count == 0) { throw new ArgumentException(SR.Format(SR.net_sockets_zerolist, nameof(buffers)), nameof(buffers)); } } private static void ConfigureBuffer( Int32TaskSocketAsyncEventArgs saea, Memory<byte> buffer, SocketFlags socketFlags, bool wrapExceptionsInIOExceptions) { // Configure the buffer. We don't clear the buffers when returning the SAEA to the pool, // so as to minimize overhead if the same buffer is used for subsequent operations (which is likely). // But SAEA doesn't support having both a buffer and a buffer list configured, so clear out a buffer list // if there is one before we set the desired buffer. if (saea.BufferList != null) saea.BufferList = null; saea.SetBuffer(buffer); saea.SocketFlags = socketFlags; saea._wrapExceptionsInIOExceptions = wrapExceptionsInIOExceptions; } private static void ConfigureBufferList( Int32TaskSocketAsyncEventArgs saea, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags) { // Configure the buffer list. We don't clear the buffers when returning the SAEA to the pool, // so as to minimize overhead if the same buffers are used for subsequent operations (which is likely). // But SAEA doesn't support having both a buffer and a buffer list configured, so clear out a buffer // if there is one before we set the desired buffer list. if (saea.Buffer != null) saea.SetBuffer(null, 0, 0); saea.BufferList = buffers; saea.SocketFlags = socketFlags; } /// <summary>Gets a task to represent the operation.</summary> /// <param name="pending">true if the operation completes asynchronously; false if it completed synchronously.</param> /// <param name="saea">The event args instance used with the operation.</param> /// <param name="fromNetworkStream"> /// true if the request is coming from NetworkStream, which has special semantics for /// exceptions and cached tasks; otherwise, false. /// </param> /// <param name="isReceive">true if this is a receive; false if this is a send.</param> private Task<int> GetTaskForSendReceive( bool pending, Int32TaskSocketAsyncEventArgs saea, bool fromNetworkStream, bool isReceive) { Task<int> t; if (pending) { // The operation is completing asynchronously (it may have already completed). // Get the task for the operation, with appropriate synchronization to coordinate // with the async callback that'll be completing the task. bool responsibleForReturningToPool; t = saea.GetCompletionResponsibility(out responsibleForReturningToPool).Task; if (responsibleForReturningToPool) { // We're responsible for returning it only if the callback has already been invoked // and gotten what it needs from the SAEA; otherwise, the callback will return it. ReturnSocketAsyncEventArgs(saea, isReceive); } } else { // The operation completed synchronously. Get a task for it. if (saea.SocketError == SocketError.Success) { // Get the number of bytes successfully received/sent. int bytesTransferred = saea.BytesTransferred; // For zero bytes transferred, we can return our cached 0 task. // We can also do so if the request came from network stream and is a send, // as for that we can return any value because it returns a non-generic Task. if (bytesTransferred == 0 || (fromNetworkStream & !isReceive)) { t = s_zeroTask; } else { // Get any cached, successfully-completed cached task that may exist on this SAEA. Task<int> lastTask = saea._successfullyCompletedTask; Debug.Assert(lastTask == null || lastTask.IsCompletedSuccessfully); // If there is a task and if it has the desired result, simply reuse it. // Otherwise, create a new one for this result value, and in addition to returning it, // also store it into the SAEA for potential future reuse. t = lastTask != null && lastTask.Result == bytesTransferred ? lastTask : (saea._successfullyCompletedTask = Task.FromResult(bytesTransferred)); } } else { t = Task.FromException<int>(GetException(saea.SocketError, wrapExceptionsInIOExceptions: fromNetworkStream)); } // There won't be a callback, and we're done with the SAEA, so return it to the pool. ReturnSocketAsyncEventArgs(saea, isReceive); } return t; } /// <summary>Gets a value task to represent the operation.</summary> /// <param name="pending">true if the operation completes asynchronously; false if it completed synchronously.</param> /// <param name="saea">The event args instance used with the operation.</param> /// <param name="fromNetworkStream"> /// true if the request is coming from NetworkStream, which has special semantics for /// exceptions and cached tasks; otherwise, false. /// </param> /// <param name="isReceive">true if this is a receive; false if this is a send.</param> private ValueTask<int> GetValueTaskForSendReceive( bool pending, Int32TaskSocketAsyncEventArgs saea, bool fromNetworkStream, bool isReceive) { ValueTask<int> t; if (pending) { // The operation is completing asynchronously (it may have already completed). // Get the task for the operation, with appropriate synchronization to coordinate // with the async callback that'll be completing the task. bool responsibleForReturningToPool; t = new ValueTask<int>(saea.GetCompletionResponsibility(out responsibleForReturningToPool).Task); if (responsibleForReturningToPool) { // We're responsible for returning it only if the callback has already been invoked // and gotten what it needs from the SAEA; otherwise, the callback will return it. ReturnSocketAsyncEventArgs(saea, isReceive); } } else { // The operation completed synchronously. Return a ValueTask for it. t = saea.SocketError == SocketError.Success ? new ValueTask<int>(saea.BytesTransferred) : new ValueTask<int>(Task.FromException<int>(GetException(saea.SocketError, wrapExceptionsInIOExceptions: fromNetworkStream))); // There won't be a callback, and we're done with the SAEA, so return it to the pool. ReturnSocketAsyncEventArgs(saea, isReceive); } return t; } /// <summary>Completes the SocketAsyncEventArg's Task with the result of the send or receive, and returns it to the specified pool.</summary> private static void CompleteAccept(Socket s, TaskSocketAsyncEventArgs<Socket> saea) { // Pull the relevant state off of the SAEA SocketError error = saea.SocketError; Socket acceptSocket = saea.AcceptSocket; // Synchronize with the initiating thread. If the synchronous caller already got what // it needs from the SAEA, then we can return it to the pool now. Otherwise, it'll be // responsible for returning it once it's gotten what it needs from it. bool responsibleForReturningToPool; AsyncTaskMethodBuilder<Socket> builder = saea.GetCompletionResponsibility(out responsibleForReturningToPool); if (responsibleForReturningToPool) { s.ReturnSocketAsyncEventArgs(saea); } // Complete the builder/task with the results. if (error == SocketError.Success) { builder.SetResult(acceptSocket); } else { builder.SetException(GetException(error)); } } /// <summary>Completes the SocketAsyncEventArg's Task with the result of the send or receive, and returns it to the specified pool.</summary> private static void CompleteSendReceive(Socket s, Int32TaskSocketAsyncEventArgs saea, bool isReceive) { // Pull the relevant state off of the SAEA SocketError error = saea.SocketError; int bytesTransferred = saea.BytesTransferred; bool wrapExceptionsInIOExceptions = saea._wrapExceptionsInIOExceptions; // Synchronize with the initiating thread. If the synchronous caller already got what // it needs from the SAEA, then we can return it to the pool now. Otherwise, it'll be // responsible for returning it once it's gotten what it needs from it. bool responsibleForReturningToPool; AsyncTaskMethodBuilder<int> builder = saea.GetCompletionResponsibility(out responsibleForReturningToPool); if (responsibleForReturningToPool) { s.ReturnSocketAsyncEventArgs(saea, isReceive); } // Complete the builder/task with the results. if (error == SocketError.Success) { builder.SetResult(bytesTransferred); } else { builder.SetException(GetException(error, wrapExceptionsInIOExceptions)); } } /// <summary>Gets a SocketException or an IOException wrapping a SocketException for the specified error.</summary> private static Exception GetException(SocketError error, bool wrapExceptionsInIOExceptions = false) { Exception e = new SocketException((int)error); return wrapExceptionsInIOExceptions ? new IOException(SR.Format(SR.net_io_readwritefailure, e.Message), e) : e; } /// <summary>Rents a <see cref="Int32TaskSocketAsyncEventArgs"/> for immediate use.</summary> /// <param name="isReceive">true if this instance will be used for a receive; false if for sends.</param> private Int32TaskSocketAsyncEventArgs RentSocketAsyncEventArgs(bool isReceive) { // Get any cached SocketAsyncEventArg we may have. CachedTaskEventArgs cea = LazyInitializer.EnsureInitialized(ref _cachedTaskEventArgs); Int32TaskSocketAsyncEventArgs saea = isReceive ? Interlocked.Exchange(ref cea.Receive, s_rentedInt32Sentinel) : Interlocked.Exchange(ref cea.Send, s_rentedInt32Sentinel); if (saea == s_rentedInt32Sentinel) { // An instance was once created (or is currently being created elsewhere), but some other // concurrent operation is using it. Since we can store at most one, and since an individual // APM operation is less expensive than creating a new SAEA and using it only once, we simply // return null, for a caller to fall back to using an APM implementation. return null; } if (saea == null) { // No instance has been created yet, so create one. saea = new Int32TaskSocketAsyncEventArgs(); saea.Completed += isReceive ? ReceiveCompletedHandler : SendCompletedHandler; } return saea; } /// <summary>Returns a <see cref="Int32TaskSocketAsyncEventArgs"/> instance for reuse.</summary> /// <param name="saea">The instance to return.</param> /// <param name="isReceive">true if this instance is used for receives; false if used for sends.</param> private void ReturnSocketAsyncEventArgs(Int32TaskSocketAsyncEventArgs saea, bool isReceive) { Debug.Assert(_cachedTaskEventArgs != null, "Should have been initialized when renting"); Debug.Assert(saea != s_rentedInt32Sentinel); // Reset state on the SAEA before returning it. But do not reset buffer state. That'll be done // if necessary by the consumer, but we want to keep the buffers due to likely subsequent reuse // and the costs associated with changing them. saea._accessed = false; saea._builder = default(AsyncTaskMethodBuilder<int>); saea._wrapExceptionsInIOExceptions = false; // Write this instance back as a cached instance. It should only ever be overwriting the sentinel, // never null or another instance. if (isReceive) { Debug.Assert(_cachedTaskEventArgs.Receive == s_rentedInt32Sentinel); Volatile.Write(ref _cachedTaskEventArgs.Receive, saea); } else { Debug.Assert(_cachedTaskEventArgs.Send == s_rentedInt32Sentinel); Volatile.Write(ref _cachedTaskEventArgs.Send, saea); } } /// <summary>Returns a <see cref="Int32TaskSocketAsyncEventArgs"/> instance for reuse.</summary> /// <param name="saea">The instance to return.</param> /// <param name="isReceive">true if this instance is used for receives; false if used for sends.</param> private void ReturnSocketAsyncEventArgs(TaskSocketAsyncEventArgs<Socket> saea) { Debug.Assert(_cachedTaskEventArgs != null, "Should have been initialized when renting"); Debug.Assert(saea != s_rentedSocketSentinel); // Reset state on the SAEA before returning it. But do not reset buffer state. That'll be done // if necessary by the consumer, but we want to keep the buffers due to likely subsequent reuse // and the costs associated with changing them. saea.AcceptSocket = null; saea._accessed = false; saea._builder = default(AsyncTaskMethodBuilder<Socket>); // Write this instance back as a cached instance. It should only ever be overwriting the sentinel, // never null or another instance. Debug.Assert(_cachedTaskEventArgs.Accept == s_rentedSocketSentinel); Volatile.Write(ref _cachedTaskEventArgs.Accept, saea); } /// <summary>Dispose of any cached <see cref="Int32TaskSocketAsyncEventArgs"/> instances.</summary> private void DisposeCachedTaskSocketAsyncEventArgs() { CachedTaskEventArgs cea = _cachedTaskEventArgs; if (cea != null) { Interlocked.Exchange(ref cea.Accept, s_rentedSocketSentinel)?.Dispose(); Interlocked.Exchange(ref cea.Receive, s_rentedInt32Sentinel)?.Dispose(); Interlocked.Exchange(ref cea.Send, s_rentedInt32Sentinel)?.Dispose(); } } /// <summary>A TaskCompletionSource that carries an extra field of strongly-typed state.</summary> private class StateTaskCompletionSource<TField1, TResult> : TaskCompletionSource<TResult> { internal TField1 _field1; public StateTaskCompletionSource(object baseState) : base(baseState) { } } /// <summary>A TaskCompletionSource that carries several extra fields of strongly-typed state.</summary> private class StateTaskCompletionSource<TField1, TField2, TResult> : StateTaskCompletionSource<TField1, TResult> { internal TField2 _field2; public StateTaskCompletionSource(object baseState) : base(baseState) { } } /// <summary>Cached event args used with Task-based async operations.</summary> private sealed class CachedTaskEventArgs { /// <summary>Cached instance for accept operations.</summary> public TaskSocketAsyncEventArgs<Socket> Accept; /// <summary>Cached instance for receive operations.</summary> public Int32TaskSocketAsyncEventArgs Receive; /// <summary>Cached instance for send operations.</summary> public Int32TaskSocketAsyncEventArgs Send; } /// <summary>A SocketAsyncEventArgs with an associated async method builder.</summary> private class TaskSocketAsyncEventArgs<TResult> : SocketAsyncEventArgs { /// <summary> /// The builder used to create the Task representing the result of the async operation. /// This is a mutable struct. /// </summary> internal AsyncTaskMethodBuilder<TResult> _builder; /// <summary> /// Whether the instance was already accessed as part of the operation. We expect /// at most two accesses: one from the synchronous caller to initiate the operation, /// and one from the callback if the operation completes asynchronously. If it completes /// synchronously, then it's the initiator's responsbility to return the instance to /// the pool. If it completes asynchronously, then it's the responsibility of whoever /// accesses this second, so we track whether it's already been accessed. /// </summary> internal bool _accessed = false; /// <summary>Gets the builder's task with appropriate synchronization.</summary> internal AsyncTaskMethodBuilder<TResult> GetCompletionResponsibility(out bool responsibleForReturningToPool) { lock (this) { responsibleForReturningToPool = _accessed; _accessed = true; var ignored = _builder.Task; // force initialization under the lock (builder itself lazily initializes w/o synchronization) return _builder; } } } /// <summary>A SocketAsyncEventArgs with an associated async method builder.</summary> private sealed class Int32TaskSocketAsyncEventArgs : TaskSocketAsyncEventArgs<int> { /// <summary>A cached, successfully completed task.</summary> internal Task<int> _successfullyCompletedTask; /// <summary>Whether exceptions that emerge should be wrapped in IOExceptions.</summary> internal bool _wrapExceptionsInIOExceptions; } } }
namespace android.location { [global::MonoJavaBridge.JavaClass()] public sealed partial class GpsStatus : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal GpsStatus(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaInterface(typeof(global::android.location.GpsStatus.Listener_))] public partial interface Listener : global::MonoJavaBridge.IJavaObject { void onGpsStatusChanged(int arg0); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.location.GpsStatus.Listener))] internal sealed partial class Listener_ : java.lang.Object, Listener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal Listener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; void android.location.GpsStatus.Listener.onGpsStatusChanged(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.GpsStatus.Listener_.staticClass, "onGpsStatusChanged", "(I)V", ref global::android.location.GpsStatus.Listener_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } static Listener_() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.location.GpsStatus.Listener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/location/GpsStatus$Listener")); } } public delegate void ListenerDelegate(int arg0); internal partial class ListenerDelegateWrapper : java.lang.Object, Listener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected ListenerDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public ListenerDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.location.GpsStatus.ListenerDelegateWrapper._m0.native == global::System.IntPtr.Zero) global::android.location.GpsStatus.ListenerDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.location.GpsStatus.ListenerDelegateWrapper.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.location.GpsStatus.ListenerDelegateWrapper.staticClass, global::android.location.GpsStatus.ListenerDelegateWrapper._m0); Init(@__env, handle); } static ListenerDelegateWrapper() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.location.GpsStatus.ListenerDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/location/GpsStatus_ListenerDelegateWrapper")); } } internal partial class ListenerDelegateWrapper { private ListenerDelegate myDelegate; public void onGpsStatusChanged(int arg0) { myDelegate(arg0); } public static implicit operator ListenerDelegateWrapper(ListenerDelegate d) { global::android.location.GpsStatus.ListenerDelegateWrapper ret = new global::android.location.GpsStatus.ListenerDelegateWrapper(); ret.myDelegate = d; global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret); return ret; } } [global::MonoJavaBridge.JavaInterface(typeof(global::android.location.GpsStatus.NmeaListener_))] public partial interface NmeaListener : global::MonoJavaBridge.IJavaObject { void onNmeaReceived(long arg0, java.lang.String arg1); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.location.GpsStatus.NmeaListener))] internal sealed partial class NmeaListener_ : java.lang.Object, NmeaListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal NmeaListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; void android.location.GpsStatus.NmeaListener.onNmeaReceived(long arg0, java.lang.String arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.GpsStatus.NmeaListener_.staticClass, "onNmeaReceived", "(JLjava/lang/String;)V", ref global::android.location.GpsStatus.NmeaListener_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } static NmeaListener_() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.location.GpsStatus.NmeaListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/location/GpsStatus$NmeaListener")); } } public delegate void NmeaListenerDelegate(long arg0, java.lang.String arg1); internal partial class NmeaListenerDelegateWrapper : java.lang.Object, NmeaListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected NmeaListenerDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public NmeaListenerDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.location.GpsStatus.NmeaListenerDelegateWrapper._m0.native == global::System.IntPtr.Zero) global::android.location.GpsStatus.NmeaListenerDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.location.GpsStatus.NmeaListenerDelegateWrapper.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.location.GpsStatus.NmeaListenerDelegateWrapper.staticClass, global::android.location.GpsStatus.NmeaListenerDelegateWrapper._m0); Init(@__env, handle); } static NmeaListenerDelegateWrapper() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.location.GpsStatus.NmeaListenerDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/location/GpsStatus_NmeaListenerDelegateWrapper")); } } internal partial class NmeaListenerDelegateWrapper { private NmeaListenerDelegate myDelegate; public void onNmeaReceived(long arg0, java.lang.String arg1) { myDelegate(arg0, arg1); } public static implicit operator NmeaListenerDelegateWrapper(NmeaListenerDelegate d) { global::android.location.GpsStatus.NmeaListenerDelegateWrapper ret = new global::android.location.GpsStatus.NmeaListenerDelegateWrapper(); ret.myDelegate = d; global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret); return ret; } } public new int TimeToFirstFix { get { return getTimeToFirstFix(); } } private static global::MonoJavaBridge.MethodId _m0; public int getTimeToFirstFix() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.location.GpsStatus.staticClass, "getTimeToFirstFix", "()I", ref global::android.location.GpsStatus._m0); } public new global::java.lang.Iterable Satellites { get { return getSatellites(); } } private static global::MonoJavaBridge.MethodId _m1; public global::java.lang.Iterable getSatellites() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.lang.Iterable>(this, global::android.location.GpsStatus.staticClass, "getSatellites", "()Ljava/lang/Iterable;", ref global::android.location.GpsStatus._m1) as java.lang.Iterable; } public new int MaxSatellites { get { return getMaxSatellites(); } } private static global::MonoJavaBridge.MethodId _m2; public int getMaxSatellites() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.location.GpsStatus.staticClass, "getMaxSatellites", "()I", ref global::android.location.GpsStatus._m2); } public static int GPS_EVENT_STARTED { get { return 1; } } public static int GPS_EVENT_STOPPED { get { return 2; } } public static int GPS_EVENT_FIRST_FIX { get { return 3; } } public static int GPS_EVENT_SATELLITE_STATUS { get { return 4; } } static GpsStatus() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.location.GpsStatus.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/location/GpsStatus")); } } }
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team // // 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.Linq; using System.Threading; namespace ICSharpCode.NRefactory { /// <summary> /// Provides an interface to handle annotations in an object. /// </summary> public interface IAnnotatable { /// <summary> /// Gets all annotations stored on this IAnnotatable. /// </summary> IEnumerable<object> Annotations { get; } /// <summary> /// Gets the first annotation of the specified type. /// Returns null if no matching annotation exists. /// </summary> /// <typeparam name='T'> /// The type of the annotation. /// </typeparam> T Annotation<T> () where T: class; /// <summary> /// Gets the first annotation of the specified type. /// Returns null if no matching annotation exists. /// </summary> /// <param name='type'> /// The type of the annotation. /// </param> object Annotation (Type type); /// <summary> /// Adds an annotation to this instance. /// </summary> /// <param name='annotation'> /// The annotation to add. /// </param> void AddAnnotation (object annotation); /// <summary> /// Removes all annotations of the specified type. /// </summary> /// <typeparam name='T'> /// The type of the annotations to remove. /// </typeparam> void RemoveAnnotations<T> () where T : class; /// <summary> /// Removes all annotations of the specified type. /// </summary> /// <param name='type'> /// The type of the annotations to remove. /// </param> void RemoveAnnotations(Type type); } /// <summary> /// Base class used to implement the IAnnotatable interface. /// This implementation is thread-safe. /// </summary> [Serializable] public abstract class AbstractAnnotatable : IAnnotatable { // Annotations: points either null (no annotations), to the single annotation, // or to an AnnotationList. // Once it is pointed at an AnnotationList, it will never change (this allows thread-safety support by locking the list) object annotations; /// <summary> /// Clones all annotations. /// This method is intended to be called by Clone() implementations in derived classes. /// <code> /// AstNode copy = (AstNode)MemberwiseClone(); /// copy.CloneAnnotations(); /// </code> /// </summary> protected void CloneAnnotations() { ICloneable cloneable = annotations as ICloneable; if (cloneable != null) annotations = cloneable.Clone(); } sealed class AnnotationList : List<object>, ICloneable { // There are two uses for this custom list type: // 1) it's private, and thus (unlike List<object>) cannot be confused with real annotations // 2) It allows us to simplify the cloning logic by making the list behave the same as a clonable annotation. public AnnotationList (int initialCapacity) : base(initialCapacity) { } public object Clone () { lock (this) { AnnotationList copy = new AnnotationList (this.Count); for (int i = 0; i < this.Count; i++) { object obj = this [i]; ICloneable c = obj as ICloneable; copy.Add (c != null ? c.Clone () : obj); } return copy; } } } public virtual void AddAnnotation (object annotation) { if (annotation == null) throw new ArgumentNullException ("annotation"); retry: // Retry until successful object oldAnnotation = Interlocked.CompareExchange (ref this.annotations, annotation, null); if (oldAnnotation == null) { return; // we successfully added a single annotation } AnnotationList list = oldAnnotation as AnnotationList; if (list == null) { // we need to transform the old annotation into a list list = new AnnotationList (4); list.Add (oldAnnotation); list.Add (annotation); if (Interlocked.CompareExchange (ref this.annotations, list, oldAnnotation) != oldAnnotation) { // the transformation failed (some other thread wrote to this.annotations first) goto retry; } } else { // once there's a list, use simple locking lock (list) { list.Add (annotation); } } } public virtual void RemoveAnnotations<T> () where T : class { retry: // Retry until successful object oldAnnotations = this.annotations; AnnotationList list = oldAnnotations as AnnotationList; if (list != null) { lock (list) list.RemoveAll (obj => obj is T); } else if (oldAnnotations is T) { if (Interlocked.CompareExchange (ref this.annotations, null, oldAnnotations) != oldAnnotations) { // Operation failed (some other thread wrote to this.annotations first) goto retry; } } } public virtual void RemoveAnnotations (Type type) { if (type == null) throw new ArgumentNullException ("type"); retry: // Retry until successful object oldAnnotations = this.annotations; AnnotationList list = oldAnnotations as AnnotationList; if (list != null) { lock (list) list.RemoveAll (obj => type.IsInstanceOfType (obj)); } else if (type.IsInstanceOfType (oldAnnotations)) { if (Interlocked.CompareExchange (ref this.annotations, null, oldAnnotations) != oldAnnotations) { // Operation failed (some other thread wrote to this.annotations first) goto retry; } } } public T Annotation<T> () where T: class { object annotations = this.annotations; AnnotationList list = annotations as AnnotationList; if (list != null) { lock (list) { foreach (object obj in list) { T t = obj as T; if (t != null) return t; } return null; } } else { return annotations as T; } } public object Annotation (Type type) { if (type == null) throw new ArgumentNullException ("type"); object annotations = this.annotations; AnnotationList list = annotations as AnnotationList; if (list != null) { lock (list) { foreach (object obj in list) { if (type.IsInstanceOfType (obj)) return obj; } } } else { if (type.IsInstanceOfType (annotations)) return annotations; } return null; } /// <summary> /// Gets all annotations stored on this AstNode. /// </summary> public IEnumerable<object> Annotations { get { object annotations = this.annotations; AnnotationList list = annotations as AnnotationList; if (list != null) { lock (list) { return list.ToArray (); } } else { if (annotations != null) return new object[] { annotations }; else return Enumerable.Empty<object> (); } } } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using QuantConnect.Logging; namespace QuantConnect.Scheduling { /// <summary> /// Real time self scheduling event /// </summary> public class ScheduledEvent : IDisposable { /// <summary> /// Gets the default time before market close end of trading day events will fire /// </summary> public static readonly TimeSpan SecurityEndOfDayDelta = TimeSpan.FromMinutes(10); /// <summary> /// Gets the default time before midnight end of day events will fire /// </summary> public static readonly TimeSpan AlgorithmEndOfDayDelta = TimeSpan.FromMinutes(2); private bool _needsMoveNext; private bool _endOfScheduledEvents; private readonly string _name; private readonly Action<string, DateTime> _callback; private readonly IEnumerator<DateTime> _orderedEventUtcTimes; /// <summary> /// Event that fires each time this scheduled event happens /// </summary> public event Action<string, DateTime> EventFired; /// <summary> /// Gets or sets whether this event is enabled /// </summary> public bool Enabled { get; set; } /// <summary> /// Gets or sets whether this event will log each time it fires /// </summary> internal bool IsLoggingEnabled { get; set; } /// <summary> /// Gets the next time this scheduled event will fire in UTC /// </summary> public DateTime NextEventUtcTime { get { return _endOfScheduledEvents ? DateTime.MaxValue : _orderedEventUtcTimes.Current; } } /// <summary> /// Gets an identifier for this event /// </summary> public string Name { get { return _name; } } /// <summary> /// Initalizes a new instance of the <see cref="ScheduledEvent"/> class /// </summary> /// <param name="name">An identifier for this event</param> /// <param name="eventUtcTime">The date time the event should fire</param> /// <param name="callback">Delegate to be called when the event time passes</param> public ScheduledEvent(string name, DateTime eventUtcTime, Action<string, DateTime> callback = null) : this(name, new[] { eventUtcTime }.AsEnumerable().GetEnumerator(), callback) { } /// <summary> /// Initalizes a new instance of the <see cref="ScheduledEvent"/> class /// </summary> /// <param name="name">An identifier for this event</param> /// <param name="orderedEventUtcTimes">An enumerable that emits event times</param> /// <param name="callback">Delegate to be called each time an event passes</param> public ScheduledEvent(string name, IEnumerable<DateTime> orderedEventUtcTimes, Action<string, DateTime> callback = null) : this(name, orderedEventUtcTimes.GetEnumerator(), callback) { } /// <summary> /// Initalizes a new instance of the <see cref="ScheduledEvent"/> class /// </summary> /// <param name="name">An identifier for this event</param> /// <param name="orderedEventUtcTimes">An enumerator that emits event times</param> /// <param name="callback">Delegate to be called each time an event passes</param> public ScheduledEvent(string name, IEnumerator<DateTime> orderedEventUtcTimes, Action<string, DateTime> callback = null) { _name = name; _callback = callback; _orderedEventUtcTimes = orderedEventUtcTimes; // prime the pump _endOfScheduledEvents = !_orderedEventUtcTimes.MoveNext(); Enabled = true; } /// <summary> /// Scans this event and fires the callback if an event happened /// </summary> /// <param name="utcTime">The current time in UTC</param> internal void Scan(DateTime utcTime) { if (_endOfScheduledEvents) { return; } do { if (_needsMoveNext) { // if we've passed an event or are just priming the pump, we need to move next if (!_orderedEventUtcTimes.MoveNext()) { if (IsLoggingEnabled) { Log.Trace(string.Format("ScheduledEvent.{0}: Completed scheduled events.", Name)); } _endOfScheduledEvents = true; return; } if (IsLoggingEnabled) { Log.Trace(string.Format("ScheduledEvent.{0}: Next event: {1} UTC", Name, _orderedEventUtcTimes.Current.ToString(DateFormat.UI))); } } // if time has passed our event if (utcTime >= _orderedEventUtcTimes.Current) { if (IsLoggingEnabled) { Log.Trace(string.Format("ScheduledEvent.{0}: Firing at {1} UTC Scheduled at {2} UTC", Name, utcTime.ToString(DateFormat.UI), _orderedEventUtcTimes.Current.ToString(DateFormat.UI)) ); } // fire the event OnEventFired(_orderedEventUtcTimes.Current); _needsMoveNext = true; } else { // we haven't passed the event time yet, so keep waiting on this Current _needsMoveNext = false; } } // keep checking events until we pass the current time, this will fire // all 'skipped' events back to back in order, perhaps this should be handled // in the real time handler while (_needsMoveNext); } /// <summary> /// Fast forwards this schedule to the specified time without invoking the events /// </summary> /// <param name="utcTime">Frontier time</param> internal void SkipEventsUntil(DateTime utcTime) { // check if our next event is in the past if (utcTime < _orderedEventUtcTimes.Current) return; while (_orderedEventUtcTimes.MoveNext()) { // zoom through the enumerator until we get to the desired time if (utcTime <= _orderedEventUtcTimes.Current) { // pump is primed and ready to go _needsMoveNext = false; if (IsLoggingEnabled) { Log.Trace(string.Format("ScheduledEvent.{0}: Skipped events before {1}. Next event: {2}", Name, utcTime.ToString(DateFormat.UI), _orderedEventUtcTimes.Current.ToString(DateFormat.UI) )); } return; } } if (IsLoggingEnabled) { Log.Trace(string.Format("ScheduledEvent.{0}: Exhausted event stream during skip until {1}", Name, utcTime.ToString(DateFormat.UI) )); } _endOfScheduledEvents = true; } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> /// <filterpriority>2</filterpriority> void IDisposable.Dispose() { _orderedEventUtcTimes.Dispose(); } /// <summary> /// Event invocator for the <see cref="EventFired"/> event /// </summary> /// <param name="triggerTime">The event's time in UTC</param> protected void OnEventFired(DateTime triggerTime) { try { // don't fire the event if we're turned off if (!Enabled) return; if (_callback != null) { _callback(_name, _orderedEventUtcTimes.Current); } var handler = EventFired; if (handler != null) handler(_name, triggerTime); } catch (Exception ex) { Log.Error($"ScheduledEvent.Scan(): Exception was thrown in OnEventFired: {ex}"); // This scheduled event failed, so don't repeat the same event _needsMoveNext = true; throw new ScheduledEventException(ex.ToString()); } } } /// <summary> /// Throw this if there is an exception in the callback function of the scheduled event /// </summary> public class ScheduledEventException : Exception { /// <summary> /// Exception message /// </summary> public string ScheduledEventExceptionMessage { get; } /// <summary> /// ScheduledEventException constructor /// </summary> /// <param name="exceptionMessage">The exception as a string</param> public ScheduledEventException(string exceptionMessage) : base(exceptionMessage) { ScheduledEventExceptionMessage = exceptionMessage; } } }
using Microsoft.Toolkit.Mvvm.Messaging; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows.Input; namespace MvvmScarletToolkit.Observables { /// <summary> /// Collection ViewModelBase wrapping around an <see cref="ObservableCollection"/> that provides methods for threadsafe modification via the dispatcher /// </summary> public abstract class ViewModelListBase<TViewModel> : ViewModelBase where TViewModel : class, INotifyPropertyChanged { protected readonly ObservableCollection<TViewModel> _items; private TViewModel? _selectedItem; [Bindable(true, BindingDirection.TwoWay)] public virtual TViewModel? SelectedItem { get { return _selectedItem; } set { SetProperty(ref _selectedItem, value); } } public TViewModel this[int index] { get { return _items[index]; } } /// <summary> /// <para>Readonly collection of all the entries managed by this instance</para> /// <para>Using <see cref="ICollection{TViewModel}.Add"/> on this, will result in a <see cref="NotSupportedException"/></para> /// </summary> [Bindable(true, BindingDirection.OneWay)] public ReadOnlyObservableCollection<TViewModel> Items { get; } [Bindable(true, BindingDirection.OneWay)] public ObservableCollection<TViewModel> SelectedItems { get; } [Bindable(true, BindingDirection.OneWay)] public int Count => Items.Count; [Bindable(true, BindingDirection.OneWay)] public bool HasItems => Items.Count > 0; [Bindable(true, BindingDirection.OneWay)] public virtual ICommand ClearCommand { get; } /// <summary> /// Removes all instances that are in <see cref="SelectedItems"/> from <see cref="Items"/> /// </summary> [Bindable(true, BindingDirection.OneWay)] public virtual ICommand RemoveRangeCommand { get; } /// <summary> /// removes the instance in <see cref="SelectedItem"/> from <see cref="Items"/> /// </summary> [Bindable(true, BindingDirection.OneWay)] public virtual ICommand RemoveCommand { get; } protected ViewModelListBase(in IScarletCommandBuilder commandBuilder) : base(commandBuilder) { _items = new ObservableCollection<TViewModel>(); SelectedItems = new ObservableCollection<TViewModel>(); Items = new ReadOnlyObservableCollection<TViewModel>(_items); RemoveCommand = commandBuilder .Create(Remove, CanRemove) .WithSingleExecution() .WithBusyNotification(BusyStack) .WithAsyncCancellation() .Build(); RemoveRangeCommand = commandBuilder .Create(RemoveRange, CanRemoveRange) .WithSingleExecution() .WithBusyNotification(BusyStack) .WithAsyncCancellation() .Build(); ClearCommand = commandBuilder .Create(() => Clear(), CanClear) .WithSingleExecution() .WithBusyNotification(BusyStack) .WithAsyncCancellation() .Build(); PropertyChanging += OnPropertyChanging; PropertyChanged += OnPropertyChanged; _items.CollectionChanged += OnCollectionChanged; SelectedItems.CollectionChanged += OnSelectedItemsCollectionChanged; } protected virtual void OnSelectedItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { OnSelectionsChanged(); } protected virtual void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { } protected virtual void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { switch (e.PropertyName) { case nameof(ViewModelListBase<TViewModel>.SelectedItem): OnSelectionChanged(); break; } } protected virtual void OnPropertyChanging(object sender, PropertyChangingEventArgs e) { switch (e.PropertyName) { case nameof(ViewModelListBase<TViewModel>.SelectedItem): OnSelectionChanging(); break; } } /// <summary> ///<para> /// This method exists for usability reasons, so that one can mdofiy the internal collection from within a constructor where Tasks can't/should't be run. /// </para> /// <para> /// Modify the internal collection synchronously. No checks are being performed here. This method is not threadsafe. /// </para> /// </summary> /// <param name="viewModel">the viewmodel instance to be added</param> protected void AddUnchecked(TViewModel viewModel) { _items.Add(viewModel); } public Task Add(TViewModel item) { if (IsDisposed) { throw new ObjectDisposedException(nameof(ViewModelListBase<TViewModel>)); } if (item is null) { return Task.CompletedTask; } return Add(item, CancellationToken.None); } public virtual async Task Add(TViewModel item, CancellationToken token) { if (IsDisposed) { throw new ObjectDisposedException(nameof(ViewModelListBase<TViewModel>)); } if (item is null) { throw new ArgumentNullException(nameof(item)); } using (BusyStack.GetToken()) { await Dispatcher.Invoke(() => _items.Add(item), token).ConfigureAwait(false); await Dispatcher.Invoke(() => OnPropertyChanged(nameof(Count)), token).ConfigureAwait(false); await Dispatcher.Invoke(() => OnPropertyChanged(nameof(HasItems)), token).ConfigureAwait(false); } } public Task AddRange(IEnumerable<TViewModel> items) { if (IsDisposed) { throw new ObjectDisposedException(nameof(ViewModelListBase<TViewModel>)); } return AddRange(items, CancellationToken.None); } public virtual async Task AddRange(IEnumerable<TViewModel> items, CancellationToken token) { if (IsDisposed) { throw new ObjectDisposedException(nameof(ViewModelListBase<TViewModel>)); } if (items is null) { throw new ArgumentNullException(nameof(items)); } using (BusyStack.GetToken()) { await items.ForEachAsync(Add, token).ConfigureAwait(false); } } public Task Remove(TViewModel? item) { if (IsDisposed) { throw new ObjectDisposedException(nameof(ViewModelListBase<TViewModel>)); } if (item is null) { return Task.CompletedTask; } return Remove(item, CancellationToken.None); } public virtual async Task Remove(TViewModel item, CancellationToken token) { if (IsDisposed) { throw new ObjectDisposedException(nameof(ViewModelListBase<TViewModel>)); } using (BusyStack.GetToken()) { await Dispatcher.Invoke(() => _items.Remove(item), token).ConfigureAwait(false); await Dispatcher.Invoke(() => OnPropertyChanged(nameof(Count)), token).ConfigureAwait(false); await Dispatcher.Invoke(() => OnPropertyChanged(nameof(HasItems)), token).ConfigureAwait(false); } } public Task RemoveRange(IEnumerable<TViewModel> items) { if (IsDisposed) { throw new ObjectDisposedException(nameof(ViewModelListBase<TViewModel>)); } return RemoveRange(items, CancellationToken.None); } public virtual async Task RemoveRange(IEnumerable<TViewModel> items, CancellationToken token) { if (IsDisposed) { throw new ObjectDisposedException(nameof(ViewModelListBase<TViewModel>)); } if (items is null) { throw new ArgumentNullException(nameof(items)); } using (BusyStack.GetToken()) { await items.ForEachAsync(Remove, token).ConfigureAwait(false); } } public Task Clear() { if (IsDisposed) { throw new ObjectDisposedException(nameof(ViewModelListBase<TViewModel>)); } return Clear(CancellationToken.None); } public virtual async Task Clear(CancellationToken token) { if (IsDisposed) { throw new ObjectDisposedException(nameof(ViewModelListBase<TViewModel>)); } using (BusyStack.GetToken()) { await Dispatcher.Invoke(() => _items.Clear(), token).ConfigureAwait(false); await Dispatcher.Invoke(() => OnPropertyChanged(nameof(Count)), token).ConfigureAwait(false); await Dispatcher.Invoke(() => OnPropertyChanged(nameof(HasItems)), token).ConfigureAwait(false); } } public virtual bool CanClear() { return !IsDisposed && HasItems && !IsBusy; } protected Task Remove() { return Remove(SelectedItem); } private async Task RemoveRange(IList items) { using (BusyStack.GetToken()) { await RemoveRange(items?.Cast<TViewModel>() ?? Enumerable.Empty<TViewModel>()).ConfigureAwait(false); } } protected virtual bool CanRemoveRange(IEnumerable<TViewModel> items) { return CanClear() && items?.Any(p => _items.Contains(p)) == true; } protected bool CanRemoveRange(IList items) { return !IsDisposed && CanRemoveRange(items?.Cast<TViewModel>() ?? Enumerable.Empty<TViewModel>()); } protected virtual bool CanRemove(TViewModel? item) { if (item is null) { return false; } return !IsDisposed && CanClear() && !(item is null) && _items.Contains(item); } private bool CanRemoveRange() { return CanRemoveRange((IList)SelectedItems); } private bool CanRemove() { return CanRemove(SelectedItem); } private Task RemoveRange() { return RemoveRange((IList)SelectedItems); } private void OnSelectionChanged() { if (IsDisposed) { return; } Messenger.Send(new ViewModelListBaseSelectionChanged<TViewModel?>(this, SelectedItem)); } private void OnSelectionChanging() { if (IsDisposed) { return; } Messenger.Send(new ViewModelListBaseSelectionChanging<TViewModel?>(this, SelectedItem)); } private void OnSelectionsChanged() { if (IsDisposed) { return; } Messenger.Send(new ViewModelListBaseSelectionsChanged<TViewModel>(SelectedItems?.Cast<TViewModel>() ?? Enumerable.Empty<TViewModel>())); } protected override async void Dispose(bool disposing) { if (IsDisposed) { throw new ObjectDisposedException(nameof(ViewModelListBase<TViewModel>)); } if (disposing) { PropertyChanging -= OnPropertyChanging; PropertyChanged -= OnPropertyChanged; SelectedItems.CollectionChanged -= OnSelectedItemsCollectionChanged; await Clear().ConfigureAwait(false); } base.Dispose(disposing); } } }
using System; using System.Text; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace BLK10.Collections { /// <summary>Helper so we can call some tuple methods recursively without knowing the underlying types.</summary> internal interface ITuple { string ToString(StringBuilder sb); int GetHashCode(IEqualityComparer comparer); int Size { get; } } public interface IStructuralEquatable { bool Equals(object other, IEqualityComparer comparer); int GetHashCode(IEqualityComparer comparer); } public interface IStructuralComparable { int CompareTo(object other, IComparer comparer); } public static class Tuple { public static Tuple<T1> Create<T1>(T1 item1) { return (new Tuple<T1>(item1)); } public static Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2) { return (new Tuple<T1, T2>(item1, item2)); } public static Tuple<T1, T2, T3> Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3) { return (new Tuple<T1, T2, T3>(item1, item2, item3)); } public static Tuple<T1, T2, T3, T4> Create<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, T4 item4) { return (new Tuple<T1, T2, T3, T4>(item1, item2, item3, item4)); } public static Tuple<T1, T2, T3, T4, T5> Create<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) { return (new Tuple<T1, T2, T3, T4, T5>(item1, item2, item3, item4, item5)); } // From System.Web.Util.HashCodeCombiner internal static int CombineHashCodes(int h1, int h2) { return (((h1 << 5) + h1) ^ h2); } internal static int CombineHashCodes(int h1, int h2, int h3) { return (Tuple.CombineHashCodes(Tuple.CombineHashCodes(h1, h2), h3)); } internal static int CombineHashCodes(int h1, int h2, int h3, int h4) { return (Tuple.CombineHashCodes(Tuple.CombineHashCodes(h1, h2), Tuple.CombineHashCodes(h3, h4))); } internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5) { return (Tuple.CombineHashCodes(Tuple.CombineHashCodes(h1, h2, h3, h4), h5)); } } [Serializable] public class Tuple<T1> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple { [SerializeField] private T1 _item1; public T1 Item1 { get { return (this._item1); } } public Tuple(T1 item1) { this._item1 = item1; } public override bool Equals(object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); } bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { if (other == null) return false; Tuple<T1> objTuple = other as Tuple<T1>; if (objTuple == null) { return false; } return comparer.Equals(this._item1, objTuple._item1); } int IComparable.CompareTo(object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); } int IStructuralComparable.CompareTo(object other, IComparer comparer) { if (other == null) return (1); Tuple<T1> objTuple = other as Tuple<T1>; if (objTuple == null) { throw new ArgumentException("object other type"); } return comparer.Compare(this._item1, objTuple._item1); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<object>.Default); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return comparer.GetHashCode(this._item1); } int ITuple.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder().Append("("); return ((ITuple)this).ToString(sb); } string ITuple.ToString(StringBuilder sb) { return (sb.Append(this._item1) .Append(")") .ToString()); } int ITuple.Size { get { return (1); } } } [Serializable] public class Tuple<T1, T2> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple { [SerializeField] private T1 _item1; [SerializeField] private T2 _item2; public T1 Item1 { get { return (this._item1); } } public T2 Item2 { get { return (this._item2); } } public Tuple(T1 item1, T2 item2) { this._item1 = item1; this._item2 = item2; } public override bool Equals(object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); ; } bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { if (other == null) return false; Tuple<T1, T2> objTuple = other as Tuple<T1, T2>; if (objTuple == null) { return (false); } return comparer.Equals(this._item1, objTuple._item1) && comparer.Equals(this._item2, objTuple._item2); } int IComparable.CompareTo(object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); } int IStructuralComparable.CompareTo(object other, IComparer comparer) { if (other == null) return (1); Tuple<T1, T2> objTuple = other as Tuple<T1, T2>; if (objTuple == null) { throw new ArgumentException("object other type"); } int c = 0; c = comparer.Compare(this._item1, objTuple._item1); if (c != 0) return (c); return comparer.Compare(this._item2, objTuple._item2); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<object>.Default); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return (Tuple.CombineHashCodes(comparer.GetHashCode(this._item1), comparer.GetHashCode(this._item2))); } int ITuple.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder().Append("("); return ((ITuple)this).ToString(sb); } string ITuple.ToString(StringBuilder sb) { return (sb.Append(this._item1) .Append(", ") .Append(this._item2) .Append(")") .ToString()); } int ITuple.Size { get { return (2); } } } [Serializable] public class Tuple<T1, T2, T3> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple { [SerializeField] private T1 _item1; [SerializeField] private T2 _item2; [SerializeField] private T3 _item3; public T1 Item1 { get { return (this._item1); } } public T2 Item2 { get { return (this._item2); } } public T3 Item3 { get { return (this._item3); } } public Tuple(T1 item1, T2 item2, T3 item3) { this._item1 = item1; this._item2 = item2; this._item3 = item3; } public override bool Equals(object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); ; } bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { if (other == null) return (false); Tuple<T1, T2, T3> objTuple = other as Tuple<T1, T2, T3>; if (objTuple == null) { return (false); } return comparer.Equals(this._item1, objTuple._item1) && comparer.Equals(this._item2, objTuple._item2) && comparer.Equals(this._item3, objTuple._item3); } int IComparable.CompareTo(object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); } int IStructuralComparable.CompareTo(object other, IComparer comparer) { if (other == null) return (1); Tuple<T1, T2, T3> objTuple = other as Tuple<T1, T2, T3>; if (objTuple == null) { throw new ArgumentException("object other type"); } int c = 0; c = comparer.Compare(this._item1, objTuple._item1); if (c != 0) return (c); c = comparer.Compare(this._item2, objTuple._item2); if (c != 0) return (c); return comparer.Compare(this._item3, objTuple._item3); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<object>.Default); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return (Tuple.CombineHashCodes(comparer.GetHashCode(this._item1), comparer.GetHashCode(this._item2), comparer.GetHashCode(this._item3))); } int ITuple.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder().Append("("); return ((ITuple)this).ToString(sb); } string ITuple.ToString(StringBuilder sb) { return (sb.Append(this._item1) .Append(", ") .Append(this._item2) .Append(", ") .Append(this._item3) .Append(")") .ToString()); } int ITuple.Size { get { return (3); } } } [Serializable] public class Tuple<T1, T2, T3, T4> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple { [SerializeField] private T1 _item1; [SerializeField] private T2 _item2; [SerializeField] private T3 _item3; [SerializeField] private T4 _item4; public T1 Item1 { get { return (this._item1); } } public T2 Item2 { get { return (this._item2); } } public T3 Item3 { get { return (this._item3); } } public T4 Item4 { get { return (this._item4); } } public Tuple(T1 item1, T2 item2, T3 item3, T4 item4) { this._item1 = item1; this._item2 = item2; this._item3 = item3; this._item4 = item4; } public override bool Equals(object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); ; } bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { if (other == null) return (false); Tuple<T1, T2, T3, T4> objTuple = other as Tuple<T1, T2, T3, T4>; if (objTuple == null) { return (false); } return (comparer.Equals(this._item1, objTuple._item1) && comparer.Equals(this._item2, objTuple._item2) && comparer.Equals(this._item3, objTuple._item3) && comparer.Equals(this._item4, objTuple._item4)); } int IComparable.CompareTo(object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); } int IStructuralComparable.CompareTo(object other, IComparer comparer) { if (other == null) return (1); Tuple<T1, T2, T3, T4> objTuple = other as Tuple<T1, T2, T3, T4>; if (objTuple == null) { throw new ArgumentException("object other type"); } int c = 0; c = comparer.Compare(this._item1, objTuple._item1); if (c != 0) return (c); c = comparer.Compare(this._item2, objTuple._item2); if (c != 0) return (c); c = comparer.Compare(this._item3, objTuple._item3); if (c != 0) return (c); return comparer.Compare(this._item4, objTuple._item4); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<object>.Default); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(this._item1), comparer.GetHashCode(this._item2), comparer.GetHashCode(this._item3), comparer.GetHashCode(this._item4)); } int ITuple.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder().Append("("); return ((ITuple)this).ToString(sb); } string ITuple.ToString(StringBuilder sb) { return (sb.Append(this._item1) .Append(", ") .Append(this._item2) .Append(", ") .Append(this._item3) .Append(", ") .Append(this._item4) .Append(")") .ToString()); } int ITuple.Size { get { return (4); } } } [Serializable] public class Tuple<T1, T2, T3, T4, T5> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple { [SerializeField] private T1 _item1; [SerializeField] private T2 _item2; [SerializeField] private T3 _item3; [SerializeField] private T4 _item4; [SerializeField] private T5 _item5; public T1 Item1 { get { return (this._item1); } } public T2 Item2 { get { return (this._item2); } } public T3 Item3 { get { return (this._item3); } } public T4 Item4 { get { return (this._item4); } } public T5 Item5 { get { return (this._item5); } } public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) { this._item1 = item1; this._item2 = item2; this._item3 = item3; this._item4 = item4; this._item5 = item5; } public override bool Equals(object obj) { return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<object>.Default); ; } bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { if (other == null) return (false); Tuple<T1, T2, T3, T4, T5> objTuple = other as Tuple<T1, T2, T3, T4, T5>; if (objTuple == null) { return (false); } return (comparer.Equals(this._item1, objTuple._item1) && comparer.Equals(this._item2, objTuple._item2) && comparer.Equals(this._item3, objTuple._item3) && comparer.Equals(this._item4, objTuple._item4) && comparer.Equals(this._item5, objTuple._item5)); } int IComparable.CompareTo(object obj) { return ((IStructuralComparable)this).CompareTo(obj, Comparer<object>.Default); } int IStructuralComparable.CompareTo(object other, IComparer comparer) { if (other == null) return (1); Tuple<T1, T2, T3, T4, T5> objTuple = other as Tuple<T1, T2, T3, T4, T5>; if (objTuple == null) { throw new ArgumentException("object other type"); } int c = 0; c = comparer.Compare(this._item1, objTuple._item1); if (c != 0) return (c); c = comparer.Compare(this._item2, objTuple._item2); if (c != 0) return (c); c = comparer.Compare(this._item3, objTuple._item3); if (c != 0) return (c); c = comparer.Compare(this._item4, objTuple._item4); if (c != 0) return (c); return comparer.Compare(this._item5, objTuple._item5); } public override int GetHashCode() { return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<object>.Default); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return (Tuple.CombineHashCodes(comparer.GetHashCode(this._item1), comparer.GetHashCode(this._item2), comparer.GetHashCode(this._item3), comparer.GetHashCode(this._item4), comparer.GetHashCode(this._item5))); } int ITuple.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } public override string ToString() { StringBuilder sb = new StringBuilder().Append("("); return ((ITuple)this).ToString(sb); } string ITuple.ToString(StringBuilder sb) { return (sb.Append(_item1) .Append(", ") .Append(_item2) .Append(", ") .Append(_item3) .Append(", ") .Append(_item4) .Append(", ") .Append(_item5) .Append(")") .ToString()); } int ITuple.Size { get { return (5); } } } }
using UnityEngine; using UnityEditor; using System.Collections; public class CreatePlane : ScriptableWizard { public enum Orientation { Horizontal, Vertical } public enum AnchorPoint { TopLeft, TopHalf, TopRight, RightHalf, BottomRight, BottomHalf, BottomLeft, LeftHalf, Center } private int widthSegments = 1; private int lengthSegments = 1; public float width = 256.0f; public float length = 256.0f; public Orientation orientation = Orientation.Horizontal; public AnchorPoint anchor = AnchorPoint.Center; public bool addCollider = true; public bool createAtOrigin = true; public string optionalName; static Camera cam; static Camera lastUsedCam; [MenuItem("GameObject/Create Other/Heat Sink Plane")] static void CreateWizard() { cam = Camera.current; // Hack because camera.current doesn't return editor camera if scene view doesn't have focus if (!cam) cam = lastUsedCam; else lastUsedCam = cam; ScriptableWizard.DisplayWizard("Create Plane",typeof(CreatePlane)); } void OnWizardUpdate() { widthSegments = Mathf.Clamp(widthSegments, 1, 254); lengthSegments = Mathf.Clamp(lengthSegments, 1, 254); } void OnWizardCreate() { string ret; ret = AssetDatabase.CreateFolder("Assets/Heat Sink/Resources","Plane"); if(AssetDatabase.GUIDToAssetPath(ret) != "Assets/Heat Sink/Resources/Plane") AssetDatabase.DeleteAsset(AssetDatabase.GUIDToAssetPath(ret)); GameObject plane = new GameObject(); if (!string.IsNullOrEmpty(optionalName)) plane.name = optionalName; else plane.name = "HeatSinkPlane"; if (!createAtOrigin && cam) plane.transform.position = cam.transform.position + cam.transform.forward*5.0f; else plane.transform.position = Vector3.zero; Vector2 anchorOffset; string anchorId; switch (anchor) { case AnchorPoint.TopLeft: anchorOffset = new Vector2(-width/2.0f,length/2.0f); anchorId = "TL"; break; case AnchorPoint.TopHalf: anchorOffset = new Vector2(0.0f,length/2.0f); anchorId = "TH"; break; case AnchorPoint.TopRight: anchorOffset = new Vector2(width/2.0f,length/2.0f); anchorId = "TR"; break; case AnchorPoint.RightHalf: anchorOffset = new Vector2(width/2.0f,0.0f); anchorId = "RH"; break; case AnchorPoint.BottomRight: anchorOffset = new Vector2(width/2.0f,-length/2.0f); anchorId = "BR"; break; case AnchorPoint.BottomHalf: anchorOffset = new Vector2(0.0f,-length/2.0f); anchorId = "BH"; break; case AnchorPoint.BottomLeft: anchorOffset = new Vector2(-width/2.0f,-length/2.0f); anchorId = "BL"; break; case AnchorPoint.LeftHalf: anchorOffset = new Vector2(-width/2.0f,0.0f); anchorId = "LH"; break; case AnchorPoint.Center: default: anchorOffset = Vector2.zero; anchorId = "C"; break; } MeshFilter meshFilter = (MeshFilter)plane.AddComponent(typeof(MeshFilter)); MeshRenderer meshRenderer = (MeshRenderer)plane.AddComponent(typeof(MeshRenderer)); meshRenderer.material = Resources.Load("Materials/Diffuse", typeof(Material)) as Material; plane.AddComponent(typeof(ColorMapping)); //string planeAssetName = plane.name + widthSegments + "x" + lengthSegments + "W" + width + "L" + length + (orientation == Orientation.Horizontal? "H" : "V") + anchorId + ".asset"; string planeAssetName = plane.name + "_W" + width + "L" + length + (orientation == Orientation.Horizontal? "H" : "V") + anchorId + ".asset"; Mesh m = (Mesh)AssetDatabase.LoadAssetAtPath("Assets/Heat Sink/Resources/Plane/" + planeAssetName,typeof(Mesh)); if (m == null) { m = new Mesh(); m.name = plane.name; int hCount2 = widthSegments+1; int vCount2 = lengthSegments+1; int numTriangles = widthSegments * lengthSegments * 6; int numVertices = hCount2 * vCount2; Vector3[] vertices = new Vector3[numVertices]; Vector2[] uvs = new Vector2[numVertices]; int[] triangles = new int[numTriangles]; int index = 0; float uvFactorX = 1.0f/widthSegments; float uvFactorY = 1.0f/lengthSegments; float scaleX = width/widthSegments; float scaleY = length/lengthSegments; for (float y = 0.0f; y < vCount2; y++) { for (float x = 0.0f; x < hCount2; x++) { if (orientation == Orientation.Horizontal) { vertices[index] = new Vector3(x*scaleX - width/2f - anchorOffset.x, 0.0f, y*scaleY - length/2f - anchorOffset.y); } else { vertices[index] = new Vector3(x*scaleX - width/2f - anchorOffset.x, y*scaleY - length/2f - anchorOffset.y, 0.0f); } uvs[index++] = new Vector2(x*uvFactorX, y*uvFactorY); } } index = 0; for (int y = 0; y < lengthSegments; y++) { for (int x = 0; x < widthSegments; x++) { triangles[index] = (y * hCount2) + x; triangles[index+1] = ((y+1) * hCount2) + x; triangles[index+2] = (y * hCount2) + x + 1; triangles[index+3] = ((y+1) * hCount2) + x; triangles[index+4] = ((y+1) * hCount2) + x + 1; triangles[index+5] = (y * hCount2) + x + 1; index += 6; } } m.vertices = vertices; m.uv = uvs; m.triangles = triangles; m.RecalculateNormals(); AssetDatabase.CreateAsset(m, "Assets/Heat Sink/Resources/Plane/" + planeAssetName); AssetDatabase.SaveAssets(); } meshFilter.sharedMesh = m; m.RecalculateBounds(); if (addCollider) plane.AddComponent(typeof(MeshCollider)); plane.AddComponent<HeatTransfer>(); Selection.activeObject = plane; } }
// 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 Microsoft.Test.ModuleCore; using System; using System.IO; using System.Text; using System.Xml; using XmlCoreTest.Common; namespace CoreXml.Test.XLinq { public partial class XNodeReaderFunctionalTests : TestModule { public partial class XNodeReaderTests : XLinqTestCase { //[TestCase(Name = "ReadContentAsBase64", Desc = "ReadContentAsBase64")] public partial class TCReadContentAsBase64 : BridgeHelpers { public const string ST_ELEM_NAME1 = "ElemAll"; public const string ST_ELEM_NAME2 = "ElemEmpty"; public const string ST_ELEM_NAME3 = "ElemNum"; public const string ST_ELEM_NAME4 = "ElemText"; public const string ST_ELEM_NAME5 = "ElemNumText"; public const string ST_ELEM_NAME6 = "ElemLong"; public const string strTextBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; public const string strNumBase64 = "0123456789+/"; public override void Init() { base.Init(); CreateBase64TestFile(pBase64Xml); } public override void Terminate() { DeleteTestFile(pBase64Xml); base.Terminate(); } private bool VerifyInvalidReadBase64(int iBufferSize, int iIndex, int iCount, Type exceptionType) { bool bPassed = false; byte[] buffer = new byte[iBufferSize]; XmlReader DataReader = GetReader(pBase64Xml); PositionOnElement(DataReader, ST_ELEM_NAME1); DataReader.Read(); if (!DataReader.CanReadBinaryContent) return true; try { DataReader.ReadContentAsBase64(buffer, iIndex, iCount); } catch (Exception e) { bPassed = (e.GetType().ToString() == exceptionType.ToString()); if (!bPassed) { TestLog.WriteLine("Actual exception:{0}", e.GetType().ToString()); TestLog.WriteLine("Expected exception:{0}", exceptionType.ToString()); } } return bPassed; } protected void TestOnInvalidNodeType(XmlNodeType nt) { XmlReader DataReader = GetReader(pBase64Xml); PositionOnNodeType(DataReader, nt); if (!DataReader.CanReadBinaryContent) return; try { byte[] buffer = new byte[1]; int nBytes = DataReader.ReadContentAsBase64(buffer, 0, 1); } catch (InvalidOperationException ioe) { if (ioe.ToString().IndexOf(nt.ToString()) < 0) TestLog.Compare(false, "Call threw wrong invalid operation exception on " + nt); else return; } TestLog.Compare(false, "Call succeeded on " + nt); } protected void TestOnNopNodeType(XmlNodeType nt) { XmlReader DataReader = GetReader(pBase64Xml); PositionOnNodeType(DataReader, nt); string name = DataReader.Name; string value = DataReader.Value; if (!DataReader.CanReadBinaryContent) return; byte[] buffer = new byte[1]; int nBytes = DataReader.ReadContentAsBase64(buffer, 0, 1); TestLog.Compare(nBytes, 0, "nBytes"); TestLog.Compare(VerifyNode(DataReader, nt, name, value), "vn"); } //[Variation("ReadBase64 Element with all valid value")] public void TestReadBase64_1() { int base64len = 0; byte[] base64 = new byte[1000]; XmlReader DataReader = GetReader(pBase64Xml); PositionOnElement(DataReader, ST_ELEM_NAME1); DataReader.Read(); if (!DataReader.CanReadBinaryContent) return; base64len = DataReader.ReadContentAsBase64(base64, 0, base64.Length); string strActbase64 = ""; for (int i = 0; i < base64len; i = i + 2) { strActbase64 += System.BitConverter.ToChar(base64, i); } TestLog.Compare(strActbase64, (strTextBase64 + strNumBase64), "Compare All Valid Base64"); } //[Variation("ReadBase64 Element with all valid Num value", Priority = 0)] public void TestReadBase64_2() { int base64len = 0; byte[] base64 = new byte[1000]; XmlReader DataReader = GetReader(pBase64Xml); PositionOnElement(DataReader, ST_ELEM_NAME3); DataReader.Read(); if (!DataReader.CanReadBinaryContent) return; base64len = DataReader.ReadContentAsBase64(base64, 0, base64.Length); string strActbase64 = ""; for (int i = 0; i < base64len; i = i + 2) { strActbase64 += System.BitConverter.ToChar(base64, i); } TestLog.Compare(strActbase64, strNumBase64, "Compare All Valid Base64"); } //[Variation("ReadBase64 Element with all valid Text value")] public void TestReadBase64_3() { int base64len = 0; byte[] base64 = new byte[1000]; XmlReader DataReader = GetReader(pBase64Xml); PositionOnElement(DataReader, ST_ELEM_NAME4); DataReader.Read(); if (!DataReader.CanReadBinaryContent) return; base64len = DataReader.ReadContentAsBase64(base64, 0, base64.Length); string strActbase64 = ""; for (int i = 0; i < base64len; i = i + 2) { strActbase64 += System.BitConverter.ToChar(base64, i); } TestLog.Compare(strActbase64, strTextBase64, "Compare All Valid Base64"); } //[Variation("ReadBase64 Element with all valid value (from concatenation), Priority=0")] public void TestReadBase64_5() { int base64len = 0; byte[] base64 = new byte[1000]; XmlReader DataReader = GetReader(pBase64Xml); PositionOnElement(DataReader, ST_ELEM_NAME5); DataReader.Read(); if (!DataReader.CanReadBinaryContent) return; base64len = DataReader.ReadContentAsBase64(base64, 0, base64.Length); string strActbase64 = ""; for (int i = 0; i < base64len; i = i + 2) { strActbase64 += System.BitConverter.ToChar(base64, i); } TestLog.Compare(strActbase64, (strTextBase64 + strNumBase64), "Compare All Valid Base64"); } //[Variation("ReadBase64 Element with Long valid value (from concatenation), Priority=0")] public void TestReadBase64_6() { int base64len = 0; byte[] base64 = new byte[2000]; XmlReader DataReader = GetReader(pBase64Xml); PositionOnElement(DataReader, ST_ELEM_NAME6); DataReader.Read(); if (!DataReader.CanReadBinaryContent) return; base64len = DataReader.ReadContentAsBase64(base64, 0, base64.Length); string strActbase64 = ""; for (int i = 0; i < base64len; i = i + 2) { strActbase64 += System.BitConverter.ToChar(base64, i); } string strExpbase64 = ""; for (int i = 0; i < 10; i++) strExpbase64 += (strTextBase64 + strNumBase64); TestLog.Compare(strActbase64, strExpbase64, "Compare All Valid Base64"); } //[Variation("ReadBase64 with count > buffer size")] public void ReadBase64_7() { BoolToLTMResult(VerifyInvalidReadBase64(5, 0, 6, typeof(NotSupportedException))); } //[Variation("ReadBase64 with count < 0")] public void ReadBase64_8() { BoolToLTMResult(VerifyInvalidReadBase64(5, 2, -1, typeof(NotSupportedException))); } //[Variation("ReadBase64 with index > buffer size")] public void ReadBase64_9() { BoolToLTMResult(VerifyInvalidReadBase64(5, 5, 1, typeof(NotSupportedException))); } //[Variation("ReadBase64 with index < 0")] public void ReadBase64_10() { BoolToLTMResult(VerifyInvalidReadBase64(5, -1, 1, typeof(NotSupportedException))); } //[Variation("ReadBase64 with index + count exceeds buffer")] public void ReadBase64_11() { BoolToLTMResult(VerifyInvalidReadBase64(5, 0, 10, typeof(NotSupportedException))); } //[Variation("ReadBase64 index & count =0")] public void ReadBase64_12() { byte[] buffer = new byte[5]; int iCount = 0; XmlReader DataReader = GetReader(pBase64Xml); PositionOnElement(DataReader, ST_ELEM_NAME1); DataReader.Read(); if (!DataReader.CanReadBinaryContent) return; iCount = DataReader.ReadContentAsBase64(buffer, 0, 0); TestLog.Compare(iCount, 0, "has to be zero"); } //[Variation("ReadBase64 Element multiple into same buffer (using offset), Priority=0")] public void TestReadBase64_13() { int base64len = 20; byte[] base64 = new byte[base64len]; XmlReader DataReader = GetReader(pBase64Xml); PositionOnElement(DataReader, ST_ELEM_NAME4); DataReader.Read(); if (!DataReader.CanReadBinaryContent) return; string strActbase64 = ""; for (int i = 0; i < base64len; i = i + 2) { DataReader.ReadContentAsBase64(base64, i, 2); strActbase64 = (System.BitConverter.ToChar(base64, i)).ToString(); TestLog.Compare(String.Compare(strActbase64, 0, strTextBase64, i / 2, 1), 0, "Compare All Valid Base64"); } } //[Variation("ReadBase64 with buffer == null")] public void TestReadBase64_14() { XmlReader DataReader = GetReader(pBase64Xml); PositionOnElement(DataReader, ST_ELEM_NAME4); DataReader.Read(); if (!DataReader.CanReadBinaryContent) return; try { DataReader.ReadContentAsBase64(null, 0, 0); } catch (ArgumentNullException) { return; } throw new TestException(TestResult.Failed, ""); } //[Variation("ReadBase64 after failure")] public void TestReadBase64_15() { XmlReader DataReader = GetReader(pBase64Xml); PositionOnElement(DataReader, "ElemErr"); DataReader.Read(); if (!DataReader.CanReadBinaryContent) return; byte[] buffer = new byte[10]; int nRead = 0; try { nRead = DataReader.ReadContentAsBase64(buffer, 0, 1); throw new TestException(TestResult.Failed, ""); } catch (XmlException e) { CheckXmlException("Xml_InvalidBase64Value", e, 0, 1); } } //[Variation("Read after partial ReadBase64", Priority = 0)] public void TestReadBase64_16() { XmlReader DataReader = GetReader(pBase64Xml); PositionOnElement(DataReader, "ElemNum"); DataReader.Read(); if (!DataReader.CanReadBinaryContent) return; byte[] buffer = new byte[10]; int nRead = DataReader.ReadContentAsBase64(buffer, 0, 8); TestLog.Compare(nRead, 8, "0"); DataReader.Read(); TestLog.Compare(DataReader.NodeType, XmlNodeType.Element, "1vn"); } //[Variation("Current node on multiple calls")] public void TestReadBase64_17() { XmlReader DataReader = GetReader(pBase64Xml); PositionOnElement(DataReader, "ElemNum"); DataReader.Read(); if (!DataReader.CanReadBinaryContent) return; byte[] buffer = new byte[30]; int nRead = DataReader.ReadContentAsBase64(buffer, 0, 2); TestLog.Compare(nRead, 2, "0"); nRead = DataReader.ReadContentAsBase64(buffer, 0, 23); TestLog.Compare(nRead, 22, "1"); DataReader.Read(); TestLog.Compare(DataReader.NodeType, XmlNodeType.Element, "Nodetype not end element"); TestLog.Compare(DataReader.Name, "ElemText", "Nodetype not end element"); } //[Variation("No op node types")] public void TestReadBase64_18() { TestOnInvalidNodeType(XmlNodeType.EndElement); } //[Variation("ReadBase64 with incomplete sequence")] public void TestTextReadBase64_23() { byte[] expected = new byte[] { 0, 16, 131, 16, 81 }; byte[] buffer = new byte[10]; string strxml = "<r><ROOT>ABCDEFG</ROOT></r>"; XmlReader DataReader = GetReaderStr(strxml); PositionOnElement(DataReader, "ROOT"); DataReader.Read(); if (!DataReader.CanReadBinaryContent) return; int result = 0; int nRead; while ((nRead = DataReader.ReadContentAsBase64(buffer, result, 1)) > 0) result += nRead; TestLog.Compare(result, expected.Length, "res"); for (int i = 0; i < result; i++) TestLog.Compare(buffer[i], expected[i], "buffer[" + i + "]"); } //[Variation("ReadBase64 when end tag doesn't exist")] public void TestTextReadBase64_24() { byte[] buffer = new byte[5000]; string strxml = "<B>" + new string('c', 5000); try { XmlReader DataReader = GetReaderStr(strxml); PositionOnElement(DataReader, "B"); DataReader.Read(); if (!DataReader.CanReadBinaryContent) return; DataReader.ReadContentAsBase64(buffer, 0, 5000); TestLog.WriteLine("Accepted incomplete element"); throw new TestException(TestResult.Failed, ""); } catch (XmlException e) { CheckXmlException("Xml_UnexpectedEOFInElementContent", e, 1, 5004); } } //[Variation("ReadBase64 with whitespace in the mIddle")] public void TestTextReadBase64_26() { byte[] buffer = new byte[1]; string strxml = "<abc> AQID B B </abc>"; int nRead; XmlReader DataReader = GetReaderStr(strxml); PositionOnElement(DataReader, "abc"); DataReader.Read(); if (!DataReader.CanReadBinaryContent) return; for (int i = 0; i < 4; i++) { nRead = DataReader.ReadContentAsBase64(buffer, 0, 1); TestLog.Compare(nRead, 1, "res" + i); TestLog.Compare(buffer[0], (byte)(i + 1), "buffer " + i); } nRead = DataReader.ReadContentAsBase64(buffer, 0, 1); TestLog.Compare(nRead, 0, "nRead 0"); } //[Variation("ReadBase64 with = in the mIddle")] public void TestTextReadBase64_27() { byte[] buffer = new byte[1]; string strxml = "<abc>AQI=ID</abc>"; int nRead; XmlReader DataReader = GetReaderStr(strxml); PositionOnElement(DataReader, "abc"); DataReader.Read(); if (!DataReader.CanReadBinaryContent) return; for (int i = 0; i < 2; i++) { nRead = DataReader.ReadContentAsBase64(buffer, 0, 1); TestLog.Compare(nRead, 1, "res" + i); TestLog.Compare(buffer[0], (byte)(i + 1), "buffer " + i); } try { DataReader.ReadContentAsBase64(buffer, 0, 1); TestLog.WriteLine("ReadBase64 with = in the middle succeeded"); throw new TestException(TestResult.Failed, ""); } catch (XmlException e) { CheckXmlException("Xml_InvalidBase64Value", e, 0, 1); } } //[Variation("ReadBase64 runs into an Overflow", Params = new object[] { "10000" })] //[Variation("ReadBase64 runs into an Overflow", Params = new object[] { "1000000" })] //[Variation("ReadBase64 runs into an Overflow", Params = new object[] { "10000000" })] public void RunBase64DoesnNotRunIntoOverflow() { int totalfilesize = Convert.ToInt32(Variation.Params[0].ToString()); string ascii = new string('c', totalfilesize); byte[] bits = Encoding.Unicode.GetBytes(ascii); string base64str = Convert.ToBase64String(bits); string fileName = "bug105376_" + Variation.Params[0].ToString() + ".xml"; FilePathUtil.addStream(fileName, new MemoryStream()); StreamWriter sw = new StreamWriter(FilePathUtil.getStream(fileName)); sw.Write("<root><base64>"); sw.Write(base64str); sw.Write("</base64></root>"); sw.Flush(); XmlReader DataReader = GetReader(fileName); int SIZE = (totalfilesize - 30); int SIZE64 = SIZE * 3 / 4; PositionOnElement(DataReader, "base64"); DataReader.Read(); if (!DataReader.CanReadBinaryContent) return; byte[] base64 = new byte[SIZE64]; int startPos = 0; int readSize = 4096; int currentSize = 0; currentSize = DataReader.ReadContentAsBase64(base64, startPos, readSize); TestLog.Compare(currentSize, readSize, "Read other than first chunk"); readSize = SIZE64 - readSize; currentSize = DataReader.ReadContentAsBase64(base64, startPos, readSize); TestLog.Compare(currentSize, readSize, "Read other than remaining Chunk Size"); readSize = 0; currentSize = DataReader.ReadContentAsBase64(base64, startPos, readSize); TestLog.Compare(currentSize, 0, "Read other than Zero Bytes"); DataReader.Dispose(); } } //[TestCase(Name = "ReadElementContentAsBase64", Desc = "ReadElementContentAsBase64")] public partial class TCReadElementContentAsBase64 : BridgeHelpers { public const string ST_ELEM_NAME1 = "ElemAll"; public const string ST_ELEM_NAME2 = "ElemEmpty"; public const string ST_ELEM_NAME3 = "ElemNum"; public const string ST_ELEM_NAME4 = "ElemText"; public const string ST_ELEM_NAME5 = "ElemNumText"; public const string ST_ELEM_NAME6 = "ElemLong"; public const string strTextBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; public const string strNumBase64 = "0123456789+/"; public override void Init() { base.Init(); CreateBase64TestFile(pBase64Xml); } public override void Terminate() { DeleteTestFile(pBase64Xml); base.Terminate(); } private bool VerifyInvalidReadBase64(int iBufferSize, int iIndex, int iCount, Type exceptionType) { bool bPassed = false; byte[] buffer = new byte[iBufferSize]; XmlReader DataReader = GetReader(pBase64Xml); PositionOnElement(DataReader, ST_ELEM_NAME1); if (!DataReader.CanReadBinaryContent) return true; try { DataReader.ReadContentAsBase64(buffer, iIndex, iCount); } catch (Exception e) { bPassed = (e.GetType().ToString() == exceptionType.ToString()); if (!bPassed) { TestLog.WriteLine("Actual exception:{0}", e.GetType().ToString()); TestLog.WriteLine("Expected exception:{0}", exceptionType.ToString()); } } return bPassed; } protected void TestOnInvalidNodeType(XmlNodeType nt) { XmlReader DataReader = GetReader(pBase64Xml); PositionOnNodeType(DataReader, nt); if (!DataReader.CanReadBinaryContent) return; try { byte[] buffer = new byte[1]; int nBytes = DataReader.ReadElementContentAsBase64(buffer, 0, 1); } catch (InvalidOperationException ioe) { if (ioe.ToString().IndexOf(nt.ToString()) < 0) TestLog.Compare(false, "Call threw wrong invalid operation exception on " + nt); else return; } TestLog.Compare(false, "Call succeeded on " + nt); } //[Variation("ReadBase64 Element with all valid value")] public void TestReadBase64_1() { int base64len = 0; byte[] base64 = new byte[1000]; XmlReader DataReader = GetReader(pBase64Xml); PositionOnElement(DataReader, ST_ELEM_NAME1); if (!DataReader.CanReadBinaryContent) return; base64len = DataReader.ReadElementContentAsBase64(base64, 0, base64.Length); string strActbase64 = ""; for (int i = 0; i < base64len; i = i + 2) { strActbase64 += System.BitConverter.ToChar(base64, i); } TestLog.Compare(strActbase64, (strTextBase64 + strNumBase64), "Compare All Valid Base64"); } //[Variation("ReadBase64 Element with all valid Num value", Priority = 0)] public void TestReadBase64_2() { int base64len = 0; byte[] base64 = new byte[1000]; XmlReader DataReader = GetReader(pBase64Xml); PositionOnElement(DataReader, ST_ELEM_NAME3); if (!DataReader.CanReadBinaryContent) return; base64len = DataReader.ReadElementContentAsBase64(base64, 0, base64.Length); string strActbase64 = ""; for (int i = 0; i < base64len; i = i + 2) { strActbase64 += System.BitConverter.ToChar(base64, i); } TestLog.Compare(strActbase64, strNumBase64, "Compare All Valid Base64"); } //[Variation("ReadBase64 Element with all valid Text value")] public void TestReadBase64_3() { int base64len = 0; byte[] base64 = new byte[1000]; XmlReader DataReader = GetReader(pBase64Xml); PositionOnElement(DataReader, ST_ELEM_NAME4); if (!DataReader.CanReadBinaryContent) return; base64len = DataReader.ReadElementContentAsBase64(base64, 0, base64.Length); string strActbase64 = ""; for (int i = 0; i < base64len; i = i + 2) { strActbase64 += System.BitConverter.ToChar(base64, i); } TestLog.Compare(strActbase64, strTextBase64, "Compare All Valid Base64"); } //[Variation("ReadBase64 Element with all valid value (from concatenation), Priority=0")] public void TestReadBase64_5() { int base64len = 0; byte[] base64 = new byte[1000]; XmlReader DataReader = GetReader(pBase64Xml); PositionOnElement(DataReader, ST_ELEM_NAME5); if (!DataReader.CanReadBinaryContent) return; base64len = DataReader.ReadElementContentAsBase64(base64, 0, base64.Length); string strActbase64 = ""; for (int i = 0; i < base64len; i = i + 2) { strActbase64 += System.BitConverter.ToChar(base64, i); } TestLog.Compare(strActbase64, (strTextBase64 + strNumBase64), "Compare All Valid Base64"); } //[Variation("ReadBase64 Element with Long valid value (from concatenation), Priority=0")] public void TestReadBase64_6() { int base64len = 0; byte[] base64 = new byte[2000]; XmlReader DataReader = GetReader(pBase64Xml); PositionOnElement(DataReader, ST_ELEM_NAME6); if (!DataReader.CanReadBinaryContent) return; base64len = DataReader.ReadElementContentAsBase64(base64, 0, base64.Length); string strActbase64 = ""; for (int i = 0; i < base64len; i = i + 2) { strActbase64 += System.BitConverter.ToChar(base64, i); } string strExpbase64 = ""; for (int i = 0; i < 10; i++) strExpbase64 += (strTextBase64 + strNumBase64); TestLog.Compare(strActbase64, strExpbase64, "Compare All Valid Base64"); } //[Variation("ReadBase64 with count > buffer size")] public void ReadBase64_7() { BoolToLTMResult(VerifyInvalidReadBase64(5, 0, 6, typeof(ArgumentOutOfRangeException))); } //[Variation("ReadBase64 with count < 0")] public void ReadBase64_8() { BoolToLTMResult(VerifyInvalidReadBase64(5, 2, -1, typeof(ArgumentOutOfRangeException))); } //[Variation("ReadBase64 with index > buffer size")] public void ReadBase64_9() { BoolToLTMResult(VerifyInvalidReadBase64(5, 5, 1, typeof(ArgumentOutOfRangeException))); } //[Variation("ReadBase64 with index < 0")] public void ReadBase64_10() { BoolToLTMResult(VerifyInvalidReadBase64(5, -1, 1, typeof(ArgumentOutOfRangeException))); } //[Variation("ReadBase64 with index + count exceeds buffer")] public void ReadBase64_11() { BoolToLTMResult(VerifyInvalidReadBase64(5, 0, 10, typeof(ArgumentOutOfRangeException))); } //[Variation("ReadBase64 index & count =0")] public void ReadBase64_12() { byte[] buffer = new byte[5]; int iCount = 0; XmlReader DataReader = GetReader(pBase64Xml); PositionOnElement(DataReader, ST_ELEM_NAME1); if (!DataReader.CanReadBinaryContent) return; iCount = DataReader.ReadElementContentAsBase64(buffer, 0, 0); TestLog.Compare(iCount, 0, "has to be zero"); } //[Variation("ReadBase64 Element multiple into same buffer (using offset), Priority=0")] public void TestReadBase64_13() { int base64len = 20; byte[] base64 = new byte[base64len]; XmlReader DataReader = GetReader(pBase64Xml); PositionOnElement(DataReader, ST_ELEM_NAME4); if (!DataReader.CanReadBinaryContent) return; string strActbase64 = ""; for (int i = 0; i < base64len; i = i + 2) { DataReader.ReadElementContentAsBase64(base64, i, 2); strActbase64 = (System.BitConverter.ToChar(base64, i)).ToString(); TestLog.Compare(String.Compare(strActbase64, 0, strTextBase64, i / 2, 1), 0, "Compare All Valid Base64"); } } //[Variation("ReadBase64 with buffer == null")] public void TestReadBase64_14() { XmlReader DataReader = GetReader(pBase64Xml); PositionOnElement(DataReader, ST_ELEM_NAME4); if (!DataReader.CanReadBinaryContent) return; try { DataReader.ReadElementContentAsBase64(null, 0, 0); } catch (ArgumentNullException) { return; } throw new TestException(TestResult.Failed, ""); } //[Variation("ReadBase64 after failure")] public void TestReadBase64_15() { XmlReader DataReader = GetReader(pBase64Xml); PositionOnElement(DataReader, "ElemErr"); if (!DataReader.CanReadBinaryContent) return; byte[] buffer = new byte[10]; int nRead = 0; try { nRead = DataReader.ReadElementContentAsBase64(buffer, 0, 1); throw new TestException(TestResult.Failed, ""); } catch (XmlException e) { CheckXmlException("Xml_InvalidBase64Value", e, 0, 1); } } //[Variation("Read after partial ReadBase64", Priority = 0)] public void TestReadBase64_16() { XmlReader DataReader = GetReader(pBase64Xml); PositionOnElement(DataReader, "ElemNum"); if (!DataReader.CanReadBinaryContent) return; byte[] buffer = new byte[10]; int nRead = DataReader.ReadElementContentAsBase64(buffer, 0, 8); TestLog.Compare(nRead, 8, "0"); DataReader.Read(); TestLog.Compare(DataReader.NodeType, XmlNodeType.Text, "1vn"); } //[Variation("Current node on multiple calls")] public void TestReadBase64_17() { XmlReader DataReader = GetReader(pBase64Xml); PositionOnElement(DataReader, "ElemNum"); if (!DataReader.CanReadBinaryContent) return; byte[] buffer = new byte[30]; int nRead = DataReader.ReadElementContentAsBase64(buffer, 0, 2); TestLog.Compare(nRead, 2, "0"); nRead = DataReader.ReadElementContentAsBase64(buffer, 0, 23); TestLog.Compare(nRead, 22, "1"); TestLog.Compare(DataReader.NodeType, XmlNodeType.EndElement, "Nodetype not end element"); TestLog.Compare(DataReader.Name, "ElemNum", "Nodetype not end element"); } //[Variation("ReadBase64 with incomplete sequence")] public void TestTextReadBase64_23() { byte[] expected = new byte[] { 0, 16, 131, 16, 81 }; byte[] buffer = new byte[10]; string strxml = "<r><ROOT>ABCDEFG</ROOT></r>"; XmlReader DataReader = GetReaderStr(strxml); PositionOnElement(DataReader, "ROOT"); if (!DataReader.CanReadBinaryContent) return; int result = 0; int nRead; while ((nRead = DataReader.ReadElementContentAsBase64(buffer, result, 1)) > 0) result += nRead; TestLog.Compare(result, expected.Length, "res"); for (int i = 0; i < result; i++) TestLog.Compare(buffer[i], expected[i], "buffer[" + i + "]"); } //[Variation("ReadBase64 when end tag doesn't exist")] public void TestTextReadBase64_24() { byte[] buffer = new byte[5000]; string strxml = "<B>" + new string('c', 5000); try { XmlReader DataReader = GetReaderStr(strxml); PositionOnElement(DataReader, "B"); if (!DataReader.CanReadBinaryContent) return; DataReader.ReadElementContentAsBase64(buffer, 0, 5000); TestLog.WriteLine("Accepted incomplete element"); throw new TestException(TestResult.Failed, ""); } catch (XmlException e) { CheckXmlException("Xml_UnexpectedEOFInElementContent", e, 1, 5004); } } //[Variation("ReadBase64 with whitespace in the mIddle")] public void TestTextReadBase64_26() { byte[] buffer = new byte[1]; string strxml = "<abc> AQID B B </abc>"; int nRead; XmlReader DataReader = GetReaderStr(strxml); PositionOnElement(DataReader, "abc"); if (!DataReader.CanReadBinaryContent) return; for (int i = 0; i < 4; i++) { nRead = DataReader.ReadElementContentAsBase64(buffer, 0, 1); TestLog.Compare(nRead, 1, "res" + i); TestLog.Compare(buffer[0], (byte)(i + 1), "buffer " + i); } nRead = DataReader.ReadElementContentAsBase64(buffer, 0, 1); TestLog.Compare(nRead, 0, "nRead 0"); } //[Variation("ReadBase64 with = in the mIddle")] public void TestTextReadBase64_27() { byte[] buffer = new byte[1]; string strxml = "<abc>AQI=ID</abc>"; int nRead; XmlReader DataReader = GetReaderStr(strxml); PositionOnElement(DataReader, "abc"); if (!DataReader.CanReadBinaryContent) return; for (int i = 0; i < 2; i++) { nRead = DataReader.ReadElementContentAsBase64(buffer, 0, 1); TestLog.Compare(nRead, 1, "res" + i); TestLog.Compare(buffer[0], (byte)(i + 1), "buffer " + i); } try { DataReader.ReadElementContentAsBase64(buffer, 0, 1); TestLog.WriteLine("ReadBase64 with = in the middle succeeded"); throw new TestException(TestResult.Failed, ""); } catch (XmlException e) { CheckXmlException("Xml_InvalidBase64Value", e, 0, 1); } } //[Variation("ReadBase64 runs into an Overflow", Params = new object[] { "10000" })] //[Variation("ReadBase64 runs into an Overflow", Params = new object[] { "1000000" })] //[Variation("ReadBase64 runs into an Overflow", Params = new object[] { "10000000" })] public void ReadBase64DoesNotRunIntoOverflow2() { int totalfilesize = Convert.ToInt32(Variation.Params[0].ToString()); string ascii = new string('c', totalfilesize); byte[] bits = Encoding.Unicode.GetBytes(ascii); string base64str = Convert.ToBase64String(bits); string fileName = "bug105376_" + Variation.Params[0].ToString() + ".xml"; FilePathUtil.addStream(fileName, new MemoryStream()); StreamWriter sw = new StreamWriter(FilePathUtil.getStream(fileName)); sw.Write("<root><base64>"); sw.Write(base64str); sw.Write("</base64></root>"); sw.Flush(); XmlReader DataReader = GetReader(fileName); int SIZE = (totalfilesize - 30); int SIZE64 = SIZE * 3 / 4; PositionOnElement(DataReader, "base64"); if (!DataReader.CanReadBinaryContent) return; byte[] base64 = new byte[SIZE64]; int startPos = 0; int readSize = 4096; int currentSize = 0; currentSize = DataReader.ReadElementContentAsBase64(base64, startPos, readSize); TestLog.Compare(currentSize, readSize, "Read other than first chunk"); readSize = SIZE64 - readSize; currentSize = DataReader.ReadElementContentAsBase64(base64, startPos, readSize); TestLog.Compare(currentSize, readSize, "Read other than remaining Chunk Size"); readSize = 0; currentSize = DataReader.ReadElementContentAsBase64(base64, startPos, readSize); TestLog.Compare(currentSize, 0, "Read other than Zero Bytes"); DataReader.Dispose(); } //[Variation("SubtreeReader inserted attributes don't work with ReadContentAsBase64")] public void SubtreeReaderInsertedAttributesWontWorkWithReadContentAsBase64() { string strxml1 = "<root xmlns='"; string strxml2 = "'><bar/></root>"; string[] binValue = new string[] { "AAECAwQFBgcI==", "0102030405060708090a0B0c" }; for (int i = 0; i < binValue.Length; i++) { string strxml = strxml1 + binValue[i] + strxml2; using (XmlReader r = GetReader(new StringReader(strxml))) { r.Read(); r.Read(); using (XmlReader sr = r.ReadSubtree()) { if (!sr.CanReadBinaryContent) return; sr.Read(); sr.MoveToFirstAttribute(); sr.MoveToFirstAttribute(); byte[] bytes = new byte[4]; while ((sr.ReadContentAsBase64(bytes, 0, bytes.Length)) > 0) { } } } } } } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class MegaMorphBase : MegaModifier { public List<MegaMorphChan> chanBank = new List<MegaMorphChan>(); public MegaMorphAnimType animtype = MegaMorphAnimType.Bezier; public override void PostCopy(MegaModifier src) { MegaMorphBase mor = (MegaMorphBase)src; chanBank = new List<MegaMorphChan>(); for ( int c = 0; c < mor.chanBank.Count; c++ ) { MegaMorphChan chan = new MegaMorphChan(); MegaMorphChan.Copy(mor.chanBank[c], chan); chanBank.Add(chan); } } public string[] GetChannelNames() { string[] names = new string[chanBank.Count]; for ( int i = 0; i < chanBank.Count; i++ ) names[i] = chanBank[i].mName; return names; } public MegaMorphChan GetChannel(string name) { for ( int i = 0; i < chanBank.Count; i++ ) { if ( chanBank[i].mName == name ) return chanBank[i]; } return null; } public int NumChannels() { return chanBank.Count; } public void SetPercent(int i, float percent) { if ( i >= 0 && i < chanBank.Count ) chanBank[i].Percent = percent; } public void SetPercentLim(int i, float alpha) { if ( i >= 0 && i < chanBank.Count ) { if ( chanBank[i].mUseLimit ) chanBank[i].Percent = chanBank[i].mSpinmin + ((chanBank[i].mSpinmax - chanBank[i].mSpinmin) * alpha); else chanBank[i].Percent = alpha * 100.0f; } } public void SetPercent(int i, float percent, float speed) { chanBank[i].SetTarget(percent, speed); } public void ResetPercent(int[] channels, float speed) { for ( int i = 0; i < channels.Length; i++ ) { int chan = channels[i]; chanBank[chan].SetTarget(0.0f, speed); } } public float GetPercent(int i) { if ( i >= 0 && i < chanBank.Count ) return chanBank[i].Percent; return 0.0f; } public void SetAnim(float t) { if ( animtype == MegaMorphAnimType.Bezier ) { for ( int i = 0; i < chanBank.Count; i++ ) { if ( chanBank[i].control != null ) { if ( chanBank[i].control.Times != null ) { if ( chanBank[i].control.Times.Length > 0 ) chanBank[i].Percent = chanBank[i].control.GetFloat(t); //, 0.0f, 100.0f); } } } } else { for ( int i = 0; i < chanBank.Count; i++ ) { if ( chanBank[i].control != null ) { if ( chanBank[i].control.Times != null ) { if ( chanBank[i].control.Times.Length > 0 ) chanBank[i].Percent = chanBank[i].control.GetHermiteFloat(t); //, 0.0f, 100.0f); } } } } } [System.Serializable] public class MegaMorphBlend { public float t; public float weight; } public int numblends; public List<MegaMorphBlend> blends; // = new List<MegaMorphBlend>(); public void SetAnimBlend(float t, float weight) { if ( blends == null ) { blends = new List<MegaMorphBlend>(); for ( int i = 0; i < 4; i++ ) { blends.Add(new MegaMorphBlend()); } } blends[numblends].t = t; blends[numblends].weight = weight; numblends++; } public void ClearBlends() { numblends = 0; } public void SetChannels() { float tweight = 0.0f; for ( int i = 0; i < numblends; i++ ) { tweight += blends[i].weight; } for ( int b = 0; b < numblends; b++ ) { for ( int c = 0; c < chanBank.Count; c++ ) { if ( animtype == MegaMorphAnimType.Bezier ) { if ( chanBank[c].control != null ) { if ( chanBank[c].control.Times != null ) { if ( chanBank[c].control.Times.Length > 0 ) { if ( b == 0 ) chanBank[c].Percent = chanBank[c].control.GetFloat(blends[b].t) * (blends[b].weight / tweight); //, 0.0f, 100.0f); else chanBank[c].Percent += chanBank[c].control.GetFloat(blends[b].t) * (blends[b].weight / tweight); //, 0.0f, 100.0f); } } } } else { if ( chanBank[c].control != null ) { if ( chanBank[c].control.Times != null ) { if ( chanBank[c].control.Times.Length > 0 ) { if ( b == 0 ) chanBank[c].Percent = chanBank[c].control.GetHermiteFloat(blends[b].t) * (blends[b].weight / tweight); //, 0.0f, 100.0f); else chanBank[c].Percent += chanBank[c].control.GetHermiteFloat(blends[b].t) * (blends[b].weight / tweight); //, 0.0f, 100.0f); } } } } } } } } public enum MegaMorphAnimType { Bezier, Hermite, } [AddComponentMenu("Modifiers/Morph")] public class MegaMorph : MegaMorphBase { public bool UseLimit; public float Max; public float Min; public Vector3[] oPoints; public int[] mapping; public float importScale = 1.0f; public bool flipyz = false; public bool negx = false; [HideInInspector] public float tolerance = 0.0001f; public bool showmapping = false; public float mappingSize = 0.001f; public int mapStart = 0; public int mapEnd = 0; public Vector3[] dif; // changed to public, check it doesnt break anything static Vector3[] endpoint = new Vector3[4]; static Vector3[] splinepoint = new Vector3[4]; static Vector3[] temppoint = new Vector3[2]; Vector3[] p1; Vector3[] p2; Vector3[] p3; Vector3[] p4; public List<float> pers = new List<float>(4); public override string ModName() { return "Morph"; } public override string GetHelpURL() { return "?page_id=257"; } [HideInInspector] public int compressedmem = 0; [HideInInspector] public int compressedmem1 = 0; [HideInInspector] public int memuse = 0; // This should be a MegaModifiers method, so on Start/Awake run through and regrab all verts // and then for each modifier call a PS3Remap method // Actually we could leave systems in place and have an end method that build a PS3 mesh, this would mean // we get the overhead of building a new vertex array but should be more than offset by not modifying dup // verts // So at start we use current verts and then remap against freshly fetched vert data public void PS3Remap() { } public override bool ModLateUpdate(MegaModContext mc) { if ( animate ) { if ( Application.isPlaying ) animtime += Time.deltaTime * speed; switch ( repeatMode ) { case MegaRepeatMode.Loop: animtime = Mathf.Repeat(animtime, looptime); break; //case RepeatMode.PingPong: animtime = Mathf.PingPong(animtime, looptime); break; case MegaRepeatMode.Clamp: animtime = Mathf.Clamp(animtime, 0.0f, looptime); break; } //animtime = Mathf.Repeat(animtime, looptime); SetAnim(animtime); } if ( dif == null ) { dif = new Vector3[mc.mod.verts.Length]; } return Prepare(mc); } public bool animate = false; public float atime = 0.0f; public float animtime = 0.0f; public float looptime = 0.0f; public MegaRepeatMode repeatMode = MegaRepeatMode.Loop; public float speed = 1.0f; public override bool Prepare(MegaModContext mc) { if ( chanBank != null && chanBank.Count > 0 ) return true; return false; } // Find the closest and not use a threshold, use sqr distance int FindVert(Vector3 vert) { float closest = Vector3.SqrMagnitude(oPoints[0] - vert); int find = 0; for ( int i = 0; i < oPoints.Length; i++ ) { float dif = Vector3.SqrMagnitude(oPoints[i] - vert); if ( dif < closest ) { closest = dif; find = i; } } return find; //0; } void DoMapping(Mesh mesh) { mapping = new int[mesh.vertexCount]; for ( int v = 0; v < mesh.vertexCount; v++ ) { Vector3 vert = mesh.vertices[v]; vert.x = -vert.x; mapping[v] = FindVert(vert); } } public void DoMapping(Vector3[] verts) { mapping = new int[verts.Length]; for ( int v = 0; v < verts.Length; v++ ) { mapping[v] = FindVert(verts[v]); } } // Only need to call if a Percent value has changed on a Channel or a target, so flag for a change void SetVerts(int j, Vector3[] p) { switch ( j ) { case 0: p1 = p; break; case 1: p2 = p; break; case 2: p3 = p; break; case 3: p4 = p; break; } } void SetVerts(MegaMorphChan chan, int j, Vector3[] p) { switch ( j ) { case 0: chan.p1 = p; break; case 1: chan.p2 = p; break; case 2: chan.p3 = p; break; case 3: chan.p4 = p; break; } } // Seperate function for compressed data, when we compress we should be able to tell if its worth it // as we will need to dup opoints etc static int framenum; // oPoints whould be verts public override void Modify(MegaModifiers mc) { if ( nonMorphedVerts != null && nonMorphedVerts.Length > 1 ) { ModifyCompressed(mc); return; } framenum++; mc.ChangeSourceVerts(); float fChannelPercent; Vector3 delt; // cycle through channels, searching for ones to use bool firstchan = true; bool morphed = false; float min = 0.0f; float max = 100.0f; if ( UseLimit ) { min = Min; max = Max; } for ( int i = 0; i < chanBank.Count; i++ ) { MegaMorphChan chan = chanBank[i]; chan.UpdatePercent(); if ( UseLimit ) fChannelPercent = Mathf.Clamp(chan.Percent, min, max); //chan.mSpinmin, chan.mSpinmax); else { if ( chan.mUseLimit ) fChannelPercent = Mathf.Clamp(chan.Percent, chan.mSpinmin, chan.mSpinmax); else fChannelPercent = Mathf.Clamp(chan.Percent, 0.0f, 100.0f); } //fChannelPercent *= chan.weight; if ( fChannelPercent != 0.0f || (fChannelPercent == 0.0f && chan.fChannelPercent != 0.0f) ) { chan.fChannelPercent = fChannelPercent; if ( chan.mTargetCache != null && chan.mTargetCache.Count > 0 && chan.mActiveOverride ) //&& fChannelPercent != 0.0f ) { morphed = true; if ( chan.mUseLimit ) //|| glUseLimit ) { } if ( firstchan ) { firstchan = false; for ( int pointnum = 0; pointnum < oPoints.Length; pointnum++ ) dif[pointnum] = oPoints[pointnum]; } if ( chan.mTargetCache.Count == 1 ) { for ( int pointnum = 0; pointnum < oPoints.Length; pointnum++ ) { delt = chan.mDeltas[pointnum]; dif[pointnum].x += delt.x * fChannelPercent; dif[pointnum].y += delt.y * fChannelPercent; dif[pointnum].z += delt.z * fChannelPercent; } } else { int totaltargs = chan.mTargetCache.Count; // + 1; // + 1; float fProgression = fChannelPercent; //Mathf.Clamp(fChannelPercent, 0.0f, 100.0f); int segment = 1; while ( segment <= totaltargs && fProgression >= chan.GetTargetPercent(segment - 2) ) segment++; if ( segment > totaltargs ) segment = totaltargs; p4 = oPoints; if ( segment == 1 ) { p1 = oPoints; p2 = chan.mTargetCache[0].points; // mpoints p3 = chan.mTargetCache[1].points; } else { if ( segment == totaltargs ) { int targnum = totaltargs - 1; for ( int j = 2; j >= 0; j-- ) { targnum--; if ( targnum == -2 ) SetVerts(j, oPoints); else SetVerts(j, chan.mTargetCache[targnum + 1].points); } } else { int targnum = segment; for ( int j = 3; j >= 0; j-- ) { targnum--; if ( targnum == -2 ) SetVerts(j, oPoints); else SetVerts(j, chan.mTargetCache[targnum + 1].points); } } } float targetpercent1 = chan.GetTargetPercent(segment - 3); float targetpercent2 = chan.GetTargetPercent(segment - 2); float top = fProgression - targetpercent1; float bottom = targetpercent2 - targetpercent1; float u = top / bottom; { for ( int pointnum = 0; pointnum < oPoints.Length; pointnum++ ) { Vector3 vert = oPoints[pointnum]; float length; Vector3 progession; endpoint[0] = p1[pointnum]; endpoint[1] = p2[pointnum]; endpoint[2] = p3[pointnum]; endpoint[3] = p4[pointnum]; if ( segment == 1 ) { splinepoint[0] = endpoint[0]; splinepoint[3] = endpoint[1]; temppoint[1] = endpoint[2] - endpoint[0]; temppoint[0] = endpoint[1] - endpoint[0]; length = temppoint[1].sqrMagnitude; if ( length == 0.0f ) { splinepoint[1] = endpoint[0]; splinepoint[2] = endpoint[1]; } else { splinepoint[2] = endpoint[1] - (Vector3.Dot(temppoint[0], temppoint[1]) * chan.mCurvature / length) * temppoint[1]; splinepoint[1] = endpoint[0] + chan.mCurvature * (splinepoint[2] - endpoint[0]); } } else { if ( segment == totaltargs ) { splinepoint[0] = endpoint[1]; splinepoint[3] = endpoint[2]; temppoint[1] = endpoint[2] - endpoint[0]; temppoint[0] = endpoint[1] - endpoint[2]; length = temppoint[1].sqrMagnitude; if ( length == 0.0f ) { splinepoint[1] = endpoint[0]; splinepoint[2] = endpoint[1]; } else { splinepoint[1] = endpoint[1] - (Vector3.Dot(temppoint[1], temppoint[0]) * chan.mCurvature / length) * temppoint[1]; splinepoint[2] = endpoint[2] + chan.mCurvature * (splinepoint[1] - endpoint[2]); } } else { temppoint[1] = endpoint[2] - endpoint[0]; temppoint[0] = endpoint[1] - endpoint[0]; length = temppoint[1].sqrMagnitude; splinepoint[0] = endpoint[1]; splinepoint[3] = endpoint[2]; if ( length == 0.0f ) splinepoint[1] = endpoint[0]; else splinepoint[1] = endpoint[1] + (Vector3.Dot(temppoint[0], temppoint[1]) * chan.mCurvature / length) * temppoint[1]; temppoint[1] = endpoint[3] - endpoint[1]; temppoint[0] = endpoint[2] - endpoint[1]; length = temppoint[1].sqrMagnitude; if ( length == 0.0f ) splinepoint[2] = endpoint[1]; else splinepoint[2] = endpoint[2] - (Vector3.Dot(temppoint[0], temppoint[1]) * chan.mCurvature / length) * temppoint[1]; } } MegaUtils.Bez3D(out progession, ref splinepoint, u); dif[pointnum].x += (progession.x - vert.x) * chan.weight; //delt; dif[pointnum].y += (progession.y - vert.y) * chan.weight; //delt; dif[pointnum].z += (progession.z - vert.z) * chan.weight; //delt; } } } } } } if ( morphed ) { for ( int i = 0; i < mapping.Length; i++ ) sverts[i] = dif[mapping[i]]; } else { for ( int i = 0; i < verts.Length; i++ ) sverts[i] = verts[i]; } } bool Changed(int v, int c) { for ( int t = 0; t < chanBank[c].mTargetCache.Count; t++ ) { if ( !oPoints[v].Equals(chanBank[c].mTargetCache[t].points[v]) ) return true; } return false; } // Move compression to editor script so not included in releases // Option for compression, per channel or per morph, will effect multicore support // morph compression means simple mt split // TODO: have a threshold for differences // Do we compress per channel or whole mesh, channel would be best // Can only compress once as we are destroying data, so if vert counts dont match dont recompress public void Compress() { if ( oPoints != null ) { List<int> altered = new List<int>(); int count = 0; for ( int c = 0; c < chanBank.Count; c++ ) { altered.Clear(); for ( int v = 0; v < oPoints.Length; v++ ) { if ( Changed(v, c) ) altered.Add(v); } count += altered.Count; } Debug.Log("Compressed will only morph " + count + " points instead of " + (oPoints.Length * chanBank.Count)); compressedmem = count * 12; } } public void ModifyCompressed(MegaModifiers mc) { framenum++; mc.ChangeSourceVerts(); float fChannelPercent; Vector3 delt; // cycle through channels, searching for ones to use bool firstchan = true; bool morphed = false; for ( int i = 0; i < chanBank.Count; i++ ) { MegaMorphChan chan = chanBank[i]; chan.UpdatePercent(); if ( chan.mUseLimit ) fChannelPercent = Mathf.Clamp(chan.Percent, chan.mSpinmin, chan.mSpinmax); else fChannelPercent = Mathf.Clamp(chan.Percent, 0.0f, 100.0f); if ( fChannelPercent != 0.0f || (fChannelPercent == 0.0f && chan.fChannelPercent != 0.0f) ) { chan.fChannelPercent = fChannelPercent; if ( chan.mTargetCache != null && chan.mTargetCache.Count > 0 && chan.mActiveOverride ) //&& fChannelPercent != 0.0f ) { morphed = true; if ( chan.mUseLimit ) //|| glUseLimit ) { } // New bit if ( firstchan ) { firstchan = false; // Save a int array of morphedpoints and use that, then only dealing with changed info for ( int pointnum = 0; pointnum < morphedVerts.Length; pointnum++ ) { // this will change when we remove points int p = morphedVerts[pointnum]; dif[p] = oPoints[p]; //morphedVerts[pointnum]]; } } // end new if ( chan.mTargetCache.Count == 1 ) { // Save a int array of morphedpoints and use that, then only dealing with changed info for ( int pointnum = 0; pointnum < morphedVerts.Length; pointnum++ ) { int p = morphedVerts[pointnum]; delt = chan.mDeltas[p]; //morphedVerts[pointnum]]; //delt = chan.mDeltas[pointnum]; //morphedVerts[pointnum]]; dif[p].x += delt.x * fChannelPercent; dif[p].y += delt.y * fChannelPercent; dif[p].z += delt.z * fChannelPercent; } } else { int totaltargs = chan.mTargetCache.Count; // + 1; // + 1; float fProgression = fChannelPercent; //Mathf.Clamp(fChannelPercent, 0.0f, 100.0f); int segment = 1; while ( segment <= totaltargs && fProgression >= chan.GetTargetPercent(segment - 2) ) segment++; if ( segment > totaltargs ) segment = totaltargs; p4 = oPoints; if ( segment == 1 ) { p1 = oPoints; p2 = chan.mTargetCache[0].points; // mpoints p3 = chan.mTargetCache[1].points; } else { if ( segment == totaltargs ) { int targnum = totaltargs - 1; for ( int j = 2; j >= 0; j-- ) { targnum--; if ( targnum == -2 ) SetVerts(j, oPoints); else SetVerts(j, chan.mTargetCache[targnum + 1].points); } } else { int targnum = segment; for ( int j = 3; j >= 0; j-- ) { targnum--; if ( targnum == -2 ) SetVerts(j, oPoints); else SetVerts(j, chan.mTargetCache[targnum + 1].points); } } } float targetpercent1 = chan.GetTargetPercent(segment - 3); float targetpercent2 = chan.GetTargetPercent(segment - 2); float top = fProgression - targetpercent1; float bottom = targetpercent2 - targetpercent1; float u = top / bottom; for ( int pointnum = 0; pointnum < morphedVerts.Length; pointnum++ ) { int p = morphedVerts[pointnum]; Vector3 vert = oPoints[p]; //pointnum]; float length; Vector3 progession; endpoint[0] = p1[p]; endpoint[1] = p2[p]; endpoint[2] = p3[p]; endpoint[3] = p4[p]; if ( segment == 1 ) { splinepoint[0] = endpoint[0]; splinepoint[3] = endpoint[1]; temppoint[1] = endpoint[2] - endpoint[0]; temppoint[0] = endpoint[1] - endpoint[0]; length = temppoint[1].sqrMagnitude; if ( length == 0.0f ) { splinepoint[1] = endpoint[0]; splinepoint[2] = endpoint[1]; } else { splinepoint[2] = endpoint[1] - (Vector3.Dot(temppoint[0], temppoint[1]) * chan.mCurvature / length) * temppoint[1]; splinepoint[1] = endpoint[0] + chan.mCurvature * (splinepoint[2] - endpoint[0]); } } else { if ( segment == totaltargs ) { splinepoint[0] = endpoint[1]; splinepoint[3] = endpoint[2]; temppoint[1] = endpoint[2] - endpoint[0]; temppoint[0] = endpoint[1] - endpoint[2]; length = temppoint[1].sqrMagnitude; if ( length == 0.0f ) { splinepoint[1] = endpoint[0]; splinepoint[2] = endpoint[1]; } else { splinepoint[1] = endpoint[1] - (Vector3.Dot(temppoint[1], temppoint[0]) * chan.mCurvature / length) * temppoint[1]; splinepoint[2] = endpoint[2] + chan.mCurvature * (splinepoint[1] - endpoint[2]); } } else { temppoint[1] = endpoint[2] - endpoint[0]; temppoint[0] = endpoint[1] - endpoint[0]; length = temppoint[1].sqrMagnitude; splinepoint[0] = endpoint[1]; splinepoint[3] = endpoint[2]; if ( length == 0.0f ) splinepoint[1] = endpoint[0]; else splinepoint[1] = endpoint[1] + (Vector3.Dot(temppoint[0], temppoint[1]) * chan.mCurvature / length) * temppoint[1]; temppoint[1] = endpoint[3] - endpoint[1]; temppoint[0] = endpoint[2] - endpoint[1]; length = temppoint[1].sqrMagnitude; if ( length == 0.0f ) splinepoint[2] = endpoint[1]; else splinepoint[2] = endpoint[2] - (Vector3.Dot(temppoint[0], temppoint[1]) * chan.mCurvature / length) * temppoint[1]; } } MegaUtils.Bez3D(out progession, ref splinepoint, u); dif[p].x += progession.x - vert.x; dif[p].y += progession.y - vert.y; dif[p].z += progession.z - vert.z; } } } } } if ( morphed ) { for ( int i = 0; i < morphMappingFrom.Length; i++ ) sverts[morphMappingTo[i]] = dif[morphMappingFrom[i]]; for ( int i = 0; i < nonMorphMappingFrom.Length; i++ ) sverts[nonMorphMappingTo[i]] = oPoints[nonMorphMappingFrom[i]]; } else { for ( int i = 0; i < verts.Length; i++ ) sverts[i] = verts[i]; } } // Build compressed data public int[] nonMorphedVerts; public int[] morphedVerts; public int[] morphMappingFrom; public int[] morphMappingTo; public int[] nonMorphMappingFrom; public int[] nonMorphMappingTo; [ContextMenu("Compress Morphs")] public void BuildCompress() { bool[] altered = new bool[oPoints.Length]; int count = 0; for ( int c = 0; c < chanBank.Count; c++ ) { for ( int v = 0; v < oPoints.Length; v++ ) { if ( Changed(v, c) ) altered[v] = true; } } for ( int i = 0; i < altered.Length; i++ ) { if ( altered[i] ) count++; } morphedVerts = new int[count]; nonMorphedVerts = new int[oPoints.Length - count]; int mindex = 0; int nmindex = 0; List<int> mappedFrom = new List<int>(); List<int> mappedTo = new List<int>(); for ( int i = 0; i < oPoints.Length; i++ ) { if ( altered[i] ) { morphedVerts[mindex++] = i; for ( int m = 0; m < mapping.Length; m++ ) { if ( mapping[m] == i ) { mappedFrom.Add(i); mappedTo.Add(m); } } } else nonMorphedVerts[nmindex++] = i; } morphMappingFrom = mappedFrom.ToArray(); morphMappingTo = mappedTo.ToArray(); mappedFrom.Clear(); mappedTo.Clear(); for ( int i = 0; i < oPoints.Length; i++ ) { if ( !altered[i] ) { for ( int m = 0; m < mapping.Length; m++ ) { if ( mapping[m] == i ) { mappedFrom.Add(i); mappedTo.Add(m); } } } } nonMorphMappingFrom = mappedFrom.ToArray(); nonMorphMappingTo = mappedTo.ToArray(); compressedmem = morphedVerts.Length * chanBank.Count * 12; } // Threaded version Vector3[] _verts; Vector3[] _sverts; public override void PrepareMT(MegaModifiers mc, int cores) { PrepareForMT(mc, cores); } public override void DoWork(MegaModifiers mc, int index, int start, int end, int cores) { ModifyCompressedMT(mc, index, cores); } public void PrepareForMT(MegaModifiers mc, int cores) { if ( setStart == null ) BuildMorphVertInfo(cores); // cycle through channels, searching for ones to use mtmorphed = false; for ( int i = 0; i < chanBank.Count; i++ ) { MegaMorphChan chan = chanBank[i]; chan.UpdatePercent(); float fChannelPercent; if ( chan.mUseLimit ) fChannelPercent = Mathf.Clamp(chan.Percent, chan.mSpinmin, chan.mSpinmax); else fChannelPercent = Mathf.Clamp(chan.Percent, 0.0f, 100.0f); if ( fChannelPercent != 0.0f || (fChannelPercent == 0.0f && chan.fChannelPercent != 0.0f) ) { chan.fChannelPercent = fChannelPercent; if ( chan.mTargetCache != null && chan.mTargetCache.Count > 0 && chan.mActiveOverride ) { mtmorphed = true; if ( chan.mTargetCache.Count > 1 ) { int totaltargs = chan.mTargetCache.Count; // + 1; // + 1; chan.fProgression = chan.fChannelPercent; //Mathf.Clamp(fChannelPercent, 0.0f, 100.0f); chan.segment = 1; while ( chan.segment <= totaltargs && chan.fProgression >= chan.GetTargetPercent(chan.segment - 2) ) chan.segment++; if ( chan.segment > totaltargs ) chan.segment = totaltargs; chan.p4 = oPoints; if ( chan.segment == 1 ) { chan.p1 = oPoints; chan.p2 = chan.mTargetCache[0].points; // mpoints chan.p3 = chan.mTargetCache[1].points; } else { if ( chan.segment == totaltargs ) { int targnum = totaltargs - 1; for ( int j = 2; j >= 0; j-- ) { targnum--; if ( targnum == -2 ) SetVerts(chan, j, oPoints); else SetVerts(chan, j, chan.mTargetCache[targnum + 1].points); } } else { int targnum = chan.segment; for ( int j = 3; j >= 0; j-- ) { targnum--; if ( targnum == -2 ) SetVerts(chan, j, oPoints); else SetVerts(chan, j, chan.mTargetCache[targnum + 1].points); } } } } } } } if ( !mtmorphed ) { for ( int i = 0; i < verts.Length; i++ ) sverts[i] = verts[i]; } else { //if ( firstchan ) //{ //firstchan = false; for ( int pointnum = 0; pointnum < morphedVerts.Length; pointnum++ ) { int p = morphedVerts[pointnum]; dif[p] = oPoints[p]; } //} } } bool mtmorphed; public void ModifyCompressedMT(MegaModifiers mc, int tindex, int cores) { if ( !mtmorphed ) return; int step = morphedVerts.Length / cores; int startvert = (tindex * step); int endvert = startvert + step; if ( tindex == cores - 1 ) endvert = morphedVerts.Length; framenum++; Vector3 delt; // cycle through channels, searching for ones to use //bool firstchan = true; Vector3[] endpoint = new Vector3[4]; // These in channel class Vector3[] splinepoint = new Vector3[4]; Vector3[] temppoint = new Vector3[2]; for ( int i = 0; i < chanBank.Count; i++ ) { MegaMorphChan chan = chanBank[i]; if ( chan.fChannelPercent != 0.0f ) { if ( chan.mTargetCache != null && chan.mTargetCache.Count > 0 && chan.mActiveOverride ) //&& fChannelPercent != 0.0f ) { #if false if ( firstchan ) { firstchan = false; for ( int pointnum = startvert; pointnum < endvert; pointnum++ ) { int p = morphedVerts[pointnum]; dif[p] = oPoints[p]; } } #endif if ( chan.mTargetCache.Count == 1 ) { for ( int pointnum = startvert; pointnum < endvert; pointnum++ ) { int p = morphedVerts[pointnum]; delt = chan.mDeltas[p]; dif[p].x += delt.x * chan.fChannelPercent; dif[p].y += delt.y * chan.fChannelPercent; dif[p].z += delt.z * chan.fChannelPercent; } } else { float targetpercent1 = chan.GetTargetPercent(chan.segment - 3); float targetpercent2 = chan.GetTargetPercent(chan.segment - 2); float top = chan.fProgression - targetpercent1; float bottom = targetpercent2 - targetpercent1; float u = top / bottom; for ( int pointnum = startvert; pointnum < endvert; pointnum++ ) { int p = morphedVerts[pointnum]; Vector3 vert = oPoints[p]; //pointnum]; float length; Vector3 progession; endpoint[0] = chan.p1[p]; endpoint[1] = chan.p2[p]; endpoint[2] = chan.p3[p]; endpoint[3] = chan.p4[p]; if ( chan.segment == 1 ) { splinepoint[0] = endpoint[0]; splinepoint[3] = endpoint[1]; temppoint[1] = endpoint[2] - endpoint[0]; temppoint[0] = endpoint[1] - endpoint[0]; length = temppoint[1].sqrMagnitude; if ( length == 0.0f ) { splinepoint[1] = endpoint[0]; splinepoint[2] = endpoint[1]; } else { splinepoint[2] = endpoint[1] - (Vector3.Dot(temppoint[0], temppoint[1]) * chan.mCurvature / length) * temppoint[1]; splinepoint[1] = endpoint[0] + chan.mCurvature * (splinepoint[2] - endpoint[0]); } } else { if ( chan.segment == chan.mTargetCache.Count ) //chan.totaltargs ) { splinepoint[0] = endpoint[1]; splinepoint[3] = endpoint[2]; temppoint[1] = endpoint[2] - endpoint[0]; temppoint[0] = endpoint[1] - endpoint[2]; length = temppoint[1].sqrMagnitude; if ( length == 0.0f ) { splinepoint[1] = endpoint[0]; splinepoint[2] = endpoint[1]; } else { splinepoint[1] = endpoint[1] - (Vector3.Dot(temppoint[1], temppoint[0]) * chan.mCurvature / length) * temppoint[1]; splinepoint[2] = endpoint[2] + chan.mCurvature * (splinepoint[1] - endpoint[2]); } } else { temppoint[1] = endpoint[2] - endpoint[0]; temppoint[0] = endpoint[1] - endpoint[0]; length = temppoint[1].sqrMagnitude; splinepoint[0] = endpoint[1]; splinepoint[3] = endpoint[2]; if ( length == 0.0f ) splinepoint[1] = endpoint[0]; else splinepoint[1] = endpoint[1] + (Vector3.Dot(temppoint[0], temppoint[1]) * chan.mCurvature / length) * temppoint[1]; temppoint[1] = endpoint[3] - endpoint[1]; temppoint[0] = endpoint[2] - endpoint[1]; length = temppoint[1].sqrMagnitude; if ( length == 0.0f ) splinepoint[2] = endpoint[1]; else splinepoint[2] = endpoint[2] - (Vector3.Dot(temppoint[0], temppoint[1]) * chan.mCurvature / length) * temppoint[1]; } } MegaUtils.Bez3D(out progession, ref splinepoint, u); dif[p].x += progession.x - vert.x; dif[p].y += progession.y - vert.y; dif[p].z += progession.z - vert.z; } } } } } if ( mtmorphed ) { //for ( int i = setStart[tindex]; i < setEnd[tindex]; i++ ) //sverts[morphMappingTo[i]] = dif[morphMappingFrom[i]]; //for ( int i = copyStart[tindex]; i < copyEnd[tindex]; i++ ) //sverts[nonMorphMappingTo[i]] = oPoints[nonMorphMappingFrom[i]]; } } public override void DoneMT(MegaModifiers mod) { if ( mtmorphed ) { for ( int i = 0; i < morphMappingFrom.Length; i++ ) sverts[morphMappingTo[i]] = dif[morphMappingFrom[i]]; for ( int i = 0; i < nonMorphMappingFrom.Length; i++ ) sverts[nonMorphMappingTo[i]] = oPoints[nonMorphMappingFrom[i]]; } } int[] setStart; int[] setEnd; int[] copyStart; int[] copyEnd; int Find(int index) { int f = morphedVerts[index]; for ( int i = 0; i < morphMappingFrom.Length; i++ ) { if ( morphMappingFrom[i] > f ) return i; } return morphMappingFrom.Length - 1; } void BuildMorphVertInfo(int cores) { int step = morphedVerts.Length / cores; setStart = new int[cores]; setEnd = new int[cores]; copyStart = new int[cores]; copyEnd = new int[cores]; int start = 0; int fv = 0; for ( int i = 0; i < cores; i++ ) { setStart[i] = start; if ( i < cores - 1 ) { setEnd[i] = Find(fv + step); } start = setEnd[i]; fv += step; } setEnd[cores - 1] = morphMappingFrom.Length; // copys can be simple split as nothing happens to them start = 0; step = nonMorphMappingFrom.Length / cores; for ( int i = 0; i < cores; i++ ) { copyStart[i] = start; copyEnd[i] = start + step; start += step; } copyEnd[cores - 1] = nonMorphMappingFrom.Length; } public void SetAnimTime(float t) { animtime = t; switch ( repeatMode ) { case MegaRepeatMode.Loop: animtime = Mathf.Repeat(animtime, looptime); break; //case RepeatMode.PingPong: animtime = Mathf.PingPong(animtime, looptime); break; case MegaRepeatMode.Clamp: animtime = Mathf.Clamp(animtime, 0.0f, looptime); break; } SetAnim(animtime); } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Rithmic.Rithmic File: RithmicClient_Callbacks.cs Created: 2015, 12, 2, 8:18 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Rithmic { using System; using com.omnesys.rapi; using Ecng.Common; using StockSharp.Logging; using StockSharp.Messages; partial class RithmicClient { private class AdmCallbacksImpl : AdmCallbacks { private readonly RithmicClient _client; private readonly ILogReceiver _receiver; public AdmCallbacksImpl(RithmicClient client, ILogReceiver receiver) { if (client == null) throw new ArgumentNullException(nameof(client)); if (receiver == null) throw new ArgumentNullException(nameof(receiver)); _client = client; _receiver = receiver; } public override void Alert(AlertInfo info) { _client.Alert.WithDump(_receiver).SafeInvoke(info); //_sessionHolder.AddWarningLog("Received unexpected AdmCallbacks.Alert():\n{0}", oInfo.DumpableToString()); } } private class RCallbacksImpl : RCallbacks { private readonly RithmicClient _client; private readonly ILogReceiver _receiver; public RCallbacksImpl(RithmicClient client, ILogReceiver receiver) { if (client == null) throw new ArgumentNullException(nameof(client)); if (receiver == null) throw new ArgumentNullException(nameof(receiver)); _client = client; _receiver = receiver; } private void MarketDataError(Exception ex) { _client.MarketDataError.SafeInvoke(ex); } private void TransactionError(Exception ex) { _client.TransactionError.SafeInvoke(ex); } #region connection public override void Alert(AlertInfo info) { _client.Alert.WithDump(_receiver).SafeInvoke(info); } public override void PasswordChange(PasswordChangeInfo info) { _client.PasswordChange.WithDump(_receiver).SafeInvoke(info); } #endregion #region orders public override void ExecutionReplay(ExecutionReplayInfo info) { _client.Execution.WithDump(_receiver).WithError(TransactionError).SafeInvoke(info); } public override void OpenOrderReplay(OrderReplayInfo info) { _client.OrderInfo.WithDump(_receiver).WithError(TransactionError).SafeInvoke(info); } public override void OrderReplay(OrderReplayInfo info) { _client.OrderInfo.WithDump(_receiver).WithError(TransactionError).SafeInvoke(info); } public override void LineUpdate(LineInfo info) { _client.OrderLineUpdate.WithDump(_receiver).WithError(TransactionError).SafeInvoke(info); } public override void BustReport(OrderBustReport report) { _client.OrderBust.WithDump(_receiver).WithError(TransactionError).SafeInvoke(report); } public override void CancelReport(OrderCancelReport report) { _client.OrderCancel.WithDump(_receiver).WithError(TransactionError).SafeInvoke(report); } public override void FailureReport(OrderFailureReport report) { _client.OrderFailure.WithDump(_receiver).WithError(TransactionError).SafeInvoke(report); } public override void FillReport(OrderFillReport report) { _client.OrderFill.WithDump(_receiver).WithError(TransactionError).SafeInvoke(report); } public override void ModifyReport(OrderModifyReport report) { _client.OrderModify.WithDump(_receiver).WithError(TransactionError).SafeInvoke(report); } public override void NotCancelledReport(OrderNotCancelledReport report) { _client.OrderCancelFailure.WithDump(_receiver).WithError(TransactionError).SafeInvoke(report); } public override void NotModifiedReport(OrderNotModifiedReport report) { _client.OrderModifyFailure.WithDump(_receiver).WithError(TransactionError).SafeInvoke(report); } public override void OtherReport(OrderReport report) { _client.OrderReport.WithDump(_receiver).WithError(TransactionError).SafeInvoke(report); } public override void RejectReport(OrderRejectReport report) { _client.OrderReject.WithDump(_receiver).WithError(TransactionError).SafeInvoke(report); } public override void StatusReport(OrderStatusReport report) { _client.OrderStatus.WithDump(_receiver).WithError(TransactionError).SafeInvoke(report); } public override void SingleOrderReplay(SingleOrderReplayInfo info) { _client.OrderReplay.WithDump(_receiver).WithError(TransactionError).SafeInvoke(info); } public override void TradeRoute(TradeRouteInfo info) { } public override void TradeRouteList(TradeRouteListInfo info) { } public override void TradeCorrectReport(OrderTradeCorrectReport report) { } public override void TriggerPulledReport(OrderTriggerPulledReport report) { } public override void TriggerReport(OrderTriggerReport report) { } #endregion #region market data public override void BestAskQuote(AskInfo info) { _client.BestAskQuote.WithDump(_receiver).WithError(MarketDataError).SafeInvoke(info); } public override void BestBidAskQuote(BidInfo oBid, AskInfo oAsk) { } public override void BestBidQuote(BidInfo info) { _client.BestBidQuote.WithDump(_receiver).WithError(MarketDataError).SafeInvoke(info); } public override void AskQuote(AskInfo info) { _client.AskQuote.WithDump(_receiver).WithError(MarketDataError).SafeInvoke(info); } public override void BidQuote(BidInfo info) { _client.BidQuote.WithDump(_receiver).WithError(MarketDataError).SafeInvoke(info); } public override void EndQuote(EndQuoteInfo info) { _client.EndQuote.WithDump(_receiver).WithError(MarketDataError).SafeInvoke(info); } public override void OpenPrice(OpenPriceInfo info) { _receiver.AddLog(LogLevels.Debug, info.DumpableToString); _client.Level1.SafeInvoke(info.Symbol, info.Exchange, Level1Fields.OpenPrice, (decimal)info.Price, RithmicUtils.ToTime(info.Ssboe, info.Usecs)); } public override void HighPrice(HighPriceInfo info) { _receiver.AddLog(LogLevels.Debug, info.DumpableToString); _client.Level1.SafeInvoke(info.Symbol, info.Exchange, Level1Fields.HighPrice, (decimal)info.Price, RithmicUtils.ToTime(info.Ssboe, info.Usecs)); } public override void LowPrice(LowPriceInfo info) { _receiver.AddLog(LogLevels.Debug, info.DumpableToString); _client.Level1.SafeInvoke(info.Symbol, info.Exchange, Level1Fields.LowPrice, (decimal)info.Price, RithmicUtils.ToTime(info.Ssboe, info.Usecs)); } public override void ClosePrice(ClosePriceInfo info) { _receiver.AddLog(LogLevels.Debug, info.DumpableToString); _client.Level1.SafeInvoke(info.Symbol, info.Exchange, Level1Fields.ClosePrice, (decimal)info.Price, RithmicUtils.ToTime(info.Ssboe, info.Usecs)); } public override void OpenInterest(OpenInterestInfo info) { if (!info.QuantityFlag) return; _client.Level1.SafeInvoke(info.Symbol, info.Exchange, Level1Fields.OpenInterest, info.Quantity, RithmicUtils.ToTime(info.Ssboe, info.Usecs)); } public override void LimitOrderBook(OrderBookInfo info) { _client.OrderBook.WithDump(_receiver).WithError(MarketDataError).SafeInvoke(info); } public override void SettlementPrice(SettlementPriceInfo info) { _client.SettlementPrice.WithDump(_receiver).WithError(MarketDataError).SafeInvoke(info); } public override void TradeCondition(TradeInfo info) { _client.TradeCondition.WithDump(_receiver).WithError(MarketDataError).SafeInvoke(info); } public override void TradePrint(TradeInfo info) { _client.TradePrint.WithDump(_receiver).WithError(MarketDataError).SafeInvoke(info); } public override void TradeVolume(TradeVolumeInfo info) { _client.TradeVolume.WithDump(_receiver).WithError(MarketDataError).SafeInvoke(info); } public override void TradeReplay(TradeReplayInfo info) { _client.TradeReplay.WithDump(_receiver).WithError(MarketDataError).SafeInvoke(info); } public override void TimeBar(TimeBarInfo info) { _client.TimeBar.WithDump(_receiver).WithError(MarketDataError).SafeInvoke(info); } public override void TimeBarReplay(TimeBarReplayInfo info) { _client.TimeBarReplay.WithDump(_receiver).WithError(MarketDataError).SafeInvoke(info); } #endregion #region portfolio info public override void AccountList(AccountListInfo info) { _client.Accounts.WithDump(_receiver).WithError(TransactionError).SafeInvoke(info); } public override void PnlUpdate(PnlInfo info) { _client.AccountPnLUpdate.WithDump(_receiver).WithError(TransactionError).SafeInvoke(info); } public override void PnlReplay(PnlReplayInfo info) { _client.AccountPnL.WithDump(_receiver).WithError(TransactionError).SafeInvoke(info); } public override void ProductRmsList(ProductRmsListInfo info) { _client.AccountRms.WithDump(_receiver).WithError(TransactionError).SafeInvoke(info); } public override void SodUpdate(SodReport report) { _client.AccountSodUpdate.WithDump(_receiver).WithError(TransactionError).SafeInvoke(report); } #endregion #region security info public override void BinaryContractList(BinaryContractListInfo info) { _client.SecurityBinaryContracts.WithDump(_receiver).WithError(MarketDataError).SafeInvoke(info); } public override void OptionList(OptionListInfo info) { _client.SecurityOptions.WithDump(_receiver).WithError(MarketDataError).SafeInvoke(info); } public override void InstrumentByUnderlying(InstrumentByUnderlyingInfo info) { _client.SecurityInstrumentByUnderlying.WithDump(_receiver).WithError(MarketDataError).SafeInvoke(info); } public override void PriceIncrUpdate(PriceIncrInfo info) { } public override void RefData(RefDataInfo info) { _client.SecurityRefData.WithDump(_receiver).WithError(MarketDataError).SafeInvoke(info); } public override void MarketMode(MarketModeInfo info) { } public override void ExchangeList(ExchangeListInfo info) { _client.Exchanges.WithDump(_receiver).WithError(MarketDataError).SafeInvoke(info); } #endregion #region other public override void ClosingIndicator(ClosingIndicatorInfo info) { } public override void OpeningIndicator(OpeningIndicatorInfo info) { } public override void EquityOptionStrategyList(EquityOptionStrategyListInfo info) { } public override void Strategy(StrategyInfo info) { } public override void StrategyList(StrategyListInfo info) { } #endregion } } }
using System; namespace SDL2Idiomatic { namespace Input { public enum Key { Unknown = 0, Return = '\r', Escape = 27, // '\033' Backspace = '\b', Tab = '\t', Space = ' ', Exclamation = '!', DoubleQuote = '"', Hash = '#', Percent = '%', DollarSign = '$', Ampersand = '&', SingleQuote = '\'', LeftParenthesis = '(', RightParenthesis = ')', Asterisk = '*', Plus = '+', Comma = ',', Minus = '-', Period = '.', Slash = '/', Digit0 = '0', Digit1 = '1', Digit2 = '2', Digit3 = '3', Digit4 = '4', Digit5 = '5', Digit6 = '6', Digit7 = '7', Digit8 = '8', Digit9 = '9', Colon = ':', Semicolon = ';', LessThan = '<', Equals = '=', GreaterThan = '>', Question = '?', At = '@', LeftBracket = '[', Backslash = '\\', RightBracket = ']', Caret = '^', Underscore = '_', Backtick = '`', A = 'a', B = 'b', C = 'c', D = 'd', E = 'e', F = 'f', G = 'g', H = 'h', I = 'i', J = 'j', K = 'k', L = 'l', M = 'm', N = 'n', O = 'o', P = 'p', Q = 'q', R = 'r', S = 's', T = 't', U = 'u', V = 'v', W = 'w', X = 'x', Y = 'y', Z = 'z', CapsLock = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_CAPSLOCK | SDL2.SDL.SDLK_SCANCODE_MASK, F1 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_F1 | SDL2.SDL.SDLK_SCANCODE_MASK, F2 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_F2 | SDL2.SDL.SDLK_SCANCODE_MASK, F3 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_F3 | SDL2.SDL.SDLK_SCANCODE_MASK, F4 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_F4 | SDL2.SDL.SDLK_SCANCODE_MASK, F5 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_F5 | SDL2.SDL.SDLK_SCANCODE_MASK, F6 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_F6 | SDL2.SDL.SDLK_SCANCODE_MASK, F7 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_F7 | SDL2.SDL.SDLK_SCANCODE_MASK, F8 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_F8 | SDL2.SDL.SDLK_SCANCODE_MASK, F9 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_F9 | SDL2.SDL.SDLK_SCANCODE_MASK, F10 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_F10 | SDL2.SDL.SDLK_SCANCODE_MASK, F11 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_F11 | SDL2.SDL.SDLK_SCANCODE_MASK, F12 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_F12 | SDL2.SDL.SDLK_SCANCODE_MASK, PrintScreen = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_PRINTSCREEN | SDL2.SDL.SDLK_SCANCODE_MASK, ScrollLock = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_SCROLLLOCK | SDL2.SDL.SDLK_SCANCODE_MASK, Pause = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_PAUSE | SDL2.SDL.SDLK_SCANCODE_MASK, Insert = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_INSERT | SDL2.SDL.SDLK_SCANCODE_MASK, Home = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_HOME | SDL2.SDL.SDLK_SCANCODE_MASK, PageUp = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_PAGEUP | SDL2.SDL.SDLK_SCANCODE_MASK, Delete = 177, End = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_END | SDL2.SDL.SDLK_SCANCODE_MASK, PageDown = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_PAGEDOWN | SDL2.SDL.SDLK_SCANCODE_MASK, Right = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_RIGHT | SDL2.SDL.SDLK_SCANCODE_MASK, Left = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_LEFT | SDL2.SDL.SDLK_SCANCODE_MASK, Down = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_DOWN | SDL2.SDL.SDLK_SCANCODE_MASK, Up = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_UP | SDL2.SDL.SDLK_SCANCODE_MASK, NumLockClear = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_NUMLOCKCLEAR | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadDivide = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_DIVIDE | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadMultiply = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_MULTIPLY | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadMinus = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_MINUS | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadPlus = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_PLUS | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadEnter = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_ENTER | SDL2.SDL.SDLK_SCANCODE_MASK, Keypad1 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_1 | SDL2.SDL.SDLK_SCANCODE_MASK, Keypad2 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_2 | SDL2.SDL.SDLK_SCANCODE_MASK, Keypad3 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_3 | SDL2.SDL.SDLK_SCANCODE_MASK, Keypad4 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_4 | SDL2.SDL.SDLK_SCANCODE_MASK, Keypad5 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_5 | SDL2.SDL.SDLK_SCANCODE_MASK, Keypad6 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_6 | SDL2.SDL.SDLK_SCANCODE_MASK, Keypad7 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_7 | SDL2.SDL.SDLK_SCANCODE_MASK, Keypad8 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_8 | SDL2.SDL.SDLK_SCANCODE_MASK, Keypad9 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_9 | SDL2.SDL.SDLK_SCANCODE_MASK, Keypad0 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_0 | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadPeriod = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_PERIOD | SDL2.SDL.SDLK_SCANCODE_MASK, Application = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_APPLICATION | SDL2.SDL.SDLK_SCANCODE_MASK, Power = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_POWER | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadEquals = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_EQUALS | SDL2.SDL.SDLK_SCANCODE_MASK, F13 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_F13 | SDL2.SDL.SDLK_SCANCODE_MASK, F14 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_F14 | SDL2.SDL.SDLK_SCANCODE_MASK, F15 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_F15 | SDL2.SDL.SDLK_SCANCODE_MASK, F16 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_F16 | SDL2.SDL.SDLK_SCANCODE_MASK, F17 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_F17 | SDL2.SDL.SDLK_SCANCODE_MASK, F18 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_F18 | SDL2.SDL.SDLK_SCANCODE_MASK, F19 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_F19 | SDL2.SDL.SDLK_SCANCODE_MASK, F20 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_F20 | SDL2.SDL.SDLK_SCANCODE_MASK, F21 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_F21 | SDL2.SDL.SDLK_SCANCODE_MASK, F22 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_F22 | SDL2.SDL.SDLK_SCANCODE_MASK, F23 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_F23 | SDL2.SDL.SDLK_SCANCODE_MASK, F24 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_F24 | SDL2.SDL.SDLK_SCANCODE_MASK, Execute = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_EXECUTE | SDL2.SDL.SDLK_SCANCODE_MASK, Help = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_HELP | SDL2.SDL.SDLK_SCANCODE_MASK, Menu = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_MENU | SDL2.SDL.SDLK_SCANCODE_MASK, Select = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_SELECT | SDL2.SDL.SDLK_SCANCODE_MASK, Stop = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_STOP | SDL2.SDL.SDLK_SCANCODE_MASK, Again = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_AGAIN | SDL2.SDL.SDLK_SCANCODE_MASK, Undo = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_UNDO | SDL2.SDL.SDLK_SCANCODE_MASK, Cut = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_CUT | SDL2.SDL.SDLK_SCANCODE_MASK, Copy = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_COPY | SDL2.SDL.SDLK_SCANCODE_MASK, Paste = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_PASTE | SDL2.SDL.SDLK_SCANCODE_MASK, Find = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_FIND | SDL2.SDL.SDLK_SCANCODE_MASK, Mute = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_MUTE | SDL2.SDL.SDLK_SCANCODE_MASK, VolumeUp = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_VOLUMEUP | SDL2.SDL.SDLK_SCANCODE_MASK, VolumeDown = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_VOLUMEDOWN | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadComma = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_COMMA | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadEqualsAS400 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_EQUALSAS400 | SDL2.SDL.SDLK_SCANCODE_MASK, AltErase = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_ALTERASE | SDL2.SDL.SDLK_SCANCODE_MASK, SysReq = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_SYSREQ | SDL2.SDL.SDLK_SCANCODE_MASK, Cancel = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_CANCEL | SDL2.SDL.SDLK_SCANCODE_MASK, Clear = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_CLEAR | SDL2.SDL.SDLK_SCANCODE_MASK, Prior = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_PRIOR | SDL2.SDL.SDLK_SCANCODE_MASK, Return2 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_RETURN2 | SDL2.SDL.SDLK_SCANCODE_MASK, Separator = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_SEPARATOR | SDL2.SDL.SDLK_SCANCODE_MASK, Out = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_OUT | SDL2.SDL.SDLK_SCANCODE_MASK, Oper = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_OPER | SDL2.SDL.SDLK_SCANCODE_MASK, ClearAgain = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_CLEARAGAIN | SDL2.SDL.SDLK_SCANCODE_MASK, CrSel = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_CRSEL | SDL2.SDL.SDLK_SCANCODE_MASK, ExSel = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_EXSEL | SDL2.SDL.SDLK_SCANCODE_MASK, Keypad00 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_00 | SDL2.SDL.SDLK_SCANCODE_MASK, Keypad000 = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_000 | SDL2.SDL.SDLK_SCANCODE_MASK, ThousandsSeparator = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_THOUSANDSSEPARATOR | SDL2.SDL.SDLK_SCANCODE_MASK, DecimalSeparator = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_DECIMALSEPARATOR | SDL2.SDL.SDLK_SCANCODE_MASK, CurrencyUnit = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_CURRENCYUNIT | SDL2.SDL.SDLK_SCANCODE_MASK, CurrencySubunit = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_CURRENCYSUBUNIT | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadLeftParenthesis = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_LEFTPAREN | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadRightParenthesis = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_RIGHTPAREN | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadLeftBrace = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_LEFTBRACE | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadRightBrace = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_RIGHTBRACE | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadTab = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_TAB | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadBackspace = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_BACKSPACE | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadA = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_A | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadB = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_B | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadC = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_C | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadD = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_D | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadE = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_E | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadF = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_F | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadXOR = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_XOR | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadPower = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_POWER | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadPercent = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_PERCENT | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadLess = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_LESS | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadGreater = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_GREATER | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadAmpersand = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_AMPERSAND | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadDoubleAmpersand = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_DBLAMPERSAND | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadVerticalBar = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_VERTICALBAR | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadDoubleVerticalBar = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_DBLVERTICALBAR | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadColon = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_COLON | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadHash = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_HASH | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadSpace = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_SPACE | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadAt = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_AT | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadExclamation = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_EXCLAM | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadMemStore = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_MEMSTORE | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadMemRecall = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_MEMRECALL | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadMemClear = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_MEMCLEAR | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadMemAdd = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_MEMADD | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadMemSubtract = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_MEMSUBTRACT | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadMemMultiply = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_MEMMULTIPLY | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadMemDivide = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_MEMDIVIDE | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadPlusMinus = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_PLUSMINUS | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadClear = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_CLEAR | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadClearEntry = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_CLEARENTRY | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadBinary = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_BINARY | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadOctal = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_OCTAL | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadDecimal = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_DECIMAL | SDL2.SDL.SDLK_SCANCODE_MASK, KeypadHex = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KP_HEXADECIMAL | SDL2.SDL.SDLK_SCANCODE_MASK, LeftCtrl = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_LCTRL | SDL2.SDL.SDLK_SCANCODE_MASK, LeftShift = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_LSHIFT | SDL2.SDL.SDLK_SCANCODE_MASK, LeftAlt = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_LALT | SDL2.SDL.SDLK_SCANCODE_MASK, LeftGUI = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_LGUI | SDL2.SDL.SDLK_SCANCODE_MASK, RightCtrl = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_RCTRL | SDL2.SDL.SDLK_SCANCODE_MASK, RightShift = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_RSHIFT | SDL2.SDL.SDLK_SCANCODE_MASK, RightAlt = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_RALT | SDL2.SDL.SDLK_SCANCODE_MASK, RightGUI = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_RGUI | SDL2.SDL.SDLK_SCANCODE_MASK, Mode = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_MODE | SDL2.SDL.SDLK_SCANCODE_MASK, AudioNext = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_AUDIONEXT | SDL2.SDL.SDLK_SCANCODE_MASK, AudioPrevious = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_AUDIOPREV | SDL2.SDL.SDLK_SCANCODE_MASK, AudioStop = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_AUDIOSTOP | SDL2.SDL.SDLK_SCANCODE_MASK, AudioPlay = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_AUDIOPLAY | SDL2.SDL.SDLK_SCANCODE_MASK, AudioMute = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_AUDIOMUTE | SDL2.SDL.SDLK_SCANCODE_MASK, MediaSelect = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_MEDIASELECT | SDL2.SDL.SDLK_SCANCODE_MASK, WWW = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_WWW | SDL2.SDL.SDLK_SCANCODE_MASK, Mail = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_MAIL | SDL2.SDL.SDLK_SCANCODE_MASK, Calculator = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_CALCULATOR | SDL2.SDL.SDLK_SCANCODE_MASK, Computer = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_COMPUTER | SDL2.SDL.SDLK_SCANCODE_MASK, AppControlSearch = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_AC_SEARCH | SDL2.SDL.SDLK_SCANCODE_MASK, AppControlHome = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_AC_HOME | SDL2.SDL.SDLK_SCANCODE_MASK, AppControlBack = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_AC_BACK | SDL2.SDL.SDLK_SCANCODE_MASK, AppControlForward = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_AC_FORWARD | SDL2.SDL.SDLK_SCANCODE_MASK, AppControlStop = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_AC_STOP | SDL2.SDL.SDLK_SCANCODE_MASK, AppControlRefresh = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_AC_REFRESH | SDL2.SDL.SDLK_SCANCODE_MASK, AppControlBookmarks = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_AC_BOOKMARKS | SDL2.SDL.SDLK_SCANCODE_MASK, BrightnessDown = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_BRIGHTNESSDOWN | SDL2.SDL.SDLK_SCANCODE_MASK, BrightnessUp = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_BRIGHTNESSUP | SDL2.SDL.SDLK_SCANCODE_MASK, DisplaySwitch = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_DISPLAYSWITCH | SDL2.SDL.SDLK_SCANCODE_MASK, KeyboardIlluminationToggle = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KBDILLUMTOGGLE | SDL2.SDL.SDLK_SCANCODE_MASK, KeyboardIlluminationDown = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KBDILLUMDOWN | SDL2.SDL.SDLK_SCANCODE_MASK, KeyboardIlluminationUp = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_KBDILLUMUP | SDL2.SDL.SDLK_SCANCODE_MASK, Eject = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_EJECT | SDL2.SDL.SDLK_SCANCODE_MASK, Sleep = (int)SDL2.SDL.SDL_Scancode.SDL_SCANCODE_SLEEP | SDL2.SDL.SDLK_SCANCODE_MASK } } }
using System; using System.Data; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using System.Text; using Epi.Analysis; using Epi.Windows.Dialogs; using Epi.Windows.Analysis; namespace Epi.Windows.Analysis.Dialogs { /// <summary> /// Dialog for Means command /// </summary> public partial class ComplexSampleMeansDialog : CommandDesignDialog { private string SetClauses = null; #region Constructors /// <summary> /// Default constructor - NOT TO BE USED FOR INSTANTIATION /// </summary> [Obsolete("Use of default constructor not allowed", true)] public ComplexSampleMeansDialog() { InitializeComponent(); Construct(); } /// <summary> /// Constructor for the Means dialog /// </summary> /// <param name="frm"></param> public ComplexSampleMeansDialog(Epi.Windows.Analysis.Forms.AnalysisMainForm frm) : base(frm) { InitializeComponent(); Construct(); } private void Construct() { if (!this.DesignMode) // designer throws an error { this.btnOK.Click += new System.EventHandler(this.btnOK_Click); this.btnSaveOnly.Click += new System.EventHandler(this.btnSaveOnly_Click); } //IProjectHost host = Module.GetService(typeof(IProjectHost)) as IProjectHost; //if (host == null) //{ // throw new GeneralException("No project is hosted by service provider."); //} //// get project reference //Project project = host.CurrentProject; //if (project == null) //{ // //A native DB has been read, no longer need to show error message // //throw new GeneralException("You must first open a project."); // //MessageBox.Show("You must first open a project."); // //this.Close(); //} } #endregion Constructors #region Private Properties private string txtMeansOf = string.Empty; private string txtCrossTab = string.Empty; private string txtWeight = string.Empty; private string txtPSU = string.Empty; private string txtStratifyBy = string.Empty; #endregion Private Properties #region Private methods #endregion #region Public Methods /// <summary> /// Sets enabled property of OK and Save Only /// </summary> public override void CheckForInputSufficiency() { bool inputValid = ValidateInput(); btnOK.Enabled = inputValid; btnSaveOnly.Enabled = inputValid; } #endregion Public Methods #region Event Handlers /// <summary> /// Handles the btnClear Click event /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void btnClear_Click(object sender, System.EventArgs e) { cmbMeansOf.Items.Clear(); cmbMeansOf.Text = string.Empty; cmbStratifyBy.Items.Clear(); cmbCrossTab.Items.Clear(); cmbCrossTab.Text = string.Empty; cmbWeight.Items.Clear(); cmbWeight.Text = string.Empty; cmbPSU.Text = string.Empty; txtOutput.Text = string.Empty; //lbxStratifyBy.Items.Clear(); ComplexSampleMeansDialog_Load(this, null); } /// <summary> /// Handles the cmbStratifyBy SelectedIndexChanged event /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cmbStratifyBy_SelectedIndexChanged(object sender, EventArgs e) { if (cmbStratifyBy.Text != StringLiterals.SPACE) { //Get the old variable chosen that was saved to the txt string. string strOld = txtStratifyBy; string strNew = cmbStratifyBy.Text; //make sure it isn't "" or the same as the new variable picked. if ((strOld.Length > 0) && (strOld != strNew)) { cmbMeansOf.Items.Add(strOld); cmbCrossTab.Items.Add(strOld); //cmbStratifyBy.Items.Add(strOld); cmbWeight.Items.Add(strOld); cmbPSU.Items.Add(strOld); } if (cmbStratifyBy.SelectedIndex >= 0) //lbxStratifyBy.Items.Add(s); cmbMeansOf.Items.Remove(strNew); cmbCrossTab.Items.Remove(strNew); //cmbStratifyBy.Items.Remove(strNew); cmbWeight.Items.Remove(strNew); cmbPSU.Items.Remove(strNew); this.txtStratifyBy = strNew; } } /// <summary> /// Handles the Attach Event for the form, fills all of the dialogs with a list of variables. /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void ComplexSampleMeansDialog_Load(object sender, EventArgs e) { VariableType scopeWord = VariableType.DataSource | VariableType.DataSourceRedefined | VariableType.Standard; FillVariableCombo(cmbMeansOf, scopeWord); cmbMeansOf.SelectedIndex = -1; FillVariableCombo(cmbCrossTab, scopeWord); cmbCrossTab.SelectedIndex = -1; FillVariableCombo(cmbStratifyBy, scopeWord); cmbStratifyBy.SelectedIndex = -1; FillVariableCombo(cmbWeight, scopeWord,DataType.Boolean | DataType.YesNo | DataType.Number ); cmbWeight.SelectedIndex = -1; FillVariableCombo(cmbPSU, scopeWord); cmbStratifyBy.SelectedIndex = -1; } /// <summary> /// Handles the Selected Index Change event for lbxStratifyBy. /// Moves the variable name back to the comboboxes /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void lbxStratifyBy_SelectedIndexChanged(object sender, EventArgs e) { if (lbxStratifyBy.SelectedIndex >= 0) // prevent the remove below from re-entering { string s = this.lbxStratifyBy.SelectedItem.ToString(); cmbMeansOf.Items.Add(s); cmbCrossTab.Items.Add(s); cmbStratifyBy.Items.Add(s); cmbWeight.Items.Add(s); cmbPSU.Items.Add(s); lbxStratifyBy.Items.Remove(s); } } /// <summary> /// Handles the KeyDown event for cmbWeight. /// Allows to delete the optional value for Weight. /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cmbWeight_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Delete) { //SelectedIndexChanged will add the var back to the other DDLs cmbWeight.Text = ""; cmbWeight.SelectedIndex = -1; } } /// <summary> /// Handles the Click event for btnSettings. /// Instantiates a new Settings dialog, sets its dialog mode = True. /// Shows the dialog and returns any settings. /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void btnSettings_Click(object sender, EventArgs e) { SetDialog SD = new SetDialog((Epi.Windows.Analysis.Forms.AnalysisMainForm)mainForm); SD.isDialogMode = true; SD.ShowDialog(); SetClauses = SD.CommandText; SD.Close(); } /// <summary> /// Handles the cmbMeansOf SelectedIndexChanged event /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cmbMeansOf_SelectedIndexChanged(object sender, EventArgs e) { if (cmbMeansOf.SelectedIndex >= 0) { string s = txtMeansOf; if ((s.Length > 0) && (s != cmbMeansOf.Text)) { //cmbMeansOf.Items.Add(s); cmbCrossTab.Items.Add(s); cmbStratifyBy.Items.Add(s); cmbWeight.Items.Add(s); cmbPSU.Items.Add(s); } s = this.cmbMeansOf.SelectedItem.ToString(); //cmbMeansOf.Items.Remove(s); cmbCrossTab.Items.Remove(s); cmbStratifyBy.Items.Remove(s); cmbWeight.Items.Remove(s); cmbPSU.Items.Remove(s); this.txtMeansOf = s; } CheckForInputSufficiency(); } /// <summary> /// Handles the Click event for cmbMeansOf. /// Saves the content of the text to the temp storage or resets. /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cmbMeansOf_Click(object sender, EventArgs e) { txtMeansOf = (cmbMeansOf.SelectedIndex >= 0) ? cmbMeansOf.Text : String.Empty; } /// <summary> /// Handles the cmbCrossTab SelectedIndexChanged event /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cmbCrossTab_SelectedIndexChanged(object sender, EventArgs e) { //Get the old variable chosen that was saved to the txt string. string strOld = txtCrossTab; string strNew = cmbCrossTab.Text; //make sure it isn't "" or the same as the new variable picked. if ((strOld.Length > 0) && (strOld != strNew)) { cmbMeansOf.Items.Add(strOld); //cmbCrossTab.Items.Add(strOld); cmbStratifyBy.Items.Add(strOld); cmbWeight.Items.Add(strOld); cmbPSU.Items.Add(strOld); } if (cmbCrossTab.SelectedIndex>=0) { cmbMeansOf.Items.Remove(strNew); //cmbCrossTab.Items.Remove(strNew); cmbStratifyBy.Items.Remove(strNew); cmbWeight.Items.Remove(strNew); cmbPSU.Items.Remove(strNew); this.txtCrossTab = strNew; } } /// <summary> /// Handles the Click event for cmbCrossTab. /// Saves the content of the text to the temp storage or resets. /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cmbCrossTab_Click(object sender, EventArgs e) { txtCrossTab = (cmbCrossTab.SelectedIndex >= 0) ? cmbCrossTab.Text : String.Empty; } /// <summary> /// Handles the KeyDown event for cmbCrossTab. /// Allows to delete the optional value for CrossTab. /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cmbCrossTab_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Delete) { //SelectedIndexChanged will add the var back to the other DDLs cmbCrossTab.Text = ""; cmbCrossTab.SelectedIndex = -1; } } /// <summary> /// Handles the cmbWeight SelectedIndexChanged event /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cmbWeight_SelectedIndexChanged(object sender, EventArgs e) { //Get the old variable chosen that was saved to the txt string. string strOld = txtWeight; string strNew = cmbWeight.Text; //make sure it isn't "" or the same as the new variable picked. if ((strOld.Length > 0) && (strOld != strNew)) { cmbMeansOf.Items.Add(strOld); cmbCrossTab.Items.Add(strOld); cmbStratifyBy.Items.Add(strOld); //cmbWeight.Items.Add(strOld); cmbPSU.Items.Add(strOld); } if (cmbWeight.SelectedIndex >= 0) { cmbMeansOf.Items.Remove(strNew); cmbCrossTab.Items.Remove(strNew); cmbStratifyBy.Items.Remove(strNew); //cmbWeight.Items.Remove(strNew); cmbPSU.Items.Remove(strNew); this.txtWeight = strNew; } } /// <summary> /// Handles the Click event for cmbWeight. /// Saves the content of the text to the temp storage or resets. /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cmbWeight_Click(object sender, EventArgs e) { txtWeight = (cmbWeight.SelectedIndex >= 0) ? cmbWeight.Text : String.Empty; } /// <summary> /// Handles the cmbPSU SelectedIndexChanged event /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cmbPSU_SelectedIndexChanged(object sender, EventArgs e) { if (cmbPSU.SelectedIndex >= 0) { string s = txtPSU; if ((s.Length > 0) && (s != cmbPSU.Text)) { cmbMeansOf.Items.Add(s); cmbCrossTab.Items.Add(s); cmbStratifyBy.Items.Add(s); cmbWeight.Items.Add(s); //cmbPSU.Items.Add(s); } s = this.cmbPSU.SelectedItem.ToString(); cmbMeansOf.Items.Remove(s); cmbCrossTab.Items.Remove(s); cmbStratifyBy.Items.Remove(s); cmbWeight.Items.Remove(s); //cmbPSU.Items.Remove(s); this.txtPSU = s; } CheckForInputSufficiency(); } /// <summary> /// Handles the Click event for cmbPSU. /// Saves the content of the text to the temp storage or resets. /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cmbPSU_Click(object sender, EventArgs e) { txtPSU = (cmbPSU.SelectedIndex >= 0) ? cmbPSU.Text : String.Empty; } /// <summary> /// Handles the KeyPress event for txtNumCol. /// Allows only digits, delete, and backspace strokes; Limits to two digits length. /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void txtNumCol_KeyPress(object sender, KeyPressEventArgs e) { string keyInput = e.KeyChar.ToString(); if (e.KeyChar.ToString().Equals("\b")) { // Backspace key is OK } else if (e.KeyChar.Equals(Keys.Delete)) { // Delete key is OK } else if (e.KeyChar.ToString().Equals("0")) { if (txtNumCol.TextLength == 0) e.Handled = true; } else if ((txtNumCol.TextLength <= 1) && (Char.IsDigit(e.KeyChar))) { // Digits are OK } else { e.Handled = true; } } /// <summary> /// Handles the Leave event for Number of Columns textbox. /// <remarks>Clears the textbox if only a 0 exists.</remarks> /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void txtNumCol_Leave(object sender, EventArgs e) { if (txtNumCol.Text.Equals("0")) txtNumCol.Text = ""; } /// <summary> /// Opens a process to show the related help topic /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> protected override void btnHelp_Click(object sender, System.EventArgs e) { System.Diagnostics.Process.Start("http://www.cdc.gov/epiinfo/user-guide/command-reference/analysis-commands-means.html"); } #endregion //Event Handlers #region Protected Methods /// <summary> /// Generates the command text /// </summary> protected override void GenerateCommand() { StringBuilder command = new StringBuilder (); command.Append(CommandNames.MEANS); command.Append(StringLiterals.SPACE); command.Append(cmbMeansOf.Text); if (cmbCrossTab.SelectedIndex >= 0) { command.Append(StringLiterals.SPACE); command.Append(cmbCrossTab.Text); } // if (lbxStratifyBy.Items.Count > 0) if (cmbStratifyBy.SelectedIndex >= 0) { command.Append(StringLiterals.SPACE); command.Append(CommandNames.STRATAVAR); command.Append(StringLiterals.EQUAL); command.Append(cmbStratifyBy.Text); /* foreach (string item in lbxStratifyBy.Items) { command.Append(item); command.Append(StringLiterals.SPACE); } */ } if (cmbWeight.SelectedIndex >= 0) { command.Append(StringLiterals.SPACE); command.Append(CommandNames.WEIGHTVAR); command.Append( StringLiterals.EQUAL ); command.Append( cmbWeight.Text ); } if (!string.IsNullOrEmpty(txtOutput.Text)) { command.Append(StringLiterals.SPACE); command.Append(CommandNames.OUTTABLE); command.Append(StringLiterals.EQUAL); command.Append(txtOutput.Text); } if (!string.IsNullOrEmpty(this.SetClauses)) { command.Append(StringLiterals.SPACE); command.Append(this.SetClauses); } command.Append(StringLiterals.SPACE); command.Append(CommandNames.PSUVAR); command.Append(StringLiterals.EQUAL); command.Append(cmbPSU.Text); if (txtNumCol.TextLength > 0) { command.Append(StringLiterals.SPACE); command.Append(CommandNames.COLUMNSIZE); command.Append(StringLiterals.EQUAL); command.Append(txtNumCol.Text); } if (cbxNoLineWrap.Checked) { command.Append(StringLiterals.SPACE); command.Append(CommandNames.NOWRAP); } CommandText = command.ToString(); } /// <summary> /// Validates user input /// </summary> /// <returns>True/False depending upon whether error messages were found</returns> protected override bool ValidateInput() { base.ValidateInput(); if (this.cmbMeansOf.SelectedIndex == -1 ) { ErrorMessages.Add(SharedStrings.SELECT_VARIABLE); } if (this.cmbPSU.SelectedIndex == -1) { ErrorMessages.Add(SharedStrings.MUST_SELECT_PSU); } //if (!string.IsNullOrEmpty(txtOutput.Text.Trim())) //{ // currentProject.CollectedData.TableExists(txtOutput.Text.Trim()); // ErrorMessages.Add(SharedStrings.TABLE_EXISTS_OUTPUT); //} return (ErrorMessages.Count == 0); } #endregion //Protected Methods } }
#region File Description //----------------------------------------------------------------------------- // Game.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; #endregion namespace Audio3D { /// <summary> /// Sample showing how to implement 3D audio. /// </summary> public class Audio3DGame : Microsoft.Xna.Framework.Game { #region Fields GraphicsDeviceManager graphics; AudioManager audioManager; SpriteEntity cat; SpriteEntity dog; Texture2D checkerTexture; QuadDrawer quadDrawer; Vector3 cameraPosition = new Vector3(0, 512, 0); Vector3 cameraForward = Vector3.Forward; Vector3 cameraUp = Vector3.Up; Vector3 cameraVelocity = Vector3.Zero; KeyboardState currentKeyboardState; GamePadState currentGamePadState; #endregion #region Initialization public Audio3DGame() { Content.RootDirectory = "Content"; graphics = new GraphicsDeviceManager(this); audioManager = new AudioManager(this); Components.Add(audioManager); cat = new Cat(); dog = new Dog(); } /// <summary> /// Load your graphics content. /// </summary> protected override void LoadContent() { cat.Texture = Content.Load<Texture2D>("CatTexture"); dog.Texture = Content.Load<Texture2D>("DogTexture"); checkerTexture = Content.Load<Texture2D>("checker"); quadDrawer = new QuadDrawer(graphics.GraphicsDevice); } #endregion #region Update and Draw /// <summary> /// Allows the game to run logic. /// </summary> protected override void Update(GameTime gameTime) { HandleInput(); UpdateCamera(); // Tell the AudioManager about the new camera position. audioManager.Listener.Position = cameraPosition; audioManager.Listener.Forward = cameraForward; audioManager.Listener.Up = cameraUp; audioManager.Listener.Velocity = cameraVelocity; // Tell our game entities to move around and play sounds. cat.Update(gameTime, audioManager); dog.Update(gameTime, audioManager); base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> protected override void Draw(GameTime gameTime) { GraphicsDevice device = graphics.GraphicsDevice; device.Clear(Color.CornflowerBlue); device.BlendState = BlendState.AlphaBlend; // Compute camera matrices. Matrix view = Matrix.CreateLookAt(cameraPosition, cameraPosition + cameraForward, cameraUp); Matrix projection = Matrix.CreatePerspectiveFieldOfView(1, device.Viewport.AspectRatio, 1, 100000); // Draw the checkered ground polygon. Matrix groundTransform = Matrix.CreateScale(20000) * Matrix.CreateRotationX(MathHelper.PiOver2); quadDrawer.DrawQuad(checkerTexture, 32, groundTransform, view, projection); // Draw the game entities. cat.Draw(quadDrawer, cameraPosition, view, projection); dog.Draw(quadDrawer, cameraPosition, view, projection); base.Draw(gameTime); } #endregion #region Handle Input /// <summary> /// Handles input for quitting the game. /// </summary> void HandleInput() { currentKeyboardState = Keyboard.GetState(); currentGamePadState = GamePad.GetState(PlayerIndex.One); // Check for exit. if (currentKeyboardState.IsKeyDown(Keys.Escape) || currentGamePadState.Buttons.Back == ButtonState.Pressed) { Exit(); } } /// <summary> /// Handles input for moving the camera. /// </summary> void UpdateCamera() { const float turnSpeed = 0.05f; const float accelerationSpeed = 4; const float frictionAmount = 0.98f; // Turn left or right. float turn = -currentGamePadState.ThumbSticks.Left.X * turnSpeed; if (currentKeyboardState.IsKeyDown(Keys.Left)) turn += turnSpeed; if (currentKeyboardState.IsKeyDown(Keys.Right)) turn -= turnSpeed; cameraForward = Vector3.TransformNormal(cameraForward, Matrix.CreateRotationY(turn)); // Accelerate forward or backward. float accel = currentGamePadState.ThumbSticks.Left.Y * accelerationSpeed; if (currentKeyboardState.IsKeyDown(Keys.Up)) accel += accelerationSpeed; if (currentKeyboardState.IsKeyDown(Keys.Down)) accel -= accelerationSpeed; cameraVelocity += cameraForward * accel; // Add velocity to the current position. cameraPosition += cameraVelocity; // Apply the friction force. cameraVelocity *= frictionAmount; } #endregion } #region Entry Point /// <summary> /// The main entry point for the application. /// </summary> static class Program { static void Main() { using (Audio3DGame game = new Audio3DGame()) { game.Run(); } } } #endregion }
using System; using System.Threading; using System.Net.Sockets; using System.Net; using System.IO; namespace PubNubMessaging.Core { #region "Network Status -- code split required" internal abstract class ClientNetworkStatus { private static bool _status = true; private static bool _failClientNetworkForTesting = false; private static bool _machineSuspendMode = false; private static IJsonPluggableLibrary _jsonPluggableLibrary; internal static IJsonPluggableLibrary JsonPluggableLibrary { get { return _jsonPluggableLibrary; } set { _jsonPluggableLibrary = value; } } #if (SILVERLIGHT || WINDOWS_PHONE) private static ManualResetEvent mres = new ManualResetEvent(false); private static ManualResetEvent mreSocketAsync = new ManualResetEvent(false); #elif(!UNITY_IOS && !UNITY_ANDROID) private static ManualResetEventSlim mres = new ManualResetEventSlim (false); #endif internal static bool SimulateNetworkFailForTesting { get { return _failClientNetworkForTesting; } set { _failClientNetworkForTesting = value; } } internal static bool MachineSuspendMode { get { return _machineSuspendMode; } set { _machineSuspendMode = value; } } /*#if(__MonoCS__ && !UNITY_IOS && !UNITY_ANDROID) static UdpClient udp; #endif*/ #if(UNITY_IOS || UNITY_ANDROID || __MonoCS__) static HttpWebRequest request; static WebResponse response; internal static int HeartbeatInterval { get; set; } internal static bool CheckInternetStatusUnity<T> (bool systemActive, Action<PubnubClientError> errorCallback, string[] channels, string[] channelGroups, int heartBeatInterval) { HeartbeatInterval = heartBeatInterval; if (_failClientNetworkForTesting) { //Only to simulate network fail return false; } else { CheckClientNetworkAvailability<T> (CallbackClientNetworkStatus, errorCallback, channels, channelGroups); return _status; } } #endif internal static bool CheckInternetStatus<T> (bool systemActive, Action<PubnubClientError> errorCallback, string[] channels, string[] channelGroups) { if (_failClientNetworkForTesting || _machineSuspendMode) { //Only to simulate network fail return false; } else { CheckClientNetworkAvailability<T> (CallbackClientNetworkStatus, errorCallback, channels, channelGroups); return _status; } } //#endif public static bool GetInternetStatus () { return _status; } private static void CallbackClientNetworkStatus (bool status) { _status = status; } private static void CheckClientNetworkAvailability<T> (Action<bool> callback, Action<PubnubClientError> errorCallback, string[] channels, string[] channelGroups) { InternetState<T> state = new InternetState<T> (); state.Callback = callback; state.ErrorCallback = errorCallback; state.Channels = channels; state.ChannelGroups = channelGroups; #if (UNITY_ANDROID || UNITY_IOS) CheckSocketConnect<T>(state); #elif(__MonoCS__) CheckSocketConnect<T> (state); #else ThreadPool.QueueUserWorkItem(CheckSocketConnect<T>, state); #endif #if (SILVERLIGHT || WINDOWS_PHONE) mres.WaitOne(); #elif(!UNITY_ANDROID && !UNITY_IOS) mres.Wait (); #endif } private static void CheckSocketConnect<T> (object internetState) { InternetState<T> state = internetState as InternetState<T>; Action<bool> callback = state.Callback; Action<PubnubClientError> errorCallback = state.ErrorCallback; string[] channels = state.Channels; string[] channelGroups = state.ChannelGroups; try { #if (SILVERLIGHT || WINDOWS_PHONE) using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { SocketAsyncEventArgs sae = new SocketAsyncEventArgs(); sae.UserToken = state; sae.RemoteEndPoint = new DnsEndPoint("pubsub.pubnub.com", 80); sae.Completed += new EventHandler<SocketAsyncEventArgs>(socketAsync_Completed<T>); bool test = socket.ConnectAsync(sae); mreSocketAsync.WaitOne(1000); sae.Completed -= new EventHandler<SocketAsyncEventArgs>(socketAsync_Completed<T>); socket.Close(); } #elif (UNITY_IOS || UNITY_ANDROID) if(request!=null){ request.Abort(); request = null; } request = (HttpWebRequest)WebRequest.Create("http://pubsub.pubnub.com"); if(request!= null){ request.Timeout = HeartbeatInterval * 1000; request.ContentType = "application/json"; if(response!=null){ response.Close(); response = null; } response = request.GetResponse (); if(response != null){ if(((HttpWebResponse)response).ContentLength <= 0){ _status = false; throw new Exception("Failed to connect"); } else { using(Stream dataStream = response.GetResponseStream ()){ using(StreamReader reader = new StreamReader (dataStream)){ string responseFromServer = reader.ReadToEnd (); LoggingMethod.WriteToLog(string.Format("DateTime {0}, Response:{1}", DateTime.Now.ToString(), responseFromServer), LoggingMethod.LevelInfo); _status = true; callback(true); reader.Close(); } dataStream.Close(); } } } } #elif(__MonoCS__) using (UdpClient udp = new UdpClient ("pubsub.pubnub.com", 80)) { IPAddress localAddress = ((IPEndPoint)udp.Client.LocalEndPoint).Address; if (udp != null && udp.Client != null && udp.Client.RemoteEndPoint != null) { udp.Client.SendTimeout = HeartbeatInterval * 1000; EndPoint remotepoint = udp.Client.RemoteEndPoint; string remoteAddress = (remotepoint != null) ? remotepoint.ToString () : ""; LoggingMethod.WriteToLog (string.Format ("DateTime {0} checkInternetStatus LocalIP: {1}, RemoteEndPoint:{2}", DateTime.Now.ToString (), localAddress.ToString (), remoteAddress), LoggingMethod.LevelVerbose); _status = true; callback (true); } } #else using (UdpClient udp = new UdpClient("pubsub.pubnub.com", 80)) { IPAddress localAddress = ((IPEndPoint)udp.Client.LocalEndPoint).Address; EndPoint remotepoint = udp.Client.RemoteEndPoint; string remoteAddress = (remotepoint != null) ? remotepoint.ToString() : ""; udp.Close(); LoggingMethod.WriteToLog(string.Format("DateTime {0} checkInternetStatus LocalIP: {1}, RemoteEndPoint:{2}", DateTime.Now.ToString(), localAddress.ToString(), remoteAddress), LoggingMethod.LevelVerbose); callback(true); } #endif } #if (UNITY_IOS || UNITY_ANDROID) catch (WebException webEx){ if(webEx.Message.Contains("404")){ _status =true; callback(true); } else { _status =false; ParseCheckSocketConnectException<T>(webEx, channels, channelGroups, errorCallback, callback); } } #endif catch (Exception ex) { #if(__MonoCS__) _status = false; #endif ParseCheckSocketConnectException<T> (ex, channels, channelGroups, errorCallback, callback); } finally { #if (UNITY_IOS || UNITY_ANDROID) if(response!=null){ response.Close(); response = null; } if(request!=null){ request = null; } #elif(__MonoCS__) #endif #if(UNITY_IOS) GC.Collect(); #endif } #if (!UNITY_ANDROID && !UNITY_IOS) mres.Set (); #endif } static void ParseCheckSocketConnectException<T> (Exception ex, string[] channels, string[] channelGroups, Action<PubnubClientError> errorCallback, Action<bool> callback) { PubnubErrorCode errorType = PubnubErrorCodeHelper.GetErrorType (ex); int statusCode = (int)errorType; string errorDescription = PubnubErrorCodeDescription.GetStatusCodeDescription (errorType); string channel = (channels == null) ? "" : string.Join (",", channels); string channelGroup = (channelGroups == null) ? "" : string.Join (",", channelGroups); PubnubClientError error = new PubnubClientError(statusCode, PubnubErrorSeverity.Warn, true, ex.ToString (), ex, PubnubMessageSource.Client, null, null, errorDescription, channel, channelGroup); GoToCallback (error, errorCallback); LoggingMethod.WriteToLog (string.Format ("DateTime {0} checkInternetStatus Error. {1}", DateTime.Now.ToString (), ex.ToString ()), LoggingMethod.LevelError); callback (false); } private static void GoToCallback<T> (object result, Action<T> Callback) { if (Callback != null) { if (typeof(T) == typeof(string)) { JsonResponseToCallback (result, Callback); } else { Callback ((T)(object)result); } } } private static void GoToCallback<T> (PubnubClientError result, Action<PubnubClientError> Callback) { if (Callback != null) { //TODO: //Include custom message related to error/status code for developer //error.AdditionalMessage = MyCustomErrorMessageRetrieverBasedOnStatusCode(error.StatusCode); Callback (result); } } private static void JsonResponseToCallback<T> (object result, Action<T> callback) { string callbackJson = ""; if (typeof(T) == typeof(string)) { callbackJson = _jsonPluggableLibrary.SerializeToJsonString (result); Action<string> castCallback = callback as Action<string>; castCallback (callbackJson); } } #if (SILVERLIGHT || WINDOWS_PHONE) static void socketAsync_Completed<T>(object sender, SocketAsyncEventArgs e) { if (e.LastOperation == SocketAsyncOperation.Connect) { Socket skt = sender as Socket; InternetState<T> state = e.UserToken as InternetState<T>; if (state != null) { LoggingMethod.WriteToLog(string.Format("DateTime {0} socketAsync_Completed.", DateTime.Now.ToString()), LoggingMethod.LevelInfo); state.Callback(true); } mreSocketAsync.Set(); } } #endif } #endregion }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.IO; using System.Threading; using ManagedBass; using ManagedBass.Fx; using osu.Framework.IO; using System.Diagnostics; using System.Threading.Tasks; using osu.Framework.Audio.Callbacks; namespace osu.Framework.Audio.Track { public sealed class TrackBass : Track, IBassAudio { public const int BYTES_PER_SAMPLE = 4; private AsyncBufferStream dataStream; /// <summary> /// Should this track only be used for preview purposes? This suggests it has not yet been fully loaded. /// </summary> public bool Preview { get; private set; } /// <summary> /// The handle for this track, if there is one. /// </summary> private int activeStream; /// <summary> /// The handle for adjusting tempo. /// </summary> private int tempoAdjustStream; /// <summary> /// This marks if the track is paused, or stopped to the end. /// </summary> private bool isPlayed; private long byteLength; /// <summary> /// The last position that a seek will succeed for. /// </summary> private double lastSeekablePosition; private FileCallbacks fileCallbacks; private SyncCallback stopCallback; private SyncCallback endCallback; private volatile bool isLoaded; public override bool IsLoaded => isLoaded; /// <summary> /// Constructs a new <see cref="TrackBass"/> from provided audio data. /// </summary> /// <param name="data">The sample data stream.</param> /// <param name="quick">If true, the track will not be fully loaded, and should only be used for preview purposes. Defaults to false.</param> public TrackBass(Stream data, bool quick = false) { if (data == null) throw new ArgumentNullException(nameof(data)); // todo: support this internally to match the underlying Track implementation (which can support this). const float tempo_minimum_supported = 0.05f; AggregateTempo.ValueChanged += t => { if (t.NewValue < tempo_minimum_supported) throw new ArgumentException($"{nameof(TrackBass)} does not support {nameof(Tempo)} specifications below {tempo_minimum_supported}. Use {nameof(Frequency)} instead."); }; EnqueueAction(() => { Preview = quick; //encapsulate incoming stream with async buffer if it isn't already. dataStream = data as AsyncBufferStream ?? new AsyncBufferStream(data, quick ? 8 : -1); fileCallbacks = new FileCallbacks(new DataStreamFileProcedures(dataStream)); BassFlags flags = Preview ? 0 : BassFlags.Decode | BassFlags.Prescan; activeStream = Bass.CreateStream(StreamSystem.NoBuffer, flags, fileCallbacks.Callbacks, fileCallbacks.Handle); if (!Preview) { // We assign the BassFlags.Decode streams to the device "bass_nodevice" to prevent them from getting // cleaned up during a Bass.Free call. This is necessary for seamless switching between audio devices. // Further, we provide the flag BassFlags.FxFreeSource such that freeing the activeStream also frees // all parent decoding streams. const int bass_nodevice = 0x20000; Bass.ChannelSetDevice(activeStream, bass_nodevice); tempoAdjustStream = BassFx.TempoCreate(activeStream, BassFlags.Decode | BassFlags.FxFreeSource); Bass.ChannelSetDevice(tempoAdjustStream, bass_nodevice); activeStream = BassFx.ReverseCreate(tempoAdjustStream, 5f, BassFlags.Default | BassFlags.FxFreeSource); Bass.ChannelSetAttribute(activeStream, ChannelAttribute.TempoUseQuickAlgorithm, 1); Bass.ChannelSetAttribute(activeStream, ChannelAttribute.TempoOverlapMilliseconds, 4); Bass.ChannelSetAttribute(activeStream, ChannelAttribute.TempoSequenceMilliseconds, 30); } // will be -1 in case of an error double seconds = Bass.ChannelBytes2Seconds(activeStream, byteLength = Bass.ChannelGetLength(activeStream)); bool success = seconds >= 0; if (success) { Length = seconds * 1000; // Bass does not allow seeking to the end of the track, so the last available position is 1 sample before. lastSeekablePosition = Bass.ChannelBytes2Seconds(activeStream, byteLength - BYTES_PER_SAMPLE) * 1000; Bass.ChannelGetAttribute(activeStream, ChannelAttribute.Frequency, out float frequency); initialFrequency = frequency; bitrate = (int)Bass.ChannelGetAttribute(activeStream, ChannelAttribute.Bitrate); stopCallback = new SyncCallback((a, b, c, d) => RaiseFailed()); endCallback = new SyncCallback((a, b, c, d) => { if (!Looping) RaiseCompleted(); }); Bass.ChannelSetSync(activeStream, SyncFlags.Stop, 0, stopCallback.Callback, stopCallback.Handle); Bass.ChannelSetSync(activeStream, SyncFlags.End, 0, endCallback.Callback, endCallback.Handle); isLoaded = true; } }); InvalidateState(); } /// <summary> /// Returns whether the playback state is considered to be running or not. /// This will only return true for <see cref="PlaybackState.Playing"/> and <see cref="PlaybackState.Stalled"/>. /// </summary> private static bool isRunningState(PlaybackState state) => state == PlaybackState.Playing || state == PlaybackState.Stalled; void IBassAudio.UpdateDevice(int deviceIndex) { Bass.ChannelSetDevice(activeStream, deviceIndex); Trace.Assert(Bass.LastError == Errors.OK); // Bass may leave us in an invalid state after the output device changes (this is true for "No sound" device) // if the observed state was playing before change, we should force things into a good state. if (isPlayed) { // While on windows, changing to "No sound" changes the playback state correctly, // on macOS it is left in a playing-but-stalled state. Forcefully stopping first fixes this. stopInternal(); startInternal(); } } protected override void UpdateState() { var running = isRunningState(Bass.ChannelIsActive(activeStream)); var bytePosition = Bass.ChannelGetPosition(activeStream); // because device validity check isn't done frequently, when switching to "No sound" device, // there will be a brief time where this track will be stopped, before we resume it manually (see comments in UpdateDevice(int).) // this makes us appear to be playing, even if we may not be. isRunning = running || (isPlayed && bytePosition != byteLength); Interlocked.Exchange(ref currentTime, Bass.ChannelBytes2Seconds(activeStream, bytePosition) * 1000); var leftChannel = isPlayed ? Bass.ChannelGetLevelLeft(activeStream) / 32768f : -1; var rightChannel = isPlayed ? Bass.ChannelGetLevelRight(activeStream) / 32768f : -1; if (leftChannel >= 0 && rightChannel >= 0) { currentAmplitudes.LeftChannel = leftChannel; currentAmplitudes.RightChannel = rightChannel; float[] tempFrequencyData = new float[256]; Bass.ChannelGetData(activeStream, tempFrequencyData, (int)DataFlags.FFT512); currentAmplitudes.FrequencyAmplitudes = tempFrequencyData; } else { currentAmplitudes.LeftChannel = 0; currentAmplitudes.RightChannel = 0; currentAmplitudes.FrequencyAmplitudes = new float[256]; } base.UpdateState(); } protected override void Dispose(bool disposing) { if (activeStream != 0) { isRunning = false; Bass.ChannelStop(activeStream); Bass.StreamFree(activeStream); } activeStream = 0; dataStream?.Dispose(); dataStream = null; fileCallbacks?.Dispose(); fileCallbacks = null; stopCallback?.Dispose(); stopCallback = null; endCallback?.Dispose(); endCallback = null; base.Dispose(disposing); } public override bool IsDummyDevice => false; public override void Stop() { base.Stop(); StopAsync().Wait(); } public Task StopAsync() => EnqueueAction(() => { stopInternal(); isPlayed = false; }); private bool stopInternal() => isRunningState(Bass.ChannelIsActive(activeStream)) && Bass.ChannelPause(activeStream); private int direction; private void setDirection(bool reverse) { direction = reverse ? -1 : 1; Bass.ChannelSetAttribute(activeStream, ChannelAttribute.ReverseDirection, direction); } public override void Start() { base.Start(); StartAsync().Wait(); } public Task StartAsync() => EnqueueAction(() => { if (startInternal()) isPlayed = true; }); private bool startInternal() { // Bass will restart the track if it has reached its end. This behavior isn't desirable so block locally. if (Bass.ChannelGetPosition(activeStream) == byteLength) return false; return Bass.ChannelPlay(activeStream); } public override bool Seek(double seek) => SeekAsync(seek).Result; public async Task<bool> SeekAsync(double seek) { // At this point the track may not yet be loaded which is indicated by a 0 length. // In that case we still want to return true, hence the conservative length. double conservativeLength = Length == 0 ? double.MaxValue : lastSeekablePosition; double conservativeClamped = Math.Clamp(seek, 0, conservativeLength); await EnqueueAction(() => { double clamped = Math.Clamp(seek, 0, Length); long pos = Bass.ChannelSeconds2Bytes(activeStream, clamped / 1000d); if (pos != Bass.ChannelGetPosition(activeStream)) Bass.ChannelSetPosition(activeStream, pos); }); return conservativeClamped == seek; } private double currentTime; public override double CurrentTime => currentTime; private volatile bool isRunning; public override bool IsRunning => isRunning; internal override void OnStateChanged() { base.OnStateChanged(); setDirection(AggregateFrequency.Value < 0); Bass.ChannelSetAttribute(activeStream, ChannelAttribute.Volume, AggregateVolume.Value); Bass.ChannelSetAttribute(activeStream, ChannelAttribute.Pan, AggregateBalance.Value); Bass.ChannelSetAttribute(activeStream, ChannelAttribute.Frequency, bassFreq); Bass.ChannelSetAttribute(tempoAdjustStream, ChannelAttribute.Tempo, (Math.Abs(AggregateTempo.Value) - 1) * 100); } private volatile float initialFrequency; private int bassFreq => (int)Math.Clamp(Math.Abs(initialFrequency * AggregateFrequency.Value), 100, 100000); private volatile int bitrate; public override int? Bitrate => bitrate; private TrackAmplitudes currentAmplitudes; public override TrackAmplitudes CurrentAmplitudes => currentAmplitudes; } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ #if !CLR2 using System.Globalization; using System.Linq; using System.Linq.Expressions; #endif using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using AstUtils = System.Management.Automation.Interpreter.Utils; using System.Runtime.CompilerServices; namespace System.Management.Automation.Interpreter { internal sealed class ExceptionHandler { public readonly Type ExceptionType; public readonly int StartIndex; public readonly int EndIndex; public readonly int LabelIndex; public readonly int HandlerStartIndex; public readonly int HandlerEndIndex; internal TryCatchFinallyHandler Parent = null; public bool IsFault { get { return ExceptionType == null; } } internal ExceptionHandler(int start, int end, int labelIndex, int handlerStartIndex, int handlerEndIndex, Type exceptionType) { StartIndex = start; EndIndex = end; LabelIndex = labelIndex; ExceptionType = exceptionType; HandlerStartIndex = handlerStartIndex; HandlerEndIndex = handlerEndIndex; } internal void SetParent(TryCatchFinallyHandler tryHandler) { Debug.Assert(Parent == null); Parent = tryHandler; } public bool Matches(Type exceptionType) { if (ExceptionType == null || ExceptionType.IsAssignableFrom(exceptionType)) { return true; } return false; } public bool IsBetterThan(ExceptionHandler other) { if (other == null) return true; Debug.Assert(StartIndex == other.StartIndex && EndIndex == other.EndIndex, "we only need to compare handlers for the same try block"); return HandlerStartIndex < other.HandlerStartIndex; } internal bool IsInsideTryBlock(int index) { return index >= StartIndex && index < EndIndex; } internal bool IsInsideCatchBlock(int index) { return index >= HandlerStartIndex && index < HandlerEndIndex; } internal bool IsInsideFinallyBlock(int index) { Debug.Assert(Parent != null); return Parent.IsFinallyBlockExist && index >= Parent.FinallyStartIndex && index < Parent.FinallyEndIndex; } public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "{0} [{1}-{2}] [{3}->{4}]", (IsFault ? "fault" : "catch(" + ExceptionType.Name + ")"), StartIndex, EndIndex, HandlerStartIndex, HandlerEndIndex ); } } internal sealed class TryCatchFinallyHandler { internal readonly int TryStartIndex = Instruction.UnknownInstrIndex; internal readonly int TryEndIndex = Instruction.UnknownInstrIndex; internal readonly int FinallyStartIndex = Instruction.UnknownInstrIndex; internal readonly int FinallyEndIndex = Instruction.UnknownInstrIndex; internal readonly int GotoEndTargetIndex = Instruction.UnknownInstrIndex; private readonly ExceptionHandler[] _handlers; internal bool IsFinallyBlockExist { get { return (FinallyStartIndex != Instruction.UnknownInstrIndex && FinallyEndIndex != Instruction.UnknownInstrIndex); } } internal bool IsCatchBlockExist { get { return (_handlers != null); } } /// <summary> /// No finally block. /// </summary> internal TryCatchFinallyHandler(int tryStart, int tryEnd, int gotoEndTargetIndex, ExceptionHandler[] handlers) : this(tryStart, tryEnd, gotoEndTargetIndex, Instruction.UnknownInstrIndex, Instruction.UnknownInstrIndex, handlers) { Debug.Assert(handlers != null, "catch blocks should exist"); } /// <summary> /// No catch blocks. /// </summary> internal TryCatchFinallyHandler(int tryStart, int tryEnd, int gotoEndTargetIndex, int finallyStart, int finallyEnd) : this(tryStart, tryEnd, gotoEndTargetIndex, finallyStart, finallyEnd, null) { Debug.Assert(finallyStart != Instruction.UnknownInstrIndex && finallyEnd != Instruction.UnknownInstrIndex, "finally block should exist"); } /// <summary> /// Generic constructor. /// </summary> internal TryCatchFinallyHandler(int tryStart, int tryEnd, int gotoEndLabelIndex, int finallyStart, int finallyEnd, ExceptionHandler[] handlers) { TryStartIndex = tryStart; TryEndIndex = tryEnd; FinallyStartIndex = finallyStart; FinallyEndIndex = finallyEnd; GotoEndTargetIndex = gotoEndLabelIndex; _handlers = handlers; if (_handlers != null) { for (int index = 0; index < _handlers.Length; index++) { var handler = _handlers[index]; handler.SetParent(this); } } } /// <summary> /// Goto the index of the first instruction of the suitable catch block. /// </summary> internal int GotoHandler(InterpretedFrame frame, object exception, out ExceptionHandler handler) { Debug.Assert(_handlers != null, "we should have at least one handler if the method gets called"); handler = Array.Find(_handlers, t => t.Matches(exception.GetType())); if (handler == null) { return 0; } return frame.Goto(handler.LabelIndex, exception, gotoExceptionHandler: true); } } /// <summary> /// The re-throw instruction will throw this exception. /// </summary> internal sealed class RethrowException : SystemException { } [Serializable] internal class DebugInfo { // TODO: readonly public int StartLine, EndLine; public int Index; public string FileName; public bool IsClear; private static readonly DebugInfoComparer s_debugComparer = new DebugInfoComparer(); private sealed class DebugInfoComparer : IComparer<DebugInfo> { // We allow comparison between int and DebugInfo here int IComparer<DebugInfo>.Compare(DebugInfo d1, DebugInfo d2) { if (d1.Index > d2.Index) return 1; else if (d1.Index == d2.Index) return 0; else return -1; } } public static DebugInfo GetMatchingDebugInfo(DebugInfo[] debugInfos, int index) { // Create a faked DebugInfo to do the search DebugInfo d = new DebugInfo { Index = index }; // to find the closest debug info before the current index int i = Array.BinarySearch<DebugInfo>(debugInfos, d, s_debugComparer); if (i < 0) { // ~i is the index for the first bigger element // if there is no bigger element, ~i is the length of the array i = ~i; if (i == 0) { return null; } // return the last one that is smaller i -= 1; } return debugInfos[i]; } public override string ToString() { if (IsClear) { return string.Format(CultureInfo.InvariantCulture, "{0}: clear", Index); } else { return string.Format(CultureInfo.InvariantCulture, "{0}: [{1}-{2}] '{3}'", Index, StartLine, EndLine, FileName); } } } // TODO: [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")] [Serializable] internal readonly struct InterpretedFrameInfo { public readonly string MethodName; // TODO: [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public readonly DebugInfo DebugInfo; public InterpretedFrameInfo(string methodName, DebugInfo info) { MethodName = methodName; DebugInfo = info; } public override string ToString() { return MethodName + (DebugInfo != null ? ": " + DebugInfo : null); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] internal sealed class LightCompiler { internal const int DefaultCompilationThreshold = 32; // zero: sync compilation private readonly int _compilationThreshold; private readonly InstructionList _instructions; private readonly LocalVariables _locals = new LocalVariables(); private readonly List<DebugInfo> _debugInfos = new List<DebugInfo>(); private readonly HybridReferenceDictionary<LabelTarget, LabelInfo> _treeLabels = new HybridReferenceDictionary<LabelTarget, LabelInfo>(); private LabelScopeInfo _labelBlock = new LabelScopeInfo(null, LabelScopeKind.Lambda); private readonly Stack<ParameterExpression> _exceptionForRethrowStack = new Stack<ParameterExpression>(); // Set to true to force compilation of this lambda. // This disables the interpreter for this lambda. We still need to // walk it, however, to resolve variables closed over from the parent // lambdas (because they may be interpreted). private bool _forceCompile; private readonly LightCompiler _parent; private static readonly LocalDefinition[] s_emptyLocals = Array.Empty<LocalDefinition>(); public LightCompiler(int compilationThreshold) { _instructions = new InstructionList(); _compilationThreshold = compilationThreshold < 0 ? DefaultCompilationThreshold : compilationThreshold; } private LightCompiler(LightCompiler parent) : this(parent._compilationThreshold) { _parent = parent; } public InstructionList Instructions { get { return _instructions; } } public LocalVariables Locals { get { return _locals; } } internal static Expression Unbox(Expression strongBoxExpression) { return Expression.Field(strongBoxExpression, typeof(StrongBox<object>).GetField("Value")); } public LightDelegateCreator CompileTop(LambdaExpression node) { for (int index = 0; index < node.Parameters.Count; index++) { var p = node.Parameters[index]; var local = _locals.DefineLocal(p, 0); _instructions.EmitInitializeParameter(local.Index); } Compile(node.Body); // pop the result of the last expression: if (node.Body.Type != typeof(void) && node.ReturnType == typeof(void)) { _instructions.EmitPop(); } Debug.Assert(_instructions.CurrentStackDepth == (node.ReturnType != typeof(void) ? 1 : 0)); return new LightDelegateCreator(MakeInterpreter(node.Name), node); } // internal LightDelegateCreator CompileTop(LightLambdaExpression node) { // foreach (var p in node.Parameters) { // var local = _locals.DefineLocal(p, 0); // _instructions.EmitInitializeParameter(local.Index); // } // // Compile(node.Body); // // // pop the result of the last expression: // if (node.Body.Type != typeof(void) && node.ReturnType == typeof(void)) { // _instructions.EmitPop(); // } // // Debug.Assert(_instructions.CurrentStackDepth == (node.ReturnType != typeof(void) ? 1 : 0)); // // return new LightDelegateCreator(MakeInterpreter(node.Name), node); // } private Interpreter MakeInterpreter(string lambdaName) { if (_forceCompile) { return null; } var debugInfos = _debugInfos.ToArray(); return new Interpreter(lambdaName, _locals, GetBranchMapping(), _instructions.ToArray(), debugInfos, _compilationThreshold); } private void CompileConstantExpression(Expression expr) { var node = (ConstantExpression)expr; _instructions.EmitLoad(node.Value, node.Type); } private void CompileDefaultExpression(Expression expr) { CompileDefaultExpression(expr.Type); } private void CompileDefaultExpression(Type type) { if (type != typeof(void)) { if (type.IsValueType) { object value = ScriptingRuntimeHelpers.GetPrimitiveDefaultValue(type); if (value != null) { _instructions.EmitLoad(value); } else { _instructions.EmitDefaultValue(type); } } else { _instructions.EmitLoad(null); } } } private LocalVariable EnsureAvailableForClosure(ParameterExpression expr) { LocalVariable local; if (_locals.TryGetLocalOrClosure(expr, out local)) { if (!local.InClosure && !local.IsBoxed) { _locals.Box(expr, _instructions); } return local; } else if (_parent != null) { _parent.EnsureAvailableForClosure(expr); return _locals.AddClosureVariable(expr); } else { throw new InvalidOperationException("unbound variable: " + expr); } } // private void EnsureVariable(ParameterExpression variable) { // if (!_locals.ContainsVariable(variable)) { // EnsureAvailableForClosure(variable); // } // } private LocalVariable ResolveLocal(ParameterExpression variable) { LocalVariable local; if (!_locals.TryGetLocalOrClosure(variable, out local)) { local = EnsureAvailableForClosure(variable); } return local; } public void CompileGetVariable(ParameterExpression variable) { LocalVariable local = ResolveLocal(variable); if (local.InClosure) { _instructions.EmitLoadLocalFromClosure(local.Index); } else if (local.IsBoxed) { _instructions.EmitLoadLocalBoxed(local.Index); } else { _instructions.EmitLoadLocal(local.Index); } _instructions.SetDebugCookie(variable.Name); } public void CompileGetBoxedVariable(ParameterExpression variable) { LocalVariable local = ResolveLocal(variable); if (local.InClosure) { _instructions.EmitLoadLocalFromClosureBoxed(local.Index); } else { Debug.Assert(local.IsBoxed); _instructions.EmitLoadLocal(local.Index); } _instructions.SetDebugCookie(variable.Name); } public void CompileSetVariable(ParameterExpression variable, bool isVoid) { LocalVariable local = ResolveLocal(variable); if (local.InClosure) { if (isVoid) { _instructions.EmitStoreLocalToClosure(local.Index); } else { _instructions.EmitAssignLocalToClosure(local.Index); } } else if (local.IsBoxed) { if (isVoid) { _instructions.EmitStoreLocalBoxed(local.Index); } else { _instructions.EmitAssignLocalBoxed(local.Index); } } else { if (isVoid) { _instructions.EmitStoreLocal(local.Index); } else { _instructions.EmitAssignLocal(local.Index); } } _instructions.SetDebugCookie(variable.Name); } public void CompileParameterExpression(Expression expr) { var node = (ParameterExpression)expr; CompileGetVariable(node); } private void CompileBlockExpression(Expression expr, bool asVoid) { var node = (BlockExpression)expr; var end = CompileBlockStart(node); var lastExpression = node.Expressions[node.Expressions.Count - 1]; Compile(lastExpression, asVoid); CompileBlockEnd(end); } private LocalDefinition[] CompileBlockStart(BlockExpression node) { var start = _instructions.Count; LocalDefinition[] locals; var variables = node.Variables; if (variables.Count != 0) { // TODO: basic flow analysis so we don't have to initialize all // variables. locals = new LocalDefinition[variables.Count]; int localCnt = 0; for (int index = 0; index < variables.Count; index++) { var variable = variables[index]; var local = _locals.DefineLocal(variable, start); locals[localCnt++] = local; _instructions.EmitInitializeLocal(local.Index, variable.Type); _instructions.SetDebugCookie(variable.Name); } } else { locals = s_emptyLocals; } for (int i = 0; i < node.Expressions.Count - 1; i++) { CompileAsVoid(node.Expressions[i]); } return locals; } private void CompileBlockEnd(LocalDefinition[] locals) { for (int index = 0; index < locals.Length; index++) { var local = locals[index]; _locals.UndefineLocal(local, _instructions.Count); } } private void CompileIndexExpression(Expression expr) { var index = (IndexExpression)expr; // instance: if (index.Object != null) { Compile(index.Object); } // indexes, byref args not allowed. for (int i = 0; i < index.Arguments.Count; i++) { var arg = index.Arguments[i]; Compile(arg); } if (index.Indexer != null) { _instructions.EmitCall(index.Indexer.GetMethod); } else if (index.Arguments.Count != 1) { _instructions.EmitCall(index.Object.Type.GetMethod("Get", BindingFlags.Public | BindingFlags.Instance)); } else { _instructions.EmitGetArrayItem(index.Object.Type); } } private void CompileIndexAssignment(BinaryExpression node, bool asVoid) { var index = (IndexExpression)node.Left; if (!asVoid) { throw new NotImplementedException(); } // instance: if (index.Object != null) { Compile(index.Object); } // indexes, byref args not allowed. for (int i = 0; i < index.Arguments.Count; i++) { var arg = index.Arguments[i]; Compile(arg); } // value: Compile(node.Right); if (index.Indexer != null) { _instructions.EmitCall(index.Indexer.SetMethod); } else if (index.Arguments.Count != 1) { _instructions.EmitCall(index.Object.Type.GetMethod("Set", BindingFlags.Public | BindingFlags.Instance)); } else { _instructions.EmitSetArrayItem(index.Object.Type); } } private void CompileMemberAssignment(BinaryExpression node, bool asVoid) { var member = (MemberExpression)node.Left; PropertyInfo pi = member.Member as PropertyInfo; if (pi != null) { var method = pi.SetMethod; if (member.Expression != null) { Compile(member.Expression); } Compile(node.Right); int start = _instructions.Count; if (!asVoid) { LocalDefinition local = _locals.DefineLocal(Expression.Parameter(node.Right.Type), start); _instructions.EmitAssignLocal(local.Index); _instructions.EmitCall(method); _instructions.EmitLoadLocal(local.Index); _locals.UndefineLocal(local, _instructions.Count); } else { _instructions.EmitCall(method); } return; } FieldInfo fi = member.Member as FieldInfo; if (fi != null) { if (member.Expression != null) { Compile(member.Expression); } Compile(node.Right); int start = _instructions.Count; if (!asVoid) { LocalDefinition local = _locals.DefineLocal(Expression.Parameter(node.Right.Type), start); _instructions.EmitAssignLocal(local.Index); _instructions.EmitStoreField(fi); _instructions.EmitLoadLocal(local.Index); _locals.UndefineLocal(local, _instructions.Count); } else { _instructions.EmitStoreField(fi); } return; } throw new NotImplementedException(); } private void CompileVariableAssignment(BinaryExpression node, bool asVoid) { this.Compile(node.Right); var target = (ParameterExpression)node.Left; CompileSetVariable(target, asVoid); } private void CompileAssignBinaryExpression(Expression expr, bool asVoid) { var node = (BinaryExpression)expr; switch (node.Left.NodeType) { case ExpressionType.Index: CompileIndexAssignment(node, asVoid); break; case ExpressionType.MemberAccess: CompileMemberAssignment(node, asVoid); break; case ExpressionType.Parameter: case ExpressionType.Extension: CompileVariableAssignment(node, asVoid); break; default: throw new InvalidOperationException("Invalid lvalue for assignment: " + node.Left.NodeType); } } private void CompileBinaryExpression(Expression expr) { var node = (BinaryExpression)expr; if (node.Method != null) { Compile(node.Left); Compile(node.Right); _instructions.EmitCall(node.Method); } else { switch (node.NodeType) { case ExpressionType.ArrayIndex: Debug.Assert(node.Right.Type == typeof(int)); Compile(node.Left); Compile(node.Right); _instructions.EmitGetArrayItem(node.Left.Type); return; case ExpressionType.Add: case ExpressionType.AddChecked: case ExpressionType.Subtract: case ExpressionType.SubtractChecked: case ExpressionType.Multiply: case ExpressionType.MultiplyChecked: case ExpressionType.Divide: CompileArithmetic(node.NodeType, node.Left, node.Right); return; case ExpressionType.Equal: CompileEqual(node.Left, node.Right); return; case ExpressionType.NotEqual: CompileNotEqual(node.Left, node.Right); return; case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: CompileComparison(node.NodeType, node.Left, node.Right); return; default: throw new NotImplementedException(node.NodeType.ToString()); } } } private void CompileEqual(Expression left, Expression right) { Debug.Assert(left.Type == right.Type || !left.Type.IsValueType && !right.Type.IsValueType); Compile(left); Compile(right); _instructions.EmitEqual(left.Type); } private void CompileNotEqual(Expression left, Expression right) { Debug.Assert(left.Type == right.Type || !left.Type.IsValueType && !right.Type.IsValueType); Compile(left); Compile(right); _instructions.EmitNotEqual(left.Type); } private void CompileComparison(ExpressionType nodeType, Expression left, Expression right) { Debug.Assert(left.Type == right.Type && TypeUtils.IsNumeric(left.Type)); // TODO: // if (TypeUtils.IsNullableType(left.Type) && liftToNull) ... Compile(left); Compile(right); switch (nodeType) { case ExpressionType.LessThan: _instructions.EmitLessThan(left.Type); break; case ExpressionType.LessThanOrEqual: _instructions.EmitLessThanOrEqual(left.Type); break; case ExpressionType.GreaterThan: _instructions.EmitGreaterThan(left.Type); break; case ExpressionType.GreaterThanOrEqual: _instructions.EmitGreaterThanOrEqual(left.Type); break; default: throw Assert.Unreachable; } } private void CompileArithmetic(ExpressionType nodeType, Expression left, Expression right) { Debug.Assert(left.Type == right.Type && TypeUtils.IsArithmetic(left.Type)); Compile(left); Compile(right); switch (nodeType) { case ExpressionType.Add: _instructions.EmitAdd(left.Type, false); break; case ExpressionType.AddChecked: _instructions.EmitAdd(left.Type, true); break; case ExpressionType.Subtract: _instructions.EmitSub(left.Type, false); break; case ExpressionType.SubtractChecked: _instructions.EmitSub(left.Type, true); break; case ExpressionType.Multiply: _instructions.EmitMul(left.Type, false); break; case ExpressionType.MultiplyChecked: _instructions.EmitMul(left.Type, true); break; case ExpressionType.Divide: _instructions.EmitDiv(left.Type); break; default: throw Assert.Unreachable; } } private void CompileConvertUnaryExpression(Expression expr) { var node = (UnaryExpression)expr; if (node.Method != null) { Compile(node.Operand); // We should be able to ignore Int32ToObject if (node.Method != ScriptingRuntimeHelpers.Int32ToObjectMethod) { _instructions.EmitCall(node.Method); } } else if (node.Type == typeof(void)) { CompileAsVoid(node.Operand); } else { Compile(node.Operand); CompileConvertToType(node.Operand.Type, node.Type, node.NodeType == ExpressionType.ConvertChecked); } } private void CompileConvertToType(Type typeFrom, Type typeTo, bool isChecked) { Debug.Assert(typeFrom != typeof(void) && typeTo != typeof(void)); if (typeTo == typeFrom) { return; } TypeCode from = typeFrom.GetTypeCode(); TypeCode to = typeTo.GetTypeCode(); if (TypeUtils.IsNumeric(from) && TypeUtils.IsNumeric(to)) { if (isChecked) { _instructions.EmitNumericConvertChecked(from, to); } else { _instructions.EmitNumericConvertUnchecked(from, to); } return; } // TODO: Conversions to a super-class or implemented interfaces are no-op. // A conversion to a non-implemented interface or an unrelated class, etc. should fail. return; } private void CompileNotExpression(UnaryExpression node) { if (node.Operand.Type == typeof(bool)) { Compile(node.Operand); _instructions.EmitNot(); } else { throw new NotImplementedException(); } } private void CompileUnaryExpression(Expression expr) { var node = (UnaryExpression)expr; if (node.Method != null) { Compile(node.Operand); _instructions.EmitCall(node.Method); } else { switch (node.NodeType) { case ExpressionType.Not: CompileNotExpression(node); return; case ExpressionType.TypeAs: CompileTypeAsExpression(node); return; default: throw new NotImplementedException(node.NodeType.ToString()); } } } private void CompileAndAlsoBinaryExpression(Expression expr) { CompileLogicalBinaryExpression(expr, true); } private void CompileOrElseBinaryExpression(Expression expr) { CompileLogicalBinaryExpression(expr, false); } private void CompileLogicalBinaryExpression(Expression expr, bool andAlso) { var node = (BinaryExpression)expr; if (node.Method != null) { throw new NotImplementedException(); } Debug.Assert(node.Left.Type == node.Right.Type); if (node.Left.Type == typeof(bool)) { var elseLabel = _instructions.MakeLabel(); var endLabel = _instructions.MakeLabel(); Compile(node.Left); if (andAlso) { _instructions.EmitBranchFalse(elseLabel); } else { _instructions.EmitBranchTrue(elseLabel); } Compile(node.Right); _instructions.EmitBranch(endLabel, false, true); _instructions.MarkLabel(elseLabel); _instructions.EmitLoad(!andAlso); _instructions.MarkLabel(endLabel); return; } Debug.Assert(node.Left.Type == typeof(bool?)); throw new NotImplementedException(); } private void CompileConditionalExpression(Expression expr, bool asVoid) { var node = (ConditionalExpression)expr; Compile(node.Test); if (node.IfTrue == AstUtils.Empty()) { var endOfFalse = _instructions.MakeLabel(); _instructions.EmitBranchTrue(endOfFalse); Compile(node.IfFalse, asVoid); _instructions.MarkLabel(endOfFalse); } else { var endOfTrue = _instructions.MakeLabel(); _instructions.EmitBranchFalse(endOfTrue); Compile(node.IfTrue, asVoid); if (node.IfFalse != AstUtils.Empty()) { var endOfFalse = _instructions.MakeLabel(); _instructions.EmitBranch(endOfFalse, false, !asVoid); _instructions.MarkLabel(endOfTrue); Compile(node.IfFalse, asVoid); _instructions.MarkLabel(endOfFalse); } else { _instructions.MarkLabel(endOfTrue); } } } #region Loops private static void CompileLoopExpression(Expression expr) { // var node = (LoopExpression)expr; // var enterLoop = new EnterLoopInstruction(node, _locals, _compilationThreshold, _instructions.Count); // // PushLabelBlock(LabelScopeKind.Statement); // LabelInfo breakLabel = DefineLabel(node.BreakLabel); // LabelInfo continueLabel = DefineLabel(node.ContinueLabel); // // _instructions.MarkLabel(continueLabel.GetLabel(this)); // // // emit loop body: // _instructions.Emit(enterLoop); // CompileAsVoid(node.Body); // // // emit loop branch: // _instructions.EmitBranch(continueLabel.GetLabel(this), expr.Type != typeof(void), false); // // _instructions.MarkLabel(breakLabel.GetLabel(this)); // // PopLabelBlock(LabelScopeKind.Statement); // // enterLoop.FinishLoop(_instructions.Count); } #endregion private void CompileSwitchExpression(Expression expr) { var node = (SwitchExpression)expr; // Currently only supports int test values, with no method if (node.SwitchValue.Type != typeof(int) || node.Comparison != null) { throw new NotImplementedException(); } // Test values must be constant if (!node.Cases.All(static c => c.TestValues.All(t => t is ConstantExpression))) { throw new NotImplementedException(); } LabelInfo end = DefineLabel(null); bool hasValue = node.Type != typeof(void); Compile(node.SwitchValue); var caseDict = new Dictionary<int, int>(); int switchIndex = _instructions.Count; _instructions.EmitSwitch(caseDict); if (node.DefaultBody != null) { Compile(node.DefaultBody); } else { Debug.Assert(!hasValue); } _instructions.EmitBranch(end.GetLabel(this), false, hasValue); for (int i = 0; i < node.Cases.Count; i++) { var switchCase = node.Cases[i]; int caseOffset = _instructions.Count - switchIndex; for (int index = 0; index < switchCase.TestValues.Count; index++) { var testValue = (ConstantExpression)switchCase.TestValues[index]; caseDict[(int)testValue.Value] = caseOffset; } Compile(switchCase.Body); if (i < node.Cases.Count - 1) { _instructions.EmitBranch(end.GetLabel(this), false, hasValue); } } _instructions.MarkLabel(end.GetLabel(this)); } private void CompileLabelExpression(Expression expr) { var node = (LabelExpression)expr; // If we're an immediate child of a block, our label will already // be defined. If not, we need to define our own block so this // label isn't exposed except to its own child expression. LabelInfo label = null; if (_labelBlock.Kind == LabelScopeKind.Block) { _labelBlock.TryGetLabelInfo(node.Target, out label); // We're in a block but didn't find our label, try switch if (label == null && _labelBlock.Parent.Kind == LabelScopeKind.Switch) { _labelBlock.Parent.TryGetLabelInfo(node.Target, out label); } // if we're in a switch or block, we should've found the label Debug.Assert(label != null); } if (label == null) { label = DefineLabel(node.Target); } if (node.DefaultValue != null) { if (node.Target.Type == typeof(void)) { CompileAsVoid(node.DefaultValue); } else { Compile(node.DefaultValue); } } _instructions.MarkLabel(label.GetLabel(this)); } private void CompileGotoExpression(Expression expr) { var node = (GotoExpression)expr; var labelInfo = ReferenceLabel(node.Target); if (node.Value != null) { Compile(node.Value); } _instructions.EmitGoto(labelInfo.GetLabel(this), node.Type != typeof(void), node.Value != null && node.Value.Type != typeof(void)); } public BranchLabel GetBranchLabel(LabelTarget target) { return ReferenceLabel(target).GetLabel(this); } public void PushLabelBlock(LabelScopeKind type) { _labelBlock = new LabelScopeInfo(_labelBlock, type); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "kind")] public void PopLabelBlock(LabelScopeKind kind) { Debug.Assert(_labelBlock != null && _labelBlock.Kind == kind); _labelBlock = _labelBlock.Parent; } private LabelInfo EnsureLabel(LabelTarget node) { LabelInfo result; if (!_treeLabels.TryGetValue(node, out result)) { _treeLabels[node] = result = new LabelInfo(node); } return result; } private LabelInfo ReferenceLabel(LabelTarget node) { LabelInfo result = EnsureLabel(node); result.Reference(_labelBlock); return result; } internal LabelInfo DefineLabel(LabelTarget node) { if (node == null) { return new LabelInfo(null); } LabelInfo result = EnsureLabel(node); result.Define(_labelBlock); return result; } private bool TryPushLabelBlock(Expression node) { // Anything that is "statement-like" -- e.g. has no associated // stack state can be jumped into, with the exception of try-blocks // We indicate this by a "Block" // // Otherwise, we push an "Expression" to indicate that it can't be // jumped into switch (node.NodeType) { default: if (_labelBlock.Kind != LabelScopeKind.Expression) { PushLabelBlock(LabelScopeKind.Expression); return true; } return false; case ExpressionType.Label: // LabelExpression is a bit special, if it's directly in a // block it becomes associate with the block's scope. Same // thing if it's in a switch case body. if (_labelBlock.Kind == LabelScopeKind.Block) { var label = ((LabelExpression)node).Target; if (_labelBlock.ContainsTarget(label)) { return false; } if (_labelBlock.Parent.Kind == LabelScopeKind.Switch && _labelBlock.Parent.ContainsTarget(label)) { return false; } } PushLabelBlock(LabelScopeKind.Statement); return true; case ExpressionType.Block: PushLabelBlock(LabelScopeKind.Block); // Labels defined immediately in the block are valid for // the whole block. if (_labelBlock.Parent.Kind != LabelScopeKind.Switch) { DefineBlockLabels(node); } return true; case ExpressionType.Switch: PushLabelBlock(LabelScopeKind.Switch); // Define labels inside of the switch cases so they are in // scope for the whole switch. This allows "goto case" and // "goto default" to be considered as local jumps. var @switch = (SwitchExpression)node; for (int index = 0; index < @switch.Cases.Count; index++) { SwitchCase c = @switch.Cases[index]; DefineBlockLabels(c.Body); } DefineBlockLabels(@switch.DefaultBody); return true; // Remove this when Convert(Void) goes away. case ExpressionType.Convert: if (node.Type != typeof(void)) { // treat it as an expression goto default; } PushLabelBlock(LabelScopeKind.Statement); return true; case ExpressionType.Conditional: case ExpressionType.Loop: case ExpressionType.Goto: PushLabelBlock(LabelScopeKind.Statement); return true; } } private void DefineBlockLabels(Expression node) { if (!(node is BlockExpression block)) { return; } for (int i = 0, n = block.Expressions.Count; i < n; i++) { Expression e = block.Expressions[i]; var label = e as LabelExpression; if (label != null) { DefineLabel(label.Target); } } } private HybridReferenceDictionary<LabelTarget, BranchLabel> GetBranchMapping() { var newLabelMapping = new HybridReferenceDictionary<LabelTarget, BranchLabel>(_treeLabels.Count); foreach (var kvp in _treeLabels) { newLabelMapping[kvp.Key] = kvp.Value.GetLabel(this); } return newLabelMapping; } private void CompileThrowUnaryExpression(Expression expr, bool asVoid) { var node = (UnaryExpression)expr; if (node.Operand == null) { CompileParameterExpression(_exceptionForRethrowStack.Peek()); if (asVoid) { _instructions.EmitRethrowVoid(); } else { _instructions.EmitRethrow(); } } else { Compile(node.Operand); if (asVoid) { _instructions.EmitThrowVoid(); } else { _instructions.EmitThrow(); } } } // TODO: remove (replace by true fault support) private bool EndsWithRethrow(Expression expr) { if (expr.NodeType == ExpressionType.Throw) { var node = (UnaryExpression)expr; return node.Operand == null; } BlockExpression block = expr as BlockExpression; if (block != null) { return EndsWithRethrow(block.Expressions[block.Expressions.Count - 1]); } return false; } // TODO: remove (replace by true fault support) private void CompileAsVoidRemoveRethrow(Expression expr) { int stackDepth = _instructions.CurrentStackDepth; if (expr.NodeType == ExpressionType.Throw) { Debug.Assert(((UnaryExpression)expr).Operand == null); return; } var node = (BlockExpression)expr; var end = CompileBlockStart(node); CompileAsVoidRemoveRethrow(node.Expressions[node.Expressions.Count - 1]); Debug.Assert(stackDepth == _instructions.CurrentStackDepth); CompileBlockEnd(end); } private void CompileTryExpression(Expression expr) { var node = (TryExpression)expr; BranchLabel end = _instructions.MakeLabel(); BranchLabel gotoEnd = _instructions.MakeLabel(); int tryStart = _instructions.Count; BranchLabel startOfFinally = null; if (node.Finally != null) { startOfFinally = _instructions.MakeLabel(); _instructions.EmitEnterTryFinally(startOfFinally); } else { _instructions.EmitEnterTryCatch(); } List<ExceptionHandler> exHandlers = null; var enterTryInstr = _instructions.GetInstruction(tryStart) as EnterTryCatchFinallyInstruction; Debug.Assert(enterTryInstr != null); PushLabelBlock(LabelScopeKind.Try); Compile(node.Body); bool hasValue = node.Body.Type != typeof(void); int tryEnd = _instructions.Count; // handlers jump here: _instructions.MarkLabel(gotoEnd); _instructions.EmitGoto(end, hasValue, hasValue); // keep the result on the stack: if (node.Handlers.Count > 0) { exHandlers = new List<ExceptionHandler>(); // TODO: emulates faults (replace by true fault support) if (node.Finally == null && node.Handlers.Count == 1) { var handler = node.Handlers[0]; if (handler.Filter == null && handler.Test == typeof(Exception) && handler.Variable == null) { if (EndsWithRethrow(handler.Body)) { if (hasValue) { _instructions.EmitEnterExceptionHandlerNonVoid(); } else { _instructions.EmitEnterExceptionHandlerVoid(); } // at this point the stack balance is prepared for the hidden exception variable: int handlerLabel = _instructions.MarkRuntimeLabel(); int handlerStart = _instructions.Count; CompileAsVoidRemoveRethrow(handler.Body); _instructions.EmitLeaveFault(hasValue); _instructions.MarkLabel(end); exHandlers.Add(new ExceptionHandler(tryStart, tryEnd, handlerLabel, handlerStart, _instructions.Count, null)); enterTryInstr.SetTryHandler(new TryCatchFinallyHandler(tryStart, tryEnd, gotoEnd.TargetIndex, exHandlers.ToArray())); PopLabelBlock(LabelScopeKind.Try); return; } } } for (int index = 0; index < node.Handlers.Count; index++) { var handler = node.Handlers[index]; PushLabelBlock(LabelScopeKind.Catch); if (handler.Filter != null) { // PushLabelBlock(LabelScopeKind.Filter); throw new NotImplementedException(); // PopLabelBlock(LabelScopeKind.Filter); } var parameter = handler.Variable ?? Expression.Parameter(handler.Test); var local = _locals.DefineLocal(parameter, _instructions.Count); _exceptionForRethrowStack.Push(parameter); // add a stack balancing nop instruction (exception handling pushes the current exception): if (hasValue) { _instructions.EmitEnterExceptionHandlerNonVoid(); } else { _instructions.EmitEnterExceptionHandlerVoid(); } // at this point the stack balance is prepared for the hidden exception variable: int handlerLabel = _instructions.MarkRuntimeLabel(); int handlerStart = _instructions.Count; CompileSetVariable(parameter, true); Compile(handler.Body); _exceptionForRethrowStack.Pop(); // keep the value of the body on the stack: Debug.Assert(hasValue == (handler.Body.Type != typeof(void))); _instructions.EmitLeaveExceptionHandler(hasValue, gotoEnd); exHandlers.Add(new ExceptionHandler(tryStart, tryEnd, handlerLabel, handlerStart, _instructions.Count, handler.Test)); PopLabelBlock(LabelScopeKind.Catch); _locals.UndefineLocal(local, _instructions.Count); } if (node.Fault != null) { throw new NotImplementedException(); } } if (node.Finally != null) { Debug.Assert(startOfFinally != null); PushLabelBlock(LabelScopeKind.Finally); _instructions.MarkLabel(startOfFinally); _instructions.EmitEnterFinally(startOfFinally); CompileAsVoid(node.Finally); _instructions.EmitLeaveFinally(); enterTryInstr.SetTryHandler( new TryCatchFinallyHandler(tryStart, tryEnd, gotoEnd.TargetIndex, startOfFinally.TargetIndex, _instructions.Count, exHandlers?.ToArray())); PopLabelBlock(LabelScopeKind.Finally); } else { Debug.Assert(exHandlers != null); enterTryInstr.SetTryHandler( new TryCatchFinallyHandler(tryStart, tryEnd, gotoEnd.TargetIndex, exHandlers.ToArray())); } _instructions.MarkLabel(end); PopLabelBlock(LabelScopeKind.Try); } private void CompileDynamicExpression(Expression expr) { var node = (DynamicExpression)expr; for (int index = 0; index < node.Arguments.Count; index++) { var arg = node.Arguments[index]; Compile(arg); } _instructions.EmitDynamic(node.DelegateType, node.Binder); } private void CompileMethodCallExpression(Expression expr) { var node = (MethodCallExpression)expr; var parameters = node.Method.GetParameters(); // TODO: // Support pass by reference. // Note that LoopCompiler needs to be updated too. // force compilation for now for ref types // also could be a mutable value type, Delegate.CreateDelegate and MethodInfo.Invoke both can't handle this, we // need to generate code. var declaringType = node.Method.DeclaringType; if (!parameters.TrueForAll(static p => !p.ParameterType.IsByRef) || (!node.Method.IsStatic && declaringType.IsValueType && !declaringType.IsPrimitive)) { _forceCompile = true; } if (!node.Method.IsStatic) { Compile(node.Object); } for (int index = 0; index < node.Arguments.Count; index++) { var arg = node.Arguments[index]; Compile(arg); } _instructions.EmitCall(node.Method, parameters); } private void CompileNewExpression(Expression expr) { var node = (NewExpression)expr; if (node.Constructor != null) { var parameters = node.Constructor.GetParameters(); if (!parameters.TrueForAll(static p => !p.ParameterType.IsByRef)) { _forceCompile = true; } } if (node.Constructor != null) { for (int index = 0; index < node.Arguments.Count; index++) { var arg = node.Arguments[index]; this.Compile(arg); } _instructions.EmitNew(node.Constructor); } else { Debug.Assert(expr.Type.IsValueType); _instructions.EmitDefaultValue(node.Type); } } private void CompileMemberExpression(Expression expr) { var node = (MemberExpression)expr; var member = node.Member; FieldInfo fi = member as FieldInfo; if (fi != null) { if (fi.IsLiteral) { _instructions.EmitLoad(fi.GetValue(null), fi.FieldType); } else if (fi.IsStatic) { if (fi.IsInitOnly) { _instructions.EmitLoad(fi.GetValue(null), fi.FieldType); } else { _instructions.EmitLoadField(fi); } } else { Compile(node.Expression); _instructions.EmitLoadField(fi); } return; } PropertyInfo pi = member as PropertyInfo; if (pi != null) { var method = pi.GetMethod; if (node.Expression != null) { Compile(node.Expression); } _instructions.EmitCall(method); return; } throw new System.NotImplementedException(); } private void CompileNewArrayExpression(Expression expr) { var node = (NewArrayExpression)expr; for (int index = 0; index < node.Expressions.Count; index++) { var arg = node.Expressions[index]; Compile(arg); } Type elementType = node.Type.GetElementType(); int rank = node.Expressions.Count; if (node.NodeType == ExpressionType.NewArrayInit) { _instructions.EmitNewArrayInit(elementType, rank); } else if (node.NodeType == ExpressionType.NewArrayBounds) { if (rank == 1) { _instructions.EmitNewArray(elementType); } else { _instructions.EmitNewArrayBounds(elementType, rank); } } else { throw new System.NotImplementedException(); } } private void CompileExtensionExpression(Expression expr) { var instructionProvider = expr as IInstructionProvider; if (instructionProvider != null) { instructionProvider.AddInstructions(this); return; } if (expr.CanReduce) { Compile(expr.Reduce()); } else { throw new System.NotImplementedException(); } } private void CompileDebugInfoExpression(Expression expr) { var node = (DebugInfoExpression)expr; int start = _instructions.Count; var info = new DebugInfo() { Index = start, FileName = node.Document.FileName, StartLine = node.StartLine, EndLine = node.EndLine, IsClear = node.IsClear }; _debugInfos.Add(info); } private void CompileRuntimeVariablesExpression(Expression expr) { // Generates IRuntimeVariables for all requested variables var node = (RuntimeVariablesExpression)expr; for (int index = 0; index < node.Variables.Count; index++) { var variable = node.Variables[index]; EnsureAvailableForClosure(variable); CompileGetBoxedVariable(variable); } _instructions.EmitNewRuntimeVariables(node.Variables.Count); } private void CompileLambdaExpression(Expression expr) { var node = (LambdaExpression)expr; var compiler = new LightCompiler(this); var creator = compiler.CompileTop(node); if (compiler._locals.ClosureVariables != null) { foreach (ParameterExpression variable in compiler._locals.ClosureVariables.Keys) { CompileGetBoxedVariable(variable); } } _instructions.EmitCreateDelegate(creator); } private void CompileCoalesceBinaryExpression(Expression expr) { var node = (BinaryExpression)expr; if (TypeUtils.IsNullableType(node.Left.Type)) { throw new NotImplementedException(); } else if (node.Conversion != null) { throw new NotImplementedException(); } else { var leftNotNull = _instructions.MakeLabel(); Compile(node.Left); _instructions.EmitCoalescingBranch(leftNotNull); _instructions.EmitPop(); Compile(node.Right); _instructions.MarkLabel(leftNotNull); } } private void CompileInvocationExpression(Expression expr) { var node = (InvocationExpression)expr; // TODO: LambdaOperand optimization (see compiler) if (typeof(LambdaExpression).IsAssignableFrom(node.Expression.Type)) { throw new System.NotImplementedException(); } // TODO: do not create a new Call Expression // if (PlatformAdaptationLayer.IsCompactFramework) { // // Workaround for a bug in Compact Framework // Compile( // AstUtils.Convert( // Expression.Call( // node.Expression, // node.Expression.Type.GetMethod("DynamicInvoke"), // Expression.NewArrayInit(typeof(object), node.Arguments.Map((e) => AstUtils.Convert(e, typeof(object)))) // ), // node.Type // ) // ); // } else { CompileMethodCallExpression(Expression.Call(node.Expression, node.Expression.Type.GetMethod("Invoke"), node.Arguments)); // } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "expr")] private void CompileListInitExpression(Expression expr) { throw new System.NotImplementedException(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "expr")] private void CompileMemberInitExpression(Expression expr) { throw new System.NotImplementedException(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "expr")] private void CompileQuoteUnaryExpression(Expression expr) { throw new System.NotImplementedException(); } private void CompileUnboxUnaryExpression(Expression expr) { var node = (UnaryExpression)expr; // unboxing is a nop: Compile(node.Operand); } private void CompileTypeEqualExpression(Expression expr) { Debug.Assert(expr.NodeType == ExpressionType.TypeEqual); var node = (TypeBinaryExpression)expr; Compile(node.Expression); _instructions.EmitLoad(node.TypeOperand); _instructions.EmitTypeEquals(); } private void CompileTypeAsExpression(UnaryExpression node) { Compile(node.Operand); _instructions.EmitTypeAs(node.Type); } private void CompileTypeIsExpression(Expression expr) { Debug.Assert(expr.NodeType == ExpressionType.TypeIs); var node = (TypeBinaryExpression)expr; Compile(node.Expression); // use TypeEqual for sealed types: if (node.TypeOperand.IsSealed) { _instructions.EmitLoad(node.TypeOperand); _instructions.EmitTypeEquals(); } else { _instructions.EmitTypeIs(node.TypeOperand); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "expr")] private void CompileReducibleExpression(Expression expr) { throw new System.NotImplementedException(); } internal void Compile(Expression expr, bool asVoid) { if (asVoid) { CompileAsVoid(expr); } else { Compile(expr); } } internal void CompileAsVoid(Expression expr) { bool pushLabelBlock = TryPushLabelBlock(expr); int startingStackDepth = _instructions.CurrentStackDepth; switch (expr.NodeType) { case ExpressionType.Assign: CompileAssignBinaryExpression(expr, true); break; case ExpressionType.Block: CompileBlockExpression(expr, true); break; case ExpressionType.Throw: CompileThrowUnaryExpression(expr, true); break; case ExpressionType.Constant: case ExpressionType.Default: case ExpressionType.Parameter: // no-op break; default: CompileNoLabelPush(expr); if (expr.Type != typeof(void)) { _instructions.EmitPop(); } break; } Debug.Assert(_instructions.CurrentStackDepth == startingStackDepth); if (pushLabelBlock) { PopLabelBlock(_labelBlock.Kind); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] private void CompileNoLabelPush(Expression expr) { int startingStackDepth = _instructions.CurrentStackDepth; switch (expr.NodeType) { case ExpressionType.Add: CompileBinaryExpression(expr); break; case ExpressionType.AddChecked: CompileBinaryExpression(expr); break; case ExpressionType.And: CompileBinaryExpression(expr); break; case ExpressionType.AndAlso: CompileAndAlsoBinaryExpression(expr); break; case ExpressionType.ArrayLength: CompileUnaryExpression(expr); break; case ExpressionType.ArrayIndex: CompileBinaryExpression(expr); break; case ExpressionType.Call: CompileMethodCallExpression(expr); break; case ExpressionType.Coalesce: CompileCoalesceBinaryExpression(expr); break; case ExpressionType.Conditional: CompileConditionalExpression(expr, expr.Type == typeof(void)); break; case ExpressionType.Constant: CompileConstantExpression(expr); break; case ExpressionType.Convert: CompileConvertUnaryExpression(expr); break; case ExpressionType.ConvertChecked: CompileConvertUnaryExpression(expr); break; case ExpressionType.Divide: CompileBinaryExpression(expr); break; case ExpressionType.Equal: CompileBinaryExpression(expr); break; case ExpressionType.ExclusiveOr: CompileBinaryExpression(expr); break; case ExpressionType.GreaterThan: CompileBinaryExpression(expr); break; case ExpressionType.GreaterThanOrEqual: CompileBinaryExpression(expr); break; case ExpressionType.Invoke: CompileInvocationExpression(expr); break; case ExpressionType.Lambda: CompileLambdaExpression(expr); break; case ExpressionType.LeftShift: CompileBinaryExpression(expr); break; case ExpressionType.LessThan: CompileBinaryExpression(expr); break; case ExpressionType.LessThanOrEqual: CompileBinaryExpression(expr); break; case ExpressionType.ListInit: CompileListInitExpression(expr); break; case ExpressionType.MemberAccess: CompileMemberExpression(expr); break; case ExpressionType.MemberInit: CompileMemberInitExpression(expr); break; case ExpressionType.Modulo: CompileBinaryExpression(expr); break; case ExpressionType.Multiply: CompileBinaryExpression(expr); break; case ExpressionType.MultiplyChecked: CompileBinaryExpression(expr); break; case ExpressionType.Negate: CompileUnaryExpression(expr); break; case ExpressionType.UnaryPlus: CompileUnaryExpression(expr); break; case ExpressionType.NegateChecked: CompileUnaryExpression(expr); break; case ExpressionType.New: CompileNewExpression(expr); break; case ExpressionType.NewArrayInit: CompileNewArrayExpression(expr); break; case ExpressionType.NewArrayBounds: CompileNewArrayExpression(expr); break; case ExpressionType.Not: CompileUnaryExpression(expr); break; case ExpressionType.NotEqual: CompileBinaryExpression(expr); break; case ExpressionType.Or: CompileBinaryExpression(expr); break; case ExpressionType.OrElse: CompileOrElseBinaryExpression(expr); break; case ExpressionType.Parameter: CompileParameterExpression(expr); break; case ExpressionType.Power: CompileBinaryExpression(expr); break; case ExpressionType.Quote: CompileQuoteUnaryExpression(expr); break; case ExpressionType.RightShift: CompileBinaryExpression(expr); break; case ExpressionType.Subtract: CompileBinaryExpression(expr); break; case ExpressionType.SubtractChecked: CompileBinaryExpression(expr); break; case ExpressionType.TypeAs: CompileUnaryExpression(expr); break; case ExpressionType.TypeIs: CompileTypeIsExpression(expr); break; case ExpressionType.Assign: CompileAssignBinaryExpression(expr, expr.Type == typeof(void)); break; case ExpressionType.Block: CompileBlockExpression(expr, expr.Type == typeof(void)); break; case ExpressionType.DebugInfo: CompileDebugInfoExpression(expr); break; case ExpressionType.Decrement: CompileUnaryExpression(expr); break; case ExpressionType.Dynamic: CompileDynamicExpression(expr); break; case ExpressionType.Default: CompileDefaultExpression(expr); break; case ExpressionType.Extension: CompileExtensionExpression(expr); break; case ExpressionType.Goto: CompileGotoExpression(expr); break; case ExpressionType.Increment: CompileUnaryExpression(expr); break; case ExpressionType.Index: CompileIndexExpression(expr); break; case ExpressionType.Label: CompileLabelExpression(expr); break; case ExpressionType.RuntimeVariables: CompileRuntimeVariablesExpression(expr); break; case ExpressionType.Loop: CompileLoopExpression(expr); break; case ExpressionType.Switch: CompileSwitchExpression(expr); break; case ExpressionType.Throw: CompileThrowUnaryExpression(expr, expr.Type == typeof(void)); break; case ExpressionType.Try: CompileTryExpression(expr); break; case ExpressionType.Unbox: CompileUnboxUnaryExpression(expr); break; case ExpressionType.TypeEqual: CompileTypeEqualExpression(expr); break; case ExpressionType.OnesComplement: CompileUnaryExpression(expr); break; case ExpressionType.IsTrue: CompileUnaryExpression(expr); break; case ExpressionType.IsFalse: CompileUnaryExpression(expr); break; case ExpressionType.AddAssign: case ExpressionType.AndAssign: case ExpressionType.DivideAssign: case ExpressionType.ExclusiveOrAssign: case ExpressionType.LeftShiftAssign: case ExpressionType.ModuloAssign: case ExpressionType.MultiplyAssign: case ExpressionType.OrAssign: case ExpressionType.PowerAssign: case ExpressionType.RightShiftAssign: case ExpressionType.SubtractAssign: case ExpressionType.AddAssignChecked: case ExpressionType.MultiplyAssignChecked: case ExpressionType.SubtractAssignChecked: case ExpressionType.PreIncrementAssign: case ExpressionType.PreDecrementAssign: case ExpressionType.PostIncrementAssign: case ExpressionType.PostDecrementAssign: CompileReducibleExpression(expr); break; default: throw Assert.Unreachable; } Debug.Assert(_instructions.CurrentStackDepth == startingStackDepth + (expr.Type == typeof(void) ? 0 : 1)); } public void Compile(Expression expr) { bool pushLabelBlock = TryPushLabelBlock(expr); CompileNoLabelPush(expr); if (pushLabelBlock) { PopLabelBlock(_labelBlock.Kind); } } } }
// 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.Specialized; using System.IO; using System.Net.Mime; using System.Text; namespace System.Net.Mail { [Flags] public enum DeliveryNotificationOptions { None = 0, OnSuccess = 1, OnFailure = 2, Delay = 4, Never = (int)0x08000000 } public class MailMessage : IDisposable { private AlternateViewCollection _views; private AttachmentCollection _attachments; private AlternateView _bodyView = null; private string _body = string.Empty; private Encoding _bodyEncoding; private TransferEncoding _bodyTransferEncoding = TransferEncoding.Unknown; private bool _isBodyHtml = false; private bool _disposed = false; private Message _message; private DeliveryNotificationOptions _deliveryStatusNotification = DeliveryNotificationOptions.None; public MailMessage() { _message = new Message(); if (NetEventSource.IsEnabled) NetEventSource.Associate(this, _message); } public MailMessage(string from, string to) { if (from == null) throw new ArgumentNullException(nameof(from)); if (to == null) throw new ArgumentNullException(nameof(to)); if (from == string.Empty) throw new ArgumentException(SR.Format(SR.net_emptystringcall, nameof(from)), nameof(from)); if (to == string.Empty) throw new ArgumentException(SR.Format(SR.net_emptystringcall, nameof(to)), nameof(to)); _message = new Message(from, to); if (NetEventSource.IsEnabled) NetEventSource.Associate(this, _message); } public MailMessage(string from, string to, string subject, string body) : this(from, to) { Subject = subject; Body = body; } public MailMessage(MailAddress from, MailAddress to) { if (from == null) throw new ArgumentNullException(nameof(from)); if (to == null) throw new ArgumentNullException(nameof(to)); _message = new Message(from, to); } public MailAddress From { get { return _message.From; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } _message.From = value; } } public MailAddress Sender { get { return _message.Sender; } set { _message.Sender = value; } } [Obsolete("ReplyTo is obsoleted for this type. Please use ReplyToList instead which can accept multiple addresses. http://go.microsoft.com/fwlink/?linkid=14202")] public MailAddress ReplyTo { get { return _message.ReplyTo; } set { _message.ReplyTo = value; } } public MailAddressCollection ReplyToList { get { return _message.ReplyToList; } } public MailAddressCollection To { get { return _message.To; } } public MailAddressCollection Bcc { get { return _message.Bcc; } } public MailAddressCollection CC { get { return _message.CC; } } public MailPriority Priority { get { return _message.Priority; } set { _message.Priority = value; } } public DeliveryNotificationOptions DeliveryNotificationOptions { get { return _deliveryStatusNotification; } set { if (7 < (uint)value && value != DeliveryNotificationOptions.Never) { throw new ArgumentOutOfRangeException(nameof(value)); } _deliveryStatusNotification = value; } } public string Subject { get { return (_message.Subject != null ? _message.Subject : string.Empty); } set { _message.Subject = value; } } public Encoding SubjectEncoding { get { return _message.SubjectEncoding; } set { _message.SubjectEncoding = value; } } public NameValueCollection Headers { get { return _message.Headers; } } public Encoding HeadersEncoding { get { return _message.HeadersEncoding; } set { _message.HeadersEncoding = value; } } public string Body { get { return (_body != null ? _body : string.Empty); } set { _body = value; if (_bodyEncoding == null && _body != null) { if (MimeBasePart.IsAscii(_body, true)) { _bodyEncoding = Text.Encoding.ASCII; } else { _bodyEncoding = Text.Encoding.GetEncoding(MimeBasePart.DefaultCharSet); } } } } public Encoding BodyEncoding { get { return _bodyEncoding; } set { _bodyEncoding = value; } } public TransferEncoding BodyTransferEncoding { get { return _bodyTransferEncoding; } set { _bodyTransferEncoding = value; } } public bool IsBodyHtml { get { return _isBodyHtml; } set { _isBodyHtml = value; } } public AttachmentCollection Attachments { get { if (_disposed) { throw new ObjectDisposedException(GetType().FullName); } if (_attachments == null) { _attachments = new AttachmentCollection(); } return _attachments; } } public AlternateViewCollection AlternateViews { get { if (_disposed) { throw new ObjectDisposedException(GetType().FullName); } if (_views == null) { _views = new AlternateViewCollection(); } return _views; } } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing && !_disposed) { _disposed = true; if (_views != null) { _views.Dispose(); } if (_attachments != null) { _attachments.Dispose(); } if (_bodyView != null) { _bodyView.Dispose(); } } } private void SetContent(bool allowUnicode) { //the attachments may have changed, so we need to reset the message if (_bodyView != null) { _bodyView.Dispose(); _bodyView = null; } if (AlternateViews.Count == 0 && Attachments.Count == 0) { if (!string.IsNullOrEmpty(_body)) { _bodyView = AlternateView.CreateAlternateViewFromString(_body, _bodyEncoding, (_isBodyHtml ? MediaTypeNames.Text.Html : null)); _message.Content = _bodyView.MimePart; } } else if (AlternateViews.Count == 0 && Attachments.Count > 0) { MimeMultiPart part = new MimeMultiPart(MimeMultiPartType.Mixed); if (!string.IsNullOrEmpty(_body)) { _bodyView = AlternateView.CreateAlternateViewFromString(_body, _bodyEncoding, (_isBodyHtml ? MediaTypeNames.Text.Html : null)); } else { _bodyView = AlternateView.CreateAlternateViewFromString(string.Empty); } part.Parts.Add(_bodyView.MimePart); foreach (Attachment attachment in Attachments) { if (attachment != null) { //ensure we can read from the stream. attachment.PrepareForSending(allowUnicode); part.Parts.Add(attachment.MimePart); } } _message.Content = part; } else { // we should not unnecessarily use Multipart/Mixed // When there is no attachement and all the alternative views are of "Alternative" types. MimeMultiPart part = null; MimeMultiPart viewsPart = new MimeMultiPart(MimeMultiPartType.Alternative); if (!string.IsNullOrEmpty(_body)) { _bodyView = AlternateView.CreateAlternateViewFromString(_body, _bodyEncoding, null); viewsPart.Parts.Add(_bodyView.MimePart); } foreach (AlternateView view in AlternateViews) { //ensure we can read from the stream. if (view != null) { view.PrepareForSending(allowUnicode); if (view.LinkedResources.Count > 0) { MimeMultiPart wholeView = new MimeMultiPart(MimeMultiPartType.Related); wholeView.ContentType.Parameters["type"] = view.ContentType.MediaType; wholeView.ContentLocation = view.MimePart.ContentLocation; wholeView.Parts.Add(view.MimePart); foreach (LinkedResource resource in view.LinkedResources) { //ensure we can read from the stream. resource.PrepareForSending(allowUnicode); wholeView.Parts.Add(resource.MimePart); } viewsPart.Parts.Add(wholeView); } else { viewsPart.Parts.Add(view.MimePart); } } } if (Attachments.Count > 0) { part = new MimeMultiPart(MimeMultiPartType.Mixed); part.Parts.Add(viewsPart); MimeMultiPart attachmentsPart = new MimeMultiPart(MimeMultiPartType.Mixed); foreach (Attachment attachment in Attachments) { if (attachment != null) { //ensure we can read from the stream. attachment.PrepareForSending(allowUnicode); attachmentsPart.Parts.Add(attachment.MimePart); } } part.Parts.Add(attachmentsPart); _message.Content = part; } // If there is no Attachement, AND only "1" Alternate View AND !!no body!! // then in fact, this is NOT a multipart region. else if (viewsPart.Parts.Count == 1 && string.IsNullOrEmpty(_body)) { _message.Content = viewsPart.Parts[0]; } else { _message.Content = viewsPart; } } if (_bodyView != null && _bodyTransferEncoding != TransferEncoding.Unknown) { _bodyView.TransferEncoding = _bodyTransferEncoding; } } internal void Send(BaseWriter writer, bool sendEnvelope, bool allowUnicode) { SetContent(allowUnicode); _message.Send(writer, sendEnvelope, allowUnicode); } internal IAsyncResult BeginSend(BaseWriter writer, bool sendEnvelope, bool allowUnicode, AsyncCallback callback, object state) { SetContent(allowUnicode); return _message.BeginSend(writer, sendEnvelope, allowUnicode, callback, state); } internal void EndSend(IAsyncResult asyncResult) { _message.EndSend(asyncResult); } internal string BuildDeliveryStatusNotificationString() { if (_deliveryStatusNotification != DeliveryNotificationOptions.None) { StringBuilder s = new StringBuilder(" NOTIFY="); bool oneSet = false; //none if (_deliveryStatusNotification == DeliveryNotificationOptions.Never) { s.Append("NEVER"); return s.ToString(); } if ((((int)_deliveryStatusNotification) & (int)DeliveryNotificationOptions.OnSuccess) > 0) { s.Append("SUCCESS"); oneSet = true; } if ((((int)_deliveryStatusNotification) & (int)DeliveryNotificationOptions.OnFailure) > 0) { if (oneSet) { s.Append(","); } s.Append("FAILURE"); oneSet = true; } if ((((int)_deliveryStatusNotification) & (int)DeliveryNotificationOptions.Delay) > 0) { if (oneSet) { s.Append(","); } s.Append("DELAY"); } return s.ToString(); } return string.Empty; } } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections; using System.IO; using log4net.Core; using log4net.Layout.Pattern; using log4net.Util; using log4net.Util.PatternStringConverters; using AppDomainPatternConverter=log4net.Layout.Pattern.AppDomainPatternConverter; using DatePatternConverter=log4net.Layout.Pattern.DatePatternConverter; using IdentityPatternConverter=log4net.Layout.Pattern.IdentityPatternConverter; using PropertyPatternConverter=log4net.Layout.Pattern.PropertyPatternConverter; using UserNamePatternConverter=log4net.Layout.Pattern.UserNamePatternConverter; using UtcDatePatternConverter=log4net.Layout.Pattern.UtcDatePatternConverter; namespace log4net.Layout { /// <summary> /// A flexible layout configurable with pattern string. /// </summary> /// <remarks> /// <para> /// The goal of this class is to <see cref="M:PatternLayout.Format(TextWriter,LoggingEvent)"/> a /// <see cref="LoggingEvent"/> as a string. The results /// depend on the <i>conversion pattern</i>. /// </para> /// <para> /// The conversion pattern is closely related to the conversion /// pattern of the printf function in C. A conversion pattern is /// composed of literal text and format control expressions called /// <i>conversion specifiers</i>. /// </para> /// <para> /// <i>You are free to insert any literal text within the conversion /// pattern.</i> /// </para> /// <para> /// Each conversion specifier starts with a percent sign (%) and is /// followed by optional <i>format modifiers</i> and a <i>conversion /// pattern name</i>. The conversion pattern name specifies the type of /// data, e.g. logger, level, date, thread name. The format /// modifiers control such things as field width, padding, left and /// right justification. The following is a simple example. /// </para> /// <para> /// Let the conversion pattern be <b>"%-5level [%thread]: %message%newline"</b> and assume /// that the log4net environment was set to use a PatternLayout. Then the /// statements /// </para> /// <code lang="C#"> /// ILog log = LogManager.GetLogger(typeof(TestApp)); /// log.Debug("Message 1"); /// log.Warn("Message 2"); /// </code> /// <para>would yield the output</para> /// <code> /// DEBUG [main]: Message 1 /// WARN [main]: Message 2 /// </code> /// <para> /// Note that there is no explicit separator between text and /// conversion specifiers. The pattern parser knows when it has reached /// the end of a conversion specifier when it reads a conversion /// character. In the example above the conversion specifier /// <b>%-5level</b> means the level of the logging event should be left /// justified to a width of five characters. /// </para> /// <para> /// The recognized conversion pattern names are: /// </para> /// <list type="table"> /// <listheader> /// <term>Conversion Pattern Name</term> /// <description>Effect</description> /// </listheader> /// <item> /// <term>a</term> /// <description>Equivalent to <b>appdomain</b></description> /// </item> /// <item> /// <term>appdomain</term> /// <description> /// Used to output the friendly name of the AppDomain where the /// logging event was generated. /// </description> /// </item> /// <item> /// <term>aspnet-cache</term> /// <description> /// <para> /// Used to output all cache items in the case of <b>%aspnet-cache</b> or just one named item if used as <b>%aspnet-cache{key}</b> /// </para> /// <para> /// This pattern is not available for Compact Framework or Client Profile assemblies. /// </para> /// </description> /// </item> /// <item> /// <term>aspnet-context</term> /// <description> /// <para> /// Used to output all context items in the case of <b>%aspnet-context</b> or just one named item if used as <b>%aspnet-context{key}</b> /// </para> /// <para> /// This pattern is not available for Compact Framework or Client Profile assemblies. /// </para> /// </description> /// </item> /// <item> /// <term>aspnet-request</term> /// <description> /// <para> /// Used to output all request parameters in the case of <b>%aspnet-request</b> or just one named param if used as <b>%aspnet-request{key}</b> /// </para> /// <para> /// This pattern is not available for Compact Framework or Client Profile assemblies. /// </para> /// </description> /// </item> /// <item> /// <term>aspnet-session</term> /// <description> /// <para> /// Used to output all session items in the case of <b>%aspnet-session</b> or just one named item if used as <b>%aspnet-session{key}</b> /// </para> /// <para> /// This pattern is not available for Compact Framework or Client Profile assemblies. /// </para> /// </description> /// </item> /// <item> /// <term>c</term> /// <description>Equivalent to <b>logger</b></description> /// </item> /// <item> /// <term>C</term> /// <description>Equivalent to <b>type</b></description> /// </item> /// <item> /// <term>class</term> /// <description>Equivalent to <b>type</b></description> /// </item> /// <item> /// <term>d</term> /// <description>Equivalent to <b>date</b></description> /// </item> /// <item> /// <term>date</term> /// <description> /// <para> /// Used to output the date of the logging event in the local time zone. /// To output the date in universal time use the <c>%utcdate</c> pattern. /// The date conversion /// specifier may be followed by a <i>date format specifier</i> enclosed /// between braces. For example, <b>%date{HH:mm:ss,fff}</b> or /// <b>%date{dd MMM yyyy HH:mm:ss,fff}</b>. If no date format specifier is /// given then ISO8601 format is /// assumed (<see cref="log4net.DateFormatter.Iso8601DateFormatter"/>). /// </para> /// <para> /// The date format specifier admits the same syntax as the /// time pattern string of the <see cref="M:DateTime.ToString(string)"/>. /// </para> /// <para> /// For better results it is recommended to use the log4net date /// formatters. These can be specified using one of the strings /// "ABSOLUTE", "DATE" and "ISO8601" for specifying /// <see cref="log4net.DateFormatter.AbsoluteTimeDateFormatter"/>, /// <see cref="log4net.DateFormatter.DateTimeDateFormatter"/> and respectively /// <see cref="log4net.DateFormatter.Iso8601DateFormatter"/>. For example, /// <b>%date{ISO8601}</b> or <b>%date{ABSOLUTE}</b>. /// </para> /// <para> /// These dedicated date formatters perform significantly /// better than <see cref="M:DateTime.ToString(string)"/>. /// </para> /// </description> /// </item> /// <item> /// <term>exception</term> /// <description> /// <para> /// Used to output the exception passed in with the log message. /// </para> /// <para> /// If an exception object is stored in the logging event /// it will be rendered into the pattern output with a /// trailing newline. /// If there is no exception then nothing will be output /// and no trailing newline will be appended. /// It is typical to put a newline before the exception /// and to have the exception as the last data in the pattern. /// </para> /// </description> /// </item> /// <item> /// <term>F</term> /// <description>Equivalent to <b>file</b></description> /// </item> /// <item> /// <term>file</term> /// <description> /// <para> /// Used to output the file name where the logging request was /// issued. /// </para> /// <para> /// <b>WARNING</b> Generating caller location information is /// extremely slow. Its use should be avoided unless execution speed /// is not an issue. /// </para> /// <para> /// See the note below on the availability of caller location information. /// </para> /// </description> /// </item> /// <item> /// <term>identity</term> /// <description> /// <para> /// Used to output the user name for the currently active user /// (Principal.Identity.Name). /// </para> /// <para> /// <b>WARNING</b> Generating caller information is /// extremely slow. Its use should be avoided unless execution speed /// is not an issue. /// </para> /// </description> /// </item> /// <item> /// <term>l</term> /// <description>Equivalent to <b>location</b></description> /// </item> /// <item> /// <term>L</term> /// <description>Equivalent to <b>line</b></description> /// </item> /// <item> /// <term>location</term> /// <description> /// <para> /// Used to output location information of the caller which generated /// the logging event. /// </para> /// <para> /// The location information depends on the CLI implementation but /// usually consists of the fully qualified name of the calling /// method followed by the callers source the file name and line /// number between parentheses. /// </para> /// <para> /// The location information can be very useful. However, its /// generation is <b>extremely</b> slow. Its use should be avoided /// unless execution speed is not an issue. /// </para> /// <para> /// See the note below on the availability of caller location information. /// </para> /// </description> /// </item> /// <item> /// <term>level</term> /// <description> /// <para> /// Used to output the level of the logging event. /// </para> /// </description> /// </item> /// <item> /// <term>line</term> /// <description> /// <para> /// Used to output the line number from where the logging request /// was issued. /// </para> /// <para> /// <b>WARNING</b> Generating caller location information is /// extremely slow. Its use should be avoided unless execution speed /// is not an issue. /// </para> /// <para> /// See the note below on the availability of caller location information. /// </para> /// </description> /// </item> /// <item> /// <term>logger</term> /// <description> /// <para> /// Used to output the logger of the logging event. The /// logger conversion specifier can be optionally followed by /// <i>precision specifier</i>, that is a decimal constant in /// brackets. /// </para> /// <para> /// If a precision specifier is given, then only the corresponding /// number of right most components of the logger name will be /// printed. By default the logger name is printed in full. /// </para> /// <para> /// For example, for the logger name "a.b.c" the pattern /// <b>%logger{2}</b> will output "b.c". /// </para> /// </description> /// </item> /// <item> /// <term>m</term> /// <description>Equivalent to <b>message</b></description> /// </item> /// <item> /// <term>M</term> /// <description>Equivalent to <b>method</b></description> /// </item> /// <item> /// <term>message</term> /// <description> /// <para> /// Used to output the application supplied message associated with /// the logging event. /// </para> /// </description> /// </item> /// <item> /// <term>mdc</term> /// <description> /// <para> /// The MDC (old name for the ThreadContext.Properties) is now part of the /// combined event properties. This pattern is supported for compatibility /// but is equivalent to <b>property</b>. /// </para> /// </description> /// </item> /// <item> /// <term>method</term> /// <description> /// <para> /// Used to output the method name where the logging request was /// issued. /// </para> /// <para> /// <b>WARNING</b> Generating caller location information is /// extremely slow. Its use should be avoided unless execution speed /// is not an issue. /// </para> /// <para> /// See the note below on the availability of caller location information. /// </para> /// </description> /// </item> /// <item> /// <term>n</term> /// <description>Equivalent to <b>newline</b></description> /// </item> /// <item> /// <term>newline</term> /// <description> /// <para> /// Outputs the platform dependent line separator character or /// characters. /// </para> /// <para> /// This conversion pattern offers the same performance as using /// non-portable line separator strings such as "\n", or "\r\n". /// Thus, it is the preferred way of specifying a line separator. /// </para> /// </description> /// </item> /// <item> /// <term>ndc</term> /// <description> /// <para> /// Used to output the NDC (nested diagnostic context) associated /// with the thread that generated the logging event. /// </para> /// </description> /// </item> /// <item> /// <term>p</term> /// <description>Equivalent to <b>level</b></description> /// </item> /// <item> /// <term>P</term> /// <description>Equivalent to <b>property</b></description> /// </item> /// <item> /// <term>properties</term> /// <description>Equivalent to <b>property</b></description> /// </item> /// <item> /// <term>property</term> /// <description> /// <para> /// Used to output the an event specific property. The key to /// lookup must be specified within braces and directly following the /// pattern specifier, e.g. <b>%property{user}</b> would include the value /// from the property that is keyed by the string 'user'. Each property value /// that is to be included in the log must be specified separately. /// Properties are added to events by loggers or appenders. By default /// the <c>log4net:HostName</c> property is set to the name of machine on /// which the event was originally logged. /// </para> /// <para> /// If no key is specified, e.g. <b>%property</b> then all the keys and their /// values are printed in a comma separated list. /// </para> /// <para> /// The properties of an event are combined from a number of different /// contexts. These are listed below in the order in which they are searched. /// </para> /// <list type="definition"> /// <item> /// <term>the event properties</term> /// <description> /// The event has <see cref="LoggingEvent.Properties"/> that can be set. These /// properties are specific to this event only. /// </description> /// </item> /// <item> /// <term>the thread properties</term> /// <description> /// The <see cref="ThreadContext.Properties"/> that are set on the current /// thread. These properties are shared by all events logged on this thread. /// </description> /// </item> /// <item> /// <term>the global properties</term> /// <description> /// The <see cref="GlobalContext.Properties"/> that are set globally. These /// properties are shared by all the threads in the AppDomain. /// </description> /// </item> /// </list> /// /// </description> /// </item> /// <item> /// <term>r</term> /// <description>Equivalent to <b>timestamp</b></description> /// </item> /// <item> /// <term>stacktrace</term> /// <description> /// <para> /// Used to output the stack trace of the logging event /// The stack trace level specifier may be enclosed /// between braces. For example, <b>%stacktrace{level}</b>. /// If no stack trace level specifier is given then 1 is assumed /// </para> /// <para> /// Output uses the format: /// type3.MethodCall3 > type2.MethodCall2 > type1.MethodCall1 /// </para> /// <para> /// This pattern is not available for Compact Framework assemblies. /// </para> /// </description> /// </item> /// <item> /// <term>stacktracedetail</term> /// <description> /// <para> /// Used to output the stack trace of the logging event /// The stack trace level specifier may be enclosed /// between braces. For example, <b>%stacktracedetail{level}</b>. /// If no stack trace level specifier is given then 1 is assumed /// </para> /// <para> /// Output uses the format: /// type3.MethodCall3(type param,...) > type2.MethodCall2(type param,...) > type1.MethodCall1(type param,...) /// </para> /// <para> /// This pattern is not available for Compact Framework assemblies. /// </para> /// </description> /// </item> /// <item> /// <term>t</term> /// <description>Equivalent to <b>thread</b></description> /// </item> /// <item> /// <term>timestamp</term> /// <description> /// <para> /// Used to output the number of milliseconds elapsed since the start /// of the application until the creation of the logging event. /// </para> /// </description> /// </item> /// <item> /// <term>thread</term> /// <description> /// <para> /// Used to output the name of the thread that generated the /// logging event. Uses the thread number if no name is available. /// </para> /// </description> /// </item> /// <item> /// <term>type</term> /// <description> /// <para> /// Used to output the fully qualified type name of the caller /// issuing the logging request. This conversion specifier /// can be optionally followed by <i>precision specifier</i>, that /// is a decimal constant in brackets. /// </para> /// <para> /// If a precision specifier is given, then only the corresponding /// number of right most components of the class name will be /// printed. By default the class name is output in fully qualified form. /// </para> /// <para> /// For example, for the class name "log4net.Layout.PatternLayout", the /// pattern <b>%type{1}</b> will output "PatternLayout". /// </para> /// <para> /// <b>WARNING</b> Generating the caller class information is /// slow. Thus, its use should be avoided unless execution speed is /// not an issue. /// </para> /// <para> /// See the note below on the availability of caller location information. /// </para> /// </description> /// </item> /// <item> /// <term>u</term> /// <description>Equivalent to <b>identity</b></description> /// </item> /// <item> /// <term>username</term> /// <description> /// <para> /// Used to output the WindowsIdentity for the currently /// active user. /// </para> /// <para> /// <b>WARNING</b> Generating caller WindowsIdentity information is /// extremely slow. Its use should be avoided unless execution speed /// is not an issue. /// </para> /// </description> /// </item> /// <item> /// <term>utcdate</term> /// <description> /// <para> /// Used to output the date of the logging event in universal time. /// The date conversion /// specifier may be followed by a <i>date format specifier</i> enclosed /// between braces. For example, <b>%utcdate{HH:mm:ss,fff}</b> or /// <b>%utcdate{dd MMM yyyy HH:mm:ss,fff}</b>. If no date format specifier is /// given then ISO8601 format is /// assumed (<see cref="log4net.DateFormatter.Iso8601DateFormatter"/>). /// </para> /// <para> /// The date format specifier admits the same syntax as the /// time pattern string of the <see cref="M:DateTime.ToString(string)"/>. /// </para> /// <para> /// For better results it is recommended to use the log4net date /// formatters. These can be specified using one of the strings /// "ABSOLUTE", "DATE" and "ISO8601" for specifying /// <see cref="log4net.DateFormatter.AbsoluteTimeDateFormatter"/>, /// <see cref="log4net.DateFormatter.DateTimeDateFormatter"/> and respectively /// <see cref="log4net.DateFormatter.Iso8601DateFormatter"/>. For example, /// <b>%utcdate{ISO8601}</b> or <b>%utcdate{ABSOLUTE}</b>. /// </para> /// <para> /// These dedicated date formatters perform significantly /// better than <see cref="M:DateTime.ToString(string)"/>. /// </para> /// </description> /// </item> /// <item> /// <term>w</term> /// <description>Equivalent to <b>username</b></description> /// </item> /// <item> /// <term>x</term> /// <description>Equivalent to <b>ndc</b></description> /// </item> /// <item> /// <term>X</term> /// <description>Equivalent to <b>mdc</b></description> /// </item> /// <item> /// <term>%</term> /// <description> /// <para> /// The sequence %% outputs a single percent sign. /// </para> /// </description> /// </item> /// </list> /// <para> /// The single letter patterns are deprecated in favor of the /// longer more descriptive pattern names. /// </para> /// <para> /// By default the relevant information is output as is. However, /// with the aid of format modifiers it is possible to change the /// minimum field width, the maximum field width and justification. /// </para> /// <para> /// The optional format modifier is placed between the percent sign /// and the conversion pattern name. /// </para> /// <para> /// The first optional format modifier is the <i>left justification /// flag</i> which is just the minus (-) character. Then comes the /// optional <i>minimum field width</i> modifier. This is a decimal /// constant that represents the minimum number of characters to /// output. If the data item requires fewer characters, it is padded on /// either the left or the right until the minimum width is /// reached. The default is to pad on the left (right justify) but you /// can specify right padding with the left justification flag. The /// padding character is space. If the data item is larger than the /// minimum field width, the field is expanded to accommodate the /// data. The value is never truncated. /// </para> /// <para> /// This behavior can be changed using the <i>maximum field /// width</i> modifier which is designated by a period followed by a /// decimal constant. If the data item is longer than the maximum /// field, then the extra characters are removed from the /// <i>beginning</i> of the data item and not from the end. For /// example, it the maximum field width is eight and the data item is /// ten characters long, then the first two characters of the data item /// are dropped. This behavior deviates from the printf function in C /// where truncation is done from the end. /// </para> /// <para> /// Below are various format modifier examples for the logger /// conversion specifier. /// </para> /// <div class="tablediv"> /// <table class="dtTABLE" cellspacing="0"> /// <tr> /// <th>Format modifier</th> /// <th>left justify</th> /// <th>minimum width</th> /// <th>maximum width</th> /// <th>comment</th> /// </tr> /// <tr> /// <td align="center">%20logger</td> /// <td align="center">false</td> /// <td align="center">20</td> /// <td align="center">none</td> /// <td> /// <para> /// Left pad with spaces if the logger name is less than 20 /// characters long. /// </para> /// </td> /// </tr> /// <tr> /// <td align="center">%-20logger</td> /// <td align="center">true</td> /// <td align="center">20</td> /// <td align="center">none</td> /// <td> /// <para> /// Right pad with spaces if the logger /// name is less than 20 characters long. /// </para> /// </td> /// </tr> /// <tr> /// <td align="center">%.30logger</td> /// <td align="center">NA</td> /// <td align="center">none</td> /// <td align="center">30</td> /// <td> /// <para> /// Truncate from the beginning if the logger /// name is longer than 30 characters. /// </para> /// </td> /// </tr> /// <tr> /// <td align="center"><nobr>%20.30logger</nobr></td> /// <td align="center">false</td> /// <td align="center">20</td> /// <td align="center">30</td> /// <td> /// <para> /// Left pad with spaces if the logger name is shorter than 20 /// characters. However, if logger name is longer than 30 characters, /// then truncate from the beginning. /// </para> /// </td> /// </tr> /// <tr> /// <td align="center">%-20.30logger</td> /// <td align="center">true</td> /// <td align="center">20</td> /// <td align="center">30</td> /// <td> /// <para> /// Right pad with spaces if the logger name is shorter than 20 /// characters. However, if logger name is longer than 30 characters, /// then truncate from the beginning. /// </para> /// </td> /// </tr> /// </table> /// </div> /// <para> /// <b>Note about caller location information.</b><br /> /// The following patterns <c>%type %file %line %method %location %class %C %F %L %l %M</c> /// all generate caller location information. /// Location information uses the <c>System.Diagnostics.StackTrace</c> class to generate /// a call stack. The caller's information is then extracted from this stack. /// </para> /// <note type="caution"> /// <para> /// The <c>System.Diagnostics.StackTrace</c> class is not supported on the /// .NET Compact Framework 1.0 therefore caller location information is not /// available on that framework. /// </para> /// </note> /// <note type="caution"> /// <para> /// The <c>System.Diagnostics.StackTrace</c> class has this to say about Release builds: /// </para> /// <para> /// "StackTrace information will be most informative with Debug build configurations. /// By default, Debug builds include debug symbols, while Release builds do not. The /// debug symbols contain most of the file, method name, line number, and column /// information used in constructing StackFrame and StackTrace objects. StackTrace /// might not report as many method calls as expected, due to code transformations /// that occur during optimization." /// </para> /// <para> /// This means that in a Release build the caller information may be incomplete or may /// not exist at all! Therefore caller location information cannot be relied upon in a Release build. /// </para> /// </note> /// <para> /// Additional pattern converters may be registered with a specific <see cref="PatternLayout"/> /// instance using the <see cref="M:AddConverter(string, Type)"/> method. /// </para> /// </remarks> /// <example> /// This is a more detailed pattern. /// <code><b>%timestamp [%thread] %level %logger %ndc - %message%newline</b></code> /// </example> /// <example> /// A similar pattern except that the relative time is /// right padded if less than 6 digits, thread name is right padded if /// less than 15 characters and truncated if longer and the logger /// name is left padded if shorter than 30 characters and truncated if /// longer. /// <code><b>%-6timestamp [%15.15thread] %-5level %30.30logger %ndc - %message%newline</b></code> /// </example> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> /// <author>Douglas de la Torre</author> /// <author>Daniel Cazzulino</author> public class PatternLayout : LayoutSkeleton { #region Constants /// <summary> /// Default pattern string for log output. /// </summary> /// <remarks> /// <para> /// Default pattern string for log output. /// Currently set to the string <b>"%message%newline"</b> /// which just prints the application supplied message. /// </para> /// </remarks> public const string DefaultConversionPattern ="%message%newline"; /// <summary> /// A detailed conversion pattern /// </summary> /// <remarks> /// <para> /// A conversion pattern which includes Time, Thread, Logger, and Nested Context. /// Current value is <b>%timestamp [%thread] %level %logger %ndc - %message%newline</b>. /// </para> /// </remarks> public const string DetailConversionPattern = "%timestamp [%thread] %level %logger %ndc - %message%newline"; #endregion #region Static Fields /// <summary> /// Internal map of converter identifiers to converter types. /// </summary> /// <remarks> /// <para> /// This static map is overridden by the m_converterRegistry instance map /// </para> /// </remarks> private static Hashtable s_globalRulesRegistry; #endregion Static Fields #region Member Variables /// <summary> /// the pattern /// </summary> private string m_pattern; /// <summary> /// the head of the pattern converter chain /// </summary> private PatternConverter m_head; /// <summary> /// patterns defined on this PatternLayout only /// </summary> private Hashtable m_instanceRulesRegistry = new Hashtable(); #endregion #region Static Constructor /// <summary> /// Initialize the global registry /// </summary> /// <remarks> /// <para> /// Defines the builtin global rules. /// </para> /// </remarks> static PatternLayout() { s_globalRulesRegistry = new Hashtable(45); s_globalRulesRegistry.Add("literal", typeof(LiteralPatternConverter)); s_globalRulesRegistry.Add("newline", typeof(NewLinePatternConverter)); s_globalRulesRegistry.Add("n", typeof(NewLinePatternConverter)); // .NET Compact Framework 1.0 has no support for ASP.NET // SSCLI 1.0 has no support for ASP.NET #if !NETCF && !SSCLI && !CLIENT_PROFILE && !MONO_IOS s_globalRulesRegistry.Add("aspnet-cache", typeof(AspNetCachePatternConverter)); s_globalRulesRegistry.Add("aspnet-context", typeof(AspNetContextPatternConverter)); s_globalRulesRegistry.Add("aspnet-request", typeof(AspNetRequestPatternConverter)); s_globalRulesRegistry.Add("aspnet-session", typeof(AspNetSessionPatternConverter)); #endif s_globalRulesRegistry.Add("c", typeof(LoggerPatternConverter)); s_globalRulesRegistry.Add("logger", typeof(LoggerPatternConverter)); s_globalRulesRegistry.Add("C", typeof(TypeNamePatternConverter)); s_globalRulesRegistry.Add("class", typeof(TypeNamePatternConverter)); s_globalRulesRegistry.Add("type", typeof(TypeNamePatternConverter)); s_globalRulesRegistry.Add("d", typeof(DatePatternConverter)); s_globalRulesRegistry.Add("date", typeof(DatePatternConverter)); s_globalRulesRegistry.Add("exception", typeof(ExceptionPatternConverter)); s_globalRulesRegistry.Add("F", typeof(FileLocationPatternConverter)); s_globalRulesRegistry.Add("file", typeof(FileLocationPatternConverter)); s_globalRulesRegistry.Add("l", typeof(FullLocationPatternConverter)); s_globalRulesRegistry.Add("location", typeof(FullLocationPatternConverter)); s_globalRulesRegistry.Add("L", typeof(LineLocationPatternConverter)); s_globalRulesRegistry.Add("line", typeof(LineLocationPatternConverter)); s_globalRulesRegistry.Add("m", typeof(MessagePatternConverter)); s_globalRulesRegistry.Add("message", typeof(MessagePatternConverter)); s_globalRulesRegistry.Add("M", typeof(MethodLocationPatternConverter)); s_globalRulesRegistry.Add("method", typeof(MethodLocationPatternConverter)); s_globalRulesRegistry.Add("p", typeof(LevelPatternConverter)); s_globalRulesRegistry.Add("level", typeof(LevelPatternConverter)); s_globalRulesRegistry.Add("P", typeof(PropertyPatternConverter)); s_globalRulesRegistry.Add("property", typeof(PropertyPatternConverter)); s_globalRulesRegistry.Add("properties", typeof(PropertyPatternConverter)); s_globalRulesRegistry.Add("r", typeof(RelativeTimePatternConverter)); s_globalRulesRegistry.Add("timestamp", typeof(RelativeTimePatternConverter)); #if !NETCF s_globalRulesRegistry.Add("stacktrace", typeof(StackTracePatternConverter)); s_globalRulesRegistry.Add("stacktracedetail", typeof(StackTraceDetailPatternConverter)); #endif s_globalRulesRegistry.Add("t", typeof(ThreadPatternConverter)); s_globalRulesRegistry.Add("thread", typeof(ThreadPatternConverter)); // For backwards compatibility the NDC patterns s_globalRulesRegistry.Add("x", typeof(NdcPatternConverter)); s_globalRulesRegistry.Add("ndc", typeof(NdcPatternConverter)); // For backwards compatibility the MDC patterns just do a property lookup s_globalRulesRegistry.Add("X", typeof(PropertyPatternConverter)); s_globalRulesRegistry.Add("mdc", typeof(PropertyPatternConverter)); s_globalRulesRegistry.Add("a", typeof(AppDomainPatternConverter)); s_globalRulesRegistry.Add("appdomain", typeof(AppDomainPatternConverter)); s_globalRulesRegistry.Add("u", typeof(IdentityPatternConverter)); s_globalRulesRegistry.Add("identity", typeof(IdentityPatternConverter)); s_globalRulesRegistry.Add("utcdate", typeof(UtcDatePatternConverter)); s_globalRulesRegistry.Add("utcDate", typeof(UtcDatePatternConverter)); s_globalRulesRegistry.Add("UtcDate", typeof(UtcDatePatternConverter)); s_globalRulesRegistry.Add("w", typeof(UserNamePatternConverter)); s_globalRulesRegistry.Add("username", typeof(UserNamePatternConverter)); } #endregion Static Constructor #region Constructors /// <summary> /// Constructs a PatternLayout using the DefaultConversionPattern /// </summary> /// <remarks> /// <para> /// The default pattern just produces the application supplied message. /// </para> /// <para> /// Note to Inheritors: This constructor calls the virtual method /// <see cref="CreatePatternParser"/>. If you override this method be /// aware that it will be called before your is called constructor. /// </para> /// <para> /// As per the <see cref="IOptionHandler"/> contract the <see cref="ActivateOptions"/> /// method must be called after the properties on this object have been /// configured. /// </para> /// </remarks> public PatternLayout() : this(DefaultConversionPattern) { } /// <summary> /// Constructs a PatternLayout using the supplied conversion pattern /// </summary> /// <param name="pattern">the pattern to use</param> /// <remarks> /// <para> /// Note to Inheritors: This constructor calls the virtual method /// <see cref="CreatePatternParser"/>. If you override this method be /// aware that it will be called before your is called constructor. /// </para> /// <para> /// When using this constructor the <see cref="ActivateOptions"/> method /// need not be called. This may not be the case when using a subclass. /// </para> /// </remarks> public PatternLayout(string pattern) { // By default we do not process the exception IgnoresException = true; m_pattern = pattern; if (m_pattern == null) { m_pattern = DefaultConversionPattern; } ActivateOptions(); } #endregion /// <summary> /// The pattern formatting string /// </summary> /// <remarks> /// <para> /// The <b>ConversionPattern</b> option. This is the string which /// controls formatting and consists of a mix of literal content and /// conversion specifiers. /// </para> /// </remarks> public string ConversionPattern { get { return m_pattern; } set { m_pattern = value; } } /// <summary> /// Create the pattern parser instance /// </summary> /// <param name="pattern">the pattern to parse</param> /// <returns>The <see cref="PatternParser"/> that will format the event</returns> /// <remarks> /// <para> /// Creates the <see cref="PatternParser"/> used to parse the conversion string. Sets the /// global and instance rules on the <see cref="PatternParser"/>. /// </para> /// </remarks> virtual protected PatternParser CreatePatternParser(string pattern) { PatternParser patternParser = new PatternParser(pattern); // Add all the builtin patterns foreach(DictionaryEntry entry in s_globalRulesRegistry) { ConverterInfo converterInfo = new ConverterInfo(); converterInfo.Name = (string)entry.Key; converterInfo.Type = (Type)entry.Value; patternParser.PatternConverters[entry.Key] = converterInfo; } // Add the instance patterns foreach(DictionaryEntry entry in m_instanceRulesRegistry) { patternParser.PatternConverters[entry.Key] = entry.Value; } return patternParser; } #region Implementation of IOptionHandler /// <summary> /// Initialize layout options /// </summary> /// <remarks> /// <para> /// This is part of the <see cref="IOptionHandler"/> delayed object /// activation scheme. The <see cref="ActivateOptions"/> method must /// be called on this object after the configuration properties have /// been set. Until <see cref="ActivateOptions"/> is called this /// object is in an undefined state and must not be used. /// </para> /// <para> /// If any of the configuration properties are modified then /// <see cref="ActivateOptions"/> must be called again. /// </para> /// </remarks> override public void ActivateOptions() { m_head = CreatePatternParser(m_pattern).Parse(); PatternConverter curConverter = m_head; while(curConverter != null) { PatternLayoutConverter layoutConverter = curConverter as PatternLayoutConverter; if (layoutConverter != null) { if (!layoutConverter.IgnoresException) { // Found converter that handles the exception this.IgnoresException = false; break; } } curConverter = curConverter.Next; } } #endregion #region Override implementation of LayoutSkeleton /// <summary> /// Produces a formatted string as specified by the conversion pattern. /// </summary> /// <param name="loggingEvent">the event being logged</param> /// <param name="writer">The TextWriter to write the formatted event to</param> /// <remarks> /// <para> /// Parse the <see cref="LoggingEvent"/> using the patter format /// specified in the <see cref="ConversionPattern"/> property. /// </para> /// </remarks> override public void Format(TextWriter writer, LoggingEvent loggingEvent) { if (writer == null) { throw new ArgumentNullException("writer"); } if (loggingEvent == null) { throw new ArgumentNullException("loggingEvent"); } PatternConverter c = m_head; // loop through the chain of pattern converters while(c != null) { c.Format(writer, loggingEvent); c = c.Next; } } #endregion /// <summary> /// Add a converter to this PatternLayout /// </summary> /// <param name="converterInfo">the converter info</param> /// <remarks> /// <para> /// This version of the method is used by the configurator. /// Programmatic users should use the alternative <see cref="M:AddConverter(string,Type)"/> method. /// </para> /// </remarks> public void AddConverter(ConverterInfo converterInfo) { if (converterInfo == null) throw new ArgumentNullException("converterInfo"); if (!typeof(PatternConverter).IsAssignableFrom(converterInfo.Type)) { throw new ArgumentException("The converter type specified [" + converterInfo.Type + "] must be a subclass of log4net.Util.PatternConverter", "converterInfo"); } m_instanceRulesRegistry[converterInfo.Name] = converterInfo; } /// <summary> /// Add a converter to this PatternLayout /// </summary> /// <param name="name">the name of the conversion pattern for this converter</param> /// <param name="type">the type of the converter</param> /// <remarks> /// <para> /// Add a named pattern converter to this instance. This /// converter will be used in the formatting of the event. /// This method must be called before <see cref="ActivateOptions"/>. /// </para> /// <para> /// The <paramref name="type"/> specified must extend the /// <see cref="PatternConverter"/> type. /// </para> /// </remarks> public void AddConverter(string name, Type type) { if (name == null) throw new ArgumentNullException("name"); if (type == null) throw new ArgumentNullException("type"); ConverterInfo converterInfo = new ConverterInfo(); converterInfo.Name = name; converterInfo.Type = type; AddConverter(converterInfo); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Collections.ArrayList.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Collections { public partial class ArrayList : IList, ICollection, IEnumerable, ICloneable { #region Methods and constructors public static System.Collections.ArrayList Adapter(IList list) { Contract.Ensures(Contract.Result<System.Collections.ArrayList>() != null); return default(System.Collections.ArrayList); } public virtual new int Add(Object value) { return default(int); } public virtual new void AddRange(ICollection c) { } public ArrayList() { } public ArrayList(int capacity) { } public ArrayList(ICollection c) { Contract.Requires(0 <= c.Count); } public virtual new int BinarySearch(Object value, IComparer comparer) { return default(int); } public virtual new int BinarySearch(Object value) { return default(int); } public virtual new int BinarySearch(int index, int count, Object value, IComparer comparer) { return default(int); } public virtual new void Clear() { } public virtual new Object Clone() { return default(Object); } public virtual new bool Contains(Object item) { return default(bool); } public virtual new void CopyTo(int index, Array array, int arrayIndex, int count) { } public virtual new void CopyTo(Array array) { } public virtual new void CopyTo(Array array, int arrayIndex) { } public static IList FixedSize(IList list) { Contract.Ensures(Contract.Result<System.Collections.IList>() != null); return default(IList); } public static System.Collections.ArrayList FixedSize(System.Collections.ArrayList list) { Contract.Ensures(Contract.Result<System.Collections.ArrayList>() != null); return default(System.Collections.ArrayList); } public virtual new IEnumerator GetEnumerator() { return default(IEnumerator); } public virtual new IEnumerator GetEnumerator(int index, int count) { return default(IEnumerator); } public virtual new System.Collections.ArrayList GetRange(int index, int count) { return default(System.Collections.ArrayList); } public virtual new int IndexOf(Object value, int startIndex) { return default(int); } public virtual new int IndexOf(Object value) { return default(int); } public virtual new int IndexOf(Object value, int startIndex, int count) { return default(int); } public virtual new void Insert(int index, Object value) { } public virtual new void InsertRange(int index, ICollection c) { } public virtual new int LastIndexOf(Object value, int startIndex, int count) { return default(int); } public virtual new int LastIndexOf(Object value, int startIndex) { return default(int); } public virtual new int LastIndexOf(Object value) { return default(int); } public static System.Collections.ArrayList ReadOnly(System.Collections.ArrayList list) { Contract.Ensures(Contract.Result<System.Collections.ArrayList>() != null); return default(System.Collections.ArrayList); } public static IList ReadOnly(IList list) { Contract.Ensures(Contract.Result<System.Collections.IList>() != null); return default(IList); } public virtual new void Remove(Object obj) { } public virtual new void RemoveAt(int index) { } public virtual new void RemoveRange(int index, int count) { } public static System.Collections.ArrayList Repeat(Object value, int count) { Contract.Ensures(Contract.Result<System.Collections.ArrayList>() != null); return default(System.Collections.ArrayList); } public virtual new void Reverse(int index, int count) { } public virtual new void Reverse() { } public virtual new void SetRange(int index, ICollection c) { } public virtual new void Sort(IComparer comparer) { } public virtual new void Sort(int index, int count, IComparer comparer) { } public virtual new void Sort() { } public static System.Collections.ArrayList Synchronized(System.Collections.ArrayList list) { Contract.Ensures(Contract.Result<System.Collections.ArrayList>() != null); return default(System.Collections.ArrayList); } public static IList Synchronized(IList list) { Contract.Ensures(Contract.Result<System.Collections.IList>() != null); return default(IList); } public virtual new Array ToArray(Type type) { return default(Array); } public virtual new Object[] ToArray() { return default(Object[]); } public virtual new void TrimToSize() { } #endregion #region Properties and indexers public virtual new int Capacity { get { return default(int); } set { } } public virtual new int Count { get { return default(int); } } public virtual new bool IsFixedSize { get { return default(bool); } } public virtual new bool IsReadOnly { get { return default(bool); } } public virtual new bool IsSynchronized { get { return default(bool); } } public virtual new Object this [int index] { get { return default(Object); } set { } } public virtual new Object SyncRoot { get { return default(Object); } } #endregion } }
#region --- License --- /* Copyright (c) 2006 - 2008 The Open Toolkit library. 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.IO; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Xml.Serialization; namespace OpenTK.Math { /// <summary> /// 3-component Vector of the Half type. Occupies 6 Byte total. /// </summary> [Obsolete("OpenTK.Math functions have been moved to the root OpenTK namespace (reason: XNA compatibility")] [Serializable, StructLayout(LayoutKind.Sequential)] public struct Vector3h : ISerializable, IEquatable<Vector3h> { #region Public Fields /// <summary>The X component of the Half3.</summary> public Half X; /// <summary>The Y component of the Half3.</summary> public Half Y; /// <summary>The Z component of the Half3.</summary> public Half Z; #endregion Public Fields #region Constructors /// <summary> /// The new Half3 instance will avoid conversion and copy directly from the Half parameters. /// </summary> /// <param name="x">An Half instance of a 16-bit half-precision floating-point number.</param> /// <param name="y">An Half instance of a 16-bit half-precision floating-point number.</param> /// <param name="z">An Half instance of a 16-bit half-precision floating-point number.</param> public Vector3h(Half x, Half y, Half z) { this.X = x; this.Y = y; this.Z = z; } /// <summary> /// The new Half3 instance will convert the 3 parameters into 16-bit half-precision floating-point. /// </summary> /// <param name="x">32-bit single-precision floating-point number.</param> /// <param name="y">32-bit single-precision floating-point number.</param> /// <param name="z">32-bit single-precision floating-point number.</param> public Vector3h(Single x, Single y, Single z) { X = new Half(x); Y = new Half(y); Z = new Half(z); } /// <summary> /// The new Half3 instance will convert the 3 parameters into 16-bit half-precision floating-point. /// </summary> /// <param name="x">32-bit single-precision floating-point number.</param> /// <param name="y">32-bit single-precision floating-point number.</param> /// <param name="z">32-bit single-precision floating-point number.</param> /// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param> public Vector3h(Single x, Single y, Single z, bool throwOnError) { X = new Half(x, throwOnError); Y = new Half(y, throwOnError); Z = new Half(z, throwOnError); } /// <summary> /// The new Half3 instance will convert the Vector3 into 16-bit half-precision floating-point. /// </summary> /// <param name="v">OpenTK.Vector3</param> [CLSCompliant(false)] public Vector3h(Vector3 v) { X = new Half(v.X); Y = new Half(v.Y); Z = new Half(v.Z); } /// <summary> /// The new Half3 instance will convert the Vector3 into 16-bit half-precision floating-point. /// </summary> /// <param name="v">OpenTK.Vector3</param> /// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param> [CLSCompliant(false)] public Vector3h(Vector3 v, bool throwOnError) { X = new Half(v.X, throwOnError); Y = new Half(v.Y, throwOnError); Z = new Half(v.Z, throwOnError); } /// <summary> /// The new Half3 instance will convert the Vector3 into 16-bit half-precision floating-point. /// This is the fastest constructor. /// </summary> /// <param name="v">OpenTK.Vector3</param> public Vector3h(ref Vector3 v) { X = new Half(v.X); Y = new Half(v.Y); Z = new Half(v.Z); } /// <summary> /// The new Half3 instance will convert the Vector3 into 16-bit half-precision floating-point. /// </summary> /// <param name="v">OpenTK.Vector3</param> /// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param> public Vector3h(ref Vector3 v, bool throwOnError) { X = new Half(v.X, throwOnError); Y = new Half(v.Y, throwOnError); Z = new Half(v.Z, throwOnError); } /// <summary> /// The new Half3 instance will convert the Vector3d into 16-bit half-precision floating-point. /// </summary> /// <param name="v">OpenTK.Vector3d</param> public Vector3h(Vector3d v) { X = new Half(v.X); Y = new Half(v.Y); Z = new Half(v.Z); } /// <summary> /// The new Half3 instance will convert the Vector3d into 16-bit half-precision floating-point. /// </summary> /// <param name="v">OpenTK.Vector3d</param> /// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param> public Vector3h(Vector3d v, bool throwOnError) { X = new Half(v.X, throwOnError); Y = new Half(v.Y, throwOnError); Z = new Half(v.Z, throwOnError); } /// <summary> /// The new Half3 instance will convert the Vector3d into 16-bit half-precision floating-point. /// This is the faster constructor. /// </summary> /// <param name="v">OpenTK.Vector3d</param> [CLSCompliant(false)] public Vector3h(ref Vector3d v) { X = new Half(v.X); Y = new Half(v.Y); Z = new Half(v.Z); } /// <summary> /// The new Half3 instance will convert the Vector3d into 16-bit half-precision floating-point. /// </summary> /// <param name="v">OpenTK.Vector3d</param> /// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param> [CLSCompliant(false)] public Vector3h(ref Vector3d v, bool throwOnError) { X = new Half(v.X, throwOnError); Y = new Half(v.Y, throwOnError); Z = new Half(v.Z, throwOnError); } #endregion Constructors #region Swizzle /// <summary> /// Gets or sets an OpenTK.Vector2h with the X and Y components of this instance. /// </summary> [XmlIgnore] public Vector2h Xy { get { return new Vector2h(X, Y); } set { X = value.X; Y = value.Y; } } #endregion #region Half -> Single /// <summary> /// Returns this Half3 instance's contents as Vector3. /// </summary> /// <returns>OpenTK.Vector3</returns> public Vector3 ToVector3() { return new Vector3(X, Y, Z); } /// <summary> /// Returns this Half3 instance's contents as Vector3d. /// </summary> public Vector3d ToVector3d() { return new Vector3d(X, Y, Z); } #endregion Half -> Single #region Conversions /// <summary>Converts OpenTK.Vector3 to OpenTK.Half3.</summary> /// <param name="v3f">The Vector3 to convert.</param> /// <returns>The resulting Half vector.</returns> public static explicit operator Vector3h(Vector3 v3f) { return new Vector3h(v3f); } /// <summary>Converts OpenTK.Vector3d to OpenTK.Half3.</summary> /// <param name="v3d">The Vector3d to convert.</param> /// <returns>The resulting Half vector.</returns> public static explicit operator Vector3h(Vector3d v3d) { return new Vector3h(v3d); } /// <summary>Converts OpenTK.Half3 to OpenTK.Vector3.</summary> /// <param name="h3">The Half3 to convert.</param> /// <returns>The resulting Vector3.</returns> public static explicit operator Vector3(Vector3h h3) { Vector3 result = new Vector3(); result.X = h3.X.ToSingle(); result.Y = h3.Y.ToSingle(); result.Z = h3.Z.ToSingle(); return result; } /// <summary>Converts OpenTK.Half3 to OpenTK.Vector3d.</summary> /// <param name="h3">The Half3 to convert.</param> /// <returns>The resulting Vector3d.</returns> public static explicit operator Vector3d(Vector3h h3) { Vector3d result = new Vector3d(); result.X = h3.X.ToSingle(); result.Y = h3.Y.ToSingle(); result.Z = h3.Z.ToSingle(); return result; } #endregion Conversions #region Constants /// <summary>The size in bytes for an instance of the Half3 struct is 6.</summary> public static readonly int SizeInBytes = 6; #endregion Constants #region ISerializable /// <summary>Constructor used by ISerializable to deserialize the object.</summary> /// <param name="info"></param> /// <param name="context"></param> public Vector3h(SerializationInfo info, StreamingContext context) { this.X = (Half)info.GetValue("X", typeof(Half)); this.Y = (Half)info.GetValue("Y", typeof(Half)); this.Z = (Half)info.GetValue("Z", typeof(Half)); } /// <summary>Used by ISerialize to serialize the object.</summary> /// <param name="info"></param> /// <param name="context"></param> public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("X", this.X); info.AddValue("Y", this.Y); info.AddValue("Z", this.Z); } #endregion ISerializable #region Binary dump /// <summary>Updates the X,Y and Z components of this instance by reading from a Stream.</summary> /// <param name="bin">A BinaryReader instance associated with an open Stream.</param> public void FromBinaryStream(BinaryReader bin) { X.FromBinaryStream(bin); Y.FromBinaryStream(bin); Z.FromBinaryStream(bin); } /// <summary>Writes the X,Y and Z components of this instance into a Stream.</summary> /// <param name="bin">A BinaryWriter instance associated with an open Stream.</param> public void ToBinaryStream(BinaryWriter bin) { X.ToBinaryStream(bin); Y.ToBinaryStream(bin); Z.ToBinaryStream(bin); } #endregion Binary dump #region IEquatable<Half3> Members /// <summary>Returns a value indicating whether this instance is equal to a specified OpenTK.Half3 vector.</summary> /// <param name="other">OpenTK.Half3 to compare to this instance..</param> /// <returns>True, if other is equal to this instance; false otherwise.</returns> public bool Equals(Vector3h other) { return (this.X.Equals(other.X) && this.Y.Equals(other.Y) && this.Z.Equals(other.Z)); } #endregion #region ToString() /// <summary>Returns a string that contains this Half3's numbers in human-legible form.</summary> public override string ToString() { return String.Format("({0}, {1}, {2})", X.ToString(), Y.ToString(), Z.ToString()); } #endregion ToString() #region BitConverter /// <summary>Returns the Half3 as an array of bytes.</summary> /// <param name="h">The Half3 to convert.</param> /// <returns>The input as byte array.</returns> public static byte[] GetBytes(Vector3h h) { byte[] result = new byte[SizeInBytes]; byte[] temp = Half.GetBytes(h.X); result[0] = temp[0]; result[1] = temp[1]; temp = Half.GetBytes(h.Y); result[2] = temp[0]; result[3] = temp[1]; temp = Half.GetBytes(h.Z); result[4] = temp[0]; result[5] = temp[1]; return result; } /// <summary>Converts an array of bytes into Half3.</summary> /// <param name="value">A Half3 in it's byte[] representation.</param> /// <param name="startIndex">The starting position within value.</param> /// <returns>A new Half3 instance.</returns> public static Vector3h FromBytes(byte[] value, int startIndex) { Vector3h h3 = new Vector3h(); h3.X = Half.FromBytes(value, startIndex); h3.Y = Half.FromBytes(value, startIndex + 2); h3.Z = Half.FromBytes(value, startIndex + 4); return h3; } #endregion BitConverter } }
// Description: Html Agility Pack - HTML Parsers, selectors, traversors, manupulators. // Website & Documentation: http://html-agility-pack.net // Forum & Issues: https://github.com/zzzprojects/html-agility-pack // License: https://github.com/zzzprojects/html-agility-pack/blob/master/LICENSE // More projects: http://www.zzzprojects.com/ // Copyright ?ZZZ Projects Inc. 2014 - 2017. All rights reserved. using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace ToolGood.ReadyGo3.Mvc.HtmlAgilityPack { /// <summary> /// A utility class to replace special characters by entities and vice-versa. /// Follows HTML 4.0 specification found at http://www.w3.org/TR/html4/sgml/entities.html /// Follows Additional specification found at https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references /// See also: https://html.spec.whatwg.org/multipage/named-characters.html#named-character-references /// </summary> public class HtmlEntity { #region Static Members private static readonly int _maxEntitySize; private static Dictionary<int, string> _entityName; private static Dictionary<string, int> _entityValue; /// <summary> /// A collection of entities indexed by name. /// </summary> public static Dictionary<int, string> EntityName { get { return _entityName; } } /// <summary> /// A collection of entities indexed by value. /// </summary> public static Dictionary<string, int> EntityValue { get { return _entityValue; } } #endregion #region Constructors static HtmlEntity() { _entityName = new Dictionary<int, string>(); _entityValue = new Dictionary<string, int>(); #region Entities Definition _entityValue.Add("quot", 34); // quotation mark = APL quote, U+0022 ISOnum _entityName.Add(34, "quot"); _entityValue.Add("amp", 38); // ampersand, U+0026 ISOnum _entityName.Add(38, "amp"); _entityValue.Add("apos", 39); // apostrophe-quote U+0027 (39) _entityName.Add(39, "apos"); _entityValue.Add("lt", 60); // less-than sign, U+003C ISOnum _entityName.Add(60, "lt"); _entityValue.Add("gt", 62); // greater-than sign, U+003E ISOnum _entityName.Add(62, "gt"); _entityValue.Add("nbsp", 160); // no-break space = non-breaking space, U+00A0 ISOnum _entityName.Add(160, "nbsp"); _entityValue.Add("iexcl", 161); // inverted exclamation mark, U+00A1 ISOnum _entityName.Add(161, "iexcl"); _entityValue.Add("cent", 162); // cent sign, U+00A2 ISOnum _entityName.Add(162, "cent"); _entityValue.Add("pound", 163); // pound sign, U+00A3 ISOnum _entityName.Add(163, "pound"); _entityValue.Add("curren", 164); // currency sign, U+00A4 ISOnum _entityName.Add(164, "curren"); _entityValue.Add("yen", 165); // yen sign = yuan sign, U+00A5 ISOnum _entityName.Add(165, "yen"); _entityValue.Add("brvbar", 166); // broken bar = broken vertical bar, U+00A6 ISOnum _entityName.Add(166, "brvbar"); _entityValue.Add("sect", 167); // section sign, U+00A7 ISOnum _entityName.Add(167, "sect"); _entityValue.Add("uml", 168); // diaeresis = spacing diaeresis, U+00A8 ISOdia _entityName.Add(168, "uml"); _entityValue.Add("copy", 169); // copyright sign, U+00A9 ISOnum _entityName.Add(169, "copy"); _entityValue.Add("ordf", 170); // feminine ordinal indicator, U+00AA ISOnum _entityName.Add(170, "ordf"); _entityValue.Add("laquo", 171); // left-pointing double angle quotation mark = left pointing guillemet, U+00AB ISOnum _entityName.Add(171, "laquo"); _entityValue.Add("not", 172); // not sign, U+00AC ISOnum _entityName.Add(172, "not"); _entityValue.Add("shy", 173); // soft hyphen = discretionary hyphen, U+00AD ISOnum _entityName.Add(173, "shy"); _entityValue.Add("reg", 174); // registered sign = registered trade mark sign, U+00AE ISOnum _entityName.Add(174, "reg"); _entityValue.Add("macr", 175); // macron = spacing macron = overline = APL overbar, U+00AF ISOdia _entityName.Add(175, "macr"); _entityValue.Add("deg", 176); // degree sign, U+00B0 ISOnum _entityName.Add(176, "deg"); _entityValue.Add("plusmn", 177); // plus-minus sign = plus-or-minus sign, U+00B1 ISOnum _entityName.Add(177, "plusmn"); _entityValue.Add("sup2", 178); // superscript two = superscript digit two = squared, U+00B2 ISOnum _entityName.Add(178, "sup2"); _entityValue.Add("sup3", 179); // superscript three = superscript digit three = cubed, U+00B3 ISOnum _entityName.Add(179, "sup3"); _entityValue.Add("acute", 180); // acute accent = spacing acute, U+00B4 ISOdia _entityName.Add(180, "acute"); _entityValue.Add("micro", 181); // micro sign, U+00B5 ISOnum _entityName.Add(181, "micro"); _entityValue.Add("para", 182); // pilcrow sign = paragraph sign, U+00B6 ISOnum _entityName.Add(182, "para"); _entityValue.Add("middot", 183); // middle dot = Georgian comma = Greek middle dot, U+00B7 ISOnum _entityName.Add(183, "middot"); _entityValue.Add("cedil", 184); // cedilla = spacing cedilla, U+00B8 ISOdia _entityName.Add(184, "cedil"); _entityValue.Add("sup1", 185); // superscript one = superscript digit one, U+00B9 ISOnum _entityName.Add(185, "sup1"); _entityValue.Add("ordm", 186); // masculine ordinal indicator, U+00BA ISOnum _entityName.Add(186, "ordm"); _entityValue.Add("raquo", 187); // right-pointing double angle quotation mark = right pointing guillemet, U+00BB ISOnum _entityName.Add(187, "raquo"); _entityValue.Add("frac14", 188); // vulgar fraction one quarter = fraction one quarter, U+00BC ISOnum _entityName.Add(188, "frac14"); _entityValue.Add("frac12", 189); // vulgar fraction one half = fraction one half, U+00BD ISOnum _entityName.Add(189, "frac12"); _entityValue.Add("frac34", 190); // vulgar fraction three quarters = fraction three quarters, U+00BE ISOnum _entityName.Add(190, "frac34"); _entityValue.Add("iquest", 191); // inverted question mark = turned question mark, U+00BF ISOnum _entityName.Add(191, "iquest"); _entityValue.Add("Agrave", 192); // latin capital letter A with grave = latin capital letter A grave, U+00C0 ISOlat1 _entityName.Add(192, "Agrave"); _entityValue.Add("Aacute", 193); // latin capital letter A with acute, U+00C1 ISOlat1 _entityName.Add(193, "Aacute"); _entityValue.Add("Acirc", 194); // latin capital letter A with circumflex, U+00C2 ISOlat1 _entityName.Add(194, "Acirc"); _entityValue.Add("Atilde", 195); // latin capital letter A with tilde, U+00C3 ISOlat1 _entityName.Add(195, "Atilde"); _entityValue.Add("Auml", 196); // latin capital letter A with diaeresis, U+00C4 ISOlat1 _entityName.Add(196, "Auml"); _entityValue.Add("Aring", 197); // latin capital letter A with ring above = latin capital letter A ring, U+00C5 ISOlat1 _entityName.Add(197, "Aring"); _entityValue.Add("AElig", 198); // latin capital letter AE = latin capital ligature AE, U+00C6 ISOlat1 _entityName.Add(198, "AElig"); _entityValue.Add("Ccedil", 199); // latin capital letter C with cedilla, U+00C7 ISOlat1 _entityName.Add(199, "Ccedil"); _entityValue.Add("Egrave", 200); // latin capital letter E with grave, U+00C8 ISOlat1 _entityName.Add(200, "Egrave"); _entityValue.Add("Eacute", 201); // latin capital letter E with acute, U+00C9 ISOlat1 _entityName.Add(201, "Eacute"); _entityValue.Add("Ecirc", 202); // latin capital letter E with circumflex, U+00CA ISOlat1 _entityName.Add(202, "Ecirc"); _entityValue.Add("Euml", 203); // latin capital letter E with diaeresis, U+00CB ISOlat1 _entityName.Add(203, "Euml"); _entityValue.Add("Igrave", 204); // latin capital letter I with grave, U+00CC ISOlat1 _entityName.Add(204, "Igrave"); _entityValue.Add("Iacute", 205); // latin capital letter I with acute, U+00CD ISOlat1 _entityName.Add(205, "Iacute"); _entityValue.Add("Icirc", 206); // latin capital letter I with circumflex, U+00CE ISOlat1 _entityName.Add(206, "Icirc"); _entityValue.Add("Iuml", 207); // latin capital letter I with diaeresis, U+00CF ISOlat1 _entityName.Add(207, "Iuml"); _entityValue.Add("ETH", 208); // latin capital letter ETH, U+00D0 ISOlat1 _entityName.Add(208, "ETH"); _entityValue.Add("Ntilde", 209); // latin capital letter N with tilde, U+00D1 ISOlat1 _entityName.Add(209, "Ntilde"); _entityValue.Add("Ograve", 210); // latin capital letter O with grave, U+00D2 ISOlat1 _entityName.Add(210, "Ograve"); _entityValue.Add("Oacute", 211); // latin capital letter O with acute, U+00D3 ISOlat1 _entityName.Add(211, "Oacute"); _entityValue.Add("Ocirc", 212); // latin capital letter O with circumflex, U+00D4 ISOlat1 _entityName.Add(212, "Ocirc"); _entityValue.Add("Otilde", 213); // latin capital letter O with tilde, U+00D5 ISOlat1 _entityName.Add(213, "Otilde"); _entityValue.Add("Ouml", 214); // latin capital letter O with diaeresis, U+00D6 ISOlat1 _entityName.Add(214, "Ouml"); _entityValue.Add("times", 215); // multiplication sign, U+00D7 ISOnum _entityName.Add(215, "times"); _entityValue.Add("Oslash", 216); // latin capital letter O with stroke = latin capital letter O slash, U+00D8 ISOlat1 _entityName.Add(216, "Oslash"); _entityValue.Add("Ugrave", 217); // latin capital letter U with grave, U+00D9 ISOlat1 _entityName.Add(217, "Ugrave"); _entityValue.Add("Uacute", 218); // latin capital letter U with acute, U+00DA ISOlat1 _entityName.Add(218, "Uacute"); _entityValue.Add("Ucirc", 219); // latin capital letter U with circumflex, U+00DB ISOlat1 _entityName.Add(219, "Ucirc"); _entityValue.Add("Uuml", 220); // latin capital letter U with diaeresis, U+00DC ISOlat1 _entityName.Add(220, "Uuml"); _entityValue.Add("Yacute", 221); // latin capital letter Y with acute, U+00DD ISOlat1 _entityName.Add(221, "Yacute"); _entityValue.Add("THORN", 222); // latin capital letter THORN, U+00DE ISOlat1 _entityName.Add(222, "THORN"); _entityValue.Add("szlig", 223); // latin small letter sharp s = ess-zed, U+00DF ISOlat1 _entityName.Add(223, "szlig"); _entityValue.Add("agrave", 224); // latin small letter a with grave = latin small letter a grave, U+00E0 ISOlat1 _entityName.Add(224, "agrave"); _entityValue.Add("aacute", 225); // latin small letter a with acute, U+00E1 ISOlat1 _entityName.Add(225, "aacute"); _entityValue.Add("acirc", 226); // latin small letter a with circumflex, U+00E2 ISOlat1 _entityName.Add(226, "acirc"); _entityValue.Add("atilde", 227); // latin small letter a with tilde, U+00E3 ISOlat1 _entityName.Add(227, "atilde"); _entityValue.Add("auml", 228); // latin small letter a with diaeresis, U+00E4 ISOlat1 _entityName.Add(228, "auml"); _entityValue.Add("aring", 229); // latin small letter a with ring above = latin small letter a ring, U+00E5 ISOlat1 _entityName.Add(229, "aring"); _entityValue.Add("aelig", 230); // latin small letter ae = latin small ligature ae, U+00E6 ISOlat1 _entityName.Add(230, "aelig"); _entityValue.Add("ccedil", 231); // latin small letter c with cedilla, U+00E7 ISOlat1 _entityName.Add(231, "ccedil"); _entityValue.Add("egrave", 232); // latin small letter e with grave, U+00E8 ISOlat1 _entityName.Add(232, "egrave"); _entityValue.Add("eacute", 233); // latin small letter e with acute, U+00E9 ISOlat1 _entityName.Add(233, "eacute"); _entityValue.Add("ecirc", 234); // latin small letter e with circumflex, U+00EA ISOlat1 _entityName.Add(234, "ecirc"); _entityValue.Add("euml", 235); // latin small letter e with diaeresis, U+00EB ISOlat1 _entityName.Add(235, "euml"); _entityValue.Add("igrave", 236); // latin small letter i with grave, U+00EC ISOlat1 _entityName.Add(236, "igrave"); _entityValue.Add("iacute", 237); // latin small letter i with acute, U+00ED ISOlat1 _entityName.Add(237, "iacute"); _entityValue.Add("icirc", 238); // latin small letter i with circumflex, U+00EE ISOlat1 _entityName.Add(238, "icirc"); _entityValue.Add("iuml", 239); // latin small letter i with diaeresis, U+00EF ISOlat1 _entityName.Add(239, "iuml"); _entityValue.Add("eth", 240); // latin small letter eth, U+00F0 ISOlat1 _entityName.Add(240, "eth"); _entityValue.Add("ntilde", 241); // latin small letter n with tilde, U+00F1 ISOlat1 _entityName.Add(241, "ntilde"); _entityValue.Add("ograve", 242); // latin small letter o with grave, U+00F2 ISOlat1 _entityName.Add(242, "ograve"); _entityValue.Add("oacute", 243); // latin small letter o with acute, U+00F3 ISOlat1 _entityName.Add(243, "oacute"); _entityValue.Add("ocirc", 244); // latin small letter o with circumflex, U+00F4 ISOlat1 _entityName.Add(244, "ocirc"); _entityValue.Add("otilde", 245); // latin small letter o with tilde, U+00F5 ISOlat1 _entityName.Add(245, "otilde"); _entityValue.Add("ouml", 246); // latin small letter o with diaeresis, U+00F6 ISOlat1 _entityName.Add(246, "ouml"); _entityValue.Add("divide", 247); // division sign, U+00F7 ISOnum _entityName.Add(247, "divide"); _entityValue.Add("oslash", 248); // latin small letter o with stroke, = latin small letter o slash, U+00F8 ISOlat1 _entityName.Add(248, "oslash"); _entityValue.Add("ugrave", 249); // latin small letter u with grave, U+00F9 ISOlat1 _entityName.Add(249, "ugrave"); _entityValue.Add("uacute", 250); // latin small letter u with acute, U+00FA ISOlat1 _entityName.Add(250, "uacute"); _entityValue.Add("ucirc", 251); // latin small letter u with circumflex, U+00FB ISOlat1 _entityName.Add(251, "ucirc"); _entityValue.Add("uuml", 252); // latin small letter u with diaeresis, U+00FC ISOlat1 _entityName.Add(252, "uuml"); _entityValue.Add("yacute", 253); // latin small letter y with acute, U+00FD ISOlat1 _entityName.Add(253, "yacute"); _entityValue.Add("thorn", 254); // latin small letter thorn, U+00FE ISOlat1 _entityName.Add(254, "thorn"); _entityValue.Add("yuml", 255); // latin small letter y with diaeresis, U+00FF ISOlat1 _entityName.Add(255, "yuml"); _entityValue.Add("fnof", 402); // latin small f with hook = function = florin, U+0192 ISOtech _entityName.Add(402, "fnof"); _entityValue.Add("Alpha", 913); // greek capital letter alpha, U+0391 _entityName.Add(913, "Alpha"); _entityValue.Add("Beta", 914); // greek capital letter beta, U+0392 _entityName.Add(914, "Beta"); _entityValue.Add("Gamma", 915); // greek capital letter gamma, U+0393 ISOgrk3 _entityName.Add(915, "Gamma"); _entityValue.Add("Delta", 916); // greek capital letter delta, U+0394 ISOgrk3 _entityName.Add(916, "Delta"); _entityValue.Add("Epsilon", 917); // greek capital letter epsilon, U+0395 _entityName.Add(917, "Epsilon"); _entityValue.Add("Zeta", 918); // greek capital letter zeta, U+0396 _entityName.Add(918, "Zeta"); _entityValue.Add("Eta", 919); // greek capital letter eta, U+0397 _entityName.Add(919, "Eta"); _entityValue.Add("Theta", 920); // greek capital letter theta, U+0398 ISOgrk3 _entityName.Add(920, "Theta"); _entityValue.Add("Iota", 921); // greek capital letter iota, U+0399 _entityName.Add(921, "Iota"); _entityValue.Add("Kappa", 922); // greek capital letter kappa, U+039A _entityName.Add(922, "Kappa"); _entityValue.Add("Lambda", 923); // greek capital letter lambda, U+039B ISOgrk3 _entityName.Add(923, "Lambda"); _entityValue.Add("Mu", 924); // greek capital letter mu, U+039C _entityName.Add(924, "Mu"); _entityValue.Add("Nu", 925); // greek capital letter nu, U+039D _entityName.Add(925, "Nu"); _entityValue.Add("Xi", 926); // greek capital letter xi, U+039E ISOgrk3 _entityName.Add(926, "Xi"); _entityValue.Add("Omicron", 927); // greek capital letter omicron, U+039F _entityName.Add(927, "Omicron"); _entityValue.Add("Pi", 928); // greek capital letter pi, U+03A0 ISOgrk3 _entityName.Add(928, "Pi"); _entityValue.Add("Rho", 929); // greek capital letter rho, U+03A1 _entityName.Add(929, "Rho"); _entityValue.Add("Sigma", 931); // greek capital letter sigma, U+03A3 ISOgrk3 _entityName.Add(931, "Sigma"); _entityValue.Add("Tau", 932); // greek capital letter tau, U+03A4 _entityName.Add(932, "Tau"); _entityValue.Add("Upsilon", 933); // greek capital letter upsilon, U+03A5 ISOgrk3 _entityName.Add(933, "Upsilon"); _entityValue.Add("Phi", 934); // greek capital letter phi, U+03A6 ISOgrk3 _entityName.Add(934, "Phi"); _entityValue.Add("Chi", 935); // greek capital letter chi, U+03A7 _entityName.Add(935, "Chi"); _entityValue.Add("Psi", 936); // greek capital letter psi, U+03A8 ISOgrk3 _entityName.Add(936, "Psi"); _entityValue.Add("Omega", 937); // greek capital letter omega, U+03A9 ISOgrk3 _entityName.Add(937, "Omega"); _entityValue.Add("alpha", 945); // greek small letter alpha, U+03B1 ISOgrk3 _entityName.Add(945, "alpha"); _entityValue.Add("beta", 946); // greek small letter beta, U+03B2 ISOgrk3 _entityName.Add(946, "beta"); _entityValue.Add("gamma", 947); // greek small letter gamma, U+03B3 ISOgrk3 _entityName.Add(947, "gamma"); _entityValue.Add("delta", 948); // greek small letter delta, U+03B4 ISOgrk3 _entityName.Add(948, "delta"); _entityValue.Add("epsilon", 949); // greek small letter epsilon, U+03B5 ISOgrk3 _entityName.Add(949, "epsilon"); _entityValue.Add("zeta", 950); // greek small letter zeta, U+03B6 ISOgrk3 _entityName.Add(950, "zeta"); _entityValue.Add("eta", 951); // greek small letter eta, U+03B7 ISOgrk3 _entityName.Add(951, "eta"); _entityValue.Add("theta", 952); // greek small letter theta, U+03B8 ISOgrk3 _entityName.Add(952, "theta"); _entityValue.Add("iota", 953); // greek small letter iota, U+03B9 ISOgrk3 _entityName.Add(953, "iota"); _entityValue.Add("kappa", 954); // greek small letter kappa, U+03BA ISOgrk3 _entityName.Add(954, "kappa"); _entityValue.Add("lambda", 955); // greek small letter lambda, U+03BB ISOgrk3 _entityName.Add(955, "lambda"); _entityValue.Add("mu", 956); // greek small letter mu, U+03BC ISOgrk3 _entityName.Add(956, "mu"); _entityValue.Add("nu", 957); // greek small letter nu, U+03BD ISOgrk3 _entityName.Add(957, "nu"); _entityValue.Add("xi", 958); // greek small letter xi, U+03BE ISOgrk3 _entityName.Add(958, "xi"); _entityValue.Add("omicron", 959); // greek small letter omicron, U+03BF NEW _entityName.Add(959, "omicron"); _entityValue.Add("pi", 960); // greek small letter pi, U+03C0 ISOgrk3 _entityName.Add(960, "pi"); _entityValue.Add("rho", 961); // greek small letter rho, U+03C1 ISOgrk3 _entityName.Add(961, "rho"); _entityValue.Add("sigmaf", 962); // greek small letter final sigma, U+03C2 ISOgrk3 _entityName.Add(962, "sigmaf"); _entityValue.Add("sigma", 963); // greek small letter sigma, U+03C3 ISOgrk3 _entityName.Add(963, "sigma"); _entityValue.Add("tau", 964); // greek small letter tau, U+03C4 ISOgrk3 _entityName.Add(964, "tau"); _entityValue.Add("upsilon", 965); // greek small letter upsilon, U+03C5 ISOgrk3 _entityName.Add(965, "upsilon"); _entityValue.Add("phi", 966); // greek small letter phi, U+03C6 ISOgrk3 _entityName.Add(966, "phi"); _entityValue.Add("chi", 967); // greek small letter chi, U+03C7 ISOgrk3 _entityName.Add(967, "chi"); _entityValue.Add("psi", 968); // greek small letter psi, U+03C8 ISOgrk3 _entityName.Add(968, "psi"); _entityValue.Add("omega", 969); // greek small letter omega, U+03C9 ISOgrk3 _entityName.Add(969, "omega"); _entityValue.Add("thetasym", 977); // greek small letter theta symbol, U+03D1 NEW _entityName.Add(977, "thetasym"); _entityValue.Add("upsih", 978); // greek upsilon with hook symbol, U+03D2 NEW _entityName.Add(978, "upsih"); _entityValue.Add("piv", 982); // greek pi symbol, U+03D6 ISOgrk3 _entityName.Add(982, "piv"); _entityValue.Add("bull", 8226); // bullet = black small circle, U+2022 ISOpub _entityName.Add(8226, "bull"); _entityValue.Add("hellip", 8230); // horizontal ellipsis = three dot leader, U+2026 ISOpub _entityName.Add(8230, "hellip"); _entityValue.Add("prime", 8242); // prime = minutes = feet, U+2032 ISOtech _entityName.Add(8242, "prime"); _entityValue.Add("Prime", 8243); // double prime = seconds = inches, U+2033 ISOtech _entityName.Add(8243, "Prime"); _entityValue.Add("oline", 8254); // overline = spacing overscore, U+203E NEW _entityName.Add(8254, "oline"); _entityValue.Add("frasl", 8260); // fraction slash, U+2044 NEW _entityName.Add(8260, "frasl"); _entityValue.Add("weierp", 8472); // script capital P = power set = Weierstrass p, U+2118 ISOamso _entityName.Add(8472, "weierp"); _entityValue.Add("image", 8465); // blackletter capital I = imaginary part, U+2111 ISOamso _entityName.Add(8465, "image"); _entityValue.Add("real", 8476); // blackletter capital R = real part symbol, U+211C ISOamso _entityName.Add(8476, "real"); _entityValue.Add("trade", 8482); // trade mark sign, U+2122 ISOnum _entityName.Add(8482, "trade"); _entityValue.Add("alefsym", 8501); // alef symbol = first transfinite cardinal, U+2135 NEW _entityName.Add(8501, "alefsym"); _entityValue.Add("larr", 8592); // leftwards arrow, U+2190 ISOnum _entityName.Add(8592, "larr"); _entityValue.Add("uarr", 8593); // upwards arrow, U+2191 ISOnum _entityName.Add(8593, "uarr"); _entityValue.Add("rarr", 8594); // rightwards arrow, U+2192 ISOnum _entityName.Add(8594, "rarr"); _entityValue.Add("darr", 8595); // downwards arrow, U+2193 ISOnum _entityName.Add(8595, "darr"); _entityValue.Add("harr", 8596); // left right arrow, U+2194 ISOamsa _entityName.Add(8596, "harr"); _entityValue.Add("crarr", 8629); // downwards arrow with corner leftwards = carriage return, U+21B5 NEW _entityName.Add(8629, "crarr"); _entityValue.Add("lArr", 8656); // leftwards double arrow, U+21D0 ISOtech _entityName.Add(8656, "lArr"); _entityValue.Add("uArr", 8657); // upwards double arrow, U+21D1 ISOamsa _entityName.Add(8657, "uArr"); _entityValue.Add("rArr", 8658); // rightwards double arrow, U+21D2 ISOtech _entityName.Add(8658, "rArr"); _entityValue.Add("dArr", 8659); // downwards double arrow, U+21D3 ISOamsa _entityName.Add(8659, "dArr"); _entityValue.Add("hArr", 8660); // left right double arrow, U+21D4 ISOamsa _entityName.Add(8660, "hArr"); _entityValue.Add("forall", 8704); // for all, U+2200 ISOtech _entityName.Add(8704, "forall"); _entityValue.Add("part", 8706); // partial differential, U+2202 ISOtech _entityName.Add(8706, "part"); _entityValue.Add("exist", 8707); // there exists, U+2203 ISOtech _entityName.Add(8707, "exist"); _entityValue.Add("empty", 8709); // empty set = null set = diameter, U+2205 ISOamso _entityName.Add(8709, "empty"); _entityValue.Add("nabla", 8711); // nabla = backward difference, U+2207 ISOtech _entityName.Add(8711, "nabla"); _entityValue.Add("isin", 8712); // element of, U+2208 ISOtech _entityName.Add(8712, "isin"); _entityValue.Add("notin", 8713); // not an element of, U+2209 ISOtech _entityName.Add(8713, "notin"); _entityValue.Add("ni", 8715); // contains as member, U+220B ISOtech _entityName.Add(8715, "ni"); _entityValue.Add("prod", 8719); // n-ary product = product sign, U+220F ISOamsb _entityName.Add(8719, "prod"); _entityValue.Add("sum", 8721); // n-ary sumation, U+2211 ISOamsb _entityName.Add(8721, "sum"); _entityValue.Add("minus", 8722); // minus sign, U+2212 ISOtech _entityName.Add(8722, "minus"); _entityValue.Add("lowast", 8727); // asterisk operator, U+2217 ISOtech _entityName.Add(8727, "lowast"); _entityValue.Add("radic", 8730); // square root = radical sign, U+221A ISOtech _entityName.Add(8730, "radic"); _entityValue.Add("prop", 8733); // proportional to, U+221D ISOtech _entityName.Add(8733, "prop"); _entityValue.Add("infin", 8734); // infinity, U+221E ISOtech _entityName.Add(8734, "infin"); _entityValue.Add("ang", 8736); // angle, U+2220 ISOamso _entityName.Add(8736, "ang"); _entityValue.Add("and", 8743); // logical and = wedge, U+2227 ISOtech _entityName.Add(8743, "and"); _entityValue.Add("or", 8744); // logical or = vee, U+2228 ISOtech _entityName.Add(8744, "or"); _entityValue.Add("cap", 8745); // intersection = cap, U+2229 ISOtech _entityName.Add(8745, "cap"); _entityValue.Add("cup", 8746); // union = cup, U+222A ISOtech _entityName.Add(8746, "cup"); _entityValue.Add("int", 8747); // integral, U+222B ISOtech _entityName.Add(8747, "int"); _entityValue.Add("there4", 8756); // therefore, U+2234 ISOtech _entityName.Add(8756, "there4"); _entityValue.Add("sim", 8764); // tilde operator = varies with = similar to, U+223C ISOtech _entityName.Add(8764, "sim"); _entityValue.Add("cong", 8773); // approximately equal to, U+2245 ISOtech _entityName.Add(8773, "cong"); _entityValue.Add("asymp", 8776); // almost equal to = asymptotic to, U+2248 ISOamsr _entityName.Add(8776, "asymp"); _entityValue.Add("ne", 8800); // not equal to, U+2260 ISOtech _entityName.Add(8800, "ne"); _entityValue.Add("equiv", 8801); // identical to, U+2261 ISOtech _entityName.Add(8801, "equiv"); _entityValue.Add("le", 8804); // less-than or equal to, U+2264 ISOtech _entityName.Add(8804, "le"); _entityValue.Add("ge", 8805); // greater-than or equal to, U+2265 ISOtech _entityName.Add(8805, "ge"); _entityValue.Add("sub", 8834); // subset of, U+2282 ISOtech _entityName.Add(8834, "sub"); _entityValue.Add("sup", 8835); // superset of, U+2283 ISOtech _entityName.Add(8835, "sup"); _entityValue.Add("nsub", 8836); // not a subset of, U+2284 ISOamsn _entityName.Add(8836, "nsub"); _entityValue.Add("sube", 8838); // subset of or equal to, U+2286 ISOtech _entityName.Add(8838, "sube"); _entityValue.Add("supe", 8839); // superset of or equal to, U+2287 ISOtech _entityName.Add(8839, "supe"); _entityValue.Add("oplus", 8853); // circled plus = direct sum, U+2295 ISOamsb _entityName.Add(8853, "oplus"); _entityValue.Add("otimes", 8855); // circled times = vector product, U+2297 ISOamsb _entityName.Add(8855, "otimes"); _entityValue.Add("perp", 8869); // up tack = orthogonal to = perpendicular, U+22A5 ISOtech _entityName.Add(8869, "perp"); _entityValue.Add("sdot", 8901); // dot operator, U+22C5 ISOamsb _entityName.Add(8901, "sdot"); _entityValue.Add("lceil", 8968); // left ceiling = apl upstile, U+2308 ISOamsc _entityName.Add(8968, "lceil"); _entityValue.Add("rceil", 8969); // right ceiling, U+2309 ISOamsc _entityName.Add(8969, "rceil"); _entityValue.Add("lfloor", 8970); // left floor = apl downstile, U+230A ISOamsc _entityName.Add(8970, "lfloor"); _entityValue.Add("rfloor", 8971); // right floor, U+230B ISOamsc _entityName.Add(8971, "rfloor"); _entityValue.Add("lang", 9001); // left-pointing angle bracket = bra, U+2329 ISOtech _entityName.Add(9001, "lang"); _entityValue.Add("rang", 9002); // right-pointing angle bracket = ket, U+232A ISOtech _entityName.Add(9002, "rang"); _entityValue.Add("loz", 9674); // lozenge, U+25CA ISOpub _entityName.Add(9674, "loz"); _entityValue.Add("spades", 9824); // black spade suit, U+2660 ISOpub _entityName.Add(9824, "spades"); _entityValue.Add("clubs", 9827); // black club suit = shamrock, U+2663 ISOpub _entityName.Add(9827, "clubs"); _entityValue.Add("hearts", 9829); // black heart suit = valentine, U+2665 ISOpub _entityName.Add(9829, "hearts"); _entityValue.Add("diams", 9830); // black diamond suit, U+2666 ISOpub _entityName.Add(9830, "diams"); _entityValue.Add("OElig", 338); // latin capital ligature OE, U+0152 ISOlat2 _entityName.Add(338, "OElig"); _entityValue.Add("oelig", 339); // latin small ligature oe, U+0153 ISOlat2 _entityName.Add(339, "oelig"); _entityValue.Add("Scaron", 352); // latin capital letter S with caron, U+0160 ISOlat2 _entityName.Add(352, "Scaron"); _entityValue.Add("scaron", 353); // latin small letter s with caron, U+0161 ISOlat2 _entityName.Add(353, "scaron"); _entityValue.Add("Yuml", 376); // latin capital letter Y with diaeresis, U+0178 ISOlat2 _entityName.Add(376, "Yuml"); _entityValue.Add("circ", 710); // modifier letter circumflex accent, U+02C6 ISOpub _entityName.Add(710, "circ"); _entityValue.Add("tilde", 732); // small tilde, U+02DC ISOdia _entityName.Add(732, "tilde"); _entityValue.Add("ensp", 8194); // en space, U+2002 ISOpub _entityName.Add(8194, "ensp"); _entityValue.Add("emsp", 8195); // em space, U+2003 ISOpub _entityName.Add(8195, "emsp"); _entityValue.Add("thinsp", 8201); // thin space, U+2009 ISOpub _entityName.Add(8201, "thinsp"); _entityValue.Add("zwnj", 8204); // zero width non-joiner, U+200C NEW RFC 2070 _entityName.Add(8204, "zwnj"); _entityValue.Add("zwj", 8205); // zero width joiner, U+200D NEW RFC 2070 _entityName.Add(8205, "zwj"); _entityValue.Add("lrm", 8206); // left-to-right mark, U+200E NEW RFC 2070 _entityName.Add(8206, "lrm"); _entityValue.Add("rlm", 8207); // right-to-left mark, U+200F NEW RFC 2070 _entityName.Add(8207, "rlm"); _entityValue.Add("ndash", 8211); // en dash, U+2013 ISOpub _entityName.Add(8211, "ndash"); _entityValue.Add("mdash", 8212); // em dash, U+2014 ISOpub _entityName.Add(8212, "mdash"); _entityValue.Add("lsquo", 8216); // left single quotation mark, U+2018 ISOnum _entityName.Add(8216, "lsquo"); _entityValue.Add("rsquo", 8217); // right single quotation mark, U+2019 ISOnum _entityName.Add(8217, "rsquo"); _entityValue.Add("sbquo", 8218); // single low-9 quotation mark, U+201A NEW _entityName.Add(8218, "sbquo"); _entityValue.Add("ldquo", 8220); // left double quotation mark, U+201C ISOnum _entityName.Add(8220, "ldquo"); _entityValue.Add("rdquo", 8221); // right double quotation mark, U+201D ISOnum _entityName.Add(8221, "rdquo"); _entityValue.Add("bdquo", 8222); // double low-9 quotation mark, U+201E NEW _entityName.Add(8222, "bdquo"); _entityValue.Add("dagger", 8224); // dagger, U+2020 ISOpub _entityName.Add(8224, "dagger"); _entityValue.Add("Dagger", 8225); // double dagger, U+2021 ISOpub _entityName.Add(8225, "Dagger"); _entityValue.Add("permil", 8240); // per mille sign, U+2030 ISOtech _entityName.Add(8240, "permil"); _entityValue.Add("lsaquo", 8249); // single left-pointing angle quotation mark, U+2039 ISO proposed _entityName.Add(8249, "lsaquo"); _entityValue.Add("rsaquo", 8250); // single right-pointing angle quotation mark, U+203A ISO proposed _entityName.Add(8250, "rsaquo"); _entityValue.Add("euro", 8364); // euro sign, U+20AC NEW _entityName.Add(8364, "euro"); _maxEntitySize = 8 + 1; // we add the # char #endregion } private HtmlEntity() { } #endregion #region Public Methods /// <summary> /// Replace known entities by characters. /// </summary> /// <param name="text">The source text.</param> /// <returns>The result text.</returns> public static string DeEntitize(string text) { if (text == null) return null; if (text.Length == 0) return text; StringBuilder sb = new StringBuilder(text.Length); ParseState state = ParseState.Text; StringBuilder entity = new StringBuilder(10); for (int i = 0; i < text.Length; i++) { switch (state) { case ParseState.Text: switch (text[i]) { case '&': state = ParseState.EntityStart; break; default: sb.Append(text[i]); break; } break; case ParseState.EntityStart: switch (text[i]) { case ';': if (entity.Length == 0) { sb.Append("&;"); } else { if (entity[0] == '#') { string e = entity.ToString(); try { string codeStr = e.Substring(1).Trim(); int fromBase; if (codeStr.StartsWith("x", StringComparison.OrdinalIgnoreCase)) { fromBase = 16; codeStr = codeStr.Substring(1); } else { fromBase = 10; } int code = Convert.ToInt32(codeStr, fromBase); sb.Append(Convert.ToChar(code)); } catch { sb.Append("&#" + e + ";"); } } else { // named entity? int code; if (!_entityValue.TryGetValue(entity.ToString(), out code)) { // nope sb.Append("&" + entity + ";"); } else { // we found one sb.Append(Convert.ToChar(code)); } } entity.Remove(0, entity.Length); } state = ParseState.Text; break; case '&': // new entity start without end, it was not an entity... sb.Append("&" + entity); entity.Remove(0, entity.Length); break; default: entity.Append(text[i]); if (entity.Length > _maxEntitySize) { // unknown stuff, just don't touch it state = ParseState.Text; sb.Append("&" + entity); entity.Remove(0, entity.Length); } break; } break; } } // finish the work if (state == ParseState.EntityStart) { sb.Append("&" + entity); } return sb.ToString(); } /// <summary> /// Clone and entitize an HtmlNode. This will affect attribute values and nodes' text. It will also entitize all child nodes. /// </summary> /// <param name="node">The node to entitize.</param> /// <returns>An entitized cloned node.</returns> public static HtmlNode Entitize(HtmlNode node) { if (node == null) { throw new ArgumentNullException("node"); } HtmlNode result = node.CloneNode(true); if (result.HasAttributes) Entitize(result.Attributes); if (result.HasChildNodes) { Entitize(result.ChildNodes); } else { if (result.NodeType == HtmlNodeType.Text) { ((HtmlTextNode) result).Text = Entitize(((HtmlTextNode) result).Text, true, true); } } return result; } /// <summary> /// Replace characters above 127 by entities. /// </summary> /// <param name="text">The source text.</param> /// <returns>The result text.</returns> public static string Entitize(string text) { return Entitize(text, true); } /// <summary> /// Replace characters above 127 by entities. /// </summary> /// <param name="text">The source text.</param> /// <param name="useNames">If set to false, the function will not use known entities name. Default is true.</param> /// <returns>The result text.</returns> public static string Entitize(string text, bool useNames) { return Entitize(text, useNames, false); } /// <summary> /// Replace characters above 127 by entities. /// </summary> /// <param name="text">The source text.</param> /// <param name="useNames">If set to false, the function will not use known entities name. Default is true.</param> /// <param name="entitizeQuotAmpAndLtGt">If set to true, the [quote], [ampersand], [lower than] and [greather than] characters will be entitized.</param> /// <returns>The result text</returns> public static string Entitize(string text, bool useNames, bool entitizeQuotAmpAndLtGt) // _entityValue.Add("quot", 34); // quotation mark = APL quote, U+0022 ISOnum // _entityName.Add(34, "quot"); // _entityValue.Add("amp", 38); // ampersand, U+0026 ISOnum // _entityName.Add(38, "amp"); // _entityValue.Add("lt", 60); // less-than sign, U+003C ISOnum // _entityName.Add(60, "lt"); // _entityValue.Add("gt", 62); // greater-than sign, U+003E ISOnum // _entityName.Add(62, "gt"); { if (text == null) return null; if (text.Length == 0) return text; StringBuilder sb = new StringBuilder(text.Length); for (int i = 0; i < text.Length; i++) { int code = text[i]; if ((code > 127) || (entitizeQuotAmpAndLtGt && ((code == 34) || (code == 38) || (code == 60) || (code == 62)))) { string entity; EntityName.TryGetValue(code, out entity); if ((entity == null) || (!useNames)) { sb.Append("&#" + code + ";"); } else { sb.Append("&" + entity + ";"); } } else { sb.Append(text[i]); } } return sb.ToString(); } #endregion #region Private Methods private static void Entitize(HtmlAttributeCollection collection) { foreach (HtmlAttribute at in collection) { if (at.Value == null) { continue; } at.Value = Entitize(at.Value); } } private static void Entitize(HtmlNodeCollection collection) { foreach (HtmlNode node in collection) { if (node.HasAttributes) Entitize(node.Attributes); if (node.HasChildNodes) { Entitize(node.ChildNodes); } else { if (node.NodeType == HtmlNodeType.Text) { ((HtmlTextNode) node).Text = Entitize(((HtmlTextNode) node).Text, true, true); } } } } #endregion #region Nested type: ParseState private enum ParseState { Text, EntityStart } #endregion } }
// DataTableReaderTest.cs - NUnit Test Cases for testing the DataTableReader // // Authors: // Sureshkumar T <tsureshkumar@novell.com> // // // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // 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. // #if NET_2_0 using System; using System.Data; using NUnit.Framework; namespace MonoTests.System.Data.SqlClient { [TestFixture] public class DataTableReaderTest { DataTable dt; [SetUp] public void Setup () { dt = new DataTable ("test"); dt.Columns.Add ("id", typeof (int)); dt.Columns.Add ("name", typeof (string)); dt.PrimaryKey = new DataColumn [] { dt.Columns ["id"] }; dt.Rows.Add (new object [] { 1, "mono 1" }); dt.Rows.Add (new object [] { 2, "mono 2" }); dt.Rows.Add (new object [] { 3, "mono 3" }); dt.AcceptChanges (); } #region Positive Tests [Test] public void CtorTest () { dt.Rows [1].Delete (); DataTableReader reader = new DataTableReader (dt); try { int i = 0; while (reader.Read ()) i++; reader.Close (); Assert.AreEqual (2, i, "no. of rows iterated is wrong"); } finally { if (reader != null && !reader.IsClosed) reader.Close (); } } [Test] [ExpectedException (typeof (InvalidOperationException))] public void RowInAccessibleTest () { DataTableReader reader = new DataTableReader (dt); try { reader.Read (); reader.Read (); // 2nd row dt.Rows [1].Delete (); string value = reader [1].ToString (); } finally { if (reader != null && !reader.IsClosed) reader.Close (); } } [Test] public void IgnoreDeletedRowsDynamicTest () { DataTableReader reader = new DataTableReader (dt); try { reader.Read (); // first row dt.Rows [1].Delete (); reader.Read (); // it should be 3rd row string value = reader [0].ToString (); Assert.AreEqual ("3", value, "#1 reader should have moved to 3rd row"); } finally { if (reader != null && !reader.IsClosed) reader.Close (); } } [Test] public void SeeTheModifiedTest () { DataTableReader reader = new DataTableReader (dt); try { reader.Read (); // first row dt.Rows [1] ["name"] = "mono changed"; reader.Read (); string value = reader [1].ToString (); Assert.AreEqual ("mono changed", value, "#2 reader should have moved to 3rd row"); } finally { if (reader != null && !reader.IsClosed) reader.Close (); } } [Test] public void SchemaTest () { DataTable another = new DataTable ("another"); another.Columns.Add ("x", typeof (string)); another.Rows.Add (new object [] {"test 1" }); another.Rows.Add (new object [] {"test 2" }); another.Rows.Add (new object [] {"test 3" }); DataTableReader reader = new DataTableReader (new DataTable [] { dt, another }); try { DataTable schema = reader.GetSchemaTable (); Assert.AreEqual (dt.Columns.Count, schema.Rows.Count, "#1 should be same"); Assert.AreEqual (dt.Columns [1].DataType.ToString (), schema.Rows [1] ["DataType"].ToString (), "#2 data type should match"); reader.NextResult (); //schema should change here schema = reader.GetSchemaTable (); Assert.AreEqual (another.Columns.Count, schema.Rows.Count, "#3 should be same"); Assert.AreEqual (another.Columns [0].DataType.ToString (), schema.Rows [0] ["DataType"].ToString (), "#4 data type should match"); } finally { if (reader != null && !reader.IsClosed) reader.Close (); } } [Test] public void MultipleResultSetsTest () { DataTable dt1 = new DataTable ("test2"); dt1.Columns.Add ("x", typeof (string)); dt1.Rows.Add (new object [] {"test"} ); dt1.Rows.Add (new object [] {"test1"} ); dt1.AcceptChanges (); DataTable [] collection = new DataTable [] { dt, dt1 } ; DataTableReader reader = new DataTableReader (collection); try { int i = 0; do { while (reader.Read ()) i++; } while (reader.NextResult ()); Assert.AreEqual (5, i, "#1 rows should be of both the tables"); } finally { if (reader != null && !reader.IsClosed) reader.Close (); } } [Test] public void GetTest () { dt.Columns.Add ("nullint", typeof (int)); dt.Rows [0] ["nullint"] = 333; DataTableReader reader = new DataTableReader (dt); try { reader.Read (); int ordinal = reader.GetOrdinal ("nullint"); // Get by name Assert.AreEqual (1, (int) reader ["id"], "#1 should be able to get by name"); Assert.AreEqual (333, reader.GetInt32 (ordinal), "#2 should get int32"); Assert.AreEqual ("System.Int32", reader.GetDataTypeName (ordinal), "#3 data type should match"); } finally { if (reader != null && !reader.IsClosed) reader.Close (); } } [Test] [ExpectedException (typeof (InvalidOperationException))] public void CloseTest () { DataTableReader reader = new DataTableReader (dt); try { int i = 0; while (reader.Read () && i < 1) i++; reader.Close (); reader.Read (); } finally { if (reader != null && !reader.IsClosed) reader.Close (); } } [Test] public void GetOrdinalTest () { DataTableReader reader = new DataTableReader (dt); try { Assert.AreEqual (1, reader.GetOrdinal ("name"), "#1 get ordinal should work even" + " without calling Read"); } finally { if (reader != null && !reader.IsClosed) reader.Close (); } } #endregion // Positive Tests #region Negative Tests [Test] public void NoRowsTest () { dt.Rows.Clear (); dt.AcceptChanges (); DataTableReader reader = new DataTableReader (dt); try { Assert.AreEqual (false, reader.Read (), "#1 there are no rows"); Assert.AreEqual (false, reader.NextResult (), "#2 there are no further resultsets"); } finally { if (reader != null && !reader.IsClosed) reader.Close (); } } [Test] [ExpectedException (typeof (ArgumentException))] public void NoTablesTest () { DataTableReader reader = new DataTableReader (new DataTable [] {}); try { reader.Read (); } finally { if (reader != null && !reader.IsClosed) reader.Close (); } } [Test] [ExpectedException (typeof (InvalidOperationException))] public void ReadAfterClosedTest () { DataTableReader reader = new DataTableReader (dt); try { reader.Read (); reader.Close (); reader.Read (); } finally { if (reader != null && !reader.IsClosed) reader.Close (); } } [Test] [ExpectedException (typeof (InvalidOperationException))] public void AccessAfterClosedTest () { DataTableReader reader = new DataTableReader (dt); try { reader.Read (); reader.Close (); int i = (int) reader [0]; i++; // to supress warning } finally { if (reader != null && !reader.IsClosed) reader.Close (); } } [Test] [ExpectedException (typeof (InvalidOperationException))] public void AccessBeforeReadTest () { DataTableReader reader = new DataTableReader (dt); try { int i = (int) reader [0]; i++; // to supress warning } finally { if (reader != null && !reader.IsClosed) reader.Close (); } } [Test] [ExpectedException (typeof (ArgumentOutOfRangeException))] public void InvalidIndexTest () { DataTableReader reader = new DataTableReader (dt); try { reader.Read (); int i = (int) reader [90]; // kidding, ;-) i++; // to supress warning } finally { if (reader != null && !reader.IsClosed) reader.Close (); } } [Test] public void DontSeeTheEarlierRowsTest () { DataTableReader reader = new DataTableReader (dt); try { reader.Read (); // first row reader.Read (); // second row // insert a row at position 0 DataRow r = dt.NewRow (); r [0] = 0; r [1] = "adhi bagavan"; dt.Rows.InsertAt (r, 0); Assert.AreEqual (2, (int) reader.GetInt32 (0), "#1 should not alter the position"); } finally { if (reader != null && !reader.IsClosed) reader.Close (); } } [Test] public void AddBeforePointTest () { DataTableReader reader = new DataTableReader (dt); try { reader.Read (); // first row reader.Read (); // second row DataRow r = dt.NewRow (); r [0] = 0; r [1] = "adhi bagavan"; dt.Rows.InsertAt (r, 0); dt.Rows.Add (new object [] { 4, "mono 4"}); // should not affect the counter Assert.AreEqual (2, (int) reader [0], "#1 should not affect the current position"); } finally { if (reader != null && !reader.IsClosed) reader.Close (); } } [Test] public void AddAtPointTest () { DataTableReader reader = new DataTableReader (dt); try { reader.Read (); // first row reader.Read (); // second row DataRow r = dt.NewRow (); r [0] = 0; r [1] = "same point"; dt.Rows.InsertAt (r, 1); dt.Rows.Add (new object [] { 4, "mono 4"}); // should not affect the counter Assert.AreEqual (2, (int) reader [0], "#1 should not affect the current position"); } finally { if (reader != null && !reader.IsClosed) reader.Close (); } } [Test] public void DeletePreviousAndAcceptChangesTest () { DataTableReader reader = new DataTableReader (dt); try { reader.Read (); // first row reader.Read (); // second row dt.Rows [0].Delete (); dt.AcceptChanges (); Assert.AreEqual (2, (int) reader [0], "#1 should not affect the current position"); } finally { if (reader != null && !reader.IsClosed) reader.Close (); } } [Test] public void DeleteCurrentAndAcceptChangesTest2 () { DataTableReader reader = new DataTableReader (dt); try { reader.Read (); // first row reader.Read (); // second row dt.Rows [1].Delete (); // delete row, where reader points to dt.AcceptChanges (); // accept the action Assert.AreEqual (1, (int) reader [0], "#1 should point to the first row"); } finally { if (reader != null && !reader.IsClosed) reader.Close (); } } [Test] [ExpectedException (typeof (InvalidOperationException))] public void DeleteFirstCurrentAndAcceptChangesTest () { DataTableReader reader = new DataTableReader (dt); try { reader.Read (); // first row dt.Rows [0].Delete (); // delete row, where reader points to dt.AcceptChanges (); // accept the action Assert.AreEqual (2, (int) reader [0], "#1 should point to the first row"); } finally { if (reader != null && !reader.IsClosed) reader.Close (); } } [Test] public void DeleteLastAndAcceptChangesTest2 () { DataTableReader reader = new DataTableReader (dt); try { reader.Read (); // first row reader.Read (); // second row reader.Read (); // third row dt.Rows [2].Delete (); // delete row, where reader points to dt.AcceptChanges (); // accept the action Assert.AreEqual (2, (int) reader [0], "#1 should point to the first row"); } finally { if (reader != null && !reader.IsClosed) reader.Close (); } } [Test] public void ClearTest () { DataTableReader reader = null; try { reader = new DataTableReader (dt); reader.Read (); // first row reader.Read (); // second row dt.Clear (); try { int i = (int) reader [0]; i++; // supress warning Assert.Fail("#1 should have thrown RowNotInTableException"); } catch (RowNotInTableException) {} // clear and add test reader.Close (); reader = new DataTableReader (dt); reader.Read (); // first row reader.Read (); // second row dt.Clear (); dt.Rows.Add (new object [] {8, "mono 8"}); dt.AcceptChanges (); bool success = reader.Read (); Assert.AreEqual (false, success, "#2 is always invalid"); // clear when reader is not read yet reader.Close (); reader = new DataTableReader (dt); dt.Clear (); dt.Rows.Add (new object [] {8, "mono 8"}); dt.AcceptChanges (); success = reader.Read (); Assert.AreEqual (true, success, "#3 should add"); } finally { if (reader != null && !reader.IsClosed) reader.Close (); } } [Test] public void MultipleDeleteTest () { dt.Rows.Add (new object [] {4, "mono 4"}); dt.Rows.Add (new object [] {5, "mono 5"}); dt.Rows.Add (new object [] {6, "mono 6"}); dt.Rows.Add (new object [] {7, "mono 7"}); dt.Rows.Add (new object [] {8, "mono 8"}); dt.AcceptChanges (); DataTableReader reader = new DataTableReader (dt); try { reader.Read (); // first row reader.Read (); reader.Read (); reader.Read (); reader.Read (); dt.Rows [3].Delete (); dt.Rows [1].Delete (); dt.Rows [2].Delete (); dt.Rows [0].Delete (); dt.Rows [6].Delete (); dt.AcceptChanges (); Assert.AreEqual (5, (int) reader [0], "#1 should keep pointing to 5"); } finally { if (reader != null && !reader.IsClosed) reader.Close (); } } #endregion // Negative Tests } } #endif // NET_2_0
// Copyright (c) Microsoft Corporation, 2001 // // File: BaseUriHelper.cs // // // History: 06/21/05 - [....] - created // 07/20/05 - weibz - Move the place // Move the BaseUri helper from Framework // down to core. // 01/31/06: brucemac - Change PreloadedPackages.AddPackage() to pass a boolean indicating // that SiteOfOriginContainer is thread-safe // //------------------------------------------------------------------------------ using System; using System.Diagnostics; using System.IO.Packaging; using System.Globalization; using System.Net; using System.Security; using System.Windows; using System.Windows.Markup; using System.Windows.Media; using System.Reflection; using System.IO; using MS.Internal; using MS.Internal.AppModel; using MS.Internal.IO.Packaging; using MS.Internal.PresentationCore; // In order to avoid generating warnings about unknown message numbers and // unknown pragmas when compiling your C# source code with the actual C# compiler, // you need to disable warnings 1634 and 1691. (Presharp Documentation) #pragma warning disable 1634, 1691 namespace System.Windows.Navigation { /// <summary> /// BaseUriHelper class provides BaseUri related property, methods. /// </summary> public static class BaseUriHelper { private const string SOOBASE = "SiteOfOrigin://"; private static readonly Uri _siteOfOriginBaseUri = PackUriHelper.Create(new Uri(SOOBASE)); private const string APPBASE = "application://"; private static readonly Uri _packAppBaseUri = PackUriHelper.Create(new Uri(APPBASE)); private static SecurityCriticalDataForSet<Uri> _baseUri; // Cached result of calling // PackUriHelper.GetPackageUri(BaseUriHelper.PackAppBaseUri).GetComponents( // UriComponents.AbsoluteUri, // UriFormat.UriEscaped); private const string _packageApplicationBaseUriEscaped = "application:///"; private const string _packageSiteOfOriginBaseUriEscaped = "siteoforigin:///"; /// <SecurityNote> /// Critical: because it sets critical data. /// Adds SiteOfOriginContainer to PreloadedPackages. /// TreatAsSafe: because it is the static ctor, and the data doesn't go anywhere. /// SiteOfOriginContainer is a well-known package and allowed to be added /// to PreloadedPackages. Also, the package is not going to be handed out /// from this API surface and as such will be protected /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] static BaseUriHelper() { _baseUri = new SecurityCriticalDataForSet<Uri>(_packAppBaseUri); // Add an instance of the ResourceContainer to PreloadedPackages so that PackWebRequestFactory can find it // and mark it as thread-safe so PackWebResponse won't protect returned streams with a synchronizing wrapper PreloadedPackages.AddPackage(PackUriHelper.GetPackageUri(SiteOfOriginBaseUri), new SiteOfOriginContainer(), true); } #region public property and method /// <summary> /// The DependencyProperty for BaseUri of current Element. /// /// Flags: None /// Default Value: null. /// </summary> public static readonly DependencyProperty BaseUriProperty = DependencyProperty.RegisterAttached( "BaseUri", typeof(Uri), typeof(BaseUriHelper), new PropertyMetadata((object)null)); /// <summary> /// Get BaseUri for a dependency object inside a tree. /// /// </summary> /// <param name="element">Dependency Object</param> /// <returns>BaseUri for the element</returns> /// <remarks> /// Callers must have FileIOPermission(FileIOPermissionAccess.PathDiscovery) for the given Uri to call this API. /// </remarks> /// <SecurityNote> /// Critical: as it access the BaseUri, which is critcal /// PublicOK: calls GetBaseUriCore that does a demand /// Not available from the Internet zone /// </SecurityNote> [SecurityCritical] public static Uri GetBaseUri(DependencyObject element) { Uri baseUri = GetBaseUriCore(element); // // Manipulate BaseUri after tree searching is done. // if (baseUri == null) { // If no BaseUri information is found from the current tree, // just take the Application's BaseUri. // Application's BaseUri must be an absolute Uri. baseUri = BaseUriHelper.BaseUri; } else { if (baseUri.IsAbsoluteUri == false) { // Most likely the BaseUriDP in element or IUriContext.BaseUri // is set to a relative Uri programmatically in user's code. // For this case, we should resolve this relative Uri to PackAppBase // to generate an absolute Uri. // // BamlRecordReader now always sets absolute Uri for UriContext // element when the tree is generated from baml/xaml stream, this // code path would not run for parser-loaded tree. // baseUri = new Uri(BaseUriHelper.BaseUri, baseUri); } } return baseUri; } #endregion public property and method #region internal properties and methods static internal Uri SiteOfOriginBaseUri { [FriendAccessAllowed] get { return _siteOfOriginBaseUri; } } static internal Uri PackAppBaseUri { [FriendAccessAllowed] get { return _packAppBaseUri; } } /// <summary> /// Checks whether the input uri is in the "pack://application:,,," form /// </summary> internal static bool IsPackApplicationUri(Uri uri) { return // Is the "outer" URI absolute? uri.IsAbsoluteUri && // Does the "outer" URI have the pack: scheme? SecurityHelper.AreStringTypesEqual(uri.Scheme, PackUriHelper.UriSchemePack) && // Does the "inner" URI have the application: scheme SecurityHelper.AreStringTypesEqual( PackUriHelper.GetPackageUri(uri).GetComponents(UriComponents.AbsoluteUri, UriFormat.UriEscaped), _packageApplicationBaseUriEscaped); } // The method accepts a relative or absolute Uri and returns the appropriate assembly. // // For absolute Uri, it accepts only "pack://application:,,,/...", throw exception for // any other absolute Uri. // // If the first segment of that Uri contains ";component", returns the assembly whose // assembly name matches the text string in the first segment. otherwise, this method // would return EntryAssembly in the AppDomain. // [FriendAccessAllowed] internal static void GetAssemblyAndPartNameFromPackAppUri(Uri uri, out Assembly assembly, out string partName) { // The input Uri is assumed to be a valid absolute pack application Uri. // The caller should guarantee that. // Perform a sanity check to make sure the assumption stays. Debug.Assert(uri != null && uri.IsAbsoluteUri && SecurityHelper.AreStringTypesEqual(uri.Scheme, PackUriHelper.UriSchemePack) && IsPackApplicationUri(uri)); // Generate a relative Uri which gets rid of the pack://application:,,, authority part. Uri partUri = new Uri(uri.AbsolutePath, UriKind.Relative); string assemblyName; string assemblyVersion; string assemblyKey; GetAssemblyNameAndPart(partUri, out partName, out assemblyName, out assemblyVersion, out assemblyKey); if (String.IsNullOrEmpty(assemblyName)) { // The uri doesn't contain ";component". it should map to the enty application assembly. assembly = ResourceAssembly; // The partName returned from GetAssemblyNameAndPart should be escaped. Debug.Assert(String.Compare(partName, uri.GetComponents(UriComponents.Path, UriFormat.UriEscaped), StringComparison.OrdinalIgnoreCase) == 0); } else { assembly = GetLoadedAssembly(assemblyName, assemblyVersion, assemblyKey); } } // // [FriendAccessAllowed] internal static Assembly GetLoadedAssembly(string assemblyName, string assemblyVersion, string assemblyKey) { Assembly assembly; AssemblyName asmName = new AssemblyName(assemblyName); // We always use the primary assembly (culture neutral) for resource manager. // if the required resource lives in satellite assembly, ResourceManager can find // the right satellite assembly later. asmName.CultureInfo = new CultureInfo(String.Empty); if (!String.IsNullOrEmpty(assemblyVersion)) { asmName.Version = new Version(assemblyVersion); } if (!String.IsNullOrEmpty(assemblyKey)) { int byteCount = assemblyKey.Length / 2; byte[] keyToken = new byte[byteCount]; for (int i = 0; i < byteCount; i++) { string byteString = assemblyKey.Substring(i * 2, 2); keyToken[i] = byte.Parse(byteString, NumberStyles.HexNumber, CultureInfo.InvariantCulture); } asmName.SetPublicKeyToken(keyToken); } assembly = SafeSecurityHelper.GetLoadedAssembly(asmName); if (assembly == null) { // The assembly is not yet loaded to the AppDomain, try to load it with information specified in resource Uri. assembly = Assembly.Load(asmName); } return assembly; } // // Return assembly Name, Version, Key and package Part from a relative Uri. // [FriendAccessAllowed] internal static void GetAssemblyNameAndPart(Uri uri, out string partName, out string assemblyName, out string assemblyVersion, out string assemblyKey) { Invariant.Assert(uri != null && uri.IsAbsoluteUri == false, "This method accepts relative uri only."); string original = uri.ToString(); // only relative Uri here (enforced by Package) // Start and end points for the first segment in the Uri. int start = 0; int end; if (original[0] == '/') { start = 1; } partName = original.Substring(start); assemblyName = string.Empty; assemblyVersion = string.Empty; assemblyKey = string.Empty; end = original.IndexOf('/', start); string firstSegment = String.Empty; bool fHasComponent = false; if (end > 0) { // get the first section firstSegment = original.Substring(start, end - start); // The resource comes from dll if (firstSegment.EndsWith(COMPONENT, StringComparison.OrdinalIgnoreCase)) { partName = original.Substring(end + 1); fHasComponent = true; } } if (fHasComponent) { string[] assemblyInfo = firstSegment.Split(new char[] { COMPONENT_DELIMITER }); int count = assemblyInfo.Length; if ((count > 4) || (count < 2)) { throw new UriFormatException(SR.Get(SRID.WrongFirstSegment)); } // // if the uri contains escaping character, // Convert it back to normal unicode string // so that the string as assembly name can be // recognized by Assembly.Load later. // assemblyName = Uri.UnescapeDataString(assemblyInfo[0]); for (int i = 1; i < count - 1; i++) { if (assemblyInfo[i].StartsWith(VERSION, StringComparison.OrdinalIgnoreCase)) { if (string.IsNullOrEmpty(assemblyVersion)) { assemblyVersion = assemblyInfo[i].Substring(1); // Get rid of the leading "v" } else { throw new UriFormatException(SR.Get(SRID.WrongFirstSegment)); } } else { if (string.IsNullOrEmpty(assemblyKey)) { assemblyKey = assemblyInfo[i]; } else { throw new UriFormatException(SR.Get(SRID.WrongFirstSegment)); } } } // end of for loop } // end of if fHasComponent } [FriendAccessAllowed] static internal bool IsComponentEntryAssembly(string component) { if (component.EndsWith(COMPONENT, StringComparison.OrdinalIgnoreCase)) { string[] assemblyInfo = component.Split(new Char[] { COMPONENT_DELIMITER }); // Check whether the assembly name is the same as the EntryAssembly. int count = assemblyInfo.Length; if ((count >= 2) && (count <= 4)) { string assemblyName = Uri.UnescapeDataString(assemblyInfo[0]); Assembly assembly = ResourceAssembly; if (assembly != null) { return (String.Compare(SafeSecurityHelper.GetAssemblyPartialName(assembly), assemblyName, StringComparison.OrdinalIgnoreCase) == 0); } else { return false; } } } return false; } [FriendAccessAllowed] static internal Uri GetResolvedUri(Uri baseUri, Uri orgUri) { return new Uri(baseUri, orgUri); } [FriendAccessAllowed] static internal Uri MakeRelativeToSiteOfOriginIfPossible(Uri sUri) { if (Uri.Compare(sUri, SiteOfOriginBaseUri, UriComponents.Scheme, UriFormat.UriEscaped, StringComparison.OrdinalIgnoreCase) == 0) { Uri packageUri; Uri partUri; PackUriHelper.ValidateAndGetPackUriComponents(sUri, out packageUri, out partUri); if (String.Compare(packageUri.GetComponents(UriComponents.AbsoluteUri, UriFormat.UriEscaped), _packageSiteOfOriginBaseUriEscaped, StringComparison.OrdinalIgnoreCase) == 0) { return (new Uri(sUri.GetComponents(UriComponents.SchemeAndServer, UriFormat.UriEscaped))).MakeRelativeUri(sUri); } } return sUri; } [FriendAccessAllowed] static internal Uri ConvertPackUriToAbsoluteExternallyVisibleUri(Uri packUri) { Invariant.Assert(packUri.IsAbsoluteUri && SecurityHelper.AreStringTypesEqual(packUri.Scheme, PackAppBaseUri.Scheme)); Uri relative = MakeRelativeToSiteOfOriginIfPossible(packUri); if (! relative.IsAbsoluteUri) { return new Uri(SiteOfOriginContainer.SiteOfOrigin, relative); } else { throw new InvalidOperationException(SR.Get(SRID.CannotNavigateToApplicationResourcesInWebBrowser, packUri)); } } // If a Uri is constructed with a legacy path such as c:\foo\bar then the Uri // object will not correctly resolve relative Uris in some cases. This method // detects and fixes this by constructing a new Uri with an original string // that contains the scheme file://. [FriendAccessAllowed] static internal Uri FixFileUri(Uri uri) { if (uri != null && uri.IsAbsoluteUri && SecurityHelper.AreStringTypesEqual(uri.Scheme, Uri.UriSchemeFile) && string.Compare(uri.OriginalString, 0, Uri.UriSchemeFile, 0, Uri.UriSchemeFile.Length, StringComparison.OrdinalIgnoreCase) != 0) { return new Uri(uri.AbsoluteUri); } return uri; } /// <SecurityNote> /// Critical: as it sets the baseUri /// </SecurityNote> static internal Uri BaseUri { [FriendAccessAllowed] get { return _baseUri.Value; } [FriendAccessAllowed] [SecurityCritical] set { // This setter should only be called from Framework through // BindUriHelper.set_BaseUri. _baseUri.Value = value; } } static internal Assembly ResourceAssembly { get { if (_resourceAssembly == null) { _resourceAssembly = Assembly.GetEntryAssembly(); } return _resourceAssembly; } [FriendAccessAllowed] set { // This should only be called from Framework through Application.ResourceAssembly setter. _resourceAssembly = value; } } #endregion internal properties and methods #region private methods /// <summary> /// Get BaseUri for a dependency object inside a tree. /// /// </summary> /// <param name="element">Dependency Object</param> /// <returns>BaseUri for the element</returns> /// <remarks> /// Callers must have FileIOPermission(FileIOPermissionAccess.PathDiscovery) for the given Uri to call this API. /// </remarks> /// <SecurityNote> /// Critical: as it access the BaseUri, which is critcal /// TreatAsSafe: since it demands File read write and path dicovery permission. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] internal static Uri GetBaseUriCore(DependencyObject element) { Uri baseUri = null; DependencyObject doCurrent; if (element == null) { throw new ArgumentNullException("element"); } try { // // Search the tree to find the closest parent which implements // IUriContext or have set value for BaseUri property. // doCurrent = element; while (doCurrent != null) { // Try to get BaseUri property value from current node. baseUri = doCurrent.GetValue(BaseUriProperty) as Uri; if (baseUri != null) { // Got the right node which is the closest to original element. // Stop searching here. break; } IUriContext uriContext = doCurrent as IUriContext; if (uriContext != null) { // If the element implements IUriContext, and if the BaseUri // is not null, just take the BaseUri from there. // and stop the search loop. baseUri = uriContext.BaseUri; if (baseUri != null) break; } // // The current node doesn't contain BaseUri value, // try its parent node in the tree. UIElement uie = doCurrent as UIElement; if (uie != null) { // Do the tree walk up doCurrent = uie.GetUIParent(true); } else { ContentElement ce = doCurrent as ContentElement; if (ce != null) { doCurrent = ce.Parent; } else { Visual vis = doCurrent as Visual; if (vis != null) { // Try the Visual tree search doCurrent = VisualTreeHelper.GetParent(vis); } else { // Not a Visual. // Stop here for the tree searching to aviod an infinite loop. break; } } } } } finally { // // Putting the permission demand in finally block can prevent from exposing a bogus // and dangerous uri to the code in upper frame. // if (baseUri != null) { SecurityHelper.DemandUriDiscoveryPermission(baseUri); } } return baseUri; } #endregion private const string COMPONENT = ";component"; private const string VERSION = "v"; private const char COMPONENT_DELIMITER = ';'; private static Assembly _resourceAssembly; } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using ThisToThat; namespace ThisToThatTests { [TestClass] public class ToUInt16Tests { /// <summary> /// Makes multiple SByte to UInt16 or default conversions and asserts that the results are correct. /// </summary> [TestMethod, TestCategory("ToUInt16 tests")] public void TestSByteToUInt16OrDefault() { // Test conversion of source type minimum value SByte source = SByte.MinValue; Assert.IsInstanceOfType(source, typeof(SByte)); UInt16? result = source.ToUInt16OrDefault((ushort)86); // Here we would expect this conversion to fail (and return the default value of (ushort)86), // since the source type's minimum value (-128) is less than the target type's minimum value (0). Assert.AreEqual((ushort)86, result); Assert.IsInstanceOfType(result, typeof(UInt16)); // Test conversion of source type value 42 to target type source = (sbyte)42; Assert.IsInstanceOfType(source, typeof(SByte)); result = source.ToUInt16OrDefault((ushort)86); Assert.AreEqual((ushort)42, result); Assert.IsInstanceOfType(result, typeof(UInt16)); // Test conversion of source type maximum value source = SByte.MaxValue; Assert.IsInstanceOfType(source, typeof(SByte)); result = source.ToUInt16OrDefault((ushort)86); Assert.AreEqual((ushort)127, result); Assert.IsInstanceOfType(result, typeof(UInt16)); } /// <summary> /// Makes multiple SByte to nullable UInt16 conversions and asserts that the results are correct. /// </summary> [TestMethod, TestCategory("ToUInt16 tests")] public void TestSByteToUInt16Nullable() { // Test conversion of source type minimum value SByte source = SByte.MinValue; Assert.IsInstanceOfType(source, typeof(SByte)); UInt16? result = source.ToUInt16Nullable(); // Here we would expect this conversion to fail (and return null), // since the source type's minimum value (-128) is less than the target type's minimum value (0). Assert.IsNull(result); // Test conversion of source type value 42 to target type source = (sbyte)42; Assert.IsInstanceOfType(source, typeof(SByte)); result = source.ToUInt16Nullable(); Assert.AreEqual((ushort)42, result); Assert.IsInstanceOfType(result, typeof(UInt16)); // Test conversion of source type maximum value source = SByte.MaxValue; Assert.IsInstanceOfType(source, typeof(SByte)); result = source.ToUInt16Nullable(); Assert.AreEqual((ushort)127, result); Assert.IsInstanceOfType(result, typeof(UInt16)); } /* Byte to UInt16: Test omitted There is a predefined implicit conversion from Byte to UInt16 */ /// <summary> /// Makes multiple Int16 to UInt16 or default conversions and asserts that the results are correct. /// </summary> [TestMethod, TestCategory("ToUInt16 tests")] public void TestInt16ToUInt16OrDefault() { // Test conversion of source type minimum value Int16 source = Int16.MinValue; Assert.IsInstanceOfType(source, typeof(Int16)); UInt16? result = source.ToUInt16OrDefault((ushort)86); // Here we would expect this conversion to fail (and return the default value of (ushort)86), // since the source type's minimum value (-32768) is less than the target type's minimum value (0). Assert.AreEqual((ushort)86, result); Assert.IsInstanceOfType(result, typeof(UInt16)); // Test conversion of source type value 42 to target type source = (short)42; Assert.IsInstanceOfType(source, typeof(Int16)); result = source.ToUInt16OrDefault((ushort)86); Assert.AreEqual((ushort)42, result); Assert.IsInstanceOfType(result, typeof(UInt16)); // Test conversion of source type maximum value source = Int16.MaxValue; Assert.IsInstanceOfType(source, typeof(Int16)); result = source.ToUInt16OrDefault((ushort)86); Assert.AreEqual((ushort)32767, result); Assert.IsInstanceOfType(result, typeof(UInt16)); } /// <summary> /// Makes multiple Int16 to nullable UInt16 conversions and asserts that the results are correct. /// </summary> [TestMethod, TestCategory("ToUInt16 tests")] public void TestInt16ToUInt16Nullable() { // Test conversion of source type minimum value Int16 source = Int16.MinValue; Assert.IsInstanceOfType(source, typeof(Int16)); UInt16? result = source.ToUInt16Nullable(); // Here we would expect this conversion to fail (and return null), // since the source type's minimum value (-32768) is less than the target type's minimum value (0). Assert.IsNull(result); // Test conversion of source type value 42 to target type source = (short)42; Assert.IsInstanceOfType(source, typeof(Int16)); result = source.ToUInt16Nullable(); Assert.AreEqual((ushort)42, result); Assert.IsInstanceOfType(result, typeof(UInt16)); // Test conversion of source type maximum value source = Int16.MaxValue; Assert.IsInstanceOfType(source, typeof(Int16)); result = source.ToUInt16Nullable(); Assert.AreEqual((ushort)32767, result); Assert.IsInstanceOfType(result, typeof(UInt16)); } /// <summary> /// Makes multiple Int32 to UInt16 or default conversions and asserts that the results are correct. /// </summary> [TestMethod, TestCategory("ToUInt16 tests")] public void TestInt32ToUInt16OrDefault() { // Test conversion of source type minimum value Int32 source = Int32.MinValue; Assert.IsInstanceOfType(source, typeof(Int32)); UInt16? result = source.ToUInt16OrDefault((ushort)86); // Here we would expect this conversion to fail (and return the default value of (ushort)86), // since the source type's minimum value (-2147483648) is less than the target type's minimum value (0). Assert.AreEqual((ushort)86, result); Assert.IsInstanceOfType(result, typeof(UInt16)); // Test conversion of source type value 42 to target type source = 42; Assert.IsInstanceOfType(source, typeof(Int32)); result = source.ToUInt16OrDefault((ushort)86); Assert.AreEqual((ushort)42, result); Assert.IsInstanceOfType(result, typeof(UInt16)); // Test conversion of source type maximum value source = Int32.MaxValue; Assert.IsInstanceOfType(source, typeof(Int32)); result = source.ToUInt16OrDefault((ushort)86); // Here we would expect this conversion to fail (and return the default value of (ushort)86), // since the source type's maximum value (2147483647) is greater than the target type's maximum value (65535). Assert.AreEqual((ushort)86, result); Assert.IsInstanceOfType(result, typeof(UInt16)); } /// <summary> /// Makes multiple Int32 to nullable UInt16 conversions and asserts that the results are correct. /// </summary> [TestMethod, TestCategory("ToUInt16 tests")] public void TestInt32ToUInt16Nullable() { // Test conversion of source type minimum value Int32 source = Int32.MinValue; Assert.IsInstanceOfType(source, typeof(Int32)); UInt16? result = source.ToUInt16Nullable(); // Here we would expect this conversion to fail (and return null), // since the source type's minimum value (-2147483648) is less than the target type's minimum value (0). Assert.IsNull(result); // Test conversion of source type value 42 to target type source = 42; Assert.IsInstanceOfType(source, typeof(Int32)); result = source.ToUInt16Nullable(); Assert.AreEqual((ushort)42, result); Assert.IsInstanceOfType(result, typeof(UInt16)); // Test conversion of source type maximum value source = Int32.MaxValue; Assert.IsInstanceOfType(source, typeof(Int32)); result = source.ToUInt16Nullable(); // Here we would expect this conversion to fail (and return null), // since the source type's maximum value (2147483647) is greater than the target type's maximum value (65535). Assert.IsNull(result); } /// <summary> /// Makes multiple UInt32 to UInt16 or default conversions and asserts that the results are correct. /// </summary> [TestMethod, TestCategory("ToUInt16 tests")] public void TestUInt32ToUInt16OrDefault() { // Test conversion of source type minimum value UInt32 source = UInt32.MinValue; Assert.IsInstanceOfType(source, typeof(UInt32)); UInt16? result = source.ToUInt16OrDefault((ushort)86); Assert.AreEqual((ushort)0, result); Assert.IsInstanceOfType(result, typeof(UInt16)); // Test conversion of source type value 42 to target type source = 42u; Assert.IsInstanceOfType(source, typeof(UInt32)); result = source.ToUInt16OrDefault((ushort)86); Assert.AreEqual((ushort)42, result); Assert.IsInstanceOfType(result, typeof(UInt16)); // Test conversion of source type maximum value source = UInt32.MaxValue; Assert.IsInstanceOfType(source, typeof(UInt32)); result = source.ToUInt16OrDefault((ushort)86); // Here we would expect this conversion to fail (and return the default value of (ushort)86), // since the source type's maximum value (4294967295) is greater than the target type's maximum value (65535). Assert.AreEqual((ushort)86, result); Assert.IsInstanceOfType(result, typeof(UInt16)); } /// <summary> /// Makes multiple UInt32 to nullable UInt16 conversions and asserts that the results are correct. /// </summary> [TestMethod, TestCategory("ToUInt16 tests")] public void TestUInt32ToUInt16Nullable() { // Test conversion of source type minimum value UInt32 source = UInt32.MinValue; Assert.IsInstanceOfType(source, typeof(UInt32)); UInt16? result = source.ToUInt16Nullable(); Assert.AreEqual((ushort)0, result); Assert.IsInstanceOfType(result, typeof(UInt16)); // Test conversion of source type value 42 to target type source = 42u; Assert.IsInstanceOfType(source, typeof(UInt32)); result = source.ToUInt16Nullable(); Assert.AreEqual((ushort)42, result); Assert.IsInstanceOfType(result, typeof(UInt16)); // Test conversion of source type maximum value source = UInt32.MaxValue; Assert.IsInstanceOfType(source, typeof(UInt32)); result = source.ToUInt16Nullable(); // Here we would expect this conversion to fail (and return null), // since the source type's maximum value (4294967295) is greater than the target type's maximum value (65535). Assert.IsNull(result); } /// <summary> /// Makes multiple Int64 to UInt16 or default conversions and asserts that the results are correct. /// </summary> [TestMethod, TestCategory("ToUInt16 tests")] public void TestInt64ToUInt16OrDefault() { // Test conversion of source type minimum value Int64 source = Int64.MinValue; Assert.IsInstanceOfType(source, typeof(Int64)); UInt16? result = source.ToUInt16OrDefault((ushort)86); // Here we would expect this conversion to fail (and return the default value of (ushort)86), // since the source type's minimum value (-9223372036854775808) is less than the target type's minimum value (0). Assert.AreEqual((ushort)86, result); Assert.IsInstanceOfType(result, typeof(UInt16)); // Test conversion of source type value 42 to target type source = 42L; Assert.IsInstanceOfType(source, typeof(Int64)); result = source.ToUInt16OrDefault((ushort)86); Assert.AreEqual((ushort)42, result); Assert.IsInstanceOfType(result, typeof(UInt16)); // Test conversion of source type maximum value source = Int64.MaxValue; Assert.IsInstanceOfType(source, typeof(Int64)); result = source.ToUInt16OrDefault((ushort)86); // Here we would expect this conversion to fail (and return the default value of (ushort)86), // since the source type's maximum value (9223372036854775807) is greater than the target type's maximum value (65535). Assert.AreEqual((ushort)86, result); Assert.IsInstanceOfType(result, typeof(UInt16)); } /// <summary> /// Makes multiple Int64 to nullable UInt16 conversions and asserts that the results are correct. /// </summary> [TestMethod, TestCategory("ToUInt16 tests")] public void TestInt64ToUInt16Nullable() { // Test conversion of source type minimum value Int64 source = Int64.MinValue; Assert.IsInstanceOfType(source, typeof(Int64)); UInt16? result = source.ToUInt16Nullable(); // Here we would expect this conversion to fail (and return null), // since the source type's minimum value (-9223372036854775808) is less than the target type's minimum value (0). Assert.IsNull(result); // Test conversion of source type value 42 to target type source = 42L; Assert.IsInstanceOfType(source, typeof(Int64)); result = source.ToUInt16Nullable(); Assert.AreEqual((ushort)42, result); Assert.IsInstanceOfType(result, typeof(UInt16)); // Test conversion of source type maximum value source = Int64.MaxValue; Assert.IsInstanceOfType(source, typeof(Int64)); result = source.ToUInt16Nullable(); // Here we would expect this conversion to fail (and return null), // since the source type's maximum value (9223372036854775807) is greater than the target type's maximum value (65535). Assert.IsNull(result); } /// <summary> /// Makes multiple UInt64 to UInt16 or default conversions and asserts that the results are correct. /// </summary> [TestMethod, TestCategory("ToUInt16 tests")] public void TestUInt64ToUInt16OrDefault() { // Test conversion of source type minimum value UInt64 source = UInt64.MinValue; Assert.IsInstanceOfType(source, typeof(UInt64)); UInt16? result = source.ToUInt16OrDefault((ushort)86); Assert.AreEqual((ushort)0, result); Assert.IsInstanceOfType(result, typeof(UInt16)); // Test conversion of source type value 42 to target type source = 42UL; Assert.IsInstanceOfType(source, typeof(UInt64)); result = source.ToUInt16OrDefault((ushort)86); Assert.AreEqual((ushort)42, result); Assert.IsInstanceOfType(result, typeof(UInt16)); // Test conversion of source type maximum value source = UInt64.MaxValue; Assert.IsInstanceOfType(source, typeof(UInt64)); result = source.ToUInt16OrDefault((ushort)86); // Here we would expect this conversion to fail (and return the default value of (ushort)86), // since the source type's maximum value (18446744073709551615) is greater than the target type's maximum value (65535). Assert.AreEqual((ushort)86, result); Assert.IsInstanceOfType(result, typeof(UInt16)); } /// <summary> /// Makes multiple UInt64 to nullable UInt16 conversions and asserts that the results are correct. /// </summary> [TestMethod, TestCategory("ToUInt16 tests")] public void TestUInt64ToUInt16Nullable() { // Test conversion of source type minimum value UInt64 source = UInt64.MinValue; Assert.IsInstanceOfType(source, typeof(UInt64)); UInt16? result = source.ToUInt16Nullable(); Assert.AreEqual((ushort)0, result); Assert.IsInstanceOfType(result, typeof(UInt16)); // Test conversion of source type value 42 to target type source = 42UL; Assert.IsInstanceOfType(source, typeof(UInt64)); result = source.ToUInt16Nullable(); Assert.AreEqual((ushort)42, result); Assert.IsInstanceOfType(result, typeof(UInt16)); // Test conversion of source type maximum value source = UInt64.MaxValue; Assert.IsInstanceOfType(source, typeof(UInt64)); result = source.ToUInt16Nullable(); // Here we would expect this conversion to fail (and return null), // since the source type's maximum value (18446744073709551615) is greater than the target type's maximum value (65535). Assert.IsNull(result); } /* Single to UInt16: Method omitted. UInt16 is an integral type. Single is non-integral (can contain fractions). Conversions involving possible rounding or truncation are not currently provided by this library. */ /* Double to UInt16: Method omitted. UInt16 is an integral type. Double is non-integral (can contain fractions). Conversions involving possible rounding or truncation are not currently provided by this library. */ /* Decimal to UInt16: Method omitted. UInt16 is an integral type. Decimal is non-integral (can contain fractions). Conversions involving possible rounding or truncation are not currently provided by this library. */ /// <summary> /// Makes multiple String to UInt16 or default conversions and asserts that the results are correct. /// </summary> [TestMethod, TestCategory("ToUInt16 tests")] public void TestStringToUInt16OrDefault() { // Test conversion of target type minimum value UInt16 resultMin = "0".ToUInt16OrDefault(); Assert.AreEqual((ushort)0, resultMin); // Test conversion of fixed value (42) UInt16 result42 = "42".ToUInt16OrDefault(); Assert.AreEqual((ushort)42, result42); // Test conversion of target type maximum value UInt16 resultMax = "65535".ToUInt16OrDefault(); Assert.AreEqual((ushort)65535, resultMax); // Test conversion of "foo" UInt16 resultFoo = "foo".ToUInt16OrDefault((ushort)86); Assert.AreEqual((ushort)86, resultFoo); } /// <summary> /// Makes multiple String to UInt16Nullable conversions and asserts that the results are correct. /// </summary> [TestMethod, TestCategory("ToUInt16 tests")] public void TestStringToUInt16Nullable() { // Test conversion of target type minimum value UInt16? resultMin = "0".ToUInt16Nullable(); Assert.AreEqual((ushort)0, resultMin); // Test conversion of fixed value (42) UInt16? result42 = "42".ToUInt16Nullable(); Assert.AreEqual((ushort)42, result42); // Test conversion of target type maximum value UInt16? resultMax = "65535".ToUInt16Nullable(); Assert.AreEqual((ushort)65535, resultMax); // Test conversion of "foo" UInt16? resultFoo = "foo".ToUInt16Nullable(); Assert.IsNull(resultFoo); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // TypeDelegator // // <OWNER>[....]</OWNER> // This class wraps a Type object and delegates all methods to that Type. namespace System.Reflection { using System; using System.Runtime.InteropServices; using System.Diagnostics.Contracts; using CultureInfo = System.Globalization.CultureInfo; [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public class TypeDelegator : #if FEATURE_CORECLR && !FEATURE_NETCORE Type #else TypeInfo #endif { #if !FEATURE_CORECLR || FEATURE_NETCORE public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo){ if(typeInfo==null) return false; return IsAssignableFrom(typeInfo.AsType()); } #endif protected Type typeImpl; #if FEATURE_CORECLR [System.Security.SecuritySafeCritical] // auto-generated #endif protected TypeDelegator() {} public TypeDelegator(Type delegatingType) { if (delegatingType == null) throw new ArgumentNullException("delegatingType"); Contract.EndContractBlock(); typeImpl = delegatingType; } public override Guid GUID { get {return typeImpl.GUID;} } public override int MetadataToken { get { return typeImpl.MetadataToken; } } public override Object InvokeMember(String name,BindingFlags invokeAttr,Binder binder,Object target, Object[] args,ParameterModifier[] modifiers,CultureInfo culture,String[] namedParameters) { return typeImpl.InvokeMember(name,invokeAttr,binder,target,args,modifiers,culture,namedParameters); } public override Module Module { get {return typeImpl.Module;} } public override Assembly Assembly { get {return typeImpl.Assembly;} } public override RuntimeTypeHandle TypeHandle { get{return typeImpl.TypeHandle;} } public override String Name { get{return typeImpl.Name;} } public override String FullName { get{return typeImpl.FullName;} } public override String Namespace { get{return typeImpl.Namespace;} } public override String AssemblyQualifiedName { get { return typeImpl.AssemblyQualifiedName; } } public override Type BaseType { get{return typeImpl.BaseType;} } protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr,Binder binder, CallingConventions callConvention, Type[] types,ParameterModifier[] modifiers) { return typeImpl.GetConstructor(bindingAttr,binder,callConvention,types,modifiers); } [System.Runtime.InteropServices.ComVisible(true)] public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { return typeImpl.GetConstructors(bindingAttr); } protected override MethodInfo GetMethodImpl(String name,BindingFlags bindingAttr,Binder binder, CallingConventions callConvention, Type[] types,ParameterModifier[] modifiers) { // This is interesting there are two paths into the impl. One that validates // type as non-null and one where type may be null. if (types == null) return typeImpl.GetMethod(name,bindingAttr); else return typeImpl.GetMethod(name,bindingAttr,binder,callConvention,types,modifiers); } public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { return typeImpl.GetMethods(bindingAttr); } public override FieldInfo GetField(String name, BindingFlags bindingAttr) { return typeImpl.GetField(name,bindingAttr); } public override FieldInfo[] GetFields(BindingFlags bindingAttr) { return typeImpl.GetFields(bindingAttr); } public override Type GetInterface(String name, bool ignoreCase) { return typeImpl.GetInterface(name,ignoreCase); } public override Type[] GetInterfaces() { return typeImpl.GetInterfaces(); } public override EventInfo GetEvent(String name,BindingFlags bindingAttr) { return typeImpl.GetEvent(name,bindingAttr); } public override EventInfo[] GetEvents() { return typeImpl.GetEvents(); } protected override PropertyInfo GetPropertyImpl(String name,BindingFlags bindingAttr,Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { if (returnType == null && types == null) return typeImpl.GetProperty(name,bindingAttr); else return typeImpl.GetProperty(name,bindingAttr,binder,returnType,types,modifiers); } public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { return typeImpl.GetProperties(bindingAttr); } public override EventInfo[] GetEvents(BindingFlags bindingAttr) { return typeImpl.GetEvents(bindingAttr); } public override Type[] GetNestedTypes(BindingFlags bindingAttr) { return typeImpl.GetNestedTypes(bindingAttr); } public override Type GetNestedType(String name, BindingFlags bindingAttr) { return typeImpl.GetNestedType(name,bindingAttr); } public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr) { return typeImpl.GetMember(name,type,bindingAttr); } public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { return typeImpl.GetMembers(bindingAttr); } protected override TypeAttributes GetAttributeFlagsImpl() { return typeImpl.Attributes; } protected override bool IsArrayImpl() { return typeImpl.IsArray; } protected override bool IsPrimitiveImpl() { return typeImpl.IsPrimitive; } protected override bool IsByRefImpl() { return typeImpl.IsByRef; } protected override bool IsPointerImpl() { return typeImpl.IsPointer; } protected override bool IsValueTypeImpl() { return typeImpl.IsValueType; } protected override bool IsCOMObjectImpl() { return typeImpl.IsCOMObject; } public override bool IsConstructedGenericType { get { return typeImpl.IsConstructedGenericType; } } public override Type GetElementType() { return typeImpl.GetElementType(); } protected override bool HasElementTypeImpl() { return typeImpl.HasElementType; } public override Type UnderlyingSystemType { get {return typeImpl.UnderlyingSystemType;} } // ICustomAttributeProvider public override Object[] GetCustomAttributes(bool inherit) { return typeImpl.GetCustomAttributes(inherit); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { return typeImpl.GetCustomAttributes(attributeType, inherit); } public override bool IsDefined(Type attributeType, bool inherit) { return typeImpl.IsDefined(attributeType, inherit); } [System.Runtime.InteropServices.ComVisible(true)] public override InterfaceMapping GetInterfaceMap(Type interfaceType) { return typeImpl.GetInterfaceMap(interfaceType); } } }
// Authors: // Rafael Mizrahi <rafim@mainsoft.com> // Erez Lotan <erezl@mainsoft.com> // Oren Gurfinkel <oreng@mainsoft.com> // Ofer Borstein // // Copyright (c) 2004 Mainsoft Co. // // 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 NUnit.Framework; using System; using System.Data; using GHTUtils; using GHTUtils.Base; namespace tests.system_data_dll.System_Data { [TestFixture] public class DataView_RowStateFilter : GHTBase { [Test] public void Main() { DataView_RowStateFilter tc = new DataView_RowStateFilter(); Exception exp = null; try { tc.BeginTest("DataView_RowStateFilter"); tc.run(); } catch(Exception ex) { exp = ex; } finally { tc.EndTest(exp); } } //Activate This Construntor to log All To Standard output //public TestClass():base(true){} //Activate this constructor to log Failures to a log file //public TestClass(System.IO.TextWriter tw):base(tw, false){} //Activate this constructor to log All to a log file //public TestClass(System.IO.TextWriter tw):base(tw, true){} //BY DEFAULT LOGGING IS DONE TO THE STANDARD OUTPUT ONLY FOR FAILURES public void run() { /* Added A new row. 4 CurrentRows Current rows including unchanged, new, and modified rows. 22 Deleted A deleted row. 8 ModifiedCurrent A current version, which is a modified version of original data (see ModifiedOriginal). 16 ModifiedOriginal The original version (although it has since been modified and is available as ModifiedCurrent). 32 None None. 0 OriginalRows Original rows including unchanged and deleted rows. 42 Unchanged An unchanged row. 2 */ //DataRowView[] drvResult = null; System.Collections.ArrayList al = new System.Collections.ArrayList(); Exception exp = null; DataTable dt = GHTUtils.DataProvider.CreateParentDataTable(); //create the dataview for the table DataView dv = new DataView(dt); DataRow[] drResult; dt.Rows[0].Delete(); dt.Rows[1]["ParentId"] = 1; dt.Rows[2]["ParentId"] = 1; dt.Rows[3].Delete(); dt.Rows.Add(new object[] {1,"A","B"}); dt.Rows.Add(new object[] {1,"C","D"}); dt.Rows.Add(new object[] {1,"E","F"}); //---------- Added -------- dv.RowStateFilter = DataViewRowState.Added ; drResult = GetResultRows(dt,DataRowState.Added); try { BeginCase("Added"); Compare(CompareSortedRows(dv,drResult),true ); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} //---------- CurrentRows -------- dv.RowStateFilter = DataViewRowState.CurrentRows ; drResult = GetResultRows(dt,DataRowState.Unchanged | DataRowState.Added | DataRowState.Modified ); try { BeginCase("CurrentRows"); Compare(CompareSortedRows(dv,drResult),true ); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} //---------- ModifiedCurrent -------- dv.RowStateFilter = DataViewRowState.ModifiedCurrent ; drResult = GetResultRows(dt,DataRowState.Modified ); try { BeginCase("ModifiedCurrent"); Compare(CompareSortedRows(dv,drResult) ,true ); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} //---------- ModifiedOriginal -------- dv.RowStateFilter = DataViewRowState.ModifiedOriginal ; drResult = GetResultRows(dt,DataRowState.Modified ); try { BeginCase("ModifiedOriginal"); Compare(CompareSortedRows(dv,drResult) ,true ); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} //---------- Deleted -------- dv.RowStateFilter = DataViewRowState.Deleted ; drResult = GetResultRows(dt,DataRowState.Deleted ); try { BeginCase("Deleted"); Compare(CompareSortedRows(dv,drResult),true ); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} /* //---------- OriginalRows -------- dv.RowStateFilter = DataViewRowState.OriginalRows ; drResult = GetResultRows(dt,DataRowState.Unchanged | DataRowState.Deleted ); try { BeginCase("OriginalRows"); Compare(CompareSortedRows(dv,drResult),true ); } catch(Exception ex) {exp = ex;} finally {EndCase(exp); exp = null;} */ } private DataRow[] GetResultRows(DataTable dt,DataRowState State) { //get expected rows System.Collections.ArrayList al = new System.Collections.ArrayList(); DataRowVersion drVer = DataRowVersion.Current; //From MSDN - The row the default version for the current DataRowState. // For a DataRowState value of Added, Modified or Current, // the default version is Current. // For a DataRowState of Deleted, the version is Original. // For a DataRowState value of Detached, the version is Proposed. if ( ((State & DataRowState.Added) > 0) | ((State & DataRowState.Modified) > 0) | ((State & DataRowState.Unchanged) > 0) ) drVer = DataRowVersion.Current; if ( (State & DataRowState.Deleted) > 0 | (State & DataRowState.Detached) > 0 ) drVer = DataRowVersion.Original; foreach (DataRow dr in dt.Rows ) { if ( dr.HasVersion(drVer) //&& ((int)dr["ParentId", drVer] == 1) && ((dr.RowState & State) > 0 ) ) al.Add(dr); } DataRow[] result = (DataRow[])al.ToArray((typeof(DataRow))); return result; } private bool CompareSortedRows(DataView dv, DataRow[] drTable) { if (dv.Count != drTable.Length) throw new Exception("DataRows[] length are different"); //comparing the rows by using columns ParentId and ChildId if ((dv.RowStateFilter & DataViewRowState.Deleted) > 0) { for (int i=0; i<dv.Count ; i++) { if (dv[i].Row["ParentId",DataRowVersion.Original ].ToString() != drTable[i]["ParentId",DataRowVersion.Original].ToString()) return false; } } else { for (int i=0; i<dv.Count ; i++) { if (dv[i].Row["ParentId"].ToString() != drTable[i]["ParentId"].ToString()) return false; } } return true; } } }
using System; using System.Collections.Generic; using System.Reflection; namespace Python.Runtime { using MaybeMethodInfo = MaybeMethodBase<MethodInfo>; /// <summary> /// Implements a Python binding type for CLR methods. These work much like /// standard Python method bindings, but the same type is used to bind /// both static and instance methods. /// </summary> [Serializable] internal class MethodBinding : ExtensionType { internal MaybeMethodInfo info; internal MethodObject m; internal IntPtr target; internal IntPtr targetType; public MethodBinding(MethodObject m, IntPtr target, IntPtr targetType) { Runtime.XIncref(target); this.target = target; if (targetType == IntPtr.Zero) { targetType = Runtime.PyObject_Type(target); } else { Runtime.XIncref(targetType); } this.targetType = targetType; this.info = null; this.m = m; } public MethodBinding(MethodObject m, IntPtr target) : this(m, target, IntPtr.Zero) { } private void ClearMembers() { Runtime.Py_CLEAR(ref target); Runtime.Py_CLEAR(ref targetType); } /// <summary> /// Implement binding of generic methods using the subscript syntax []. /// </summary> public static IntPtr mp_subscript(IntPtr tp, IntPtr idx) { var self = (MethodBinding)GetManagedObject(tp); Type[] types = Runtime.PythonArgsToTypeArray(idx); if (types == null) { return Exceptions.RaiseTypeError("type(s) expected"); } MethodInfo mi = MethodBinder.MatchParameters(self.m.info, types); if (mi == null) { return Exceptions.RaiseTypeError("No match found for given type params"); } var mb = new MethodBinding(self.m, self.target) { info = mi }; return mb.pyHandle; } /// <summary> /// MethodBinding __getattribute__ implementation. /// </summary> public static IntPtr tp_getattro(IntPtr ob, IntPtr key) { var self = (MethodBinding)GetManagedObject(ob); if (!Runtime.PyString_Check(key)) { Exceptions.SetError(Exceptions.TypeError, "string expected"); return IntPtr.Zero; } string name = InternString.GetManagedString(key); switch (name) { case "__doc__": IntPtr doc = self.m.GetDocString(); Runtime.XIncref(doc); return doc; // FIXME: deprecate __overloads__ soon... case "__overloads__": case "Overloads": var om = new OverloadMapper(self.m, self.target); return om.pyHandle; default: return Runtime.PyObject_GenericGetAttr(ob, key); } } /// <summary> /// MethodBinding __call__ implementation. /// </summary> public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw) { var self = (MethodBinding)GetManagedObject(ob); // This works around a situation where the wrong generic method is picked, // for example this method in the tests: string Overloaded<T>(int arg1, int arg2, string arg3) if (self.info.Valid) { var info = self.info.Value; if (info.IsGenericMethod) { var len = Runtime.PyTuple_Size(args); //FIXME: Never used Type[] sigTp = Runtime.PythonArgsToTypeArray(args, true); if (sigTp != null) { Type[] genericTp = info.GetGenericArguments(); MethodInfo betterMatch = MethodBinder.MatchSignatureAndParameters(self.m.info, genericTp, sigTp); if (betterMatch != null) { self.info = betterMatch; } } } } // This supports calling a method 'unbound', passing the instance // as the first argument. Note that this is not supported if any // of the overloads are static since we can't know if the intent // was to call the static method or the unbound instance method. var disposeList = new List<IntPtr>(); try { IntPtr target = self.target; if (target == IntPtr.Zero && !self.m.IsStatic()) { var len = Runtime.PyTuple_Size(args); if (len < 1) { Exceptions.SetError(Exceptions.TypeError, "not enough arguments"); return IntPtr.Zero; } target = Runtime.PyTuple_GetItem(args, 0); Runtime.XIncref(target); disposeList.Add(target); args = Runtime.PyTuple_GetSlice(args, 1, len); disposeList.Add(args); } // if the class is a IPythonDerivedClass and target is not the same as self.targetType // (eg if calling the base class method) then call the original base class method instead // of the target method. IntPtr superType = IntPtr.Zero; if (Runtime.PyObject_TYPE(target) != self.targetType) { var inst = GetManagedObject(target) as CLRObject; if (inst?.inst is IPythonDerivedType) { var baseType = GetManagedObject(self.targetType) as ClassBase; if (baseType != null && baseType.type.Valid) { string baseMethodName = "_" + baseType.type.Value.Name + "__" + self.m.name; IntPtr baseMethod = Runtime.PyObject_GetAttrString(target, baseMethodName); if (baseMethod != IntPtr.Zero) { var baseSelf = GetManagedObject(baseMethod) as MethodBinding; if (baseSelf != null) { self = baseSelf; } Runtime.XDecref(baseMethod); } else { Runtime.PyErr_Clear(); } } } } return self.m.Invoke(target, args, kw, self.info.UnsafeValue); } finally { foreach (IntPtr ptr in disposeList) { Runtime.XDecref(ptr); } } } /// <summary> /// MethodBinding __hash__ implementation. /// </summary> public static nint tp_hash(IntPtr ob) { var self = (MethodBinding)GetManagedObject(ob); nint x = 0; if (self.target != IntPtr.Zero) { x = Runtime.PyObject_Hash(self.target); if (x == -1) { return x; } } nint y = Runtime.PyObject_Hash(self.m.pyHandle); if (y == -1) { return y; } return x ^ y; } /// <summary> /// MethodBinding __repr__ implementation. /// </summary> public static IntPtr tp_repr(IntPtr ob) { var self = (MethodBinding)GetManagedObject(ob); string type = self.target == IntPtr.Zero ? "unbound" : "bound"; string name = self.m.name; return Runtime.PyString_FromString($"<{type} method '{name}'>"); } /// <summary> /// MethodBinding dealloc implementation. /// </summary> public new static void tp_dealloc(IntPtr ob) { var self = (MethodBinding)GetManagedObject(ob); self.ClearMembers(); self.Dealloc(); } public static int tp_clear(IntPtr ob) { var self = (MethodBinding)GetManagedObject(ob); self.ClearMembers(); return 0; } protected override void OnSave(InterDomainContext context) { base.OnSave(context); Runtime.XIncref(target); Runtime.XIncref(targetType); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudioTools.Project { //[DefaultRegistryRoot("Software\\Microsoft\\VisualStudio\\9.0Exp")] //[PackageRegistration(UseManagedResourcesOnly = true)] public abstract class CommonProjectPackage : ProjectPackage, IVsInstalledProduct, IOleComponent { private IOleComponentManager _compMgr; private uint _componentID; public abstract ProjectFactory CreateProjectFactory(); public abstract CommonEditorFactory CreateEditorFactory(); public virtual CommonEditorFactory CreateEditorFactoryPromptForEncoding() { return null; } /// <summary> /// This method is called to get the icon that will be displayed in the /// Help About dialog when this package is selected. /// </summary> /// <returns>The resource id corresponding to the icon to display on the Help About dialog</returns> public abstract uint GetIconIdForAboutBox(); /// <summary> /// This method is called during Devenv /Setup to get the bitmap to /// display on the splash screen for this package. /// </summary> /// <returns>The resource id corresponding to the bitmap to display on the splash screen</returns> public abstract uint GetIconIdForSplashScreen(); /// <summary> /// This methods provides the product official name, it will be /// displayed in the help about dialog. /// </summary> public abstract string GetProductName(); /// <summary> /// This methods provides the product description, it will be /// displayed in the help about dialog. /// </summary> public abstract string GetProductDescription(); /// <summary> /// This methods provides the product version, it will be /// displayed in the help about dialog. /// </summary> public abstract string GetProductVersion(); protected override void Initialize() { UIThread.EnsureService(this); base.Initialize(); this.RegisterProjectFactory(CreateProjectFactory()); var editFactory = CreateEditorFactory(); if (editFactory != null) { this.RegisterEditorFactory(editFactory); } var encodingEditorFactory = CreateEditorFactoryPromptForEncoding(); if (encodingEditorFactory != null) { RegisterEditorFactory(encodingEditorFactory); } var componentManager = this._compMgr = (IOleComponentManager)GetService(typeof(SOleComponentManager)); var crinfo = new OLECRINFO[1]; crinfo[0].cbSize = (uint)Marshal.SizeOf(typeof(OLECRINFO)); crinfo[0].grfcrf = (uint)_OLECRF.olecrfNeedIdleTime; crinfo[0].grfcadvf = (uint)_OLECADVF.olecadvfModal | (uint)_OLECADVF.olecadvfRedrawOff | (uint)_OLECADVF.olecadvfWarningsOff; crinfo[0].uIdleTimeInterval = 0; ErrorHandler.ThrowOnFailure(componentManager.FRegisterComponent(this, crinfo, out this._componentID)); } protected override void Dispose(bool disposing) { try { if (this._componentID != 0) { var mgr = GetService(typeof(SOleComponentManager)) as IOleComponentManager; if (mgr != null) { mgr.FRevokeComponent(this._componentID); } this._componentID = 0; } } finally { base.Dispose(disposing); } } /// <summary> /// This method loads a localized string based on the specified resource. /// </summary> /// <param name="resourceName">Resource to load</param> /// <returns>String loaded for the specified resource</returns> public string GetResourceString(string resourceName) { string resourceValue; var resourceManager = (IVsResourceManager)GetService(typeof(SVsResourceManager)); if (resourceManager == null) { throw new InvalidOperationException("Could not get SVsResourceManager service. Make sure the package is Sited before calling this method"); } var packageGuid = this.GetType().GUID; var hr = resourceManager.LoadResourceString(ref packageGuid, -1, resourceName, out resourceValue); Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(hr); return resourceValue; } #region IVsInstalledProduct Members /// <summary> /// This method is called during Devenv /Setup to get the bitmap to /// display on the splash screen for this package. /// </summary> /// <param name="pIdBmp">The resource id corresponding to the bitmap to display on the splash screen</param> /// <returns>HRESULT, indicating success or failure</returns> public int IdBmpSplash(out uint pIdBmp) { pIdBmp = GetIconIdForSplashScreen(); return VSConstants.S_OK; } /// <summary> /// This method is called to get the icon that will be displayed in the /// Help About dialog when this package is selected. /// </summary> /// <param name="pIdIco">The resource id corresponding to the icon to display on the Help About dialog</param> /// <returns>HRESULT, indicating success or failure</returns> public int IdIcoLogoForAboutbox(out uint pIdIco) { pIdIco = GetIconIdForAboutBox(); return VSConstants.S_OK; } /// <summary> /// This methods provides the product official name, it will be /// displayed in the help about dialog. /// </summary> /// <param name="pbstrName">Out parameter to which to assign the product name</param> /// <returns>HRESULT, indicating success or failure</returns> public int OfficialName(out string pbstrName) { pbstrName = GetProductName(); return VSConstants.S_OK; } /// <summary> /// This methods provides the product description, it will be /// displayed in the help about dialog. /// </summary> /// <param name="pbstrProductDetails">Out parameter to which to assign the description of the package</param> /// <returns>HRESULT, indicating success or failure</returns> public int ProductDetails(out string pbstrProductDetails) { pbstrProductDetails = GetProductDescription(); return VSConstants.S_OK; } /// <summary> /// This methods provides the product version, it will be /// displayed in the help about dialog. /// </summary> /// <param name="pbstrPID">Out parameter to which to assign the version number</param> /// <returns>HRESULT, indicating success or failure</returns> public int ProductID(out string pbstrPID) { pbstrPID = GetProductVersion(); return VSConstants.S_OK; } #endregion #region IOleComponent Members public int FContinueMessageLoop(uint uReason, IntPtr pvLoopData, MSG[] pMsgPeeked) { return 1; } public int FDoIdle(uint grfidlef) { var onIdle = OnIdle; if (onIdle != null) { onIdle(this, new ComponentManagerEventArgs(this._compMgr)); } return 0; } internal event EventHandler<ComponentManagerEventArgs> OnIdle; public int FPreTranslateMessage(MSG[] pMsg) { return 0; } public int FQueryTerminate(int fPromptUser) { return 1; } public int FReserved1(uint dwReserved, uint message, IntPtr wParam, IntPtr lParam) { return 1; } public IntPtr HwndGetWindow(uint dwWhich, uint dwReserved) { return IntPtr.Zero; } public void OnActivationChange(IOleComponent pic, int fSameComponent, OLECRINFO[] pcrinfo, int fHostIsActivating, OLECHOSTINFO[] pchostinfo, uint dwReserved) { } public void OnAppActivate(int fActive, uint dwOtherThreadID) { } public void OnEnterState(uint uStateID, int fEnter) { } public void OnLoseActivation() { } public void Terminate() { } #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 Apache.Ignite.Core.Impl { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Datastream; using Apache.Ignite.Core.DataStructures; using Apache.Ignite.Core.Events; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Cluster; using Apache.Ignite.Core.Lifecycle; using Apache.Ignite.Core.Messaging; using Apache.Ignite.Core.Services; using Apache.Ignite.Core.Transactions; /// <summary> /// Grid proxy with fake serialization. /// </summary> [Serializable] internal class IgniteProxy : IIgnite, IClusterGroupEx, IBinaryWriteAware, ICluster { /** */ [NonSerialized] private readonly Ignite _ignite; /// <summary> /// Default ctor for marshalling. /// </summary> public IgniteProxy() { // No-op. } /// <summary> /// Constructor. /// </summary> /// <param name="ignite">Grid.</param> public IgniteProxy(Ignite ignite) { _ignite = ignite; } /** <inheritdoc /> */ public string Name { get { return _ignite.Name; } } /** <inheritdoc /> */ public ICluster GetCluster() { return this; } /** <inheritdoc /> */ public IIgnite Ignite { get { return this; } } /** <inheritdoc /> */ public IClusterGroup ForLocal() { return _ignite.GetCluster().ForLocal(); } /** <inheritdoc /> */ public ICompute GetCompute() { return _ignite.GetCompute(); } /** <inheritdoc /> */ public IClusterGroup ForNodes(IEnumerable<IClusterNode> nodes) { return _ignite.GetCluster().ForNodes(nodes); } /** <inheritdoc /> */ public IClusterGroup ForNodes(params IClusterNode[] nodes) { return _ignite.GetCluster().ForNodes(nodes); } /** <inheritdoc /> */ public IClusterGroup ForNodeIds(IEnumerable<Guid> ids) { return _ignite.GetCluster().ForNodeIds(ids); } /** <inheritdoc /> */ public IClusterGroup ForNodeIds(ICollection<Guid> ids) { return _ignite.GetCluster().ForNodeIds(ids); } /** <inheritdoc /> */ public IClusterGroup ForNodeIds(params Guid[] ids) { return _ignite.GetCluster().ForNodeIds(ids); } /** <inheritdoc /> */ public IClusterGroup ForPredicate(Func<IClusterNode, bool> p) { return _ignite.GetCluster().ForPredicate(p); } /** <inheritdoc /> */ public IClusterGroup ForAttribute(string name, string val) { return _ignite.GetCluster().ForAttribute(name, val); } /** <inheritdoc /> */ public IClusterGroup ForCacheNodes(string name) { return _ignite.GetCluster().ForCacheNodes(name); } /** <inheritdoc /> */ public IClusterGroup ForDataNodes(string name) { return _ignite.GetCluster().ForDataNodes(name); } /** <inheritdoc /> */ public IClusterGroup ForClientNodes(string name) { return _ignite.GetCluster().ForClientNodes(name); } /** <inheritdoc /> */ public IClusterGroup ForRemotes() { return _ignite.GetCluster().ForRemotes(); } /** <inheritdoc /> */ public IClusterGroup ForHost(IClusterNode node) { return _ignite.GetCluster().ForHost(node); } /** <inheritdoc /> */ public IClusterGroup ForRandom() { return _ignite.GetCluster().ForRandom(); } /** <inheritdoc /> */ public IClusterGroup ForOldest() { return _ignite.GetCluster().ForOldest(); } /** <inheritdoc /> */ public IClusterGroup ForYoungest() { return _ignite.GetCluster().ForYoungest(); } /** <inheritdoc /> */ public IClusterGroup ForDotNet() { return _ignite.GetCluster().ForDotNet(); } /** <inheritdoc /> */ public IClusterGroup ForServers() { return _ignite.GetCluster().ForServers(); } /** <inheritdoc /> */ public ICollection<IClusterNode> GetNodes() { return _ignite.GetCluster().GetNodes(); } /** <inheritdoc /> */ public IClusterNode GetNode(Guid id) { return _ignite.GetCluster().GetNode(id); } /** <inheritdoc /> */ public IClusterNode GetNode() { return _ignite.GetCluster().GetNode(); } /** <inheritdoc /> */ public IClusterMetrics GetMetrics() { return _ignite.GetCluster().GetMetrics(); } /** <inheritdoc /> */ [SuppressMessage("Microsoft.Usage", "CA1816:CallGCSuppressFinalizeCorrectly", Justification = "There is no finalizer.")] public void Dispose() { _ignite.Dispose(); } /** <inheritdoc /> */ public ICache<TK, TV> GetCache<TK, TV>(string name) { return _ignite.GetCache<TK, TV>(name); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateCache<TK, TV>(string name) { return _ignite.GetOrCreateCache<TK, TV>(name); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration) { return _ignite.GetOrCreateCache<TK, TV>(configuration); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration, NearCacheConfiguration nearConfiguration) { return _ignite.GetOrCreateCache<TK, TV>(configuration, nearConfiguration); } /** <inheritdoc /> */ public ICache<TK, TV> CreateCache<TK, TV>(string name) { return _ignite.CreateCache<TK, TV>(name); } /** <inheritdoc /> */ public ICache<TK, TV> CreateCache<TK, TV>(CacheConfiguration configuration) { return _ignite.CreateCache<TK, TV>(configuration); } /** <inheritdoc /> */ public ICache<TK, TV> CreateCache<TK, TV>(CacheConfiguration configuration, NearCacheConfiguration nearConfiguration) { return _ignite.CreateCache<TK, TV>(configuration, nearConfiguration); } /** <inheritdoc /> */ public void DestroyCache(string name) { _ignite.DestroyCache(name); } /** <inheritdoc /> */ public IClusterNode GetLocalNode() { return _ignite.GetCluster().GetLocalNode(); } /** <inheritdoc /> */ public bool PingNode(Guid nodeId) { return _ignite.GetCluster().PingNode(nodeId); } /** <inheritdoc /> */ public long TopologyVersion { get { return _ignite.GetCluster().TopologyVersion; } } /** <inheritdoc /> */ public ICollection<IClusterNode> GetTopology(long ver) { return _ignite.GetCluster().GetTopology(ver); } /** <inheritdoc /> */ public void ResetMetrics() { _ignite.GetCluster().ResetMetrics(); } /** <inheritdoc /> */ public Task<bool> ClientReconnectTask { get { return _ignite.GetCluster().ClientReconnectTask; } } /** <inheritdoc /> */ public IDataStreamer<TK, TV> GetDataStreamer<TK, TV>(string cacheName) { return _ignite.GetDataStreamer<TK, TV>(cacheName); } /** <inheritdoc /> */ public IBinary GetBinary() { return _ignite.GetBinary(); } /** <inheritdoc /> */ public ICacheAffinity GetAffinity(string name) { return _ignite.GetAffinity(name); } /** <inheritdoc /> */ public ITransactions GetTransactions() { return _ignite.GetTransactions(); } /** <inheritdoc /> */ public IMessaging GetMessaging() { return _ignite.GetMessaging(); } /** <inheritdoc /> */ public IEvents GetEvents() { return _ignite.GetEvents(); } /** <inheritdoc /> */ public IServices GetServices() { return _ignite.GetServices(); } /** <inheritdoc /> */ public IAtomicLong GetAtomicLong(string name, long initialValue, bool create) { return _ignite.GetAtomicLong(name, initialValue, create); } /** <inheritdoc /> */ public IgniteConfiguration GetConfiguration() { return _ignite.GetConfiguration(); } /** <inheritdoc /> */ public ICache<TK, TV> CreateNearCache<TK, TV>(string name, NearCacheConfiguration configuration) { return _ignite.CreateNearCache<TK, TV>(name, configuration); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateNearCache<TK, TV>(string name, NearCacheConfiguration configuration) { return _ignite.GetOrCreateNearCache<TK, TV>(name, configuration); } /** <inheritdoc /> */ public ICollection<string> GetCacheNames() { return _ignite.GetCacheNames(); } /** <inheritdoc /> */ public event EventHandler Stopping { add { _ignite.Stopping += value; } remove { _ignite.Stopping -= value; } } /** <inheritdoc /> */ public event EventHandler Stopped { add { _ignite.Stopped += value; } remove { _ignite.Stopped -= value; } } /** <inheritdoc /> */ public event EventHandler ClientDisconnected { add { _ignite.ClientDisconnected += value; } remove { _ignite.ClientDisconnected -= value; } } /** <inheritdoc /> */ public event EventHandler<ClientReconnectEventArgs> ClientReconnected { add { _ignite.ClientReconnected += value; } remove { _ignite.ClientReconnected -= value; } } /** <inheritdoc /> */ public IAtomicSequence GetAtomicSequence(string name, long initialValue, bool create) { return _ignite.GetAtomicSequence(name, initialValue, create); } /** <inheritdoc /> */ public IAtomicReference<T> GetAtomicReference<T>(string name, T initialValue, bool create) { return _ignite.GetAtomicReference(name, initialValue, create); } /** <inheritdoc /> */ public void WriteBinary(IBinaryWriter writer) { // No-op. } /// <summary> /// Target grid. /// </summary> internal Ignite Target { get { return _ignite; } } /** <inheritdoc /> */ public IBinaryType GetBinaryType(int typeId) { return _ignite.GetBinaryType(typeId); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace BloggingSystem.Services.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ActionDescriptor.ReturnType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Management.Automation; using System.Management.Automation.Runspaces; using EnvDTE; using NuGet.VisualStudio; using NuGet.VisualStudio.Resources; namespace NuGet.PowerShell.Commands { /// <summary> /// This class acts as the base class for InstallPackage, UninstallPackage and UpdatePackage commands. /// </summary> public abstract class ProcessPackageBaseCommand : NuGetBaseCommand { // If this command is executed by getting the project from the pipeline, then we need we keep track of all of the // project managers since the same cmdlet instance can be used across invocations. private readonly Dictionary<string, IProjectManager> _projectManagers = new Dictionary<string, IProjectManager>(); private readonly Dictionary<IProjectManager, Project> _projectManagerToProject = new Dictionary<IProjectManager, Project>(); private string _readmeFile; private readonly IVsCommonOperations _vsCommonOperations; private IDisposable _expandedNodesDisposable; protected ProcessPackageBaseCommand( ISolutionManager solutionManager, IVsPackageManagerFactory packageManagerFactory, IHttpClientEvents httpClientEvents, IVsCommonOperations vsCommonOperations) : base(solutionManager, packageManagerFactory, httpClientEvents) { Debug.Assert(vsCommonOperations != null); _vsCommonOperations = vsCommonOperations; } [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, Position = 0)] public virtual string Id { get; set; } [Parameter(Position = 1, ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] public virtual string ProjectName { get; set; } protected IProjectManager ProjectManager { get { // We take a snapshot of the default project, the first time it is accessed so if it changes during // the executing of this cmdlet we won't take it into consideration. (which is really an edge case anyway) string name = ProjectName ?? String.Empty; IProjectManager projectManager; if (!_projectManagers.TryGetValue(name, out projectManager)) { Tuple<IProjectManager, Project> tuple = GetProjectManager(); if (tuple != null) { projectManager = tuple.Item1; if (projectManager != null) { _projectManagers.Add(name, projectManager); } } } return projectManager; } } protected override void BeginProcessing() { base.BeginProcessing(); _readmeFile = null; if (PackageManager != null) { PackageManager.PackageInstalling += OnPackageInstalling; PackageManager.PackageInstalled += OnPackageInstalled; } // remember currently expanded nodes so that we can leave them expanded // after the operation has finished. SaveExpandedNodes(); } protected override void EndProcessing() { base.EndProcessing(); if (PackageManager != null) { PackageManager.PackageInstalling -= OnPackageInstalling; PackageManager.PackageInstalled -= OnPackageInstalled; } foreach (var projectManager in _projectManagers.Values) { projectManager.PackageReferenceAdded -= OnPackageReferenceAdded; projectManager.PackageReferenceRemoving -= OnPackageReferenceRemoving; } WriteLine(); OpenReadMeFile(); CollapseNodes(); } private Tuple<IProjectManager, Project> GetProjectManager() { if (PackageManager == null) { return null; } Project project = null; // If the user specified a project then use it if (!String.IsNullOrEmpty(ProjectName)) { project = SolutionManager.GetProject(ProjectName); // If that project was invalid then throw if (project == null) { ErrorHandler.ThrowNoCompatibleProjectsTerminatingError(); } } else if (!String.IsNullOrEmpty(SolutionManager.DefaultProjectName)) { // If there is a default project then use it project = SolutionManager.GetProject(SolutionManager.DefaultProjectName); Debug.Assert(project != null, "default project should never be invalid"); } if (project == null) { // No project specified and default project was null return null; } return GetProjectManager(project); } private Tuple<IProjectManager, Project> GetProjectManager(Project project) { IProjectManager projectManager = RegisterProjectEvents(project); return Tuple.Create(projectManager, project); } protected IProjectManager RegisterProjectEvents(Project project) { IProjectManager projectManager = PackageManager.GetProjectManager(project); if (!_projectManagerToProject.ContainsKey(projectManager)) { projectManager.PackageReferenceAdded += OnPackageReferenceAdded; projectManager.PackageReferenceRemoving += OnPackageReferenceRemoving; // Associate the project manager with this project _projectManagerToProject[projectManager] = project; } return projectManager; } private void OnPackageInstalling(object sender, PackageOperationEventArgs e) { // Write disclaimer text before a package is installed WriteDisclaimerText(e.Package); } private void OnPackageInstalled(object sender, PackageOperationEventArgs e) { AddToolsFolderToEnvironmentPath(e.InstallPath); ExecuteScript(e.InstallPath, PowerShellScripts.Init, e.Package, null); PrepareOpenReadMeFile(e); } private void PrepareOpenReadMeFile(PackageOperationEventArgs e) { // only open the read me file for the first package that initiates this operation. if (e.Package.Id.Equals(this.Id, StringComparison.OrdinalIgnoreCase) && e.Package.HasReadMeFileAtRoot()) { _readmeFile = Path.Combine(e.InstallPath, NuGetConstants.ReadmeFileName); } } private void OpenReadMeFile() { if (_readmeFile != null ) { _vsCommonOperations.OpenFile(_readmeFile); } } protected virtual void AddToolsFolderToEnvironmentPath(string installPath) { string toolsPath = Path.Combine(installPath, "tools"); if (Directory.Exists(toolsPath)) { var envPath = (string)GetVariableValue("env:path"); if (!envPath.EndsWith(";", StringComparison.OrdinalIgnoreCase)) { envPath = envPath + ";"; } envPath += toolsPath; SessionState.PSVariable.Set("env:path", envPath); } } private void OnPackageReferenceAdded(object sender, PackageOperationEventArgs e) { var projectManager = (ProjectManager)sender; Project project; if (!_projectManagerToProject.TryGetValue(projectManager, out project)) { throw new ArgumentException(Resources.Cmdlet_InvalidProjectManagerInstance, "sender"); } ExecuteScript(e.InstallPath, PowerShellScripts.Install, e.Package, project); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void OnPackageReferenceRemoving(object sender, PackageOperationEventArgs e) { var projectManager = (ProjectManager)sender; Project project; if (!_projectManagerToProject.TryGetValue(projectManager, out project)) { throw new ArgumentException(Resources.Cmdlet_InvalidProjectManagerInstance, "sender"); } try { ExecuteScript(e.InstallPath, PowerShellScripts.Uninstall, e.Package, project); } catch (Exception ex) { Log(MessageLevel.Warning, ex.Message); } } protected virtual void ExecuteScript(string rootPath, string scriptFileName, IPackage package, Project project) { string toolsPath = Path.Combine(rootPath, "tools"); string fullPath = Path.Combine(toolsPath, scriptFileName); if (File.Exists(fullPath)) { var psVariable = SessionState.PSVariable; // set temp variables to pass to the script psVariable.Set("__rootPath", rootPath); psVariable.Set("__toolsPath", toolsPath); psVariable.Set("__package", package); psVariable.Set("__project", project); string command = "& " + PathHelper.EscapePSPath(fullPath) + " $__rootPath $__toolsPath $__package $__project"; WriteVerbose(String.Format(CultureInfo.CurrentCulture, VsResources.ExecutingScript, fullPath)); InvokeCommand.InvokeScript(command, false, PipelineResultTypes.Error, null, null); // clear temp variables psVariable.Remove("__rootPath"); psVariable.Remove("__toolsPath"); psVariable.Remove("__package"); psVariable.Remove("__project"); } } protected virtual void WriteDisclaimerText(IPackageMetadata package) { if (package.RequireLicenseAcceptance) { string message = String.Format( CultureInfo.CurrentCulture, Resources.Cmdlet_InstallSuccessDisclaimerText, package.Id, String.Join(", ", package.Authors), package.LicenseUrl); WriteLine(message); } } private void SaveExpandedNodes() { // remember which nodes are currently open so that we can keep them open after the operation _expandedNodesDisposable = _vsCommonOperations.SaveSolutionExplorerNodeStates(SolutionManager); } private void CollapseNodes() { // collapse all nodes in solution explorer that we expanded during the operation if (_expandedNodesDisposable != null) { _expandedNodesDisposable.Dispose(); _expandedNodesDisposable = null; } } } }
// *********************************************************************** // Copyright (c) 2009 Charlie Poole, Rob Prouse // // 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 NUnit.Framework.Constraints.Comparers; namespace NUnit.Framework.Constraints { /// <summary> /// NUnitEqualityComparer encapsulates NUnit's handling of /// equality tests between objects. /// </summary> public sealed class NUnitEqualityComparer { #region Static and Instance Fields /// <summary> /// If true, all string comparisons will ignore case /// </summary> private bool caseInsensitive; /// <summary> /// If true, arrays will be treated as collections, allowing /// those of different dimensions to be compared /// </summary> private bool compareAsCollection; /// <summary> /// Comparison objects used in comparisons for some constraints. /// </summary> private readonly List<EqualityAdapter> externalComparers = new List<EqualityAdapter>(); /// <summary> /// List of points at which a failure occurred. /// </summary> private List<FailurePoint> failurePoints; /// <summary> /// List of comparers used to compare pairs of objects. /// </summary> private readonly List<IChainComparer> _comparers; #endregion /// <summary> /// Initializes a new instance of the <see cref="NUnitEqualityComparer"/> class. /// </summary> public NUnitEqualityComparer() { var enumerablesComparer = new EnumerablesComparer(this); _comparers = new List<IChainComparer> { new ArraysComparer(this, enumerablesComparer), new DictionariesComparer(this), new DictionaryEntriesComparer(this), new KeyValuePairsComparer(this), new StringsComparer(this ), new StreamsComparer(this), new CharsComparer(this), new DirectoriesComparer(), new NumericsComparer(), new DateTimeOffsetsComparer(this), new TimeSpanToleranceComparer(), new EquatablesComparer(this), new TupleComparer(this), new ValueTupleComparer(this), enumerablesComparer }; } #region Properties /// <summary> /// Returns the default NUnitEqualityComparer /// </summary> [Obsolete("Deprecated. Use the default constructor instead.")] public static NUnitEqualityComparer Default { get { return new NUnitEqualityComparer(); } } /// <summary> /// Gets and sets a flag indicating whether case should /// be ignored in determining equality. /// </summary> public bool IgnoreCase { get { return caseInsensitive; } set { caseInsensitive = value; } } /// <summary> /// Gets and sets a flag indicating that arrays should be /// compared as collections, without regard to their shape. /// </summary> public bool CompareAsCollection { get { return compareAsCollection; } set { compareAsCollection = value; } } /// <summary> /// Gets the list of external comparers to be used to /// test for equality. They are applied to members of /// collections, in place of NUnit's own logic. /// </summary> public IList<EqualityAdapter> ExternalComparers { get { return externalComparers; } } // TODO: Define some sort of FailurePoint struct or otherwise // eliminate the type-unsafeness of the current approach /// <summary> /// Gets the list of failure points for the last Match performed. /// The list consists of objects to be interpreted by the caller. /// This generally means that the caller may only make use of /// objects it has placed on the list at a particular depth. /// </summary> public IList<FailurePoint> FailurePoints { get { return failurePoints; } } /// <summary> /// Flags the comparer to include <see cref="DateTimeOffset.Offset"/> /// property in comparison of two <see cref="DateTimeOffset"/> values. /// </summary> /// <remarks> /// Using this modifier does not allow to use the <see cref="Tolerance"/> /// modifier. /// </remarks> public bool WithSameOffset { get; set; } #endregion #region Public Methods /// <summary> /// Compares two objects for equality within a tolerance. /// </summary> public bool AreEqual(object x, object y, ref Tolerance tolerance, bool topLevelComparison = true) { this.failurePoints = new List<FailurePoint>(); if (x == null && y == null) return true; if (x == null || y == null) return false; if (object.ReferenceEquals(x, y)) return true; EqualityAdapter externalComparer = GetExternalComparer(x, y); if (externalComparer != null) return externalComparer.AreEqual(x, y); foreach (IChainComparer comparer in _comparers) { bool? result = comparer.Equal(x, y, ref tolerance, topLevelComparison); if (result.HasValue) return result.Value; } return x.Equals(y); } #endregion #region Helper Methods private EqualityAdapter GetExternalComparer(object x, object y) { foreach (EqualityAdapter adapter in externalComparers) if (adapter.CanCompare(x, y)) return adapter; return null; } #endregion #region Nested FailurePoint Class /// <summary> /// FailurePoint class represents one point of failure /// in an equality test. /// </summary> public sealed class FailurePoint { /// <summary> /// The location of the failure /// </summary> public long Position; /// <summary> /// The expected value /// </summary> public object ExpectedValue; /// <summary> /// The actual value /// </summary> public object ActualValue; /// <summary> /// Indicates whether the expected value is valid /// </summary> public bool ExpectedHasData; /// <summary> /// Indicates whether the actual value is valid /// </summary> public bool ActualHasData; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Abp.Authorization.Users; using Abp.Dependency; using Abp.IdentityFramework; using Abp.Localization; using Abp.MultiTenancy; using Abp.Runtime.Caching; using Abp.Runtime.Session; using Abp.Zero; using Abp.Zero.Configuration; using Microsoft.AspNet.Identity; namespace Abp.Authorization.Roles { /// <summary> /// Extends <see cref="RoleManager{TRole,TKey}"/> of ASP.NET Identity Framework. /// Applications should derive this class with appropriate generic arguments. /// </summary> public abstract class AbpRoleManager<TTenant, TRole, TUser> : RoleManager<TRole, int>, ITransientDependency where TTenant : AbpTenant<TTenant, TUser> where TRole : AbpRole<TTenant, TUser>, new() where TUser : AbpUser<TTenant, TUser> { public ILocalizationManager LocalizationManager { get; set; } public IAbpSession AbpSession { get; set; } public IRoleManagementConfig RoleManagementConfig { get; private set; } private IRolePermissionStore<TTenant, TRole, TUser> RolePermissionStore { get { if (!(Store is IRolePermissionStore<TTenant, TRole, TUser>)) { throw new AbpException("Store is not IRolePermissionStore"); } return Store as IRolePermissionStore<TTenant, TRole, TUser>; } } protected AbpRoleStore<TTenant, TRole, TUser> AbpStore { get; private set; } private readonly IPermissionManager _permissionManager; private readonly ICacheManager _cacheManager; /// <summary> /// Constructor. /// </summary> protected AbpRoleManager( AbpRoleStore<TTenant, TRole, TUser> store, IPermissionManager permissionManager, IRoleManagementConfig roleManagementConfig, ICacheManager cacheManager) : base(store) { _permissionManager = permissionManager; _cacheManager = cacheManager; RoleManagementConfig = roleManagementConfig; AbpStore = store; AbpSession = NullAbpSession.Instance; LocalizationManager = NullLocalizationManager.Instance; } #region Obsolete methods /// <summary> /// Checks if a role has a permission. /// </summary> /// <param name="roleName">The role's name to check it's permission</param> /// <param name="permissionName">Name of the permission</param> /// <returns>True, if the role has the permission</returns> [Obsolete("Use IsGrantedAsync instead.")] public virtual async Task<bool> HasPermissionAsync(string roleName, string permissionName) { return await IsGrantedAsync((await GetRoleByNameAsync(roleName)).Id, _permissionManager.GetPermission(permissionName)); } /// <summary> /// Checks if a role has a permission. /// </summary> /// <param name="roleId">The role's id to check it's permission</param> /// <param name="permissionName">Name of the permission</param> /// <returns>True, if the role has the permission</returns> [Obsolete("Use IsGrantedAsync instead.")] public virtual async Task<bool> HasPermissionAsync(int roleId, string permissionName) { return await IsGrantedAsync(roleId, _permissionManager.GetPermission(permissionName)); } /// <summary> /// Checks if a role has a permission. /// </summary> /// <param name="role">The role</param> /// <param name="permission">The permission</param> /// <returns>True, if the role has the permission</returns> [Obsolete("Use IsGrantedAsync instead.")] public Task<bool> HasPermissionAsync(TRole role, Permission permission) { return IsGrantedAsync(role.Id, permission); } /// <summary> /// Checks if a role has a permission. /// </summary> /// <param name="roleId">role id</param> /// <param name="permission">The permission</param> /// <returns>True, if the role has the permission</returns> [Obsolete("Use IsGrantedAsync instead.")] public Task<bool> HasPermissionAsync(int roleId, Permission permission) { return IsGrantedAsync(roleId, permission); } #endregion /// <summary> /// Checks if a role is granted for a permission. /// </summary> /// <param name="roleName">The role's name to check it's permission</param> /// <param name="permissionName">Name of the permission</param> /// <returns>True, if the role has the permission</returns> public virtual async Task<bool> IsGrantedAsync(string roleName, string permissionName) { return await IsGrantedAsync((await GetRoleByNameAsync(roleName)).Id, _permissionManager.GetPermission(permissionName)); } /// <summary> /// Checks if a role has a permission. /// </summary> /// <param name="roleId">The role's id to check it's permission</param> /// <param name="permissionName">Name of the permission</param> /// <returns>True, if the role has the permission</returns> public virtual async Task<bool> IsGrantedAsync(int roleId, string permissionName) { return await IsGrantedAsync(roleId, _permissionManager.GetPermission(permissionName)); } /// <summary> /// Checks if a role is granted for a permission. /// </summary> /// <param name="role">The role</param> /// <param name="permission">The permission</param> /// <returns>True, if the role has the permission</returns> public Task<bool> IsGrantedAsync(TRole role, Permission permission) { return IsGrantedAsync(role.Id, permission); } /// <summary> /// Checks if a role is granted for a permission. /// </summary> /// <param name="roleId">role id</param> /// <param name="permission">The permission</param> /// <returns>True, if the role has the permission</returns> public virtual async Task<bool> IsGrantedAsync(int roleId, Permission permission) { //Get cached role permissions var cacheItem = await GetRolePermissionCacheItemAsync(roleId); //Check the permission return permission.IsGrantedByDefault ? !(cacheItem.ProhibitedPermissions.Contains(permission.Name)) : (cacheItem.GrantedPermissions.Contains(permission.Name)); } /// <summary> /// Gets granted permission names for a role. /// </summary> /// <param name="roleId">Role id</param> /// <returns>List of granted permissions</returns> public virtual async Task<IReadOnlyList<Permission>> GetGrantedPermissionsAsync(int roleId) { return await GetGrantedPermissionsAsync(await GetRoleByIdAsync(roleId)); } /// <summary> /// Gets granted permission names for a role. /// </summary> /// <param name="roleName">Role name</param> /// <returns>List of granted permissions</returns> public virtual async Task<IReadOnlyList<Permission>> GetGrantedPermissionsAsync(string roleName) { return await GetGrantedPermissionsAsync(await GetRoleByNameAsync(roleName)); } /// <summary> /// Gets granted permissions for a role. /// </summary> /// <param name="role">Role</param> /// <returns>List of granted permissions</returns> public virtual async Task<IReadOnlyList<Permission>> GetGrantedPermissionsAsync(TRole role) { var permissionList = new List<Permission>(); foreach (var permission in _permissionManager.GetAllPermissions()) { if (await IsGrantedAsync(role.Id, permission)) { permissionList.Add(permission); } } return permissionList; } /// <summary> /// Sets all granted permissions of a role at once. /// Prohibits all other permissions. /// </summary> /// <param name="roleId">Role id</param> /// <param name="permissions">Permissions</param> public virtual async Task SetGrantedPermissionsAsync(int roleId, IEnumerable<Permission> permissions) { await SetGrantedPermissionsAsync(await GetRoleByIdAsync(roleId), permissions); } /// <summary> /// Sets all granted permissions of a role at once. /// Prohibits all other permissions. /// </summary> /// <param name="role">The role</param> /// <param name="permissions">Permissions</param> public virtual async Task SetGrantedPermissionsAsync(TRole role, IEnumerable<Permission> permissions) { var oldPermissions = await GetGrantedPermissionsAsync(role); var newPermissions = permissions.ToArray(); foreach (var permission in oldPermissions.Where(p => !newPermissions.Contains(p))) { await ProhibitPermissionAsync(role, permission); } foreach (var permission in newPermissions.Where(p => !oldPermissions.Contains(p))) { await GrantPermissionAsync(role, permission); } } /// <summary> /// Grants a permission for a role. /// </summary> /// <param name="role">Role</param> /// <param name="permission">Permission</param> public async Task GrantPermissionAsync(TRole role, Permission permission) { if (await IsGrantedAsync(role.Id, permission)) { return; } if (permission.IsGrantedByDefault) { await RolePermissionStore.RemovePermissionAsync(role, new PermissionGrantInfo(permission.Name, false)); } else { await RolePermissionStore.AddPermissionAsync(role, new PermissionGrantInfo(permission.Name, true)); } } /// <summary> /// Prohibits a permission for a role. /// </summary> /// <param name="role">Role</param> /// <param name="permission">Permission</param> public async Task ProhibitPermissionAsync(TRole role, Permission permission) { if (!await IsGrantedAsync(role.Id, permission)) { return; } if (permission.IsGrantedByDefault) { await RolePermissionStore.AddPermissionAsync(role, new PermissionGrantInfo(permission.Name, false)); } else { await RolePermissionStore.RemovePermissionAsync(role, new PermissionGrantInfo(permission.Name, true)); } } /// <summary> /// Prohibits all permissions for a role. /// </summary> /// <param name="role">Role</param> public async Task ProhibitAllPermissionsAsync(TRole role) { foreach (var permission in _permissionManager.GetAllPermissions()) { await ProhibitPermissionAsync(role, permission); } } /// <summary> /// Resets all permission settings for a role. /// It removes all permission settings for the role. /// Role will have permissions those have <see cref="Permission.IsGrantedByDefault"/> set to true. /// </summary> /// <param name="role">Role</param> public async Task ResetAllPermissionsAsync(TRole role) { await RolePermissionStore.RemoveAllPermissionSettingsAsync(role); } /// <summary> /// Creates a role. /// </summary> /// <param name="role">Role</param> public override async Task<IdentityResult> CreateAsync(TRole role) { var result = await CheckDuplicateRoleNameAsync(role.Id, role.Name, role.DisplayName); if (!result.Succeeded) { return result; } if (AbpSession.TenantId.HasValue) { role.TenantId = AbpSession.TenantId.Value; } return await base.CreateAsync(role); } public override async Task<IdentityResult> UpdateAsync(TRole role) { var result = await CheckDuplicateRoleNameAsync(role.Id, role.Name, role.DisplayName); if (!result.Succeeded) { return result; } return await base.UpdateAsync(role); } /// <summary> /// Deletes a role. /// </summary> /// <param name="role">Role</param> public async override Task<IdentityResult> DeleteAsync(TRole role) { if (role.IsStatic) { return AbpIdentityResult.Failed(string.Format(L("CanNotDeleteStaticRole"), role.Name)); } return await base.DeleteAsync(role); } /// <summary> /// Gets a role by given id. /// Throws exception if no role with given id. /// </summary> /// <param name="roleId">Role id</param> /// <returns>Role</returns> /// <exception cref="AbpException">Throws exception if no role with given id</exception> public virtual async Task<TRole> GetRoleByIdAsync(int roleId) { var role = await FindByIdAsync(roleId); if (role == null) { throw new AbpException("There is no role with id: " + roleId); } return role; } /// <summary> /// Gets a role by given name. /// Throws exception if no role with given roleName. /// </summary> /// <param name="roleName">Role name</param> /// <returns>Role</returns> /// <exception cref="AbpException">Throws exception if no role with given roleName</exception> public virtual async Task<TRole> GetRoleByNameAsync(string roleName) { var role = await FindByNameAsync(roleName); if (role == null) { throw new AbpException("There is no role with name: " + roleName); } return role; } public async Task GrantAllPermissionsAsync(TRole role) { var permissions = _permissionManager.GetAllPermissions(role.GetMultiTenancySide()); await SetGrantedPermissionsAsync(role, permissions); } public virtual async Task<IdentityResult> CreateStaticRoles(int tenantId) { var staticRoleDefinitions = RoleManagementConfig.StaticRoles.Where(sr => sr.Side == MultiTenancySides.Tenant); foreach (var staticRoleDefinition in staticRoleDefinitions) { var role = new TRole { TenantId = tenantId, Name = staticRoleDefinition.RoleName, DisplayName = staticRoleDefinition.RoleName, IsStatic = true }; var identityResult = await CreateAsync(role); if (!identityResult.Succeeded) { return identityResult; } } return IdentityResult.Success; } public virtual async Task<IdentityResult> CheckDuplicateRoleNameAsync(int? expectedRoleId, string name, string displayName) { var role = await FindByNameAsync(name); if (role != null && role.Id != expectedRoleId) { return AbpIdentityResult.Failed(string.Format(L("RoleNameIsAlreadyTaken"), name)); } role = await FindByDisplayNameAsync(displayName); if (role != null && role.Id != expectedRoleId) { return AbpIdentityResult.Failed(string.Format(L("RoleDisplayNameIsAlreadyTaken"), displayName)); } return IdentityResult.Success; } private Task<TRole> FindByDisplayNameAsync(string displayName) { return AbpStore.FindByDisplayNameAsync(displayName); } private async Task<RolePermissionCacheItem> GetRolePermissionCacheItemAsync(int roleId) { return await _cacheManager.GetRolePermissionCache().GetAsync(roleId, async () => { var newCacheItem = new RolePermissionCacheItem(roleId); foreach (var permissionInfo in await RolePermissionStore.GetPermissionsAsync(roleId)) { if (permissionInfo.IsGranted) { newCacheItem.GrantedPermissions.Add(permissionInfo.Name); } else { newCacheItem.ProhibitedPermissions.Add(permissionInfo.Name); } } return newCacheItem; }); } private string L(string name) { return LocalizationManager.GetString(AbpZeroConsts.LocalizationSourceName, name); } } }
//------------------------------------------------------------------------------ // <copyright file="SystemFonts.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Drawing { using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.IO; using System.Runtime.Versioning; /// <include file='doc\SystemFonts.uex' path='docs/doc[@for="SystemFonts"]/*' /> /// <devdoc> /// Selected system-wide fonts. /// </devdoc> public sealed class SystemFonts { private static readonly object SystemFontsKey = new object(); // Cannot be instantiated. private SystemFonts() { } /// <include file='doc\SystemFonts.uex' path='docs/doc[@for="SystemFonts.CaptionFont"]/*' /> /// <devdoc> /// <para> /// Gets the system's font for captions. /// </para> /// </devdoc> public static Font CaptionFont { get { Font captionFont = null; NativeMethods.NONCLIENTMETRICS data = new NativeMethods.NONCLIENTMETRICS(); bool result = UnsafeNativeMethods.SystemParametersInfo(NativeMethods.SPI_GETNONCLIENTMETRICS, data.cbSize, data, 0); if (result && data.lfCaptionFont != null) { // SECREVIEW : This assert is ok. The LOGFONT struct passed to Font.FromLogFont was obtained from the system. // IntSecurity.ObjectFromWin32Handle.Assert(); try { captionFont = Font.FromLogFont(data.lfCaptionFont); } catch (Exception ex) { if( IsCriticalFontException(ex) ){ throw; } } finally { CodeAccessPermission.RevertAssert(); } if( captionFont == null ) { captionFont = DefaultFont; } else if (captionFont.Unit != GraphicsUnit.Point) { captionFont = FontInPoints(captionFont); } } captionFont.SetSystemFontName("CaptionFont"); return captionFont; } } /// <include file='doc\SystemFonts.uex' path='docs/doc[@for="SystemFonts.SmallCaptionFont"]/*' /> /// <devdoc> /// <para> /// Gets the system's font for small captions. /// </para> /// </devdoc> public static Font SmallCaptionFont { get { Font smcaptionFont = null; NativeMethods.NONCLIENTMETRICS data = new NativeMethods.NONCLIENTMETRICS(); bool result = UnsafeNativeMethods.SystemParametersInfo(NativeMethods.SPI_GETNONCLIENTMETRICS, data.cbSize, data, 0); if (result && data.lfSmCaptionFont != null) { // SECREVIEW : This assert is ok. The LOGFONT struct passed to Font.FromLogFont was obtained from the system. // IntSecurity.ObjectFromWin32Handle.Assert(); try { smcaptionFont = Font.FromLogFont(data.lfSmCaptionFont); } catch (Exception ex) { if( IsCriticalFontException(ex) ){ throw; } } finally { CodeAccessPermission.RevertAssert(); } if( smcaptionFont == null ) { smcaptionFont = DefaultFont; } else if (smcaptionFont.Unit != GraphicsUnit.Point) { smcaptionFont = FontInPoints(smcaptionFont); } } smcaptionFont.SetSystemFontName("SmallCaptionFont"); return smcaptionFont; } } /// <include file='doc\SystemFonts.uex' path='docs/doc[@for="SystemFonts.MenuFont"]/*' /> /// <devdoc> /// <para> /// Gets the system's font for menus. /// </para> /// </devdoc> public static Font MenuFont { get { Font menuFont = null; NativeMethods.NONCLIENTMETRICS data = new NativeMethods.NONCLIENTMETRICS(); bool result = UnsafeNativeMethods.SystemParametersInfo(NativeMethods.SPI_GETNONCLIENTMETRICS, data.cbSize, data, 0); if (result && data.lfMenuFont != null) { // SECREVIEW : This assert is ok. The LOGFONT struct passed to Font.FromLogFont was obtained from the system. // IntSecurity.ObjectFromWin32Handle.Assert(); try { menuFont = Font.FromLogFont(data.lfMenuFont); } catch (Exception ex) { if( IsCriticalFontException(ex) ){ throw; } } finally { CodeAccessPermission.RevertAssert(); } if( menuFont == null ) { menuFont = DefaultFont; } else if (menuFont.Unit != GraphicsUnit.Point) { menuFont = FontInPoints(menuFont); } } menuFont.SetSystemFontName("MenuFont"); return menuFont; } } /// <include file='doc\SystemFonts.uex' path='docs/doc[@for="SystemFonts.StatusFont"]/*' /> /// <devdoc> /// <para> /// Gets the system's font for status bars. /// </para> /// </devdoc> public static Font StatusFont { get { Font statusFont = null; NativeMethods.NONCLIENTMETRICS data = new NativeMethods.NONCLIENTMETRICS(); bool result = UnsafeNativeMethods.SystemParametersInfo(NativeMethods.SPI_GETNONCLIENTMETRICS, data.cbSize, data, 0); if (result && data.lfStatusFont != null) { // SECREVIEW : This assert is ok. The LOGFONT struct passed to Font.FromLogFont was obtained from the system. // IntSecurity.ObjectFromWin32Handle.Assert(); try { statusFont = Font.FromLogFont(data.lfStatusFont); } catch (Exception ex) { if( IsCriticalFontException(ex) ){ throw; } } finally { CodeAccessPermission.RevertAssert(); } if( statusFont == null ) { statusFont = DefaultFont; } else if (statusFont.Unit != GraphicsUnit.Point) { statusFont = FontInPoints(statusFont); } } statusFont.SetSystemFontName("StatusFont"); return statusFont; } } /// <include file='doc\SystemFonts.uex' path='docs/doc[@for="SystemFonts.MessageBoxFont"]/*' /> /// <devdoc> /// <para> /// Gets the system's font for message boxes. /// </para> /// </devdoc> public static Font MessageBoxFont { get { Font messageboxFont = null; NativeMethods.NONCLIENTMETRICS data = new NativeMethods.NONCLIENTMETRICS(); bool result = UnsafeNativeMethods.SystemParametersInfo(NativeMethods.SPI_GETNONCLIENTMETRICS, data.cbSize, data, 0); if (result && data.lfMessageFont != null) { // SECREVIEW : This assert is ok. The LOGFONT struct passed to Font.FromLogFont was obtained from the system. // IntSecurity.ObjectFromWin32Handle.Assert(); try { messageboxFont = Font.FromLogFont(data.lfMessageFont); } catch (Exception ex) { if( IsCriticalFontException(ex) ){ throw; } } finally { CodeAccessPermission.RevertAssert(); } if( messageboxFont == null ) { messageboxFont = DefaultFont; } else if (messageboxFont.Unit != GraphicsUnit.Point) { messageboxFont = FontInPoints(messageboxFont); } } messageboxFont.SetSystemFontName("MessageBoxFont"); return messageboxFont; } } /// <devdoc> /// Determines whether the specified exception should be handled. /// </devdoc> private static bool IsCriticalFontException( Exception ex ){ return !( // In any of these cases we'll handle the exception. ex is ExternalException || ex is ArgumentException || ex is OutOfMemoryException || // GDI+ throws this one for many reasons other than actual OOM. ex is InvalidOperationException || ex is NotImplementedException || ex is FileNotFoundException ); } /// <include file='doc\SystemFonts.uex' path='docs/doc[@for="SystemFonts.IconTitleFont"]/*' /> /// <devdoc> /// <para> /// Gets the system's font for icon titles. /// </para> /// </devdoc> public static Font IconTitleFont { get { Font icontitleFont = null; SafeNativeMethods.LOGFONT itfont = new SafeNativeMethods.LOGFONT(); bool result = UnsafeNativeMethods.SystemParametersInfo(NativeMethods.SPI_GETICONTITLELOGFONT, Marshal.SizeOf(itfont), itfont, 0); if (result && itfont != null) { // SECREVIEW : This assert is ok. The LOGFONT struct passed to Font.FromLogFont was obtained from the system. // IntSecurity.ObjectFromWin32Handle.Assert(); try { icontitleFont = Font.FromLogFont(itfont); } catch (Exception ex) { if( IsCriticalFontException(ex) ){ throw; } } finally { CodeAccessPermission.RevertAssert(); } if (icontitleFont == null ) { icontitleFont = DefaultFont; } else if (icontitleFont.Unit != GraphicsUnit.Point) { icontitleFont = FontInPoints(icontitleFont); } } icontitleFont.SetSystemFontName("IconTitleFont"); return icontitleFont; } } ////////////////////////////////////////////////////////////////////////////////////////////// // // // SystemFonts.DefaultFont is code moved from System.Windows.Forms.Control.DefaultFont // // System.Windows.Forms.Control.DefaultFont delegates to SystemFonts.DefaultFont now. // // Treat any changes to this code as you would treat breaking changes. // // // ////////////////////////////////////////////////////////////////////////////////////////////// /// <include file='doc\SystemFonts.uex' path='docs/doc[@for="SystemFonts.DefaultFont"]/*' /> /// <devdoc> /// <para> /// Gets the system's default font. /// </para> /// </devdoc> public static Font DefaultFont { get { Font defaultFont = null; //special case defaultfont for arabic systems too bool systemDefaultLCIDIsArabic = false; // For Japanese on Win9x get the MS UI Gothic font if (Environment.OSVersion.Platform == System.PlatformID.Win32NT && Environment.OSVersion.Version.Major <= 4) { if((UnsafeNativeMethods.GetSystemDefaultLCID() & 0x3ff) == 0x0011) { try { defaultFont = new Font("MS UI Gothic", 9); } //fall through here if this fails and we'll get the default //font via the DEFAULT_GUI method catch (Exception ex) { if( IsCriticalFontException(ex) ){ throw; } } } } if (defaultFont == null) { systemDefaultLCIDIsArabic = ((UnsafeNativeMethods.GetSystemDefaultLCID() & 0x3ff) == 0x0001); } // For arabic systems, regardless of the platform, always return Tahoma 8. // vsWhidbey 82453. if (systemDefaultLCIDIsArabic) { Debug.Assert(defaultFont == null); // Try TAHOMA 8 try { defaultFont = new Font("Tahoma", 8); } catch (Exception ex) { if( IsCriticalFontException(ex) ){ throw; } } } // // Neither Japanese on Win9x nor Arabic. // First try DEFAULT_GUI, then Tahoma 8, then GenericSansSerif 8. // // first, try DEFAULT_GUI font. // if (defaultFont == null) { IntPtr handle = UnsafeNativeMethods.GetStockObject(NativeMethods.DEFAULT_GUI_FONT); try { Font fontInWorldUnits = null; // SECREVIEW : We know that we got the handle from the stock object, // : so this is always safe. // IntSecurity.ObjectFromWin32Handle.Assert(); try { fontInWorldUnits = Font.FromHfont(handle); } finally { CodeAccessPermission.RevertAssert(); } try{ defaultFont = FontInPoints(fontInWorldUnits); } finally{ fontInWorldUnits.Dispose(); } } catch (ArgumentException) { } } // If DEFAULT_GUI didn't work, we try Tahoma. // if (defaultFont == null) { try { defaultFont = new Font("Tahoma", 8); } catch (ArgumentException) { } } // Last resort, we use the GenericSansSerif - this will // always work. // if (defaultFont == null) { defaultFont = new Font(FontFamily.GenericSansSerif, 8); } if (defaultFont.Unit != GraphicsUnit.Point) { defaultFont = FontInPoints(defaultFont); } Debug.Assert(defaultFont != null, "defaultFont wasn't set!"); defaultFont.SetSystemFontName("DefaultFont"); return defaultFont; } } /// <include file='doc\SystemFonts.uex' path='docs/doc[@for="SystemFonts.DialogFont"]/*' /> /// <devdoc> /// <para> /// Gets the system's font for dialogs. /// </para> /// </devdoc> public static Font DialogFont { get { Font dialogFont = null; if((UnsafeNativeMethods.GetSystemDefaultLCID() & 0x3ff) == 0x0011) { // for JAPANESE culture always return DefaultFont dialogFont = DefaultFont; } else if (Environment.OSVersion.Platform == System.PlatformID.Win32Windows) { // use DefaultFont for Win9X dialogFont = DefaultFont; } else { try { // use MS Shell Dlg 2, 8pt for anything else than Japanese and Win9x dialogFont = new Font("MS Shell Dlg 2", 8); } catch (ArgumentException) { } } if (dialogFont == null) { dialogFont = DefaultFont; } else if (dialogFont.Unit != GraphicsUnit.Point) { dialogFont = FontInPoints(dialogFont); } // // JAPANESE or Win9x: SystemFonts.DefaultFont returns a new Font object every time it is invoked. // So for JAPANESE or Win9x we return the DefaultFont w/ its SystemFontName set to DialogFont. // dialogFont.SetSystemFontName("DialogFont"); return dialogFont; } } //Copied from System.Windows.Forms.ControlPaint [ResourceExposure(ResourceScope.Process)] [ResourceConsumption(ResourceScope.Process)] private static Font FontInPoints(Font font) { return new Font(font.FontFamily, font.SizeInPoints, font.Style, GraphicsUnit.Point, font.GdiCharSet, font.GdiVerticalFont); } /// <include file='doc\SystemFonts.uex' path='docs/doc[@for="SystemFonts.GetFontByName"]/*' /> /// <devdoc> /// <para> /// Gets the <see cref='System.Drawing.SystemFont'/> that corresponds to a given SystemFont name. /// </para> /// </devdoc> public static Font GetFontByName(string systemFontName) { if ("CaptionFont".Equals(systemFontName)) { return CaptionFont; } else if ("DefaultFont".Equals(systemFontName)) { return DefaultFont; } else if ("DialogFont".Equals(systemFontName)) { return DialogFont; } else if ("IconTitleFont".Equals(systemFontName)) { return IconTitleFont; } else if ("MenuFont".Equals(systemFontName)) { return MenuFont; } else if ("MessageBoxFont".Equals(systemFontName)) { return MessageBoxFont; } else if ("SmallCaptionFont".Equals(systemFontName)) { return SmallCaptionFont; } else if ("StatusFont".Equals(systemFontName)) { return StatusFont; } else { return null; } } } }
// 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 Microsoft.Protocols.TestTools.StackSdk; namespace Microsoft.Protocols.TestTools.StackSdk.Security.Nlmp { /// <summary> /// the authenticate packet of nlmp /// </summary> public class NlmpAuthenticatePacket : NlmpPacket { /// <summary> /// 2.2.1.3 AUTHENTICATE_MESSAGE The AUTHENTICATE_MESSAGE defines an NTLM authenticate message that is sent /// from the client to the server after the CHALLENGE_MESSAGE (section 2.2.1.2) is processed by the client. /// </summary> private AUTHENTICATE_MESSAGE payload; /// <summary> /// 2.2.1.3 AUTHENTICATE_MESSAGE The AUTHENTICATE_MESSAGE defines an NTLM authenticate message that is sent /// from the client to the server after the CHALLENGE_MESSAGE (section 2.2.1.2) is processed by the client. /// </summary> public AUTHENTICATE_MESSAGE Payload { get { return this.payload; } set { this.payload = value; } } /// <summary> /// the length of authenticate message /// </summary> protected override int PayLoadLength { get { return NlmpUtility.AUTHENTICATE_MESSAGE_CONST_SIZE + payload.DomainNameFields.Len + payload.EncryptedRandomSessionKeyFields.Len + payload.LmChallengeResponseFields.Len + payload.NtChallengeResponseFields.Len + payload.UserNameFields.Len + payload.WorkstationFields.Len; } } /// <summary> /// default empty constructor /// </summary> public NlmpAuthenticatePacket() { this.header.MessageType = MessageType_Values.AUTHENTICATE; this.payload.MIC = new byte[NlmpUtility.AUTHENTICATE_MESSAGE_MIC_CONST_SIZE]; } /// <summary> /// copy constructor. /// </summary> /// <param name="stackPacket">the source packet</param> /// <exception cref="ArgumentNullException">the stackPacket.payload.MIC must not be null</exception> /// <exception cref="ArgumentException">the stackPacket.payload.MIC.Length is wrong</exception> public NlmpAuthenticatePacket( NlmpAuthenticatePacket stackPacket ) : base(stackPacket) { this.payload = stackPacket.payload; if (stackPacket.payload.MIC == null) { throw new ArgumentNullException("stackPacket", "the stackPacket.payload.MIC must not be null"); } if (stackPacket.payload.MIC.Length != NlmpUtility.AUTHENTICATE_MESSAGE_MIC_CONST_SIZE) { throw new ArgumentException( string.Format("the stackPacket.payload.MIC.Length must be {0}, actually {1}", NlmpUtility.AUTHENTICATE_MESSAGE_MIC_CONST_SIZE, stackPacket.payload.MIC.Length), "stackPacket"); } this.payload.MIC = new byte[stackPacket.payload.MIC.Length]; Array.Copy(stackPacket.payload.MIC, this.payload.MIC, stackPacket.payload.MIC.Length); if (stackPacket.payload.DomainName != null) { this.payload.DomainName = new byte[stackPacket.payload.DomainName.Length]; Array.Copy( stackPacket.payload.DomainName, this.payload.DomainName, stackPacket.payload.DomainName.Length); } if (stackPacket.payload.UserName != null) { this.payload.UserName = new byte[stackPacket.payload.UserName.Length]; Array.Copy( stackPacket.payload.UserName, this.payload.UserName, stackPacket.payload.UserName.Length); } if (stackPacket.payload.Workstation != null) { this.payload.Workstation = new byte[stackPacket.payload.Workstation.Length]; Array.Copy( stackPacket.payload.Workstation, this.payload.Workstation, stackPacket.payload.Workstation.Length); } if (stackPacket.payload.LmChallengeResponse != null) { this.payload.LmChallengeResponse = new byte[stackPacket.payload.LmChallengeResponse.Length]; Array.Copy( stackPacket.payload.LmChallengeResponse, this.payload.LmChallengeResponse, stackPacket.payload.LmChallengeResponse.Length); } if (stackPacket.payload.NtChallengeResponse != null) { this.payload.NtChallengeResponse = new byte[stackPacket.payload.NtChallengeResponse.Length]; Array.Copy( stackPacket.payload.NtChallengeResponse, this.payload.NtChallengeResponse, stackPacket.payload.NtChallengeResponse.Length); } if (stackPacket.payload.EncryptedRandomSessionKey != null) { this.payload.EncryptedRandomSessionKey = new byte[stackPacket.payload.EncryptedRandomSessionKey.Length]; Array.Copy( stackPacket.payload.EncryptedRandomSessionKey, this.payload.EncryptedRandomSessionKey, stackPacket.payload.EncryptedRandomSessionKey.Length); } } /// <summary> /// decode packet from bytes /// </summary> /// <param name="packetBytes">the bytes contain packet</param> public NlmpAuthenticatePacket( byte[] packetBytes ) : base(packetBytes) { } /// <summary> /// to create an instance of the StackPacket class that is identical to the current StackPacket. /// </summary> /// <returns>return the clone of this packet</returns> public override StackPacket Clone() { return new NlmpAuthenticatePacket(this); } /// <summary> /// write the payload to bytes. For all sub class to marshal itself. /// </summary> /// <returns>the bytes of struct</returns> protected override byte[] WriteStructToBytes() { byte[] bytes = NlmpUtility.StructGetBytes(payload); if (PayLoadLength != bytes.Length) { throw new InvalidOperationException("the payload length is not equal to the marshal size!"); } return bytes; } /// <summary> /// read struct from bytes. All sub class override this to unmarshal itself. /// </summary> /// <param name="start">the start to read bytes</param> /// <param name="packetBytes">the bytes of struct</param> /// <returns>the read result, if success, return true.</returns> protected override bool ReadStructFromBytes( byte[] packetBytes, int start ) { AUTHENTICATE_MESSAGE authenticate = new AUTHENTICATE_MESSAGE(); authenticate.LmChallengeResponseFields = NlmpUtility.BytesToStruct<MESSAGE_FIELDS>( packetBytes, ref start); authenticate.NtChallengeResponseFields = NlmpUtility.BytesToStruct<MESSAGE_FIELDS>( packetBytes, ref start); authenticate.DomainNameFields = NlmpUtility.BytesToStruct<MESSAGE_FIELDS>( packetBytes, ref start); authenticate.UserNameFields = NlmpUtility.BytesToStruct<MESSAGE_FIELDS>( packetBytes, ref start); authenticate.WorkstationFields = NlmpUtility.BytesToStruct<MESSAGE_FIELDS>( packetBytes, ref start); authenticate.EncryptedRandomSessionKeyFields = NlmpUtility.BytesToStruct<MESSAGE_FIELDS>( packetBytes, ref start); authenticate.NegotiateFlags = (NegotiateTypes)NlmpUtility.BytesToStruct<uint>( packetBytes, ref start); authenticate.Version = NlmpUtility.BytesToStruct<VERSION>( packetBytes, ref start); authenticate.MIC = NlmpUtility.ReadBytes( packetBytes, ref start, NlmpUtility.AUTHENTICATE_MESSAGE_MIC_CONST_SIZE); int currentIndex = 0; while (currentIndex != start) { currentIndex = start; if (authenticate.DomainNameFields.Len != 0 && authenticate.DomainNameFields.BufferOffset == start) { authenticate.DomainName = NlmpUtility.ReadBytes( packetBytes, ref start, authenticate.DomainNameFields.Len); continue; } else if (authenticate.EncryptedRandomSessionKeyFields.Len != 0 && authenticate.EncryptedRandomSessionKeyFields.BufferOffset == start) { authenticate.EncryptedRandomSessionKey = NlmpUtility.ReadBytes( packetBytes, ref start, authenticate.EncryptedRandomSessionKeyFields.Len); continue; } else if (authenticate.LmChallengeResponseFields.Len != 0 && authenticate.LmChallengeResponseFields.BufferOffset == start) { authenticate.LmChallengeResponse = NlmpUtility.ReadBytes( packetBytes, ref start, authenticate.LmChallengeResponseFields.Len); continue; } else if (authenticate.NtChallengeResponseFields.Len != 0 && authenticate.NtChallengeResponseFields.BufferOffset == start) { authenticate.NtChallengeResponse = NlmpUtility.ReadBytes( packetBytes, ref start, authenticate.NtChallengeResponseFields.Len); continue; } else if (authenticate.UserNameFields.Len != 0 && authenticate.UserNameFields.BufferOffset == start) { authenticate.UserName = NlmpUtility.ReadBytes( packetBytes, ref start, authenticate.UserNameFields.Len); continue; } else if (authenticate.WorkstationFields.Len != 0 && authenticate.WorkstationFields.BufferOffset == start) { authenticate.Workstation = NlmpUtility.ReadBytes( packetBytes, ref start, authenticate.WorkstationFields.Len); continue; } else { break; } } this.payload = authenticate; return true; } /// <summary> /// set the version /// </summary> /// <param name="version">the new version</param> public override void SetVersion( VERSION version ) { payload.Version = version; } /// <summary> /// set the negotiate flags /// </summary> /// <param name="negotiateFlags">the new flags</param> public override void SetNegotiateFlags( NegotiateTypes negotiateFlags ) { payload.NegotiateFlags = negotiateFlags; } /// <summary> /// set the DomainName of payload /// </summary> /// <param name="domainName">the new payload value</param> public void SetDomainName( string domainName ) { payload.DomainName = NlmpUtility.StringGetBytes( NlmpUtility.UpperCase(domainName), NlmpUtility.IsUnicode(this.payload.NegotiateFlags)); payload.DomainNameFields.Len = (ushort)payload.DomainName.Length; payload.DomainNameFields.MaxLen = (ushort)payload.DomainName.Length; UpdateOffset(); } /// <summary> /// set the UserName of payload /// </summary> /// <param name="userName">the new payload value</param> public void SetUserName( string userName ) { payload.UserName = NlmpUtility.StringGetBytes( userName, NlmpUtility.IsUnicode(this.payload.NegotiateFlags)); payload.UserNameFields.Len = (ushort)payload.UserName.Length; payload.UserNameFields.MaxLen = (ushort)payload.UserName.Length; UpdateOffset(); } /// <summary> /// set the Workstation of payload /// </summary> /// <param name="workstation">the new payload value</param> public void SetWorkstation( string workstation ) { payload.Workstation = NlmpUtility.StringGetBytes( workstation, NlmpUtility.IsUnicode(this.payload.NegotiateFlags)); payload.WorkstationFields.Len = (ushort)payload.Workstation.Length; payload.WorkstationFields.MaxLen = (ushort)payload.Workstation.Length; UpdateOffset(); } /// <summary> /// set the Workstation of payload /// </summary> /// <param name="lmChallengeResponse">the new payload value</param> public void SetLmChallengeResponse( byte[] lmChallengeResponse ) { if (lmChallengeResponse == null) { return; } payload.LmChallengeResponseFields.Len = (ushort)lmChallengeResponse.Length; payload.LmChallengeResponseFields.MaxLen = (ushort)lmChallengeResponse.Length; payload.LmChallengeResponse = lmChallengeResponse; UpdateOffset(); } /// <summary> /// set the Workstation of payload /// </summary> /// <param name="ntChallengeResponse">the new payload value</param> public void SetNtChallengeResponse( byte[] ntChallengeResponse ) { if (ntChallengeResponse == null) { return; } payload.NtChallengeResponseFields.Len = (ushort)ntChallengeResponse.Length; payload.NtChallengeResponseFields.MaxLen = (ushort)ntChallengeResponse.Length; payload.NtChallengeResponse = ntChallengeResponse; UpdateOffset(); } /// <summary> /// set the Workstation of payload /// </summary> /// <param name="encryptedRandomSessionKey">the new payload value</param> public void SetEncryptedRandomSessionKey( byte[] encryptedRandomSessionKey ) { if (encryptedRandomSessionKey == null) { return; } payload.EncryptedRandomSessionKeyFields.Len = (ushort)encryptedRandomSessionKey.Length; payload.EncryptedRandomSessionKeyFields.MaxLen = (ushort)encryptedRandomSessionKey.Length; payload.EncryptedRandomSessionKey = encryptedRandomSessionKey; UpdateOffset(); } /// <summary> /// update the offset of payload /// </summary> private void UpdateOffset() { payload.DomainNameFields.BufferOffset = (uint)(HeaderLength + NlmpUtility.AUTHENTICATE_MESSAGE_CONST_SIZE); payload.UserNameFields.BufferOffset = (uint)( HeaderLength + NlmpUtility.AUTHENTICATE_MESSAGE_CONST_SIZE + payload.DomainNameFields.Len); payload.WorkstationFields.BufferOffset = (uint)( HeaderLength + NlmpUtility.AUTHENTICATE_MESSAGE_CONST_SIZE + payload.DomainNameFields.Len + payload.UserNameFields.Len); payload.LmChallengeResponseFields.BufferOffset = (uint)( HeaderLength + NlmpUtility.AUTHENTICATE_MESSAGE_CONST_SIZE + payload.DomainNameFields.Len + payload.UserNameFields.Len + payload.WorkstationFields.Len); payload.NtChallengeResponseFields.BufferOffset = (uint)( HeaderLength + NlmpUtility.AUTHENTICATE_MESSAGE_CONST_SIZE + payload.DomainNameFields.Len + payload.UserNameFields.Len + payload.WorkstationFields.Len + payload.LmChallengeResponseFields.Len); payload.EncryptedRandomSessionKeyFields.BufferOffset = (uint)( HeaderLength + NlmpUtility.AUTHENTICATE_MESSAGE_CONST_SIZE + payload.DomainNameFields.Len + payload.UserNameFields.Len + payload.WorkstationFields.Len + payload.LmChallengeResponseFields.Len + payload.NtChallengeResponseFields.Len); } } }
/* * 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; using System.Collections.Generic; using System.Text; /// <summary> /// Represents the base class for all time zone transitions. /// </summary> internal class TimeZoneTransition : ComplexProperty { private const string PeriodTarget = "Period"; private const string GroupTarget = "Group"; private TimeZoneDefinition timeZoneDefinition; private TimeZonePeriod targetPeriod; private TimeZoneTransitionGroup targetGroup; /// <summary> /// Creates a time zone period transition of the appropriate type given an XML element name. /// </summary> /// <param name="timeZoneDefinition">The time zone definition to which the transition will belong.</param> /// <param name="xmlElementName">The XML element name.</param> /// <returns>A TimeZonePeriodTransition instance.</returns> internal static TimeZoneTransition Create(TimeZoneDefinition timeZoneDefinition, string xmlElementName) { switch (xmlElementName) { case XmlElementNames.AbsoluteDateTransition: return new AbsoluteDateTransition(timeZoneDefinition); case XmlElementNames.RecurringDayTransition: return new RelativeDayOfMonthTransition(timeZoneDefinition); case XmlElementNames.RecurringDateTransition: return new AbsoluteDayOfMonthTransition(timeZoneDefinition); case XmlElementNames.Transition: return new TimeZoneTransition(timeZoneDefinition); default: throw new ServiceLocalException( string.Format( Strings.UnknownTimeZonePeriodTransitionType, xmlElementName)); } } /// <summary> /// Creates a time zone transition based on the specified transition time. /// </summary> /// <param name="timeZoneDefinition">The time zone definition that will own the transition.</param> /// <param name="targetPeriod">The period the transition will target.</param> /// <param name="transitionTime">The transition time to initialize from.</param> /// <returns>A TimeZoneTransition.</returns> internal static TimeZoneTransition CreateTimeZoneTransition( TimeZoneDefinition timeZoneDefinition, TimeZonePeriod targetPeriod, TimeZoneInfo.TransitionTime transitionTime) { TimeZoneTransition transition; if (transitionTime.IsFixedDateRule) { transition = new AbsoluteDayOfMonthTransition(timeZoneDefinition, targetPeriod); } else { transition = new RelativeDayOfMonthTransition(timeZoneDefinition, targetPeriod); } transition.InitializeFromTransitionTime(transitionTime); return transition; } /// <summary> /// Gets the XML element name associated with the transition. /// </summary> /// <returns>The XML element name associated with the transition.</returns> internal virtual string GetXmlElementName() { return XmlElementNames.Transition; } /// <summary> /// Creates a time zone transition time. /// </summary> /// <returns>A TimeZoneInfo.TransitionTime.</returns> internal virtual TimeZoneInfo.TransitionTime CreateTransitionTime() { throw new ServiceLocalException(Strings.InvalidOrUnsupportedTimeZoneDefinition); } /// <summary> /// Initializes this transition based on the specified transition time. /// </summary> /// <param name="transitionTime">The transition time to initialize from.</param> internal virtual void InitializeFromTransitionTime(TimeZoneInfo.TransitionTime transitionTime) { } /// <summary> /// Tries to read element from XML. /// </summary> /// <param name="reader">The reader.</param> /// <returns>True if element was read.</returns> internal override bool TryReadElementFromXml(EwsServiceXmlReader reader) { switch (reader.LocalName) { case XmlElementNames.To: string targetKind = reader.ReadAttributeValue(XmlAttributeNames.Kind); string targetId = reader.ReadElementValue(); switch (targetKind) { case TimeZoneTransition.PeriodTarget: if (!this.timeZoneDefinition.Periods.TryGetValue(targetId, out this.targetPeriod)) { throw new ServiceLocalException( string.Format( Strings.PeriodNotFound, targetId)); } break; case TimeZoneTransition.GroupTarget: if (!this.timeZoneDefinition.TransitionGroups.TryGetValue(targetId, out this.targetGroup)) { throw new ServiceLocalException( string.Format( Strings.TransitionGroupNotFound, targetId)); } break; default: throw new ServiceLocalException(Strings.UnsupportedTimeZonePeriodTransitionTarget); } return true; default: return false; } } /// <summary> /// Writes elements to XML. /// </summary> /// <param name="writer">The writer.</param> internal override void WriteElementsToXml(EwsServiceXmlWriter writer) { writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.To); if (this.targetPeriod != null) { writer.WriteAttributeValue(XmlAttributeNames.Kind, PeriodTarget); writer.WriteValue(this.targetPeriod.Id, XmlElementNames.To); } else { writer.WriteAttributeValue(XmlAttributeNames.Kind, GroupTarget); writer.WriteValue(this.targetGroup.Id, XmlElementNames.To); } writer.WriteEndElement(); // To } /// <summary> /// Loads from XML. /// </summary> /// <param name="reader">The reader.</param> internal void LoadFromXml(EwsServiceXmlReader reader) { this.LoadFromXml(reader, this.GetXmlElementName()); } /// <summary> /// Writes to XML. /// </summary> /// <param name="writer">The writer.</param> internal void WriteToXml(EwsServiceXmlWriter writer) { this.WriteToXml(writer, this.GetXmlElementName()); } /// <summary> /// Initializes a new instance of the <see cref="TimeZoneTransition"/> class. /// </summary> /// <param name="timeZoneDefinition">The time zone definition the transition will belong to.</param> internal TimeZoneTransition(TimeZoneDefinition timeZoneDefinition) : base() { this.timeZoneDefinition = timeZoneDefinition; } /// <summary> /// Initializes a new instance of the <see cref="TimeZoneTransition"/> class. /// </summary> /// <param name="timeZoneDefinition">The time zone definition the transition will belong to.</param> /// <param name="targetGroup">The transition group the transition will target.</param> internal TimeZoneTransition(TimeZoneDefinition timeZoneDefinition, TimeZoneTransitionGroup targetGroup) : this(timeZoneDefinition) { this.targetGroup = targetGroup; } /// <summary> /// Initializes a new instance of the <see cref="TimeZoneTransition"/> class. /// </summary> /// <param name="timeZoneDefinition">The time zone definition the transition will belong to.</param> /// <param name="targetPeriod">The period the transition will target.</param> internal TimeZoneTransition(TimeZoneDefinition timeZoneDefinition, TimeZonePeriod targetPeriod) : this(timeZoneDefinition) { this.targetPeriod = targetPeriod; } /// <summary> /// Gets the target period of the transition. /// </summary> internal TimeZonePeriod TargetPeriod { get { return this.targetPeriod; } } /// <summary> /// Gets the target transition group of the transition. /// </summary> internal TimeZoneTransitionGroup TargetGroup { get { return this.targetGroup; } } } }
namespace NEventStore { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading.Tasks; using NEventStore.Logging; using ALinq; [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "This behaves like a stream--not a .NET 'Stream' object, but a stream nonetheless.")] public sealed class OptimisticEventStream : IEventStream { private static readonly ILog Logger = LogFactory.BuildLogger(typeof(OptimisticEventStream)); private readonly ICollection<EventMessage> _committed = new LinkedList<EventMessage>(); private readonly IDictionary<string, object> _committedHeaders = new Dictionary<string, object>(); private readonly ICollection<EventMessage> _events = new LinkedList<EventMessage>(); private readonly ICollection<Guid> _identifiers = new HashSet<Guid>(); private readonly ICommitEvents _persistence; private readonly IDictionary<string, object> _uncommittedHeaders = new Dictionary<string, object>(); private readonly ISystemTimeProvider _systemTypeProvider; private bool _disposed; public OptimisticEventStream( string bucketId, string streamId, ICommitEvents persistence, ISystemTimeProvider systemTypeProvider ) { BucketId = bucketId; StreamId = streamId; _persistence = persistence; _systemTypeProvider = systemTypeProvider; } public string BucketId { get; private set; } public string StreamId { get; private set; } public int StreamRevision { get; private set; } public int CommitSequence { get; private set; } public ICollection<EventMessage> CommittedEvents { get { return new ImmutableCollection<EventMessage>(_committed); } } public IDictionary<string, object> CommittedHeaders { get { return _committedHeaders; } } public ICollection<EventMessage> UncommittedEvents { get { return new ImmutableCollection<EventMessage>(_events); } } public IDictionary<string, object> UncommittedHeaders { get { return _uncommittedHeaders; } } public async Task Initialize(int minRevision, int maxRevision) { var commits = _persistence.GetFrom(BucketId, StreamId, minRevision, maxRevision); await PopulateStream(minRevision, maxRevision, commits); if (minRevision > 0 && _committed.Count == 0) { throw new StreamNotFoundException(); } } public async Task Initialize(ISnapshot snapshot, int maxRevision) { if (snapshot.BucketId != BucketId || snapshot.StreamId != StreamId) { throw new ArgumentException("Invalid snapshot."); } var commits = _persistence.GetFrom(snapshot.BucketId, snapshot.StreamId, snapshot.StreamRevision, maxRevision); await PopulateStream(snapshot.StreamRevision + 1, maxRevision, commits); StreamRevision = snapshot.StreamRevision + _committed.Count; } public void Add(EventMessage uncommittedEvent) { if (uncommittedEvent == null || uncommittedEvent.Body == null) { return; } Logger.Debug(Resources.AppendingUncommittedToStream, StreamId); _events.Add(uncommittedEvent); } public async Task CommitChanges(Guid commitId) { Logger.Debug(Resources.AttemptingToCommitChanges, StreamId); if (_identifiers.Contains(commitId)) { throw new DuplicateCommitException(); } if (!HasChanges()) { return; } ConcurrencyException exceptionToThrow = null; try { await PersistChanges(commitId); } catch (ConcurrencyException exception) { exceptionToThrow = exception; Logger.Info(Resources.UnderlyingStreamHasChanged, StreamId); } if (exceptionToThrow != null) { var commits = _persistence.GetFrom(BucketId, StreamId, StreamRevision + 1, int.MaxValue); await PopulateStream(StreamRevision + 1, int.MaxValue, commits); throw exceptionToThrow; } } public void ClearChanges() { Logger.Debug(Resources.ClearingUncommittedChanges, StreamId); _events.Clear(); _uncommittedHeaders.Clear(); } private Task PopulateStream(int minRevision, int maxRevision, IAsyncEnumerable<ICommit> commits) { commits = commits ?? AsyncEnumerable.Empty<ICommit>(); return commits.ForEach(context => { var commit = context.Item; Logger.Verbose(Resources.AddingCommitsToStream, commit.CommitId, commit.Events.Count, StreamId); _identifiers.Add(commit.CommitId); CommitSequence = commit.CommitSequence; int currentRevision = commit.StreamRevision - commit.Events.Count + 1; if (currentRevision > maxRevision) { context.Break(); return Task.FromResult(false); } CopyToCommittedHeaders(commit); CopyToEvents(minRevision, maxRevision, currentRevision, commit); return Task.FromResult(false); }); } private void CopyToCommittedHeaders(ICommit commit) { foreach (var key in commit.Headers.Keys) { _committedHeaders[key] = commit.Headers[key]; } } private void CopyToEvents(int minRevision, int maxRevision, int currentRevision, ICommit commit) { foreach (var @event in commit.Events) { if (currentRevision > maxRevision) { Logger.Debug(Resources.IgnoringBeyondRevision, commit.CommitId, StreamId, maxRevision); break; } if (currentRevision++ < minRevision) { Logger.Debug(Resources.IgnoringBeforeRevision, commit.CommitId, StreamId, maxRevision); continue; } _committed.Add(@event); StreamRevision = currentRevision - 1; } } private bool HasChanges() { if (_disposed) { throw new ObjectDisposedException(Resources.AlreadyDisposed); } if (_events.Count > 0) { return true; } Logger.Warn(Resources.NoChangesToCommit, StreamId); return false; } private async Task PersistChanges(Guid commitId) { CommitAttempt attempt = BuildCommitAttempt(commitId); Logger.Debug(Resources.PersistingCommit, commitId, StreamId); ICommit commit = await _persistence.Commit(attempt); if (commit != null) { await PopulateStream(StreamRevision + 1, attempt.StreamRevision, AsyncEnumerable.Create(commit)); } ClearChanges(); } private CommitAttempt BuildCommitAttempt(Guid commitId) { Logger.Debug(Resources.BuildingCommitAttempt, commitId, StreamId); return new CommitAttempt( BucketId, StreamId, StreamRevision + _events.Count, commitId, CommitSequence + 1, _systemTypeProvider.UtcNow, _uncommittedHeaders.ToDictionary(x => x.Key, x => x.Value), _events.ToList()); } public void Dispose() { _disposed = true; } } }
using System; /// <summary> /// Convert.ToChar(Object) /// Converts the value of the specified Object to a Unicode character. /// </summary> public class ConvertTochar { public static int Main() { ConvertTochar testObj = new ConvertTochar(); TestLibrary.TestFramework.BeginTestCase("for method: Convert.ToChar(Object)"); if(testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; retVal = NegTest4() && retVal; retVal = NegTest5() && retVal; retVal = NegTest6() && retVal; return retVal; } #region Positive tests public bool PosTest1() { bool retVal = true; string errorDesc; object obj; char expectedValue; char actualValue; Int64 i = TestLibrary.Generator.GetInt64(-55) % (UInt16.MaxValue + 1); obj = i; TestLibrary.TestFramework.BeginScenario("PosTest1: Object is Int64 value between 0 and UInt16.MaxValue."); try { actualValue = Convert.ToChar(obj); expectedValue = (char)i; if (actualValue != expectedValue) { errorDesc = string.Format("The character of Int64 value " + obj + " is not the value \\u{0:x}" + " as expected: actual(\\u{1:x})", (int)expectedValue, (int)actualValue); TestLibrary.TestFramework.LogError("001", errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpect exception:" + e; errorDesc += "\nThe Int64 value is " + obj; TestLibrary.TestFramework.LogError("002", errorDesc); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; string errorDesc; object obj; char expectedValue; char actualValue; byte b = TestLibrary.Generator.GetByte(-55); obj = b; TestLibrary.TestFramework.BeginScenario("PosTest2: Object is byte value"); try { actualValue = Convert.ToChar(obj); expectedValue = (char)b; if (actualValue != expectedValue) { errorDesc = string.Format("The character of byte value " + obj + " is not the value \\u{0:x}" + " as expected: actual(\\u{1:x})", (int)expectedValue, (int)actualValue); TestLibrary.TestFramework.LogError("003", errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpect exception:" + e; errorDesc += "\nThe byte value is " + obj; TestLibrary.TestFramework.LogError("004", errorDesc); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; string errorDesc; object obj; char expectedValue; char actualValue; expectedValue = TestLibrary.Generator.GetChar(-55); obj = new string(expectedValue, 1); TestLibrary.TestFramework.BeginScenario("PosTest3: Object instance is string"); try { actualValue = Convert.ToChar(obj); if (actualValue != expectedValue) { errorDesc = string.Format("The character of \"" + obj + "\" is not the value \\u{0:x}" + " as expected: actual(\\u{1:x})", (int)expectedValue, (int)actualValue); TestLibrary.TestFramework.LogError("005", errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpect exception:" + e; errorDesc += "\nThe string is " + obj; TestLibrary.TestFramework.LogError("006", errorDesc); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; string errorDesc; object obj; char expectedValue; char actualValue; obj = TestLibrary.Generator.GetChar(-55); TestLibrary.TestFramework.BeginScenario("PosTest4: Object instance is character."); try { actualValue = Convert.ToChar(obj); expectedValue = (char)obj; if (actualValue != expectedValue) { errorDesc = string.Format("The character of \"" + obj + "\" is not the value \\u{0:x}" + " as expected: actual(\\u{1:x})", (int)expectedValue, (int)actualValue); TestLibrary.TestFramework.LogError("007", errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpect exception:" + e; errorDesc += "\nThe string is \"" + obj + "\""; TestLibrary.TestFramework.LogError("008", errorDesc); retVal = false; } return retVal; } #endregion #region Negative tests //OverflowException public bool NegTest1() { bool retVal = true; const string c_TEST_ID = "N001"; const string c_TEST_DESC = "NegTest1: Object instance is a negative Int32 value between Int32.MinValue and -1."; string errorDesc; Int32 i = -1 * TestLibrary.Generator.GetInt32(-55) - 1; object obj = i; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { Convert.ToChar(obj); errorDesc = "OverflowException is not thrown as expected."; errorDesc += string.Format("\nThe Int32 value is {0}", i); TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } catch (OverflowException) { } catch (Exception e) { errorDesc = "Unexpected exception: " + e; errorDesc += string.Format("\nThe Int32 value is {0}", i); TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; const string c_TEST_ID = "N002"; const string c_TEST_DESC = "NegTest2: Object instance is a Int64 value between UInt16.MaxValue and Int64.MaxValue."; string errorDesc; Int64 i = TestLibrary.Generator.GetInt64(-55) % (Int64.MaxValue - UInt16.MaxValue) + UInt16.MaxValue + 1; object obj = i; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { Convert.ToChar(obj); errorDesc = "OverflowException is not thrown as expected."; errorDesc += string.Format("\nThe Int64 value is {0}", i); TestLibrary.TestFramework.LogError("011" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } catch (OverflowException) { } catch (Exception e) { errorDesc = "Unexpected exception: " + e; errorDesc += string.Format("\nThe Int64 value is {0}", i); TestLibrary.TestFramework.LogError("012" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } //InvalidCastException public bool NegTest3() { bool retVal = true; const string c_TEST_ID = "N003"; const string c_TEST_DESC = "NegTes3: Object instance does not implement the IConvertible interface. "; string errorDesc; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { Convert.ToChar(new MyFoo()); errorDesc = "InvalidCastException is not thrown as expected."; TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } catch (InvalidCastException) { } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("014" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } //FormatException public bool NegTest4() { bool retVal = true; const string c_TEST_ID = "N004"; const string c_TEST_DESC = "NegTest4: Object instance is a string whose length is longer than 1 characters."; string errorDesc; string str = TestLibrary.Generator.GetString(-55, false, 2, 256); object obj = str; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { Convert.ToChar(obj); errorDesc = "FormatException is not thrown as expected."; errorDesc += "\nThe string is \"" + str + "\""; TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } catch (FormatException) { } catch (Exception e) { errorDesc = "Unexpected exception: " + e; errorDesc += "\nThe string is \"" + str + "\""; TestLibrary.TestFramework.LogError("015" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } //ArgumentNullException public bool NegTest5() { bool retVal = true; const string c_TEST_ID = "N005"; const string c_TEST_DESC = "NegTes5: Object instance is a null reference."; string errorDesc; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { Convert.ToChar(null); errorDesc = "ArgumentNullException is not thrown as expected."; errorDesc += "\nThe string is <null>"; TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { errorDesc = "Unexpected exception: " + e; errorDesc += "\nThe object is a null reference"; TestLibrary.TestFramework.LogError("016" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } //InvalidCastException public bool NegTest6() { bool retVal = true; const string c_TEST_ID = "N006"; const string c_TEST_DESC = "NegTes6: Object instance is double value."; string errorDesc; double d = TestLibrary.Generator.GetDouble(-55); object obj = d; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { Convert.ToChar(obj); errorDesc = "InvalidCastException is not thrown as expected."; errorDesc += "\nThe string is \"" + obj.ToString() + "\""; TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } catch (InvalidCastException) { } catch (Exception e) { errorDesc = "Unexpected exception: " + e; errorDesc += "\nThe object is a null reference"; TestLibrary.TestFramework.LogError("016" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } #endregion #region Helper type //A class which does not implement the interface IConvertible internal class MyFoo {} #endregion }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the SysMotivoNI class. /// </summary> [Serializable] public partial class SysMotivoNICollection : ActiveList<SysMotivoNI, SysMotivoNICollection> { public SysMotivoNICollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>SysMotivoNICollection</returns> public SysMotivoNICollection Filter() { for (int i = this.Count - 1; i > -1; i--) { SysMotivoNI o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the Sys_MotivoNI table. /// </summary> [Serializable] public partial class SysMotivoNI : ActiveRecord<SysMotivoNI>, IActiveRecord { #region .ctors and Default Settings public SysMotivoNI() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public SysMotivoNI(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public SysMotivoNI(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public SysMotivoNI(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("Sys_MotivoNI", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdMotivoNI = new TableSchema.TableColumn(schema); colvarIdMotivoNI.ColumnName = "idMotivoNI"; colvarIdMotivoNI.DataType = DbType.Int32; colvarIdMotivoNI.MaxLength = 0; colvarIdMotivoNI.AutoIncrement = true; colvarIdMotivoNI.IsNullable = false; colvarIdMotivoNI.IsPrimaryKey = true; colvarIdMotivoNI.IsForeignKey = false; colvarIdMotivoNI.IsReadOnly = false; colvarIdMotivoNI.DefaultSetting = @""; colvarIdMotivoNI.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdMotivoNI); TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema); colvarNombre.ColumnName = "nombre"; colvarNombre.DataType = DbType.String; colvarNombre.MaxLength = 50; colvarNombre.AutoIncrement = false; colvarNombre.IsNullable = false; colvarNombre.IsPrimaryKey = false; colvarNombre.IsForeignKey = false; colvarNombre.IsReadOnly = false; colvarNombre.DefaultSetting = @"('')"; colvarNombre.ForeignKeyTableName = ""; schema.Columns.Add(colvarNombre); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("Sys_MotivoNI",schema); } } #endregion #region Props [XmlAttribute("IdMotivoNI")] [Bindable(true)] public int IdMotivoNI { get { return GetColumnValue<int>(Columns.IdMotivoNI); } set { SetColumnValue(Columns.IdMotivoNI, value); } } [XmlAttribute("Nombre")] [Bindable(true)] public string Nombre { get { return GetColumnValue<string>(Columns.Nombre); } set { SetColumnValue(Columns.Nombre, value); } } #endregion #region PrimaryKey Methods protected override void SetPrimaryKey(object oValue) { base.SetPrimaryKey(oValue); SetPKValues(); } private DalSic.SysPacienteCollection colSysPacienteRecords; public DalSic.SysPacienteCollection SysPacienteRecords { get { if(colSysPacienteRecords == null) { colSysPacienteRecords = new DalSic.SysPacienteCollection().Where(SysPaciente.Columns.IdMotivoNI, IdMotivoNI).Load(); colSysPacienteRecords.ListChanged += new ListChangedEventHandler(colSysPacienteRecords_ListChanged); } return colSysPacienteRecords; } set { colSysPacienteRecords = value; colSysPacienteRecords.ListChanged += new ListChangedEventHandler(colSysPacienteRecords_ListChanged); } } void colSysPacienteRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colSysPacienteRecords[e.NewIndex].IdMotivoNI = IdMotivoNI; } } private DalSic.SysRelEstadoMotivoNICollection colSysRelEstadoMotivoNIRecords; public DalSic.SysRelEstadoMotivoNICollection SysRelEstadoMotivoNIRecords { get { if(colSysRelEstadoMotivoNIRecords == null) { colSysRelEstadoMotivoNIRecords = new DalSic.SysRelEstadoMotivoNICollection().Where(SysRelEstadoMotivoNI.Columns.IdMotivoNI, IdMotivoNI).Load(); colSysRelEstadoMotivoNIRecords.ListChanged += new ListChangedEventHandler(colSysRelEstadoMotivoNIRecords_ListChanged); } return colSysRelEstadoMotivoNIRecords; } set { colSysRelEstadoMotivoNIRecords = value; colSysRelEstadoMotivoNIRecords.ListChanged += new ListChangedEventHandler(colSysRelEstadoMotivoNIRecords_ListChanged); } } void colSysRelEstadoMotivoNIRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colSysRelEstadoMotivoNIRecords[e.NewIndex].IdMotivoNI = IdMotivoNI; } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varNombre) { SysMotivoNI item = new SysMotivoNI(); item.Nombre = varNombre; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdMotivoNI,string varNombre) { SysMotivoNI item = new SysMotivoNI(); item.IdMotivoNI = varIdMotivoNI; item.Nombre = varNombre; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdMotivoNIColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn NombreColumn { get { return Schema.Columns[1]; } } #endregion #region Columns Struct public struct Columns { public static string IdMotivoNI = @"idMotivoNI"; public static string Nombre = @"nombre"; } #endregion #region Update PK Collections public void SetPKValues() { if (colSysPacienteRecords != null) { foreach (DalSic.SysPaciente item in colSysPacienteRecords) { if (item.IdMotivoNI != IdMotivoNI) { item.IdMotivoNI = IdMotivoNI; } } } if (colSysRelEstadoMotivoNIRecords != null) { foreach (DalSic.SysRelEstadoMotivoNI item in colSysRelEstadoMotivoNIRecords) { if (item.IdMotivoNI != IdMotivoNI) { item.IdMotivoNI = IdMotivoNI; } } } } #endregion #region Deep Save public void DeepSave() { Save(); if (colSysPacienteRecords != null) { colSysPacienteRecords.SaveAll(); } if (colSysRelEstadoMotivoNIRecords != null) { colSysRelEstadoMotivoNIRecords.SaveAll(); } } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using moogle.SmartTile2D.TileManager; namespace moogle.SmartTile2D { public class ST2D_ComponentTiled : MonoBehaviour { public string tileTag = "None"; public int zOrder = 0; public Material mat; [SerializeField] public TileChilds tileChilds; public int pixelPerUnit_texture = 32; public int tile_size = 32; private string[] childNameTable = TileBase.subID; private Vector2[] childPosBase = TileBase.subPos; public void initTileObject() { if (mat == null){ mat = Resources.Load("Material/Default2D") as Material; } Sprite[] sprites; for (int i = 0;i< 4;i++) { //first build first-level child object NW NE SW SE GameObject childObject = new GameObject(); childObject.transform.SetParent(transform); childObject.name = childNameTable[i]; childObject.transform.localPosition = childPosBase[i]* ((float)tile_size / (float)pixelPerUnit_texture); childObject.transform.localScale = Vector3.one * 1f; SpriteRenderer render = childObject.AddComponent<SpriteRenderer>(); render.sortingOrder = zOrder; if (mat != null){ render.material = mat; } switch (childObject.name) { case "NW": sprites = tileChilds.GetSpritesFromID("AANW"); if (sprites.Length>=1) render.sprite = sprites[Random.Range(sprites.GetLowerBound(0), sprites.GetUpperBound(0))]; break; case "NE": sprites = tileChilds.GetSpritesFromID("AANE"); if (sprites.Length>=1) render.sprite = sprites[Random.Range(sprites.GetLowerBound(0), sprites.GetUpperBound(0))]; break; case "SW": sprites = tileChilds.GetSpritesFromID("AASW"); if (sprites.Length>=1) render.sprite = sprites[Random.Range(sprites.GetLowerBound(0), sprites.GetUpperBound(0))]; break; case "SE": sprites = tileChilds.GetSpritesFromID("AASE"); if (sprites.Length>=1) render.sprite = sprites[Random.Range(sprites.GetLowerBound(0), sprites.GetUpperBound(0))]; break; } } } public void ResetSortingOrder() { var renders = transform.GetComponentsInChildren<SpriteRenderer>(); foreach (var r in renders) { r.sortingOrder = zOrder; } } public void ReloadSprites(Neighbor neighborData) { Sprite nw_sprite = tileChilds.GetRandSpriteFromID("AANW"); Sprite ne_sprite = tileChilds.GetRandSpriteFromID("AANE"); Sprite sw_sprite = tileChilds.GetRandSpriteFromID("AASW"); Sprite se_sprite = tileChilds.GetRandSpriteFromID("AASE"); if (neighborData.N == false && neighborData.W == false && neighborData.S == false && neighborData.E == false){ for (int i=0;i<4;i++){ var subObjectName = TileBase.subID[i]; if (subObjectName == "NW") { transform.FindChild("NW").GetComponent<SpriteRenderer>().sprite = nw_sprite;} if (subObjectName == "NE") { transform.FindChild("NE").GetComponent<SpriteRenderer>().sprite = ne_sprite;} if (subObjectName == "SW") { transform.FindChild("SW").GetComponent<SpriteRenderer>().sprite = sw_sprite;} if (subObjectName == "SE") { transform.FindChild("SE").GetComponent<SpriteRenderer>().sprite = se_sprite;} } return; } #region NW if (neighborData.N == true && neighborData.W == true && neighborData.NW == true){ nw_sprite = tileChilds.GetRandSpriteFromID("CTNW"); } if (neighborData.N == true && neighborData.W == true && neighborData.NW == false){ //concave edge :Set to [NWU] nw_sprite = tileChilds.GetRandSpriteFromID("CCNW"); } if (neighborData.N == false && neighborData.W == true && neighborData.NW == true){ //no edge :Set to [N] nw_sprite = tileChilds.GetRandSpriteFromID("UDNW"); } if (neighborData.N == false && neighborData.W == true && neighborData.NW == false){ //no edge :Set to [N] nw_sprite = tileChilds.GetRandSpriteFromID("UDNW"); } if (neighborData.N == false && neighborData.W == false && neighborData.NW == true){ //convex edge :Set to [NW] nw_sprite = tileChilds.GetRandSpriteFromID("CVNW"); } if (neighborData.N == true && neighborData.W == false && neighborData.NW == true){ //no edge :Set to [W] nw_sprite = tileChilds.GetRandSpriteFromID("LRNW"); } if (neighborData.N == true && neighborData.W == false && neighborData.NW == false){ //no edge :Set to [W] nw_sprite = tileChilds.GetRandSpriteFromID("LRNW"); } if (neighborData.N == false && neighborData.W == false && neighborData.NW == false){ //convex edge :Set to [NW] nw_sprite = tileChilds.GetRandSpriteFromID("CVNW"); } #endregion #region NE //EDGE NE if (neighborData.N == true && neighborData.E == true && neighborData.NE == true){ //no edge & all Neighbor :Set to [C] ne_sprite = tileChilds.GetRandSpriteFromID("CTNE"); } if (neighborData.N == true && neighborData.E == true && neighborData.NE == false){ //concave edge :Set to [NEU] ne_sprite = tileChilds.GetRandSpriteFromID("CCNE"); } if (neighborData.N == false && neighborData.E == true && neighborData.NE == true){ //no edge :Set to [N] ne_sprite = tileChilds.GetRandSpriteFromID("UDNE"); } if (neighborData.N == false && neighborData.E == true && neighborData.NE == false){ //no edge :Set to [N] ne_sprite = tileChilds.GetRandSpriteFromID("UDNE"); } if (neighborData.N == false && neighborData.E == false && neighborData.NE == true){ //convex edge :Set to [NE] ne_sprite = tileChilds.GetRandSpriteFromID("CVNE"); } if (neighborData.N == true && neighborData.E == false && neighborData.NE == true){ //no edge :Set to [E] ne_sprite = tileChilds.GetRandSpriteFromID("LRNE"); } if (neighborData.N == true && neighborData.E == false && neighborData.NE == false){ //no edge :Set to [E] ne_sprite = tileChilds.GetRandSpriteFromID("LRNE"); } if (neighborData.N == false && neighborData.E == false && neighborData.NE == false){ //convex edge :Set to [NE] ne_sprite = tileChilds.GetRandSpriteFromID("CVNE"); } #endregion #region SW //EDGE SW if (neighborData.S == true && neighborData.W == true && neighborData.SW == true){ //no edge & all Neighbor :Set to [C] sw_sprite = tileChilds.GetRandSpriteFromID("CTSW"); } if (neighborData.S == true && neighborData.W == true && neighborData.SW == false){ //concave edge :Set to [SWU] sw_sprite = tileChilds.GetRandSpriteFromID("CCSW"); } if (neighborData.S == false && neighborData.W == true && neighborData.SW == true){ //no edge :Set to [S] sw_sprite = tileChilds.GetRandSpriteFromID("UDSW"); } if (neighborData.S == false && neighborData.W == true && neighborData.SW == false){ //no edge :Set to [S] sw_sprite = tileChilds.GetRandSpriteFromID("UDSW"); } if (neighborData.S == false && neighborData.W == false && neighborData.SW == true){ //convex edge :Set to [SW] sw_sprite = tileChilds.GetRandSpriteFromID("CVSW"); } if (neighborData.S == true && neighborData.W == false && neighborData.SW == true){ //no edge :Set to [W] sw_sprite = tileChilds.GetRandSpriteFromID("LRSW"); } if (neighborData.S == true && neighborData.W == false && neighborData.SW == false){ //no edge :Set to [W] sw_sprite = tileChilds.GetRandSpriteFromID("LRSW"); } if (neighborData.S == false && neighborData.W == false && neighborData.SW == false){ //convex edge :Set to [SW] sw_sprite = tileChilds.GetRandSpriteFromID("CVSW"); } #endregion #region SE //EDGE NE if (neighborData.S == true && neighborData.E == true && neighborData.SE == true){ //no edge & all Neighbor :Set to [C] se_sprite = tileChilds.GetRandSpriteFromID("CTSE"); } if (neighborData.S == true && neighborData.E == true && neighborData.SE == false){ //concave edge :Set to [SEU] se_sprite = tileChilds.GetRandSpriteFromID("CCSE"); } if (neighborData.S == false && neighborData.E == true && neighborData.SE == true){ //no edge :Set to [S] se_sprite = tileChilds.GetRandSpriteFromID("UDSE"); } if (neighborData.S == false && neighborData.E == true && neighborData.SE == false){ //no edge :Set to [S] se_sprite = tileChilds.GetRandSpriteFromID("UDSE"); } if (neighborData.S == false && neighborData.E == false && neighborData.SE == true){ //convex edge :Set to [SE] se_sprite = tileChilds.GetRandSpriteFromID("CVSE"); } if (neighborData.S == true && neighborData.E == false && neighborData.SE == true){ //no edge :Set to [E] se_sprite = tileChilds.GetRandSpriteFromID("LRSE"); } if (neighborData.S == true && neighborData.E == false && neighborData.SE == false){ //no edge :Set to [E] se_sprite = tileChilds.GetRandSpriteFromID("LRSE"); } if (neighborData.S == false && neighborData.E == false && neighborData.SE == false){ //convex edge :Set to [SE] se_sprite = tileChilds.GetRandSpriteFromID("CVSE"); } #endregion for (int i=0;i<4;i++){ var subObjectName = TileBase.subID[i]; if (subObjectName == "NW") { transform.FindChild("NW").GetComponent<SpriteRenderer>().sprite = nw_sprite;} if (subObjectName == "NE") { transform.FindChild("NE").GetComponent<SpriteRenderer>().sprite = ne_sprite;} if (subObjectName == "SW") { transform.FindChild("SW").GetComponent<SpriteRenderer>().sprite = sw_sprite;} if (subObjectName == "SE") { transform.FindChild("SE").GetComponent<SpriteRenderer>().sprite = se_sprite;} } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Security.Cryptography.Asn1; namespace System.Security.Cryptography { /// <summary> /// Abstract base class for implementations of elliptic curve Diffie-Hellman to derive from /// </summary> public abstract partial class ECDiffieHellman : AsymmetricAlgorithm { private static readonly string[] s_validOids = { Oids.EcPublicKey, // Neither Windows nor OpenSSL seem to read id-ecDH Pkcs8/SPKI. // ECMQV is not valid in this context. }; public override string KeyExchangeAlgorithm { get { return "ECDiffieHellman"; } } public override string SignatureAlgorithm { get { return null; } } public static new ECDiffieHellman Create(string algorithm) { if (algorithm == null) { throw new ArgumentNullException(nameof(algorithm)); } return CryptoConfig.CreateFromName(algorithm) as ECDiffieHellman; } public abstract ECDiffieHellmanPublicKey PublicKey { get; } // This method must be implemented by derived classes. In order to conform to the contract, it cannot be abstract. public virtual byte[] DeriveKeyMaterial(ECDiffieHellmanPublicKey otherPartyPublicKey) { throw DerivedClassMustOverride(); } /// <summary> /// Derive key material using the formula HASH(x) where x is the computed result of the EC Diffie-Hellman algorithm. /// </summary> /// <param name="otherPartyPublicKey">The public key of the party with which to derive a mutual secret.</param> /// <param name="hashAlgorithm">The identifier for the hash algorithm to use.</param> /// <returns>A hashed output suitable for key material</returns> /// <exception cref="ArgumentException"><paramref name="otherPartyPublicKey"/> is over a different curve than this key</exception> public byte[] DeriveKeyFromHash(ECDiffieHellmanPublicKey otherPartyPublicKey, HashAlgorithmName hashAlgorithm) { return DeriveKeyFromHash(otherPartyPublicKey, hashAlgorithm, null, null); } /// <summary> /// Derive key material using the formula HASH(secretPrepend || x || secretAppend) where x is the computed /// result of the EC Diffie-Hellman algorithm. /// </summary> /// <param name="otherPartyPublicKey">The public key of the party with which to derive a mutual secret.</param> /// <param name="hashAlgorithm">The identifier for the hash algorithm to use.</param> /// <param name="secretPrepend">A value to prepend to the derived secret before hashing. A <c>null</c> value is treated as an empty array.</param> /// <param name="secretAppend">A value to append to the derived secret before hashing. A <c>null</c> value is treated as an empty array.</param> /// <returns>A hashed output suitable for key material</returns> /// <exception cref="ArgumentException"><paramref name="otherPartyPublicKey"/> is over a different curve than this key</exception> public virtual byte[] DeriveKeyFromHash( ECDiffieHellmanPublicKey otherPartyPublicKey, HashAlgorithmName hashAlgorithm, byte[] secretPrepend, byte[] secretAppend) { throw DerivedClassMustOverride(); } /// <summary> /// Derive key material using the formula HMAC(hmacKey, x) where x is the computed /// result of the EC Diffie-Hellman algorithm. /// </summary> /// <param name="otherPartyPublicKey">The public key of the party with which to derive a mutual secret.</param> /// <param name="hashAlgorithm">The identifier for the hash algorithm to use.</param> /// <param name="hmacKey">The key to use in the HMAC. A <c>null</c> value indicates that the result of the EC Diffie-Hellman algorithm should be used as the HMAC key.</param> /// <returns>A hashed output suitable for key material</returns> /// <exception cref="ArgumentException"><paramref name="otherPartyPublicKey"/> is over a different curve than this key</exception> public byte[] DeriveKeyFromHmac( ECDiffieHellmanPublicKey otherPartyPublicKey, HashAlgorithmName hashAlgorithm, byte[] hmacKey) { return DeriveKeyFromHmac(otherPartyPublicKey, hashAlgorithm, hmacKey, null, null); } /// <summary> /// Derive key material using the formula HMAC(hmacKey, secretPrepend || x || secretAppend) where x is the computed /// result of the EC Diffie-Hellman algorithm. /// </summary> /// <param name="otherPartyPublicKey">The public key of the party with which to derive a mutual secret.</param> /// <param name="hashAlgorithm">The identifier for the hash algorithm to use.</param> /// <param name="hmacKey">The key to use in the HMAC. A <c>null</c> value indicates that the result of the EC Diffie-Hellman algorithm should be used as the HMAC key.</param> /// <param name="secretPrepend">A value to prepend to the derived secret before hashing. A <c>null</c> value is treated as an empty array.</param> /// <param name="secretAppend">A value to append to the derived secret before hashing. A <c>null</c> value is treated as an empty array.</param> /// <returns>A hashed output suitable for key material</returns> /// <exception cref="ArgumentException"><paramref name="otherPartyPublicKey"/> is over a different curve than this key</exception> public virtual byte[] DeriveKeyFromHmac( ECDiffieHellmanPublicKey otherPartyPublicKey, HashAlgorithmName hashAlgorithm, byte[] hmacKey, byte[] secretPrepend, byte[] secretAppend) { throw DerivedClassMustOverride(); } /// <summary> /// Derive key material using the TLS pseudo-random function (PRF) derivation algorithm. /// </summary> /// <param name="otherPartyPublicKey">The public key of the party with which to derive a mutual secret.</param> /// <param name="prfLabel">The ASCII encoded PRF label.</param> /// <param name="prfSeed">The 64-byte PRF seed.</param> /// <returns>A 48-byte output of the TLS pseudo-random function.</returns> /// <exception cref="ArgumentException"><paramref name="otherPartyPublicKey"/> is over a different curve than this key</exception> /// <exception cref="ArgumentNullException"><paramref name="prfLabel"/> is null</exception> /// <exception cref="ArgumentNullException"><paramref name="prfSeed"/> is null</exception> /// <exception cref="CryptographicException"><paramref name="prfSeed"/> is not exactly 64 bytes in length</exception> public virtual byte[] DeriveKeyTls(ECDiffieHellmanPublicKey otherPartyPublicKey, byte[] prfLabel, byte[] prfSeed) { throw DerivedClassMustOverride(); } private static Exception DerivedClassMustOverride() { return new NotImplementedException(SR.NotSupported_SubclassOverride); } /// <summary> /// When overridden in a derived class, exports the named or explicit ECParameters for an ECCurve. /// If the curve has a name, the Curve property will contain named curve parameters, otherwise it /// will contain explicit parameters. /// </summary> /// <param name="includePrivateParameters">true to include private parameters, otherwise, false.</param> /// <returns>The ECParameters representing the point on the curve for this key.</returns> public virtual ECParameters ExportParameters(bool includePrivateParameters) { throw DerivedClassMustOverride(); } /// <summary> /// When overridden in a derived class, exports the explicit ECParameters for an ECCurve. /// </summary> /// <param name="includePrivateParameters">true to include private parameters, otherwise, false.</param> /// <returns>The ECParameters representing the point on the curve for this key, using the explicit curve format.</returns> public virtual ECParameters ExportExplicitParameters(bool includePrivateParameters) { throw DerivedClassMustOverride(); } /// <summary> /// When overridden in a derived class, imports the specified ECParameters. /// </summary> /// <param name="parameters">The curve parameters.</param> public virtual void ImportParameters(ECParameters parameters) { throw DerivedClassMustOverride(); } /// <summary> /// When overridden in a derived class, generates a new public/private keypair for the specified curve. /// </summary> /// <param name="curve">The curve to use.</param> public virtual void GenerateKey(ECCurve curve) { throw new NotSupportedException(SR.NotSupported_SubclassOverride); } public override unsafe bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte> passwordBytes, PbeParameters pbeParameters, Span<byte> destination, out int bytesWritten) { if (pbeParameters == null) throw new ArgumentNullException(nameof(pbeParameters)); PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, ReadOnlySpan<char>.Empty, passwordBytes); ECParameters ecParameters = ExportParameters(true); fixed (byte* privPtr = ecParameters.D) { try { using (AsnWriter pkcs8PrivateKey = EccKeyFormatHelper.WritePkcs8PrivateKey(ecParameters)) using (AsnWriter writer = KeyFormatHelper.WriteEncryptedPkcs8( passwordBytes, pkcs8PrivateKey, pbeParameters)) { return writer.TryEncode(destination, out bytesWritten); } } finally { CryptographicOperations.ZeroMemory(ecParameters.D); } } } public override unsafe bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan<char> password, PbeParameters pbeParameters, Span<byte> destination, out int bytesWritten) { if (pbeParameters == null) throw new ArgumentNullException(nameof(pbeParameters)); PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, password, ReadOnlySpan<byte>.Empty); ECParameters ecParameters = ExportParameters(true); fixed (byte* privPtr = ecParameters.D) { try { using (AsnWriter pkcs8PrivateKey = EccKeyFormatHelper.WritePkcs8PrivateKey(ecParameters)) using (AsnWriter writer = KeyFormatHelper.WriteEncryptedPkcs8( password, pkcs8PrivateKey, pbeParameters)) { return writer.TryEncode(destination, out bytesWritten); } } finally { CryptographicOperations.ZeroMemory(ecParameters.D); } } } public override unsafe bool TryExportPkcs8PrivateKey( Span<byte> destination, out int bytesWritten) { ECParameters ecParameters = ExportParameters(true); fixed (byte* privPtr = ecParameters.D) { try { using (AsnWriter writer = EccKeyFormatHelper.WritePkcs8PrivateKey(ecParameters)) { return writer.TryEncode(destination, out bytesWritten); } } finally { CryptographicOperations.ZeroMemory(ecParameters.D); } } } public override bool TryExportSubjectPublicKeyInfo( Span<byte> destination, out int bytesWritten) { ECParameters ecParameters = ExportParameters(false); using (AsnWriter writer = EccKeyFormatHelper.WriteSubjectPublicKeyInfo(ecParameters)) { return writer.TryEncode(destination, out bytesWritten); } } public override unsafe void ImportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte> passwordBytes, ReadOnlySpan<byte> source, out int bytesRead) { KeyFormatHelper.ReadEncryptedPkcs8<ECParameters>( s_validOids, source, passwordBytes, EccKeyFormatHelper.FromECPrivateKey, out int localRead, out ECParameters ret); fixed (byte* privPin = ret.D) { try { ImportParameters(ret); bytesRead = localRead; } finally { CryptographicOperations.ZeroMemory(ret.D); } } } public override unsafe void ImportEncryptedPkcs8PrivateKey( ReadOnlySpan<char> password, ReadOnlySpan<byte> source, out int bytesRead) { KeyFormatHelper.ReadEncryptedPkcs8<ECParameters>( s_validOids, source, password, EccKeyFormatHelper.FromECPrivateKey, out int localRead, out ECParameters ret); fixed (byte* privPin = ret.D) { try { ImportParameters(ret); bytesRead = localRead; } finally { CryptographicOperations.ZeroMemory(ret.D); } } } public override unsafe void ImportPkcs8PrivateKey( ReadOnlySpan<byte> source, out int bytesRead) { KeyFormatHelper.ReadPkcs8<ECParameters>( s_validOids, source, EccKeyFormatHelper.FromECPrivateKey, out int localRead, out ECParameters key); fixed (byte* privPin = key.D) { try { ImportParameters(key); bytesRead = localRead; } finally { CryptographicOperations.ZeroMemory(key.D); } } } public override void ImportSubjectPublicKeyInfo( ReadOnlySpan<byte> source, out int bytesRead) { KeyFormatHelper.ReadSubjectPublicKeyInfo<ECParameters>( s_validOids, source, EccKeyFormatHelper.FromECPublicKey, out int localRead, out ECParameters key); ImportParameters(key); bytesRead = localRead; } public virtual unsafe void ImportECPrivateKey(ReadOnlySpan<byte> source, out int bytesRead) { ECParameters ecParameters = EccKeyFormatHelper.FromECPrivateKey(source, out int localRead); fixed (byte* privPin = ecParameters.D) { try { ImportParameters(ecParameters); bytesRead = localRead; } finally { CryptographicOperations.ZeroMemory(ecParameters.D); } } } public virtual unsafe byte[] ExportECPrivateKey() { ECParameters ecParameters = ExportParameters(true); fixed (byte* privPin = ecParameters.D) { try { using (AsnWriter writer = EccKeyFormatHelper.WriteECPrivateKey(ecParameters)) { return writer.Encode(); } } finally { CryptographicOperations.ZeroMemory(ecParameters.D); } } } public virtual unsafe bool TryExportECPrivateKey(Span<byte> destination, out int bytesWritten) { ECParameters ecParameters = ExportParameters(true); fixed (byte* privPin = ecParameters.D) { try { using (AsnWriter writer = EccKeyFormatHelper.WriteECPrivateKey(ecParameters)) { return writer.TryEncode(destination, out bytesWritten); } } finally { CryptographicOperations.ZeroMemory(ecParameters.D); } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using Microsoft.Extensions.Logging; using Orleans.Runtime.Scheduler; namespace Orleans.Runtime.GrainDirectory { internal class AdaptiveDirectoryCacheMaintainer<TValue> : DedicatedAsynchAgent { private static readonly TimeSpan SLEEP_TIME_BETWEEN_REFRESHES = Debugger.IsAttached ? TimeSpan.FromMinutes(5) : TimeSpan.FromMinutes(1); // this should be something like minTTL/4 private readonly AdaptiveGrainDirectoryCache<TValue> cache; private readonly LocalGrainDirectory router; private readonly Func<List<ActivationAddress>, TValue> updateFunc; private readonly IInternalGrainFactory grainFactory; private long lastNumAccesses; // for stats private long lastNumHits; // for stats internal AdaptiveDirectoryCacheMaintainer( LocalGrainDirectory router, AdaptiveGrainDirectoryCache<TValue> cache, Func<List<ActivationAddress>, TValue> updateFunc, IInternalGrainFactory grainFactory, ExecutorService executorService, ILoggerFactory loggerFactory) :base(executorService, loggerFactory) { this.updateFunc = updateFunc; this.grainFactory = grainFactory; this.router = router; this.cache = cache; lastNumAccesses = 0; lastNumHits = 0; OnFault = FaultBehavior.RestartOnFault; } protected override void Run() { while (router.Running) { // Run through all cache entries and do the following: // 1. If the entry is not expired, skip it // 2. If the entry is expired and was not accessed in the last time interval -- throw it away // 3. If the entry is expired and was accessed in the last time interval, put into "fetch-batch-requests" list // At the end of the process, fetch batch requests for entries that need to be refreshed // Upon receiving refreshing answers, if the entry was not changed, double its expiration timer. // If it was changed, update the cache and reset the expiration timer. // this dictionary holds a map between a silo address and the list of grains that need to be refreshed var fetchInBatchList = new Dictionary<SiloAddress, List<GrainId>>(); // get the list of cached grains // for debug only int cnt1 = 0, cnt2 = 0, cnt3 = 0, cnt4 = 0; // run through all cache entries var enumerator = cache.GetStoredEntries(); while (enumerator.MoveNext()) { var pair = enumerator.Current; GrainId grain = pair.Key; var entry = pair.Value; SiloAddress owner = router.CalculateTargetSilo(grain); if (owner == null) // Null means there's no other silo and we're shutting down, so skip this entry { continue; } if (owner.Equals(router.MyAddress)) { // we found our owned entry in the cache -- it is not supposed to happen unless there were // changes in the membership Log.Warn(ErrorCode.Runtime_Error_100185, "Grain {0} owned by {1} was found in the cache of {1}", grain, owner, owner); cache.Remove(grain); cnt1++; // for debug } else { if (entry == null) { // 0. If the entry was deleted in parallel, presumably due to cleanup after silo death cache.Remove(grain); // for debug cnt3++; } else if (!entry.IsExpired()) { // 1. If the entry is not expired, skip it cnt2++; // for debug } else if (entry.NumAccesses == 0) { // 2. If the entry is expired and was not accessed in the last time interval -- throw it away cache.Remove(grain); // for debug cnt3++; } else { // 3. If the entry is expired and was accessed in the last time interval, put into "fetch-batch-requests" list if (!fetchInBatchList.ContainsKey(owner)) { fetchInBatchList[owner] = new List<GrainId>(); } fetchInBatchList[owner].Add(grain); // And reset the entry's access count for next time entry.NumAccesses = 0; cnt4++; // for debug } } } if (Log.IsEnabled(LogLevel.Trace)) Log.Trace("Silo {0} self-owned (and removed) {1}, kept {2}, removed {3} and tries to refresh {4} grains", router.MyAddress, cnt1, cnt2, cnt3, cnt4); // send batch requests SendBatchCacheRefreshRequests(fetchInBatchList); ProduceStats(); // recheck every X seconds (Consider making it a configurable parameter) Thread.Sleep(SLEEP_TIME_BETWEEN_REFRESHES); } } private void SendBatchCacheRefreshRequests(Dictionary<SiloAddress, List<GrainId>> refreshRequests) { foreach (SiloAddress silo in refreshRequests.Keys) { List<Tuple<GrainId, int>> cachedGrainAndETagList = BuildGrainAndETagList(refreshRequests[silo]); SiloAddress capture = silo; router.CacheValidationsSent.Increment(); // Send all of the items in one large request var validator = this.grainFactory.GetSystemTarget<IRemoteGrainDirectory>(Constants.DirectoryCacheValidatorId, capture); router.Scheduler.QueueTask(async () => { var response = await validator.LookUpMany(cachedGrainAndETagList); ProcessCacheRefreshResponse(capture, response); }, router.CacheValidator.SchedulingContext).Ignore(); if (Log.IsEnabled(LogLevel.Trace)) Log.Trace("Silo {0} is sending request to silo {1} with {2} entries", router.MyAddress, silo, cachedGrainAndETagList.Count); } } private void ProcessCacheRefreshResponse( SiloAddress silo, IReadOnlyCollection<Tuple<GrainId, int, List<ActivationAddress>>> refreshResponse) { if (Log.IsEnabled(LogLevel.Trace)) Log.Trace("Silo {0} received ProcessCacheRefreshResponse. #Response entries {1}.", router.MyAddress, refreshResponse.Count); int cnt1 = 0, cnt2 = 0, cnt3 = 0; // pass through returned results and update the cache if needed foreach (Tuple<GrainId, int, List<ActivationAddress>> tuple in refreshResponse) { if (tuple.Item3 != null) { // the server returned an updated entry var updated = updateFunc(tuple.Item3); cache.AddOrUpdate(tuple.Item1, updated, tuple.Item2); cnt1++; } else if (tuple.Item2 == -1) { // The server indicates that it does not own the grain anymore. // It could be that by now, the cache has been already updated and contains an entry received from another server (i.e., current owner for the grain). // For simplicity, we do not care about this corner case and simply remove the cache entry. cache.Remove(tuple.Item1); cnt2++; } else { // The server returned only a (not -1) generation number, indicating that we hold the most // updated copy of the grain's activations list. // Validate that the generation number in the request and the response are equal // Contract.Assert(tuple.Item2 == refreshRequest.Find(o => o.Item1 == tuple.Item1).Item2); // refresh the entry in the cache cache.MarkAsFresh(tuple.Item1); cnt3++; } } if (Log.IsEnabled(LogLevel.Trace)) Log.Trace("Silo {0} processed refresh response from {1} with {2} updated, {3} removed, {4} unchanged grains", router.MyAddress, silo, cnt1, cnt2, cnt3); } /// <summary> /// Gets the list of grains (all owned by the same silo) and produces a new list /// of tuples, where each tuple holds the grain and its generation counter currently stored in the cache /// </summary> /// <param name="grains">List of grains owned by the same silo</param> /// <returns>List of grains in input along with their generation counters stored in the cache </returns> private List<Tuple<GrainId, int>> BuildGrainAndETagList(IEnumerable<GrainId> grains) { var grainAndETagList = new List<Tuple<GrainId, int>>(); foreach (GrainId grain in grains) { // NOTE: should this be done with TryGet? Won't Get invoke the LRU getter function? AdaptiveGrainDirectoryCache<TValue>.GrainDirectoryCacheEntry entry = cache.Get(grain); if (entry != null) { grainAndETagList.Add(new Tuple<GrainId, int>(grain, entry.ETag)); } else { // this may happen only if the LRU cache is full and decided to drop this grain // while we try to refresh it Log.Warn(ErrorCode.Runtime_Error_100199, "Grain {0} disappeared from the cache during maintainance", grain); } } return grainAndETagList; } private void ProduceStats() { // We do not want to synchronize the access on numAccess and numHits in cache to avoid performance issues. // Thus we take the current reading of these fields and calculate the stats. We might miss an access or two, // but it should not be matter. long curNumAccesses = cache.NumAccesses; long curNumHits = cache.NumHits; long numAccesses = curNumAccesses - lastNumAccesses; long numHits = curNumHits - lastNumHits; if (Log.IsEnabled(LogLevel.Trace)) Log.Trace("#accesses: {0}, hit-ratio: {1}%", numAccesses, (numHits / Math.Max(numAccesses, 0.00001)) * 100); lastNumAccesses = curNumAccesses; lastNumHits = curNumHits; } } }
// // ProjectInformation.cs // // Authors: // Levi Bard <taktaktaktaktaktaktaktaktaktak@gmail.com> // // Copyright (C) 2008 Levi Bard // Based on CBinding by Marcos David Marin Amador <MarcosMarin@gmail.com> // // This source code is licenced under The 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. // using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Threading; using System.Text; using System.Text.RegularExpressions; using MonoDevelop.Projects; using MonoDevelop.Core; using MonoDevelop.Ide; using MonoDevelop.Core.Execution; using MonoDevelop.Ide.CodeCompletion; namespace MonoDevelop.ValaBinding.Parser { /// <summary> /// Class to obtain parse information for a project /// </summary> public class ProjectInformation { private bool vtgInstalled = false; private bool checkedVtgInstalled = false; private Afrodite.CompletionEngine engine; static readonly string[] containerTypes = new string[]{ "class", "struct", "interface" }; public Project Project{ get; set; } //// <value> /// Checks whether <see cref="http://code.google.com/p/vtg/">Vala Toys for GEdit</see> /// is installed. /// </value> bool DepsInstalled { get { if (!checkedVtgInstalled) { checkedVtgInstalled = true; vtgInstalled = false; try { Afrodite.Utils.GetPackagePaths ("glib-2.0"); return (vtgInstalled = true); } catch (DllNotFoundException) { LoggingService.LogWarning ("Cannot update Vala parser database because libafrodite (VTG) is not installed: {0}{1}{2}{3}", Environment.NewLine, "http://code.google.com/p/vtg/", Environment.NewLine, "Note: If you're using Vala 0.10 or higher, you may need to symlink libvala-YOUR_VERSION.so to libvala.so"); } catch (Exception ex) { LoggingService.LogError ("ValaBinding: Error while checking for libafrodite", ex); } } return vtgInstalled; } set { //don't assume that the caller is correct :-) if (value) checkedVtgInstalled = false; //will re-determine on next getting else vtgInstalled = false; } } public ProjectInformation (Project project) { this.Project = project; string projectName = (null == project)? "NoExistingProject": project.Name; if (DepsInstalled) { engine = new Afrodite.CompletionEngine (projectName); } } /// <summary> /// Gets the completion list for a given type name in a given file /// </summary> internal List<Afrodite.Symbol> CompleteType (string typename, string filename, int linenum, int column, ValaCompletionDataList results) { List<Afrodite.Symbol> nodes = new List<Afrodite.Symbol> (); if (!DepsInstalled){ return nodes; } using (Afrodite.CodeDom parseTree = engine.TryAcquireCodeDom ()) { if (null != parseTree) { Afrodite.Symbol symbol = parseTree.GetSymbolForNameAndPath (typename, filename, linenum, column); if (null == symbol){ LoggingService.LogDebug ("CompleteType: Unable to lookup {0} in {1} at {2}:{3}", typename, filename, linenum, column); } else{ nodes = symbol.Children; } } else { LoggingService.LogDebug ("CompleteType: Unable to acquire codedom"); } } return nodes; } /// <summary> /// Adds a file to be parsed /// </summary> public void AddFile (string filename) { if (vtgInstalled) { LoggingService.LogDebug ("Adding file {0}", filename); engine.QueueSourcefile (filename, filename.EndsWith (".vapi", StringComparison.OrdinalIgnoreCase), false); } }// AddFile /// <summary> /// Removes a file from the parse list /// </summary> public void RemoveFile (string filename) { // Not currently possible with Afrodite completion engine }// RemoveFile /// <summary> /// Adds a package to be parsed /// </summary> public void AddPackage (string packagename) { if (!DepsInstalled){ return; } if ("glib-2.0".Equals (packagename, StringComparison.Ordinal)) { LoggingService.LogDebug ("AddPackage: Skipping {0}", packagename); return; } else { LoggingService.LogDebug ("AddPackage: Adding package {0}", packagename); } foreach (string path in Afrodite.Utils.GetPackagePaths (packagename)) { LoggingService.LogDebug ("AddPackage: Queueing {0} for package {1}", path, packagename); engine.QueueSourcefile (path, true, false); } }// AddPackage /// <summary> /// Gets the completion list for a given symbol at a given location /// </summary> internal List<Afrodite.Symbol> Complete (string symbol, string filename, int line, int column, ValaCompletionDataList results) { List<Afrodite.Symbol> nodes = new List<Afrodite.Symbol> (); if (!DepsInstalled){ return nodes; } using (Afrodite.CodeDom parseTree = engine.TryAcquireCodeDom ()) { if (null != parseTree) { LoggingService.LogDebug ("Complete: Looking up symbol at {0}:{1}:{2}", filename, line, column); Afrodite.Symbol sym = parseTree.GetSymbolForNameAndPath (symbol, filename, line, column); LoggingService.LogDebug ("Complete: Got {0}", (null == sym)? "null": sym.Name); if (null != sym) { nodes = sym.Children; AddResults (nodes, results); } } else { LoggingService.LogDebug ("Complete: Unable to acquire codedom"); } } return nodes; }// Complete internal Afrodite.Symbol GetFunction (string name, string filename, int line, int column) { if (!DepsInstalled){ return null; } using (Afrodite.CodeDom parseTree = engine.TryAcquireCodeDom ()) { if (null != parseTree) { LoggingService.LogDebug ("GetFunction: Looking up symbol at {0}:{1}:{2}", filename, line, column); Afrodite.Symbol symbol = parseTree.GetSymbolForNameAndPath (name, filename, line, column); LoggingService.LogDebug ("GetFunction: Got {0}", (null == symbol)? "null": symbol.Name); return symbol; } else { LoggingService.LogDebug ("GetFunction: Unable to acquire codedom"); } } return null; } /// <summary> /// Get the type of a given expression /// </summary> public string GetExpressionType (string symbol, string filename, int line, int column) { if (!DepsInstalled){ return symbol; } using (Afrodite.CodeDom parseTree = engine.TryAcquireCodeDom ()) { if (null != parseTree) { LoggingService.LogDebug ("GetExpressionType: Looking up symbol at {0}:{1}:{2}", filename, line, column); Afrodite.Symbol sym = parseTree.LookupSymbolAt (filename, line, column); if (null != sym) { LoggingService.LogDebug ("Got {0}", sym.SymbolType.TypeName); return sym.SymbolType.TypeName; } } else { LoggingService.LogDebug ("GetExpressionType: Unable to acquire codedom"); } } return symbol; }// GetExpressionType /// <summary> /// Get overloads for a method /// </summary> internal List<Afrodite.Symbol> GetOverloads (string name, string filename, int line, int column) { List<Afrodite.Symbol> overloads = new List<Afrodite.Symbol> (); if (!DepsInstalled){ return overloads; } using (Afrodite.CodeDom parseTree = engine.TryAcquireCodeDom ()) { if (null != parseTree) { Afrodite.Symbol symbol = parseTree.GetSymbolForNameAndPath (name, filename, line, column); overloads = new List<Afrodite.Symbol> (){ symbol }; } else { LoggingService.LogDebug ("GetOverloads: Unable to acquire codedom"); } } return overloads; }// GetOverloads /// <summary> /// Get constructors for a given type /// </summary> internal List<Afrodite.Symbol> GetConstructorsForType (string typename, string filename, int line, int column, ValaCompletionDataList results) { List<Afrodite.Symbol> functions = new List<Afrodite.Symbol> (); foreach (Afrodite.Symbol node in CompleteType (typename, filename, line, column, null)) { if ("constructor".Equals (node.MemberType, StringComparison.OrdinalIgnoreCase) || "creationmethod".Equals (node.MemberType, StringComparison.OrdinalIgnoreCase)) { functions.Add (node); } } AddResults ((IList<Afrodite.Symbol>)functions, results); return functions; }// GetConstructorsForType /// <summary> /// Get constructors for a given expression /// </summary> internal List<Afrodite.Symbol> GetConstructorsForExpression (string expression, string filename, int line, int column, ValaCompletionDataList results) { string typename = GetExpressionType (expression, filename, line, column); return GetConstructorsForType (typename, filename, line, column, results); }// GetConstructorsForExpression /// <summary> /// Get types visible from a given source location /// </summary> internal void GetTypesVisibleFrom (string filename, int line, int column, ValaCompletionDataList results) { if (!DepsInstalled){ return; } // Add contents of parents ICollection<Afrodite.Symbol> containers = GetClassesForFile (filename); AddResults (containers, results); foreach (Afrodite.Symbol klass in containers) { // TODO: check source references once afrodite reliably captures the entire range for (Afrodite.Symbol parent = klass.Parent; parent != null; parent = parent.Parent) { AddResults (parent.Children.FindAll (delegate (Afrodite.Symbol sym){ return 0 <= Array.IndexOf (containerTypes, sym.MemberType.ToLower ()); }), results); } } using (Afrodite.CodeDom parseTree = engine.TryAcquireCodeDom ()) { if (null == parseTree){ return; } AddResults (GetNamespacesForFile (filename), results); AddResults (GetClassesForFile (filename), results); Afrodite.SourceFile file = parseTree.LookupSourceFile (filename); if (null != file) { Afrodite.Symbol parent; foreach (Afrodite.DataType directive in file.UsingDirectives) { if (directive.Symbol == null) { continue; } Afrodite.Symbol ns = parseTree.Lookup (directive.Symbol.FullyQualifiedName, out parent); if (null != ns) { containers = new List<Afrodite.Symbol> (); AddResults (new Afrodite.Symbol[]{ ns }, results); foreach (Afrodite.Symbol child in ns.Children) { foreach (string containerType in containerTypes) { if (containerType.Equals (child.MemberType, StringComparison.OrdinalIgnoreCase)) containers.Add (child); } } AddResults (containers, results); } } } } }// GetTypesVisibleFrom /// <summary> /// Get symbols visible from a given source location /// </summary> internal void GetSymbolsVisibleFrom (string filename, int line, int column, ValaCompletionDataList results) { GetTypesVisibleFrom (filename, line, column, results); Complete ("this", filename, line, column, results); }// GetSymbolsVisibleFrom /// <summary> /// Add results to a ValaCompletionDataList on the GUI thread /// </summary> private static void AddResults (IEnumerable<Afrodite.Symbol> list, ValaCompletionDataList results) { if (null == list || null == results) { LoggingService.LogDebug ("AddResults: null list or results!"); return; } List<CompletionData> data = new List<CompletionData> (); foreach (Afrodite.Symbol symbol in list) { data.Add (new CompletionData (symbol)); } DispatchService.GuiDispatch (delegate { results.IsChanging = true; results.AddRange (data); results.IsChanging = false; }); }// AddResults /// <summary> /// Get a list of classes declared in a given file /// </summary> internal List<Afrodite.Symbol> GetClassesForFile (string file) { return GetSymbolsForFile (file, containerTypes); }// GetClassesForFile /// <summary> /// Get a list of namespaces declared in a given file /// </summary> internal List<Afrodite.Symbol> GetNamespacesForFile (string file) { return GetSymbolsForFile (file, new string[]{ "namespace" }); } /// <summary> /// Get a list of symbols declared in a given file /// </summary> /// <param name="file"> /// A <see cref="System.String"/>: The file to check /// </param> /// <param name="desiredTypes"> /// A <see cref="IEnumerable<System.String>"/>: The types of symbols to allow /// </param> List<Afrodite.Symbol> GetSymbolsForFile (string file, IEnumerable<string> desiredTypes) { List<Afrodite.Symbol> symbols = null; List<Afrodite.Symbol> classes = new List<Afrodite.Symbol> (); if (!DepsInstalled){ return classes; } using (Afrodite.CodeDom parseTree = engine.TryAcquireCodeDom ()) { if (null != parseTree){ Afrodite.SourceFile sourceFile = parseTree.LookupSourceFile (file); if (null != sourceFile) { symbols = sourceFile.Symbols; if (null != symbols) { foreach (Afrodite.Symbol symbol in symbols) { foreach (string containerType in desiredTypes) { if (containerType.Equals (symbol.MemberType, StringComparison.OrdinalIgnoreCase)) classes.Add (symbol); } } } } else { LoggingService.LogDebug ("GetClassesForFile: Unable to lookup source file {0}", file); } } else { LoggingService.LogDebug ("GetClassesForFile: Unable to acquire codedom"); } } return classes; } } }
// 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.Linq; using Xunit; namespace System.Text.Tests { public partial class StringBuilderTests { [Fact] public static void AppendJoin_NullValues_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("values", () => new StringBuilder().AppendJoin('|', (object[])null)); AssertExtensions.Throws<ArgumentNullException>("values", () => new StringBuilder().AppendJoin('|', (IEnumerable<object>)null)); AssertExtensions.Throws<ArgumentNullException>("values", () => new StringBuilder().AppendJoin('|', (string[])null)); AssertExtensions.Throws<ArgumentNullException>("values", () => new StringBuilder().AppendJoin("|", (object[])null)); AssertExtensions.Throws<ArgumentNullException>("values", () => new StringBuilder().AppendJoin("|", (IEnumerable<object>)null)); AssertExtensions.Throws<ArgumentNullException>("values", () => new StringBuilder().AppendJoin("|", (string[])null)); } [Theory] [InlineData(new object[0], "")] [InlineData(new object[] { null }, "")] [InlineData(new object[] { 10 }, "10")] [InlineData(new object[] { null, null }, "|")] [InlineData(new object[] { null, 20 }, "|20")] [InlineData(new object[] { 10, null }, "10|")] [InlineData(new object[] { 10, 20 }, "10|20")] [InlineData(new object[] { null, null, null }, "||")] [InlineData(new object[] { null, null, 30 }, "||30")] [InlineData(new object[] { null, 20, null }, "|20|")] [InlineData(new object[] { null, 20, 30 }, "|20|30")] [InlineData(new object[] { 10, null, null }, "10||")] [InlineData(new object[] { 10, null, 30 }, "10||30")] [InlineData(new object[] { 10, 20, null }, "10|20|")] [InlineData(new object[] { 10, 20, 30 }, "10|20|30")] [InlineData(new object[] { "" }, "")] [InlineData(new object[] { "", "" }, "|")] public static void AppendJoin_TestValues(object[] values, string expected) { var stringValues = Array.ConvertAll(values, _ => _?.ToString()); var enumerable = values.Select(_ => _); Assert.Equal(expected, new StringBuilder().AppendJoin('|', values).ToString()); Assert.Equal(expected, new StringBuilder().AppendJoin('|', enumerable).ToString()); Assert.Equal(expected, new StringBuilder().AppendJoin('|', stringValues).ToString()); Assert.Equal(expected, new StringBuilder().AppendJoin("|", values).ToString()); Assert.Equal(expected, new StringBuilder().AppendJoin("|", enumerable).ToString()); Assert.Equal(expected, new StringBuilder().AppendJoin("|", stringValues).ToString()); } [Fact] public static void AppendJoin_NullToStringValues() { AppendJoin_TestValues(new object[] { new NullToStringObject() }, ""); AppendJoin_TestValues(new object[] { new NullToStringObject(), new NullToStringObject() }, "|"); } private sealed class NullToStringObject { public override string ToString() => null; } [Theory] [InlineData(null, "123")] [InlineData("", "123")] [InlineData(" ", "1 2 3")] [InlineData(", ", "1, 2, 3")] public static void AppendJoin_TestStringSeparators(string separator, string expected) { Assert.Equal(expected, new StringBuilder().AppendJoin(separator, new object[] { 1, 2, 3 }).ToString()); Assert.Equal(expected, new StringBuilder().AppendJoin(separator, Enumerable.Range(1, 3)).ToString()); Assert.Equal(expected, new StringBuilder().AppendJoin(separator, new string[] { "1", "2", "3" }).ToString()); } private static StringBuilder CreateBuilderWithNoSpareCapacity() { return new StringBuilder(0, 5).Append("Hello"); } [Theory] [InlineData(null, new object[] { null, null })] [InlineData("", new object[] { "", "" })] [InlineData(" ", new object[] { })] [InlineData(", ", new object[] { "" })] public static void AppendJoin_NoValues_NoSpareCapacity_DoesNotThrow(string separator, object[] values) { var stringValues = Array.ConvertAll(values, _ => _?.ToString()); var enumerable = values.Select(_ => _); if (separator?.Length == 1) { CreateBuilderWithNoSpareCapacity().AppendJoin(separator[0], values); CreateBuilderWithNoSpareCapacity().AppendJoin(separator[0], enumerable); CreateBuilderWithNoSpareCapacity().AppendJoin(separator[0], stringValues); } CreateBuilderWithNoSpareCapacity().AppendJoin(separator, values); CreateBuilderWithNoSpareCapacity().AppendJoin(separator, enumerable); CreateBuilderWithNoSpareCapacity().AppendJoin(separator, stringValues); } [Theory] [InlineData(null, new object[] { " " })] [InlineData(" ", new object[] { " " })] [InlineData(" ", new object[] { null, null })] [InlineData(" ", new object[] { "", "" })] public static void AppendJoin_NoSpareCapacity_ThrowsArgumentOutOfRangeException(string separator, object[] values) { var builder = new StringBuilder(0, 5); builder.Append("Hello"); var stringValues = Array.ConvertAll(values, _ => _?.ToString()); var enumerable = values.Select(_ => _); if (separator?.Length == 1) { AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => CreateBuilderWithNoSpareCapacity().AppendJoin(separator[0], values)); AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => CreateBuilderWithNoSpareCapacity().AppendJoin(separator[0], enumerable)); AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => CreateBuilderWithNoSpareCapacity().AppendJoin(separator[0], stringValues)); } AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => CreateBuilderWithNoSpareCapacity().AppendJoin(separator, values)); AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => CreateBuilderWithNoSpareCapacity().AppendJoin(separator, enumerable)); AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => CreateBuilderWithNoSpareCapacity().AppendJoin(separator, stringValues)); } [Theory] [InlineData("Hello", new char[] { 'a' }, "Helloa")] [InlineData("Hello", new char[] { 'b', 'c', 'd' }, "Hellobcd")] [InlineData("Hello", new char[] { 'b', '\0', 'd' }, "Hellob\0d")] [InlineData("", new char[] { 'e', 'f', 'g' }, "efg")] [InlineData("Hello", new char[0], "Hello")] public static void Append_CharSpan(string original, char[] value, string expected) { var builder = new StringBuilder(original); builder.Append(new ReadOnlySpan<char>(value)); Assert.Equal(expected, builder.ToString()); } [Theory] [InlineData("Hello", new char[] { 'a' }, "Helloa")] [InlineData("Hello", new char[] { 'b', 'c', 'd' }, "Hellobcd")] [InlineData("Hello", new char[] { 'b', '\0', 'd' }, "Hellob\0d")] [InlineData("", new char[] { 'e', 'f', 'g' }, "efg")] [InlineData("Hello", new char[0], "Hello")] public static void Append_CharMemory(string original, char[] value, string expected) { var builder = new StringBuilder(original); builder.Append(value.AsMemory()); Assert.Equal(expected, builder.ToString()); } [Theory] [InlineData(1)] [InlineData(10000)] public static void Clear_AppendAndInsertBeforeClearManyTimes_CapacityStaysWithinRange(int times) { var builder = new StringBuilder(); var originalCapacity = builder.Capacity; var s = new string(' ', 10); int oldLength = 0; for (int i = 0; i < times; i++) { builder.Append(s); builder.Append(s); builder.Append(s); builder.Insert(0, s); builder.Insert(0, s); oldLength = builder.Length; builder.Clear(); } Assert.InRange(builder.Capacity, 1, oldLength * 1.2); } [Fact] public static void Clear_InitialCapacityMuchLargerThanLength_CapacityReducedToInitialCapacity() { var builder = new StringBuilder(100); var initialCapacity = builder.Capacity; builder.Append(new string('a', 40)); builder.Insert(0, new string('a', 10)); builder.Insert(0, new string('a', 10)); builder.Insert(0, new string('a', 10)); var oldCapacity = builder.Capacity; var oldLength = builder.Length; builder.Clear(); Assert.NotEqual(oldCapacity, builder.Capacity); Assert.Equal(initialCapacity, builder.Capacity); Assert.NotInRange(builder.Capacity, 1, oldLength * 1.2); Assert.InRange(builder.Capacity, 1, Math.Max(initialCapacity, oldLength * 1.2)); } [Fact] public static void Clear_StringBuilderHasTwoChunks_OneChunkIsEmpty_ClearReducesCapacity() { var sb = new StringBuilder(string.Empty); int initialCapacity = sb.Capacity; for (int i = 0; i < initialCapacity; i++) { sb.Append('a'); } sb.Insert(0, 'a'); while (sb.Length > 1) { sb.Remove(1, 1); } int oldCapacity = sb.Capacity; sb.Clear(); Assert.Equal(oldCapacity - 1, sb.Capacity); Assert.Equal(initialCapacity, sb.Capacity); } [Theory] [InlineData("Hello", 0, new char[] { '\0', '\0', '\0', '\0', '\0' }, 5, new char[] { 'H', 'e', 'l', 'l', 'o' })] [InlineData("Hello", 0, new char[] { '\0', '\0', '\0', '\0' }, 4, new char[] { 'H', 'e', 'l', 'l' })] [InlineData("Hello", 1, new char[] { '\0', '\0', '\0', '\0', '\0' }, 4, new char[] { 'e', 'l', 'l', 'o', '\0' })] public static void CopyTo_CharSpan(string value, int sourceIndex, char[] destination, int count, char[] expected) { var builder = new StringBuilder(value); builder.CopyTo(sourceIndex, new Span<char>(destination), count); Assert.Equal(expected, destination); } [Fact] public static void CopyTo_CharSpan_StringBuilderWithMultipleChunks() { StringBuilder builder = StringBuilderWithMultipleChunks(); char[] destination = new char[builder.Length]; builder.CopyTo(0, new Span<char>(destination), destination.Length); Assert.Equal(s_chunkSplitSource.ToCharArray(), destination); } [Fact] public static void CopyTo_CharSpan_Invalid() { var builder = new StringBuilder("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceIndex", () => builder.CopyTo(-1, new Span<char>(new char[10]), 0)); // Source index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceIndex", () => builder.CopyTo(6, new Span<char>(new char[10]), 0)); // Source index > builder.Length AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => builder.CopyTo(0, new Span<char>(new char[10]), -1)); // Count < 0 AssertExtensions.Throws<ArgumentException>(null, () => builder.CopyTo(5, new Span<char>(new char[10]), 1)); // Source index + count > builder.Length AssertExtensions.Throws<ArgumentException>(null, () => builder.CopyTo(4, new Span<char>(new char[10]), 2)); // Source index + count > builder.Length AssertExtensions.Throws<ArgumentException>(null, () => builder.CopyTo(0, new Span<char>(new char[10]), 11)); // count > destinationArray.Length } [Theory] [InlineData("Hello", 0, new char[] { '\0' }, "\0Hello")] [InlineData("Hello", 3, new char[] { 'a', 'b', 'c' }, "Helabclo")] [InlineData("Hello", 5, new char[] { 'd', 'e', 'f' }, "Hellodef")] [InlineData("Hello", 0, new char[0], "Hello")] public static void Insert_CharSpan(string original, int index, char[] value, string expected) { var builder = new StringBuilder(original); builder.Insert(index, new ReadOnlySpan<char>(value)); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Insert_CharSpan_Invalid() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(-1, new ReadOnlySpan<char>(new char[0]))); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(builder.Length + 1, new ReadOnlySpan<char>(new char[0]))); // Index > builder.Length AssertExtensions.Throws<ArgumentOutOfRangeException>("requiredLength", () => builder.Insert(builder.Length, new ReadOnlySpan<char>(new char[1]))); // New length > builder.MaxCapacity } public static IEnumerable<object[]> Append_StringBuilder_TestData() { string mediumString = new string('a', 30); string largeString = new string('b', 1000); var sb1 = new StringBuilder("Hello"); var sb2 = new StringBuilder("one"); var sb3 = new StringBuilder(20).Append(mediumString); yield return new object[] { new StringBuilder("Hello"), sb1, "HelloHello" }; yield return new object[] { new StringBuilder("Hello"), sb2, "Helloone" }; yield return new object[] { new StringBuilder("Hello"), new StringBuilder(), "Hello" }; yield return new object[] { new StringBuilder("one"), sb3, "one" + mediumString }; yield return new object[] { new StringBuilder(20).Append(mediumString), sb3, mediumString + mediumString }; yield return new object[] { new StringBuilder(10).Append(mediumString), sb3, mediumString + mediumString }; yield return new object[] { new StringBuilder(20).Append(largeString), sb3, largeString + mediumString }; yield return new object[] { new StringBuilder(10).Append(largeString), sb3, largeString + mediumString }; yield return new object[] { new StringBuilder(10), sb3, mediumString }; yield return new object[] { new StringBuilder(30), sb3, mediumString }; yield return new object[] { new StringBuilder(10), new StringBuilder(20), string.Empty}; yield return new object[] { sb1, null, "Hello" }; yield return new object[] { sb1, sb1, "HelloHello" }; } [Theory] [MemberData(nameof(Append_StringBuilder_TestData))] public static void Append_StringBuilder(StringBuilder s1, StringBuilder s2, string s) { Assert.Equal(s, s1.Append(s2).ToString()); } public static IEnumerable<object[]> Append_StringBuilder_Substring_TestData() { string mediumString = new string('a', 30); string largeString = new string('b', 1000); var sb1 = new StringBuilder("Hello"); var sb2 = new StringBuilder("one"); var sb3 = new StringBuilder(20).Append(mediumString); yield return new object[] { new StringBuilder("Hello"), sb1, 0, 5, "HelloHello" }; yield return new object[] { new StringBuilder("Hello"), sb1, 0, 0, "Hello" }; yield return new object[] { new StringBuilder("Hello"), sb1, 2, 3, "Hellollo" }; yield return new object[] { new StringBuilder("Hello"), sb1, 2, 2, "Helloll" }; yield return new object[] { new StringBuilder("Hello"), sb1, 2, 0, "Hello" }; yield return new object[] { new StringBuilder("Hello"), new StringBuilder(), 0, 0, "Hello" }; yield return new object[] { new StringBuilder("Hello"), null, 0, 0, "Hello" }; yield return new object[] { new StringBuilder(), new StringBuilder("Hello"), 2, 3, "llo" }; yield return new object[] { new StringBuilder("Hello"), sb2, 0, 3, "Helloone" }; yield return new object[] { new StringBuilder("one"), sb3, 5, 25, "one" + new string('a', 25) }; yield return new object[] { new StringBuilder("one"), sb3, 5, 20, "one" + new string('a', 20) }; yield return new object[] { new StringBuilder("one"), sb3, 10, 10, "one" + new string('a', 10) }; yield return new object[] { new StringBuilder(20).Append(mediumString), sb3, 20, 10, new string('a', 40) }; yield return new object[] { new StringBuilder(10).Append(mediumString), sb3, 10, 10, new string('a', 40) }; yield return new object[] { new StringBuilder(20).Append(largeString), new StringBuilder(20).Append(largeString), 100, 50, largeString + new string('b', 50) }; yield return new object[] { new StringBuilder(10).Append(mediumString), new StringBuilder(20).Append(largeString), 20, 10, mediumString + new string('b', 10) }; yield return new object[] { new StringBuilder(10).Append(mediumString), new StringBuilder(20).Append(largeString), 100, 50, mediumString + new string('b', 50) }; yield return new object[] { sb1, sb1, 2, 3, "Hellollo" }; yield return new object[] { sb2, sb2, 2, 0, "one" }; } [Theory] [MemberData(nameof(Append_StringBuilder_Substring_TestData))] public static void Append_StringBuilder_Substring(StringBuilder s1, StringBuilder s2, int startIndex, int count, string s) { Assert.Equal(s, s1.Append(s2, startIndex, count).ToString()); } [Fact] public static void Append_StringBuilder_InvalidInput() { StringBuilder sb = new StringBuilder(5, 5).Append("Hello"); Assert.Throws<ArgumentOutOfRangeException>(() => sb.Append(sb, -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => sb.Append(sb, 0, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => sb.Append(sb, 4, 5)); Assert.Throws<ArgumentNullException>(() => sb.Append( (StringBuilder)null, 2, 2)); Assert.Throws<ArgumentNullException>(() => sb.Append((StringBuilder)null, 2, 3)); Assert.Throws<ArgumentOutOfRangeException>(() => new StringBuilder(3, 6).Append("Hello").Append(sb)); Assert.Throws<ArgumentOutOfRangeException>(() => new StringBuilder(3, 6).Append("Hello").Append("Hello")); Assert.Throws<ArgumentOutOfRangeException>(() => sb.Append(sb)); } public static IEnumerable<object[]> Equals_String_TestData() { string mediumString = new string('a', 30); string largeString = new string('a', 1000); string extraLargeString = new string('a', 41000); // 8000 is the maximum chunk size var sb1 = new StringBuilder("Hello"); var sb2 = new StringBuilder(20).Append(mediumString); var sb3 = new StringBuilder(20).Append(largeString); var sb4 = new StringBuilder(20).Append(extraLargeString); yield return new object[] { sb1, "Hello", true }; yield return new object[] { sb1, "Hel", false }; yield return new object[] { sb1, "Hellz", false }; yield return new object[] { sb1, "Helloz", false }; yield return new object[] { sb1, "", false }; yield return new object[] { new StringBuilder(), "", true }; yield return new object[] { new StringBuilder(), "Hello", false }; yield return new object[] { sb2, mediumString, true }; yield return new object[] { sb2, "H", false }; yield return new object[] { sb3, largeString, true }; yield return new object[] { sb3, "H", false }; yield return new object[] { sb3, new string('a', 999) + 'b', false }; yield return new object[] { sb4, extraLargeString, true }; yield return new object[] { sb4, "H", false }; } [Theory] [MemberData(nameof(Equals_String_TestData))] public static void Equals(StringBuilder sb1, string value, bool expected) { Assert.Equal(expected, sb1.Equals(value.AsSpan())); } [Fact] public static void ForEach() { // Test on a variety of lengths, at least up to the point of 9 8K chunks = 72K because this is where // we start using a different technique for creating the ChunkEnumerator. 200 * 500 = 100K which hits this. for (int i = 0; i < 200; i++) { StringBuilder inBuilder = new StringBuilder(); for (int j = 0; j < i; j++) { // Make some unique strings that are at least 500 bytes long. inBuilder.Append(j); inBuilder.Append("_abcdefghijklmnopqrstuvwxyz01234567890__Abcdefghijklmnopqrstuvwxyz01234567890__ABcdefghijklmnopqrstuvwxyz01_"); inBuilder.Append("_abcdefghijklmnopqrstuvwxyz01234567890__Abcdefghijklmnopqrstuvwxyz01234567890__ABcdefghijklmnopqrstuvwxyz0123_"); inBuilder.Append("_abcdefghijklmnopqrstuvwxyz01234567890__Abcdefghijklmnopqrstuvwxyz01234567890__ABcdefghijklmnopqrstuvwxyz012345_"); inBuilder.Append("_abcdefghijklmnopqrstuvwxyz01234567890__Abcdefghijklmnopqrstuvwxyz01234567890__ABcdefghijklmnopqrstuvwxyz012345678_"); inBuilder.Append("_abcdefghijklmnopqrstuvwxyz01234567890__Abcdefghijklmnopqrstuvwxyz01234567890__ABcdefghijklmnopqrstuvwxyz01234567890_"); } // Copy the string out (not using StringBuilder). string outStr = ""; foreach (ReadOnlyMemory<char> chunk in inBuilder.GetChunks()) outStr += new string(chunk.Span); // The strings formed by concatenating the chunks should be the same as the value in the StringBuilder. Assert.Equal(outStr, inBuilder.ToString()); } } [Fact] public static void EqualsIgnoresCapacity() { var sb1 = new StringBuilder(5); var sb2 = new StringBuilder(10); Assert.True(sb1.Equals(sb2)); sb1.Append("12345"); sb2.Append("12345"); Assert.True(sb1.Equals(sb2)); } [Fact] public static void EqualsIgnoresMaxCapacity() { var sb1 = new StringBuilder(5, 5); var sb2 = new StringBuilder(5, 10); Assert.True(sb1.Equals(sb2)); sb1.Append("12345"); sb2.Append("12345"); Assert.True(sb1.Equals(sb2)); } } }
using System; using System.Collections.Generic; using System.Text; namespace iControl { //======================================================================= // Enums //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.FilterAction", Namespace = "urn:iControl")] public enum NetworkingFilterAction { FILTER_ACTION_NONE, FILTER_ACTION_ACCEPT, FILTER_ACTION_DISCARD, FILTER_ACTION_REJECT, FILTER_ACTION_CONTINUE, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.FlowControlType", Namespace = "urn:iControl")] public enum NetworkingFlowControlType { FLOW_CONTROL_PAUSE_NONE, FLOW_CONTROL_PAUSE_TX, FLOW_CONTROL_PAUSE_RX, FLOW_CONTROL_PAUSE_TX_RX, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.IPCompAlgorithm", Namespace = "urn:iControl")] public enum NetworkingIPCompAlgorithm { IPCOMP_ALGORITHM_UNKNOWN, IPCOMP_ALGORITHM_NONE, IPCOMP_ALGORITHM_DEFLATE, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.IPsecDiffieHellmanGroup", Namespace = "urn:iControl")] public enum NetworkingIPsecDiffieHellmanGroup { IPSEC_DIFFIE_HELLMAN_GROUP_UNKNOWN, IPSEC_DIFFIE_HELLMAN_GROUP_MODP768, IPSEC_DIFFIE_HELLMAN_GROUP_MODP1024, IPSEC_DIFFIE_HELLMAN_GROUP_MODP1536, IPSEC_DIFFIE_HELLMAN_GROUP_MODP2048, IPSEC_DIFFIE_HELLMAN_GROUP_MODP3072, IPSEC_DIFFIE_HELLMAN_GROUP_MODP4096, IPSEC_DIFFIE_HELLMAN_GROUP_MODP6144, IPSEC_DIFFIE_HELLMAN_GROUP_MODP8192, IPSEC_ECDH_GROUP_ECP256, IPSEC_ECDH_GROUP_ECP384, IPSEC_ECDH_GROUP_ECP521, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.IPsecDirection", Namespace = "urn:iControl")] public enum NetworkingIPsecDirection { IPSEC_DIR_UNKNOWN, IPSEC_DIR_IN, IPSEC_DIR_OUT, IPSEC_DIR_BOTH, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.IPsecDynSaEncryptAlgorithm", Namespace = "urn:iControl")] public enum NetworkingIPsecDynSaEncryptAlgorithm { IPSEC_DYNAMIC_ENCR_UNKNOWN, IPSEC_DYNAMIC_ENCR_NULL, IPSEC_DYNAMIC_ENCR_3DES, IPSEC_DYNAMIC_ENCR_AES128, IPSEC_DYNAMIC_ENCR_AES192, IPSEC_DYNAMIC_ENCR_AES256, IPSEC_DYNAMIC_ENCR_AES_GCM128, IPSEC_DYNAMIC_ENCR_AES_GCM192, IPSEC_DYNAMIC_ENCR_AES_GCM256, IPSEC_DYNAMIC_ENCR_AES_GMAC128, IPSEC_DYNAMIC_ENCR_AES_GMAC192, IPSEC_DYNAMIC_ENCR_AES_GMAC256, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.IPsecIkeEncrAlgorithm", Namespace = "urn:iControl")] public enum NetworkingIPsecIkeEncrAlgorithm { IPSEC_IKE_ENCR_ALG_UNKNOWN, IPSEC_IKE_ENCR_ALG_DES, IPSEC_IKE_ENCR_ALG_3DES, IPSEC_IKE_ENCR_ALG_BLOWFISH, IPSEC_IKE_ENCR_ALG_CAST128, IPSEC_IKE_ENCR_ALG_AES128, IPSEC_IKE_ENCR_ALG_AES192, IPSEC_IKE_ENCR_ALG_AES256, IPSEC_IKE_ENCR_ALG_CAMELLIA, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.IPsecIkeHashAlgorithm", Namespace = "urn:iControl")] public enum NetworkingIPsecIkeHashAlgorithm { IPSEC_IKE_HASH_ALG_UNKNOWN, IPSEC_IKE_HASH_ALG_MD5, IPSEC_IKE_HASH_ALG_SHA1, IPSEC_IKE_HASH_ALG_SHA256, IPSEC_IKE_HASH_ALG_SHA384, IPSEC_IKE_HASH_ALG_SHA512, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.IPsecIkeLogLevel", Namespace = "urn:iControl")] public enum NetworkingIPsecIkeLogLevel { IPSEC_IKE_LOG_LEVEL_UNKNOWN, IPSEC_IKE_LOG_LEVEL_ERROR, IPSEC_IKE_LOG_LEVEL_WARNING, IPSEC_IKE_LOG_LEVEL_NOTIFY, IPSEC_IKE_LOG_LEVEL_INFO, IPSEC_IKE_LOG_LEVEL_DEBUG, IPSEC_IKE_LOG_LEVEL_DEBUG2, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.IPsecIkePeerCertType", Namespace = "urn:iControl")] public enum NetworkingIPsecIkePeerCertType { IPSEC_IKE_PEER_CERT_TYPE_UNKNOWN, IPSEC_IKE_PEER_CERT_TYPE_NONE, IPSEC_IKE_PEER_CERT_TYPE_CERTFILE, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.IPsecIkePeerGeneratePolicy", Namespace = "urn:iControl")] public enum NetworkingIPsecIkePeerGeneratePolicy { IPSEC_IKE_PEER_GENERATE_POLICY_UNKNOWN, IPSEC_IKE_PEER_GENERATE_POLICY_OFF, IPSEC_IKE_PEER_GENERATE_POLICY_ON, IPSEC_IKE_PEER_GENERATE_POLICY_UNIQUE, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.IPsecIkePeerIDType", Namespace = "urn:iControl")] public enum NetworkingIPsecIkePeerIDType { IPSEC_IKE_PEER_TYPE_UNKNOWN, IPSEC_IKE_PEER_TYPE_ADDRESS, IPSEC_IKE_PEER_TYPE_FQDN, IPSEC_IKE_PEER_TYPE_USER_FQDN, IPSEC_IKE_PEER_TYPE_KEYID_TAG, IPSEC_IKE_PEER_TYPE_ASN1DN, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.IPsecIkePeerMode", Namespace = "urn:iControl")] public enum NetworkingIPsecIkePeerMode { IPSEC_IKE_EXCHANGE_MODE_UNKNOWN, IPSEC_IKE_EXCHANGE_MODE_AGGRESSIVE, IPSEC_IKE_EXCHANGE_MODE_MAIN, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.IPsecIkePeerNatTraversal", Namespace = "urn:iControl")] public enum NetworkingIPsecIkePeerNatTraversal { IPSEC_IKE_PEER_NAT_TRAVERSAL_UNKNOWN, IPSEC_IKE_PEER_NAT_TRAVERSAL_OFF, IPSEC_IKE_PEER_NAT_TRAVERSAL_ON, IPSEC_IKE_PEER_NAT_TRAVERSAL_FORCE, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.IPsecIkeVersion", Namespace = "urn:iControl")] public enum NetworkingIPsecIkeVersion { IPSEC_IKE_VERSION_UNKNOWN, IPSEC_IKE_VERSION_1, IPSEC_IKE_VERSION_2, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.IPsecManSaEncrAlgorithm", Namespace = "urn:iControl")] public enum NetworkingIPsecManSaEncrAlgorithm { IPSEC_MANUAL_SA_ENCR_UNKNOWN, IPSEC_MANUAL_SA_ENCR_NULL, IPSEC_MANUAL_SA_ENCR_3DES, IPSEC_MANUAL_SA_ENCR_AES128, IPSEC_MANUAL_SA_ENCR_AES192, IPSEC_MANUAL_SA_ENCR_AES256, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.IPsecMode", Namespace = "urn:iControl")] public enum NetworkingIPsecMode { IPSEC_MODE_UNKNOWN, IPSEC_MODE_TRANSPORT, IPSEC_MODE_TUNNEL, IPSEC_MODE_ISESSION, IPSEC_MODE_INTERFACE, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.IPsecProtocol", Namespace = "urn:iControl")] public enum NetworkingIPsecProtocol { IPSEC_PROTOCOL_UNKNOWN, IPSEC_PROTOCOL_ESP, IPSEC_PROTOCOL_AH, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.IPsecSaAuthAlgorithm", Namespace = "urn:iControl")] public enum NetworkingIPsecSaAuthAlgorithm { IPSEC_DYNAMIC_SA_AUTH_UNKNOWN, IPSEC_DYNAMIC_SA_AUTH_SHA1, IPSEC_DYNAMIC_SA_AUTH_AES_GCM128, IPSEC_DYNAMIC_SA_AUTH_AES_GCM192, IPSEC_DYNAMIC_SA_AUTH_AES_GCM256, IPSEC_DYNAMIC_SA_AUTH_AES_GMAC128, IPSEC_DYNAMIC_SA_AUTH_AES_GMAC192, IPSEC_DYNAMIC_SA_AUTH_AES_GMAC256, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.IPsecSaManAlgorithm", Namespace = "urn:iControl")] public enum NetworkingIPsecSaManAlgorithm { IPSEC_MANUAL_SA_AUTH_UNKNOWN, IPSEC_MANUAL_SA_AUTH_SHA1, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.IPsecSaMethod", Namespace = "urn:iControl")] public enum NetworkingIPsecSaMethod { IPSEC_AUTH_METHOD_UNKNOWN, IPSEC_AUTH_METHOD_PRE_SHARED_KEY, IPSEC_AUTH_METHOD_RSA_SIGNATURE, IPSEC_AUTH_METHOD_DSS, IPSEC_AUTH_METHOD_ECDSA_256, IPSEC_AUTH_METHOD_ECDSA_384, IPSEC_AUTH_METHOD_ECDSA_521, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.IPsecTrafficSelectorAction", Namespace = "urn:iControl")] public enum NetworkingIPsecTrafficSelectorAction { IPSEC_TRAFFIC_SELECTOR_ACTION_UNKNOWN, IPSEC_TRAFFIC_SELECTOR_ACTION_DISCARD, IPSEC_TRAFFIC_SELECTOR_ACTION_PROTECT, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.LearningMode", Namespace = "urn:iControl")] public enum NetworkingLearningMode { LEARNING_MODE_ENABLE_FORWARD, LEARNING_MODE_DISABLE_FORWARD, LEARNING_MODE_DISABLE_DROP, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.MediaStatus", Namespace = "urn:iControl")] public enum NetworkingMediaStatus { MEDIA_STATUS_UP, MEDIA_STATUS_DOWN, MEDIA_STATUS_DISABLED, MEDIA_STATUS_UNINITIALIZED, MEDIA_STATUS_LOOPBACK, MEDIA_STATUS_UNPOPULATED, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.MemberTagMode", Namespace = "urn:iControl")] public enum NetworkingMemberTagMode { MEMBER_TAG_MODE_UNKNOWN, MEMBER_TAG_MODE_NONE, MEMBER_TAG_MODE_SERVICE, MEMBER_TAG_MODE_CUSTOMER, MEMBER_TAG_MODE_DOUBLE, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.MemberTagType", Namespace = "urn:iControl")] public enum NetworkingMemberTagType { MEMBER_TAGGED, MEMBER_UNTAGGED, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.MemberType", Namespace = "urn:iControl")] public enum NetworkingMemberType { MEMBER_INTERFACE, MEMBER_TRUNK, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.PhyMasterSlaveMode", Namespace = "urn:iControl")] public enum NetworkingPhyMasterSlaveMode { PHY_MODE_NONE, PHY_MODE_SLAVE, PHY_MODE_MASTER, PHY_MODE_AUTO, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.RouteEntryType", Namespace = "urn:iControl")] public enum NetworkingRouteEntryType { ROUTE_TYPE_GATEWAY, ROUTE_TYPE_POOL, ROUTE_TYPE_INTERFACE, ROUTE_TYPE_REJECT, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.STPLinkType", Namespace = "urn:iControl")] public enum NetworkingSTPLinkType { STP_LINK_TYPE_P2P, STP_LINK_TYPE_SHARED, STP_LINK_TYPE_AUTO, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.STPModeType", Namespace = "urn:iControl")] public enum NetworkingSTPModeType { STP_MODE_TYPE_DISABLED, STP_MODE_TYPE_PASSTHROUGH, STP_MODE_TYPE_STP, STP_MODE_TYPE_RSTP, STP_MODE_TYPE_MSTP, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.STPRoleType", Namespace = "urn:iControl")] public enum NetworkingSTPRoleType { STP_ROLE_TYPE_DISABLE, STP_ROLE_TYPE_ROOT, STP_ROLE_TYPE_DESIGNATE, STP_ROLE_TYPE_ALTERNATE, STP_ROLE_TYPE_BACKUP, STP_ROLE_TYPE_MASTER, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.STPStateType", Namespace = "urn:iControl")] public enum NetworkingSTPStateType { STP_STATE_TYPE_DETACH, STP_STATE_TYPE_BLOCK, STP_STATE_TYPE_LISTEN, STP_STATE_TYPE_LEARN, STP_STATE_TYPE_FORWARD, STP_STATE_TYPE_DISABLE, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.TunnelProfileType", Namespace = "urn:iControl")] public enum NetworkingTunnelProfileType { TUNNEL_PROFILE_UNKNOWN, TUNNEL_PROFILE_ETHERIP, TUNNEL_PROFILE_FEC, TUNNEL_PROFILE_GRE, TUNNEL_PROFILE_IPIP, TUNNEL_PROFILE_PPP, TUNNEL_PROFILE_TCPFORWARD, TUNNEL_PROFILE_VXLAN, TUNNEL_PROFILE_WCCPGRE, TUNNEL_PROFILE_V6RD, TUNNEL_PROFILE_IPSEC, TUNNEL_PROFILE_GENEVE, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.TunnelProtocol", Namespace = "urn:iControl")] public enum NetworkingTunnelProtocol { TUNNEL_PROTOCOL_UNKNOWN, TUNNEL_PROTOCOL_IPV4, TUNNEL_PROTOCOL_IPV6, } //======================================================================= // Structs //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.ProfileTunnelProtocol", Namespace = "urn:iControl")] public partial class NetworkingProfileTunnelProtocol { private NetworkingTunnelProtocol valueField; public NetworkingTunnelProtocol value { get { return this.valueField; } set { this.valueField = value; } } private bool default_flagField; public bool default_flag { get { return this.default_flagField; } set { this.default_flagField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.Uuid_128", Namespace = "urn:iControl")] public partial class NetworkingUuid_128 { private CommonULong64 low_partField; public CommonULong64 low_part { get { return this.low_partField; } set { this.low_partField = value; } } private CommonULong64 high_partField; public CommonULong64 high_part { get { return this.high_partField; } set { this.high_partField = value; } } }; }
using System; using System.Collections.Generic; using System.Text; namespace Hydra.Framework.Mapping.Layers { // // ********************************************************************** /// <summary> /// Label layer class /// </summary> /// <example> /// Creates a new label layer and sets the label text to the "StateName" column in the FeatureDataTable of the datasource /// <code lang="C#"> /// //Set up a label layer /// Hydra.Framework.Mapping.Layers.LabelLayer layLabel = new Hydra.Framework.Mapping.Layers.LabelLayer("Country labels"); /// layLabel.DataSource = layCountries.DataSource; /// layLabel.Enabled = true; /// layLabel.LabelColumn = "StateName"; /// layLabel.AbstractStyle = new Hydra.Framework.Mapping.Styles.LabelStyle(); /// layLabel.AbstractStyle.CollisionDetection = true; /// layLabel.AbstractStyle.CollisionBuffer = new SizeF(20, 20); /// layLabel.AbstractStyle.ForeColor = Color.White; /// layLabel.AbstractStyle.Font = new Font(FontFamily.GenericSerif, 8); /// layLabel.MaxVisible = 90; /// layLabel.AbstractStyle.HorizontalAlignment = Hydra.Framework.Mapping.Styles.LabelStyle.HorizontalAlignmentEnum.Center; /// </code> /// </example> // ********************************************************************** // public class LabelLayer : Layer, IDisposable { #region Private Member Variables // // ********************************************************************** /// <summary> /// Multipart AbstractGeometry Behaviour /// </summary> // ********************************************************************** // private MultipartGeometryBehaviourEnum m_MultipartGeometryBehaviour; // // ********************************************************************** /// <summary> /// Label Filter /// </summary> // ********************************************************************** // private Hydra.Framework.Mapping.Rendering.LabelCollisionDetection.LabelFilterMethod m_LabelFilter; // // ********************************************************************** /// <summary> /// Smoothing Mode /// </summary> // ********************************************************************** // private System.Drawing.Drawing2D.SmoothingMode m_SmoothingMode; // // ********************************************************************** /// <summary> /// Text Rendering Hint /// </summary> // ********************************************************************** // private System.Drawing.Text.TextRenderingHint m_TextRenderingHint; // // ********************************************************************** /// <summary> /// Mapping Data Source /// </summary> // ********************************************************************** // private Hydra.Framework.Mapping.Data.Providers.IProvider m_DataSource; // // ********************************************************************** /// <summary> /// AbstractStyle /// </summary> // ********************************************************************** // private Hydra.Framework.Mapping.Styles.LabelStyle m_Style; // // ********************************************************************** /// <summary> /// Priority /// </summary> // ********************************************************************** // private int m_Priority; // // ********************************************************************** /// <summary> /// Get Label Method /// </summary> // ********************************************************************** // private GetLabelMethod m_GetLabelMethod; // // ********************************************************************** /// <summary> /// Label Column /// </summary> // ********************************************************************** // private string m_LabelColumn; // // ********************************************************************** /// <summary> /// Theme /// </summary> // ********************************************************************** // private Hydra.Framework.Mapping.Rendering.Thematics.ITheme m_Theme; // // ********************************************************************** /// <summary> /// Rotation Column /// </summary> // ********************************************************************** // private string m_RotationColumn; #endregion #region Delegates // // ********************************************************************** /// <summary> /// Delegate method for creating advanced label texts /// </summary> /// <param name="fdr"></param> /// <returns></returns> // ********************************************************************** // public delegate string GetLabelMethod(Hydra.Framework.Mapping.Data.FeatureDataRow fdr); #endregion #region Constructors // // ********************************************************************** /// <summary> /// Creates a new instance of a LabelLayer /// </summary> /// <param name="layername">The layername.</param> // ********************************************************************** // public LabelLayer(string layername) { m_Style = new Hydra.Framework.Mapping.Styles.LabelStyle(); this.LayerName = layername; this.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; this.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; m_MultipartGeometryBehaviour = MultipartGeometryBehaviourEnum.All; m_LabelFilter = Hydra.Framework.Mapping.Rendering.LabelCollisionDetection.SimpleCollisionDetection; } #endregion #region Properties // // ********************************************************************** /// <summary> /// Gets or sets labelling behavior on multipart geometries /// </summary> /// <value>The multipart geometry behaviour.</value> /// <remarks>Default value is <see cref="MultipartGeometryBehaviourEnum.All"/></remarks> // ********************************************************************** // public MultipartGeometryBehaviourEnum MultipartGeometryBehaviour { get { return m_MultipartGeometryBehaviour; } set { m_MultipartGeometryBehaviour = value; } } // // ********************************************************************** /// <summary> /// Filtermethod delegate for performing filtering /// </summary> /// <value>The label filter.</value> /// <remarks> /// Default method is <see cref="Hydra.Framework.Mapping.Rendering.LabelCollisionDetection.SimpleCollisionDetection"/> /// </remarks> // ********************************************************************** // public Hydra.Framework.Mapping.Rendering.LabelCollisionDetection.LabelFilterMethod LabelFilter { get { return m_LabelFilter; } set { m_LabelFilter = value; } } // // ********************************************************************** /// <summary> /// Render whether smoothing (antialiasing) is applied to lines and curves and the edges of filled areas /// </summary> /// <value>The smoothing mode.</value> // ********************************************************************** // public System.Drawing.Drawing2D.SmoothingMode SmoothingMode { get { return m_SmoothingMode; } set { m_SmoothingMode = value; } } // // ********************************************************************** /// <summary> /// Specifies the quality of text rendering /// </summary> /// <value>The text rendering hint.</value> // ********************************************************************** // public System.Drawing.Text.TextRenderingHint TextRenderingHint { get { return m_TextRenderingHint; } set { m_TextRenderingHint = value; } } // // ********************************************************************** /// <summary> /// Gets or sets the datasource /// </summary> /// <value>The data source.</value> // ********************************************************************** // public Hydra.Framework.Mapping.Data.Providers.IProvider DataSource { get { return m_DataSource; } set { m_DataSource = value; } } // // ********************************************************************** /// <summary> /// Gets or sets the rendering style of the label layer. /// </summary> /// <value>The style.</value> // ********************************************************************** // public Hydra.Framework.Mapping.Styles.LabelStyle Style { get { return m_Style; } set { m_Style = value; } } // // ********************************************************************** /// <summary> /// Gets or sets thematic settings for the layer. Set to null to ignore thematics /// </summary> /// <value>The theme.</value> // ********************************************************************** // public Hydra.Framework.Mapping.Rendering.Thematics.ITheme Theme { get { return m_Theme; } set { m_Theme = value; } } // // ********************************************************************** /// <summary> /// Data column or expression where label text is extracted from. /// </summary> /// <value>The label column.</value> /// <remarks> /// This property is overriden by the <see cref="LabelStringDelegate"/>. /// </remarks> // ********************************************************************** // public string LabelColumn { get { return m_LabelColumn; } set { m_LabelColumn = value; } } // // ********************************************************************** /// <summary> /// Gets or sets the method for creating a custom label string based on a feature. /// </summary> /// <value>The label string delegate.</value> /// <remarks> /// <para>If this method is not null, it will override the <see cref="LabelColumn"/> value.</para> /// <para>The label delegate must take a <see cref="Hydra.Framework.Mapping.Data.FeatureDataRow"/> and return a string.</para> /// <example> /// Creating a label-text by combining attributes "ROADNAME" and "STATE" into one string, using /// an anonymous delegate: /// <code lang="C#"> /// myLabelLayer.LabelStringDelegate = delegate(Hydra.Framework.Mapping.Data.FeatureDataRow fdr) /// { return fdr["ROADNAME"].ToString() + ", " + fdr["STATE"].ToString(); }; /// </code> /// </example> /// </remarks> // ********************************************************************** // public GetLabelMethod LabelStringDelegate { get { return m_GetLabelMethod; } set { m_GetLabelMethod = value; } } // // ********************************************************************** /// <summary> /// Data column from where the label rotation is derived. /// If this is empty, rotation will be zero, or aligned to a linestring. /// Rotation are in degrees (positive = clockwise). /// </summary> /// <value>The rotation column.</value> // ********************************************************************** // public string RotationColumn { get { return m_RotationColumn; } set { m_RotationColumn = value; } } // // ********************************************************************** /// <summary> /// A value indication the priority of the label in cases of label-collision detection /// </summary> /// <value>The priority.</value> // ********************************************************************** // public int Priority { get { return m_Priority; } set { m_Priority = value; } } #endregion #region ILayer Implementation // // ********************************************************************** /// <summary> /// Renders the layer /// </summary> /// <param name="g">Graphics object reference</param> /// <param name="map">Map which is rendered</param> // ********************************************************************** // public override void Render(System.Drawing.Graphics g, Map map) { if (this.Style.Enabled && this.Style.MaxVisible >= map.Zoom && this.Style.MinVisible < map.Zoom) { if (this.DataSource == null) throw (new ApplicationException("DataSource property not set on layer '" + this.LayerName + "'")); g.TextRenderingHint = this.TextRenderingHint; g.SmoothingMode = this.SmoothingMode; Hydra.Framework.Mapping.Geometries.BoundingBox envelope = map.Envelope; // View to render if (this.CoordinateTransformation != null) envelope = Hydra.Framework.Mapping.CoordinateSystems.Transformations.GeometryTransform.TransformBox(envelope, this.CoordinateTransformation.MathTransform.Inverse()); Hydra.Framework.Mapping.Data.FeatureDataSet ds = new Hydra.Framework.Mapping.Data.FeatureDataSet(); this.DataSource.Open(); this.DataSource.ExecuteIntersectionQuery(envelope, ds); this.DataSource.Close(); if (ds.Tables.Count == 0) { base.Render(g, map); return; } Hydra.Framework.Mapping.Data.FeatureDataTable features = (Hydra.Framework.Mapping.Data.FeatureDataTable)ds.Tables[0]; // // Initialize label collection // List<Rendering.Label> labels = new List<Hydra.Framework.Mapping.Rendering.Label>(); // // Render labels // for (int i = 0; i < features.Count; i++) { Hydra.Framework.Mapping.Data.FeatureDataRow feature = features[i]; if (this.CoordinateTransformation != null) features[i].Geometry = Hydra.Framework.Mapping.CoordinateSystems.Transformations.GeometryTransform.TransformGeometry(features[i].Geometry, this.CoordinateTransformation.MathTransform); Hydra.Framework.Mapping.Styles.LabelStyle style = null; if (this.Theme != null) // If thematics is enabled, lets override the style style = this.Theme.GetStyle(feature) as Hydra.Framework.Mapping.Styles.LabelStyle; else style = this.Style; float rotation = 0; if (this.RotationColumn != null && this.RotationColumn != "") float.TryParse(feature[this.RotationColumn].ToString(), System.Globalization.NumberStyles.Any, Hydra.Framework.Mapping.Map.numberFormat_EnUS, out rotation); string text; if (m_GetLabelMethod != null) text = m_GetLabelMethod(feature); else text = feature[this.LabelColumn].ToString(); if (text != null && text != String.Empty) { if (feature.Geometry is Hydra.Framework.Mapping.Geometries.GeometryCollection) { if (this.MultipartGeometryBehaviour == MultipartGeometryBehaviourEnum.All) { foreach (Hydra.Framework.Mapping.Geometries.AbstractGeometry geom in (feature.Geometry as Geometries.GeometryCollection)) { Hydra.Framework.Mapping.Rendering.Label lbl = CreateLabel(geom, text, rotation, style, map, g); if (lbl != null) labels.Add(lbl); } } else if (this.MultipartGeometryBehaviour == MultipartGeometryBehaviourEnum.CommonCenter) { Hydra.Framework.Mapping.Rendering.Label lbl = CreateLabel(feature.Geometry, text, rotation, style, map, g); if (lbl != null) labels.Add(lbl); } else if (this.MultipartGeometryBehaviour == MultipartGeometryBehaviourEnum.First) { if ((feature.Geometry as Geometries.GeometryCollection).Collection.Count > 0) { Hydra.Framework.Mapping.Rendering.Label lbl = CreateLabel((feature.Geometry as Geometries.GeometryCollection).Collection[0], text, rotation, style, map, g); if (lbl != null) labels.Add(lbl); } } else if (this.MultipartGeometryBehaviour == MultipartGeometryBehaviourEnum.Largest) { Geometries.GeometryCollection coll = (feature.Geometry as Geometries.GeometryCollection); if (coll.NumGeometries > 0) { double largestVal = 0; int idxOfLargest = 0; for (int j = 0; j < coll.NumGeometries; j++) { Hydra.Framework.Mapping.Geometries.AbstractGeometry geom = coll.Geometry(j); if (geom is Geometries.LineString && ((Geometries.LineString)geom).Length > largestVal) { largestVal = ((Geometries.LineString)geom).Length; idxOfLargest = j; } if (geom is Geometries.MultiLineString && ((Geometries.MultiLineString)geom).Length > largestVal) { largestVal = ((Geometries.LineString)geom).Length; idxOfLargest = j; } if (geom is Geometries.Polygon && ((Geometries.Polygon)geom).Area > largestVal) { largestVal = ((Geometries.Polygon)geom).Area; idxOfLargest = j; } if (geom is Geometries.MultiPolygon && ((Geometries.MultiPolygon)geom).Area > largestVal) { largestVal = ((Geometries.MultiPolygon)geom).Area; idxOfLargest = j; } } Hydra.Framework.Mapping.Rendering.Label lbl = CreateLabel(coll.Geometry(idxOfLargest), text, rotation, style, map, g); if (lbl != null) labels.Add(lbl); } } } else { Hydra.Framework.Mapping.Rendering.Label lbl = CreateLabel(feature.Geometry, text, rotation, style, map, g); if (lbl != null) labels.Add(lbl); } } } if (labels.Count > 0) // We have labels to render... { if (this.Style.CollisionDetection && this.m_LabelFilter != null) this.m_LabelFilter(labels); for (int i = 0; i < labels.Count; i++) Hydra.Framework.Mapping.Rendering.VectorRenderer.DrawLabel(g, labels[i].LabelPoint, labels[i].Style.Offset, labels[i].Style.Font, labels[i].Style.ForeColor, labels[i].Style.BackColor, Style.Halo, labels[i].Rotation, labels[i].Text, map); } labels = null; } base.Render(g, map); } // // ********************************************************************** /// <summary> /// Creates the label. /// </summary> /// <param name="feature">The feature.</param> /// <param name="text">The text.</param> /// <param name="rotation">The rotation.</param> /// <param name="style">The style.</param> /// <param name="map">The map.</param> /// <param name="g">The g.</param> /// <returns></returns> // ********************************************************************** // private Hydra.Framework.Mapping.Rendering.Label CreateLabel(Hydra.Framework.Mapping.Geometries.AbstractGeometry feature, string text, float rotation, Hydra.Framework.Mapping.Styles.LabelStyle style, Map map, System.Drawing.Graphics g) { System.Drawing.SizeF size = g.MeasureString(text, style.Font); System.Drawing.PointF position = map.WorldToImage(feature.GetBoundingBox().GetCentroid()); position.X = position.X - size.Width * (short)style.HorizontalAlignment * 0.5f; position.Y = position.Y - size.Height * (short)style.VerticalAlignment * 0.5f; if (position.X - size.Width > map.Size.Width || position.X + size.Width < 0 || position.Y - size.Height > map.Size.Height || position.Y + size.Height < 0) { return null; } else { Hydra.Framework.Mapping.Rendering.Label lbl; if (!style.CollisionDetection) lbl = new Hydra.Framework.Mapping.Rendering.Label(text, position, rotation, this.Priority, null, style); else { // // Collision detection is enabled so we need to measure the size of the string // lbl = new Hydra.Framework.Mapping.Rendering.Label(text, position, rotation, this.Priority, new Hydra.Framework.Mapping.Styles.LabelBox(position.X - size.Width * 0.5f - style.CollisionBuffer.Width, position.Y + size.Height * 0.5f + style.CollisionBuffer.Height, size.Width + 2f * style.CollisionBuffer.Width, size.Height + style.CollisionBuffer.Height * 2f), style); } if (feature.GetType() == typeof(Hydra.Framework.Mapping.Geometries.LineString)) { Hydra.Framework.Mapping.Geometries.LineString line = feature as Hydra.Framework.Mapping.Geometries.LineString; if (line.Length / map.PixelSize > size.Width) // Only label feature if it is long enough CalculateLabelOnLinestring(line, ref lbl, map); else return null; } return lbl; } } // // ********************************************************************** /// <summary> /// Calculates the label on linestring. /// </summary> /// <param name="line">The line.</param> /// <param name="label">The label.</param> /// <param name="map">The map.</param> // ********************************************************************** // private void CalculateLabelOnLinestring(Hydra.Framework.Mapping.Geometries.LineString line, ref Hydra.Framework.Mapping.Rendering.Label label, Map map) { double dx, dy; double tmpx, tmpy; double angle = 0.0; // // first find the middle segment of the line // int midPoint = (line.Vertices.Count - 1) / 2; if (line.Vertices.Count > 2) { dx = line.Vertices[midPoint + 1].X - line.Vertices[midPoint].X; dy = line.Vertices[midPoint + 1].Y - line.Vertices[midPoint].Y; } else { midPoint = 0; dx = line.Vertices[1].X - line.Vertices[0].X; dy = line.Vertices[1].Y - line.Vertices[0].Y; } if (dy == 0) label.Rotation = 0; else if (dx == 0) label.Rotation = 90; else { // // calculate angle of line // angle = -Math.Atan(dy / dx) + Math.PI * 0.5; angle *= (180d / Math.PI); // convert radians to degrees label.Rotation = (float)angle - 90; // -90 text orientation } tmpx = line.Vertices[midPoint].X + (dx * 0.5); tmpy = line.Vertices[midPoint].Y + (dy * 0.5); label.LabelPoint = map.WorldToImage(new Hydra.Framework.Mapping.Geometries.Point(tmpx, tmpy)); } // // ********************************************************************** /// <summary> /// Gets the boundingbox of the entire layer /// </summary> /// <value>The envelope.</value> /// <returns>Bounding box corresponding to the extent of the features in the layer</returns> // ********************************************************************** // public override Hydra.Framework.Mapping.Geometries.BoundingBox Envelope { get { if (this.DataSource == null) throw (new ApplicationException("DataSource property not set on layer '" + this.LayerName + "'")); bool wasOpen = this.DataSource.IsOpen; if (!wasOpen) this.DataSource.Open(); Hydra.Framework.Mapping.Geometries.BoundingBox box = this.DataSource.GetExtents(); if (!wasOpen) // Restore state this.DataSource.Close(); return box; } } // // ********************************************************************** /// <summary> /// Gets or sets the SRID of this VectorLayer's data source /// </summary> /// <value>The SRID.</value> // ********************************************************************** // public override int SRID { get { if (this.DataSource == null) throw (new ApplicationException("DataSource property not set on layer '" + this.LayerName + "'")); return this.DataSource.SRID; } set { this.DataSource.SRID = value; } } #endregion #region IConeable Implementation // // ********************************************************************** /// <summary> /// Clones the object /// </summary> /// <returns>cloned object</returns> // ********************************************************************** // public override object Clone() { throw new NotImplementedException(); } #endregion #region IDisposable Implementation // // ********************************************************************** /// <summary> /// Disposes the object /// </summary> // ********************************************************************** // public void Dispose() { if (DataSource is IDisposable) ((IDisposable)DataSource).Dispose(); } #endregion } }
// // MailboxAddress.cs // // Author: Jeffrey Stedfast <jeff@xamarin.com> // // Copyright (c) 2013-2016 Xamarin Inc. (www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND 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.Collections.Generic; #if PORTABLE using Encoding = Portable.Text.Encoding; #endif #if ENABLE_SNM using System.Net.Mail; #endif using MimeKit.Utils; namespace MimeKit { /// <summary> /// A mailbox address, as specified by rfc822. /// </summary> /// <remarks> /// Represents a mailbox address (commonly referred to as an email address) /// for a single recipient. /// </remarks> public class MailboxAddress : InternetAddress { string address; /// <summary> /// Initializes a new instance of the <see cref="MimeKit.MailboxAddress"/> class. /// </summary> /// <remarks> /// Creates a new <see cref="MailboxAddress"/> with the specified name, address and route. The /// specified text encoding is used when encoding the name according to the rules of rfc2047. /// </remarks> /// <param name="encoding">The character encoding to be used for encoding the name.</param> /// <param name="name">The name of the mailbox.</param> /// <param name="route">The route of the mailbox.</param> /// <param name="address">The address of the mailbox.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="encoding"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="route"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="address"/> is <c>null</c>.</para> /// </exception> public MailboxAddress (Encoding encoding, string name, IEnumerable<string> route, string address) : base (encoding, name) { if (address == null) throw new ArgumentNullException ("address"); Route = new DomainList (route); Route.Changed += RouteChanged; Address = address; } /// <summary> /// Initializes a new instance of the <see cref="MimeKit.MailboxAddress"/> class. /// </summary> /// <remarks> /// Creates a new <see cref="MailboxAddress"/> with the specified name, address and route. /// </remarks> /// <param name="name">The name of the mailbox.</param> /// <param name="route">The route of the mailbox.</param> /// <param name="address">The address of the mailbox.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="route"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="address"/> is <c>null</c>.</para> /// </exception> public MailboxAddress (string name, IEnumerable<string> route, string address) : this (Encoding.UTF8, name, route, address) { } /// <summary> /// Initializes a new instance of the <see cref="MimeKit.MailboxAddress"/> class. /// </summary> /// <remarks> /// Creates a new <see cref="MailboxAddress"/> with the specified name and address. The /// specified text encoding is used when encoding the name according to the rules of rfc2047. /// </remarks> /// <param name="encoding">The character encoding to be used for encoding the name.</param> /// <param name="name">The name of the mailbox.</param> /// <param name="address">The address of the mailbox.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="encoding"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="address"/> is <c>null</c>.</para> /// </exception> public MailboxAddress (Encoding encoding, string name, string address) : base (encoding, name) { Route = new DomainList (); Route.Changed += RouteChanged; this.address = address; } /// <summary> /// Initializes a new instance of the <see cref="MimeKit.MailboxAddress"/> class. /// </summary> /// <remarks> /// Creates a new <see cref="MailboxAddress"/> with the specified name and address. /// </remarks> /// <param name="name">The name of the mailbox.</param> /// <param name="address">The address of the mailbox.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="address"/> is <c>null</c>. /// </exception> public MailboxAddress (string name, string address) : this (Encoding.UTF8, name, address) { } /// <summary> /// Clone the mailbox address. /// </summary> /// <remarks> /// Clones the mailbox address. /// </remarks> /// <returns>The cloned mailbox address.</returns> public override InternetAddress Clone () { return new MailboxAddress (Encoding, Name, Route, Address); } /// <summary> /// Gets the mailbox route. /// </summary> /// <remarks> /// A route is convention that is rarely seen in modern email systems, but is supported /// for compatibility with email archives. /// </remarks> /// <value>The mailbox route.</value> public DomainList Route { get; private set; } /// <summary> /// Gets or sets the mailbox address. /// </summary> /// <remarks> /// Represents the actual email address and is in the form of <c>"name@example.com"</c>. /// </remarks> /// <value>The mailbox address.</value> /// <exception cref="System.ArgumentNullException"> /// <paramref name="value"/> is <c>null</c>. /// </exception> public string Address { get { return address; } set { if (value == null) throw new ArgumentNullException ("value"); if (value == address) return; address = value; OnChanged (); } } /// <summary> /// Gets whether or not the address is an international address. /// </summary> /// <remarks> /// <para>International addresses are addresses that contain international /// characters in either their local-parts or their domains.</para> /// <para>For more information, see section 3.2 of /// <a href="https://tools.ietf.org/html/rfc6532#section-3.2">rfc6532</a>.</para> /// </remarks> /// <value><c>true</c> if the address is an international address; otherwise, <c>false</c>.</value> public bool IsInternational { get { if (address == null) return false; for (int i = 0; i < address.Length; i++) { if (address[i] > 127) return true; } foreach (var domain in Route) { for (int i = 0; i < domain.Length; i++) { if (domain[i] > 127) return true; } } return false; } } internal override void Encode (FormatOptions options, StringBuilder builder, ref int lineLength) { if (builder == null) throw new ArgumentNullException ("builder"); if (lineLength < 0) throw new ArgumentOutOfRangeException ("lineLength"); string route = Route.ToString (); if (!string.IsNullOrEmpty (route)) route += ":"; if (!string.IsNullOrEmpty (Name)) { string name; if (!options.International) { var encoded = Rfc2047.EncodePhrase (options, Encoding, Name); name = Encoding.ASCII.GetString (encoded, 0, encoded.Length); } else { name = EncodeInternationalizedPhrase (Name); } if (lineLength + name.Length > options.MaxLineLength) { if (name.Length > options.MaxLineLength) { // we need to break up the name... builder.AppendFolded (options, name, ref lineLength); } else { // the name itself is short enough to fit on a single line, // but only if we write it on a line by itself if (lineLength > 1) { builder.LineWrap (options); lineLength = 1; } lineLength += name.Length; builder.Append (name); } } else { // we can safely fit the name on this line... lineLength += name.Length; builder.Append (name); } if ((lineLength + route.Length + Address.Length + 3) > options.MaxLineLength) { builder.Append (options.NewLine); builder.Append ("\t<"); lineLength = 2; } else { builder.Append (" <"); lineLength += 2; } lineLength += route.Length; builder.Append (route); lineLength += Address.Length + 1; builder.Append (Address); builder.Append ('>'); } else if (!string.IsNullOrEmpty (route)) { if ((lineLength + route.Length + Address.Length + 2) > options.MaxLineLength) { builder.Append (options.NewLine); builder.Append ("\t<"); lineLength = 2; } else { builder.Append ('<'); lineLength++; } lineLength += route.Length; builder.Append (route); lineLength += Address.Length + 1; builder.Append (Address); builder.Append ('>'); } else { if ((lineLength + Address.Length) > options.MaxLineLength) { builder.LineWrap (options); lineLength = 1; } lineLength += Address.Length; builder.Append (Address); } } /// <summary> /// Returns a string representation of the <see cref="MailboxAddress"/>, /// optionally encoding it for transport. /// </summary> /// <remarks> /// Returns a string containing the formatted mailbox address. If the <paramref name="encode"/> /// parameter is <c>true</c>, then the mailbox name will be encoded according to the rules defined /// in rfc2047, otherwise the name will not be encoded at all and will therefor only be suitable /// for display purposes. /// </remarks> /// <returns>A string representing the <see cref="MailboxAddress"/>.</returns> /// <param name="options">The formatting options.</param> /// <param name="encode">If set to <c>true</c>, the <see cref="MailboxAddress"/> will be encoded.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="options"/> is <c>null</c>. /// </exception> public override string ToString (FormatOptions options, bool encode) { if (options == null) throw new ArgumentNullException ("options"); if (encode) { var builder = new StringBuilder (); int lineLength = 0; Encode (options, builder, ref lineLength); return builder.ToString (); } string route = Route.ToString (); if (!string.IsNullOrEmpty (route)) route += ":"; if (!string.IsNullOrEmpty (Name)) return MimeUtils.Quote (Name) + " <" + route + Address + ">"; if (!string.IsNullOrEmpty (route)) return "<" + route + Address + ">"; return Address; } #region IEquatable implementation /// <summary> /// Determines whether the specified <see cref="MimeKit.MailboxAddress"/> is equal to the current <see cref="MimeKit.MailboxAddress"/>. /// </summary> /// <remarks> /// Compares two mailbox addresses to determine if they are identical or not. /// </remarks> /// <param name="other">The <see cref="MimeKit.MailboxAddress"/> to compare with the current <see cref="MimeKit.MailboxAddress"/>.</param> /// <returns><c>true</c> if the specified <see cref="MimeKit.MailboxAddress"/> is equal to the current /// <see cref="MimeKit.MailboxAddress"/>; otherwise, <c>false</c>.</returns> public override bool Equals (InternetAddress other) { var mailbox = other as MailboxAddress; if (mailbox == null) return false; return Name == mailbox.Name && Address == mailbox.Address; } #endregion void RouteChanged (object sender, EventArgs e) { OnChanged (); } internal static bool TryParse (ParserOptions options, byte[] text, ref int index, int endIndex, bool throwOnError, out MailboxAddress mailbox) { var flags = AddressParserFlags.AllowMailboxAddress; InternetAddress address; if (throwOnError) flags |= AddressParserFlags.ThrowOnError; if (!InternetAddress.TryParse (options, text, ref index, endIndex, flags, out address)) { mailbox = null; return false; } mailbox = (MailboxAddress) address; return true; } /// <summary> /// Tries to parse the given input buffer into a new <see cref="MimeKit.MailboxAddress"/> instance. /// </summary> /// <remarks> /// Parses a single <see cref="MailboxAddress"/>. If the address is not a mailbox address or /// there is more than a single mailbox address, then parsing will fail. /// </remarks> /// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns> /// <param name="options">The parser options to use.</param> /// <param name="buffer">The input buffer.</param> /// <param name="startIndex">The starting index of the input buffer.</param> /// <param name="length">The number of bytes in the input buffer to parse.</param> /// <param name="mailbox">The parsed mailbox address.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="options"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="buffer"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="startIndex"/> and <paramref name="length"/> do not specify /// a valid range in the byte array. /// </exception> public static bool TryParse (ParserOptions options, byte[] buffer, int startIndex, int length, out MailboxAddress mailbox) { ParseUtils.ValidateArguments (options, buffer, startIndex, length); int endIndex = startIndex + length; int index = startIndex; if (!TryParse (options, buffer, ref index, endIndex, false, out mailbox)) return false; if (!ParseUtils.SkipCommentsAndWhiteSpace (buffer, ref index, endIndex, false) || index != endIndex) { mailbox = null; return false; } return true; } /// <summary> /// Tries to parse the given input buffer into a new <see cref="MimeKit.MailboxAddress"/> instance. /// </summary> /// <remarks> /// Parses a single <see cref="MailboxAddress"/>. If the address is not a mailbox address or /// there is more than a single mailbox address, then parsing will fail. /// </remarks> /// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns> /// <param name="buffer">The input buffer.</param> /// <param name="startIndex">The starting index of the input buffer.</param> /// <param name="length">The number of bytes in the input buffer to parse.</param> /// <param name="mailbox">The parsed mailbox address.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="buffer"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="startIndex"/> and <paramref name="length"/> do not specify /// a valid range in the byte array. /// </exception> public static bool TryParse (byte[] buffer, int startIndex, int length, out MailboxAddress mailbox) { return TryParse (ParserOptions.Default, buffer, startIndex, length, out mailbox); } /// <summary> /// Tries to parse the given input buffer into a new <see cref="MimeKit.MailboxAddress"/> instance. /// </summary> /// <remarks> /// Parses a single <see cref="MailboxAddress"/>. If the address is not a mailbox address or /// there is more than a single mailbox address, then parsing will fail. /// </remarks> /// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns> /// <param name="options">The parser options to use.</param> /// <param name="buffer">The input buffer.</param> /// <param name="startIndex">The starting index of the input buffer.</param> /// <param name="mailbox">The parsed mailbox address.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="options"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="buffer"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="startIndex"/> is out of range. /// </exception> public static bool TryParse (ParserOptions options, byte[] buffer, int startIndex, out MailboxAddress mailbox) { ParseUtils.ValidateArguments (options, buffer, startIndex); int endIndex = buffer.Length; int index = startIndex; if (!TryParse (options, buffer, ref index, endIndex, false, out mailbox)) return false; if (!ParseUtils.SkipCommentsAndWhiteSpace (buffer, ref index, endIndex, false) || index != endIndex) { mailbox = null; return false; } return true; } /// <summary> /// Tries to parse the given input buffer into a new <see cref="MimeKit.MailboxAddress"/> instance. /// </summary> /// <remarks> /// Parses a single <see cref="MailboxAddress"/>. If the address is not a mailbox address or /// there is more than a single mailbox address, then parsing will fail. /// </remarks> /// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns> /// <param name="buffer">The input buffer.</param> /// <param name="startIndex">The starting index of the input buffer.</param> /// <param name="mailbox">The parsed mailbox address.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="buffer"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="startIndex"/> is out of range. /// </exception> public static bool TryParse (byte[] buffer, int startIndex, out MailboxAddress mailbox) { return TryParse (ParserOptions.Default, buffer, startIndex, out mailbox); } /// <summary> /// Tries to parse the given input buffer into a new <see cref="MimeKit.MailboxAddress"/> instance. /// </summary> /// <remarks> /// Parses a single <see cref="MailboxAddress"/>. If the address is not a mailbox address or /// there is more than a single mailbox address, then parsing will fail. /// </remarks> /// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns> /// <param name="options">The parser options to use.</param> /// <param name="buffer">The input buffer.</param> /// <param name="mailbox">The parsed mailbox address.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="options"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="buffer"/> is <c>null</c>.</para> /// </exception> public static bool TryParse (ParserOptions options, byte[] buffer, out MailboxAddress mailbox) { ParseUtils.ValidateArguments (options, buffer); int endIndex = buffer.Length; int index = 0; if (!TryParse (options, buffer, ref index, endIndex, false, out mailbox)) return false; if (!ParseUtils.SkipCommentsAndWhiteSpace (buffer, ref index, endIndex, false) || index != endIndex) { mailbox = null; return false; } return true; } /// <summary> /// Tries to parse the given input buffer into a new <see cref="MimeKit.MailboxAddress"/> instance. /// </summary> /// <remarks> /// Parses a single <see cref="MailboxAddress"/>. If the address is not a mailbox address or /// there is more than a single mailbox address, then parsing will fail. /// </remarks> /// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns> /// <param name="buffer">The input buffer.</param> /// <param name="mailbox">The parsed mailbox address.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="buffer"/> is <c>null</c>. /// </exception> public static bool TryParse (byte[] buffer, out MailboxAddress mailbox) { return TryParse (ParserOptions.Default, buffer, out mailbox); } /// <summary> /// Tries to parse the given text into a new <see cref="MimeKit.MailboxAddress"/> instance. /// </summary> /// <remarks> /// Parses a single <see cref="MailboxAddress"/>. If the address is not a mailbox address or /// there is more than a single mailbox address, then parsing will fail. /// </remarks> /// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns> /// <param name="options">The parser options to use.</param> /// <param name="text">The text.</param> /// <param name="mailbox">The parsed mailbox address.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="text"/> is <c>null</c>. /// </exception> public static bool TryParse (ParserOptions options, string text, out MailboxAddress mailbox) { if (options == null) throw new ArgumentNullException ("options"); if (text == null) throw new ArgumentNullException ("text"); var buffer = Encoding.UTF8.GetBytes (text); int endIndex = buffer.Length; int index = 0; if (!TryParse (options, buffer, ref index, endIndex, false, out mailbox)) return false; if (!ParseUtils.SkipCommentsAndWhiteSpace (buffer, ref index, endIndex, false) || index != endIndex) { mailbox = null; return false; } return true; } /// <summary> /// Tries to parse the given text into a new <see cref="MimeKit.MailboxAddress"/> instance. /// </summary> /// <remarks> /// Parses a single <see cref="MailboxAddress"/>. If the address is not a mailbox address or /// there is more than a single mailbox address, then parsing will fail. /// </remarks> /// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns> /// <param name="text">The text.</param> /// <param name="mailbox">The parsed mailbox address.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="text"/> is <c>null</c>. /// </exception> public static bool TryParse (string text, out MailboxAddress mailbox) { return TryParse (ParserOptions.Default, text, out mailbox); } /// <summary> /// Parses the given input buffer into a new <see cref="MimeKit.MailboxAddress"/> instance. /// </summary> /// <remarks> /// Parses a single <see cref="MailboxAddress"/>. If the address is not a mailbox address or /// there is more than a single mailbox address, then parsing will fail. /// </remarks> /// <returns>The parsed <see cref="MimeKit.MailboxAddress"/>.</returns> /// <param name="options">The parser options to use.</param> /// <param name="buffer">The input buffer.</param> /// <param name="startIndex">The starting index of the input buffer.</param> /// <param name="length">The number of bytes in the input buffer to parse.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="options"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="buffer"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="startIndex"/> and <paramref name="length"/> do not specify /// a valid range in the byte array. /// </exception> /// <exception cref="MimeKit.ParseException"> /// <paramref name="buffer"/> could not be parsed. /// </exception> public static new MailboxAddress Parse (ParserOptions options, byte[] buffer, int startIndex, int length) { ParseUtils.ValidateArguments (options, buffer, startIndex, length); int endIndex = startIndex + length; MailboxAddress mailbox; int index = startIndex; if (!TryParse (options, buffer, ref index, endIndex, true, out mailbox)) throw new ParseException ("No mailbox address found.", startIndex, startIndex); ParseUtils.SkipCommentsAndWhiteSpace (buffer, ref index, endIndex, true); if (index != endIndex) throw new ParseException (string.Format ("Unexpected token at offset {0}", index), index, index); return mailbox; } /// <summary> /// Parses the given input buffer into a new <see cref="MimeKit.MailboxAddress"/> instance. /// </summary> /// <remarks> /// Parses a single <see cref="MailboxAddress"/>. If the address is not a mailbox address or /// there is more than a single mailbox address, then parsing will fail. /// </remarks> /// <returns>The parsed <see cref="MimeKit.MailboxAddress"/>.</returns> /// <param name="buffer">The input buffer.</param> /// <param name="startIndex">The starting index of the input buffer.</param> /// <param name="length">The number of bytes in the input buffer to parse.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="buffer"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="startIndex"/> and <paramref name="length"/> do not specify /// a valid range in the byte array. /// </exception> /// <exception cref="MimeKit.ParseException"> /// <paramref name="buffer"/> could not be parsed. /// </exception> public static new MailboxAddress Parse (byte[] buffer, int startIndex, int length) { return Parse (ParserOptions.Default, buffer, startIndex, length); } /// <summary> /// Parses the given input buffer into a new <see cref="MimeKit.MailboxAddress"/> instance. /// </summary> /// <remarks> /// Parses a single <see cref="MailboxAddress"/>. If the address is not a mailbox address or /// there is more than a single mailbox address, then parsing will fail. /// </remarks> /// <returns>The parsed <see cref="MimeKit.MailboxAddress"/>.</returns> /// <param name="options">The parser options to use.</param> /// <param name="buffer">The input buffer.</param> /// <param name="startIndex">The starting index of the input buffer.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="options"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="buffer"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="startIndex"/>is out of range. /// </exception> /// <exception cref="MimeKit.ParseException"> /// <paramref name="buffer"/> could not be parsed. /// </exception> public static new MailboxAddress Parse (ParserOptions options, byte[] buffer, int startIndex) { ParseUtils.ValidateArguments (options, buffer, startIndex); int endIndex = buffer.Length; MailboxAddress mailbox; int index = startIndex; if (!TryParse (options, buffer, ref index, endIndex, true, out mailbox)) throw new ParseException ("No mailbox address found.", startIndex, startIndex); ParseUtils.SkipCommentsAndWhiteSpace (buffer, ref index, endIndex, true); if (index != endIndex) throw new ParseException (string.Format ("Unexpected token at offset {0}", index), index, index); return mailbox; } /// <summary> /// Parses the given input buffer into a new <see cref="MimeKit.MailboxAddress"/> instance. /// </summary> /// <remarks> /// Parses a single <see cref="MailboxAddress"/>. If the address is not a mailbox address or /// there is more than a single mailbox address, then parsing will fail. /// </remarks> /// <returns>The parsed <see cref="MimeKit.MailboxAddress"/>.</returns> /// <param name="buffer">The input buffer.</param> /// <param name="startIndex">The starting index of the input buffer.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="buffer"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="startIndex"/> is out of range. /// </exception> /// <exception cref="MimeKit.ParseException"> /// <paramref name="buffer"/> could not be parsed. /// </exception> public static new MailboxAddress Parse (byte[] buffer, int startIndex) { return Parse (ParserOptions.Default, buffer, startIndex); } /// <summary> /// Parses the given input buffer into a new <see cref="MimeKit.MailboxAddress"/> instance. /// </summary> /// <remarks> /// Parses a single <see cref="MailboxAddress"/>. If the address is not a mailbox address or /// there is more than a single mailbox address, then parsing will fail. /// </remarks> /// <returns>The parsed <see cref="MimeKit.MailboxAddress"/>.</returns> /// <param name="options">The parser options to use.</param> /// <param name="buffer">The input buffer.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="options"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="buffer"/> is <c>null</c>.</para> /// </exception> /// <exception cref="MimeKit.ParseException"> /// <paramref name="buffer"/> could not be parsed. /// </exception> public static new MailboxAddress Parse (ParserOptions options, byte[] buffer) { ParseUtils.ValidateArguments (options, buffer); int endIndex = buffer.Length; MailboxAddress mailbox; int index = 0; if (!TryParse (options, buffer, ref index, endIndex, true, out mailbox)) throw new ParseException ("No mailbox address found.", 0, 0); ParseUtils.SkipCommentsAndWhiteSpace (buffer, ref index, endIndex, true); if (index != endIndex) throw new ParseException (string.Format ("Unexpected token at offset {0}", index), index, index); return mailbox; } /// <summary> /// Parses the given input buffer into a new <see cref="MimeKit.MailboxAddress"/> instance. /// </summary> /// <remarks> /// Parses a single <see cref="MailboxAddress"/>. If the address is not a mailbox address or /// there is more than a single mailbox address, then parsing will fail. /// </remarks> /// <returns>The parsed <see cref="MimeKit.MailboxAddress"/>.</returns> /// <param name="buffer">The input buffer.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="buffer"/> is <c>null</c>. /// </exception> /// <exception cref="MimeKit.ParseException"> /// <paramref name="buffer"/> could not be parsed. /// </exception> public static new MailboxAddress Parse (byte[] buffer) { return Parse (ParserOptions.Default, buffer); } /// <summary> /// Parses the given text into a new <see cref="MimeKit.MailboxAddress"/> instance. /// </summary> /// <remarks> /// Parses a single <see cref="MailboxAddress"/>. If the address is not a mailbox address or /// there is more than a single mailbox address, then parsing will fail. /// </remarks> /// <returns>The parsed <see cref="MimeKit.MailboxAddress"/>.</returns> /// <param name="options">The parser options to use.</param> /// <param name="text">The text.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="options"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="text"/> is <c>null</c>.</para> /// </exception> /// <exception cref="MimeKit.ParseException"> /// <paramref name="text"/> could not be parsed. /// </exception> public static new MailboxAddress Parse (ParserOptions options, string text) { if (options == null) throw new ArgumentNullException ("options"); if (text == null) throw new ArgumentNullException ("text"); var buffer = Encoding.UTF8.GetBytes (text); int endIndex = buffer.Length; MailboxAddress mailbox; int index = 0; if (!TryParse (options, buffer, ref index, endIndex, true, out mailbox)) throw new ParseException ("No mailbox address found.", 0, 0); ParseUtils.SkipCommentsAndWhiteSpace (buffer, ref index, endIndex, true); if (index != endIndex) throw new ParseException (string.Format ("Unexpected token at offset {0}", index), index, index); return mailbox; } /// <summary> /// Parses the given text into a new <see cref="MimeKit.MailboxAddress"/> instance. /// </summary> /// <remarks> /// Parses a single <see cref="MailboxAddress"/>. If the address is not a mailbox address or /// there is more than a single mailbox address, then parsing will fail. /// </remarks> /// <returns>The parsed <see cref="MimeKit.MailboxAddress"/>.</returns> /// <param name="text">The text.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="text"/> is <c>null</c>. /// </exception> /// <exception cref="MimeKit.ParseException"> /// <paramref name="text"/> could not be parsed. /// </exception> public static new MailboxAddress Parse (string text) { return Parse (ParserOptions.Default, text); } #if ENABLE_SNM /// <summary> /// Explicit cast to convert a <see cref="MailboxAddress"/> to a /// <see cref="System.Net.Mail.MailAddress"/>. /// </summary> /// <remarks> /// Casts a <see cref="MailboxAddress"/> to a <see cref="System.Net.Mail.MailAddress"/> /// in cases where you might want to make use of the System.Net.Mail APIs. /// </remarks> /// <returns>The equivalent <see cref="System.Net.Mail.MailAddress"/>.</returns> /// <param name="mailbox">The mailbox.</param> public static explicit operator MailAddress (MailboxAddress mailbox) { return mailbox != null ? new MailAddress (mailbox.Address, mailbox.Name, mailbox.Encoding) : null; } /// <summary> /// Explicit cast to convert a <see cref="System.Net.Mail.MailAddress"/> /// to a <see cref="MailboxAddress"/>. /// </summary> /// <remarks> /// Casts a <see cref="System.Net.Mail.MailAddress"/> to a <see cref="MailboxAddress"/> /// in cases where you might want to make use of the the superior MimeKit APIs. /// </remarks> /// <returns>The equivalent <see cref="MailboxAddress"/>.</returns> /// <param name="address">The mail address.</param> public static explicit operator MailboxAddress (MailAddress address) { return address != null ? new MailboxAddress (address.DisplayName, address.Address) : null; } #endif } }
using System; using System.Collections; using System.Xml; namespace nessusssharp { public class NessusManager : IDisposable { NessusManagerSession _session; int RandomNumber { get { return new Random().Next(9999); } } /// <summary> /// Initializes a new instance of the <see cref="AutoAssess.Data.Nessus.NessusManager"/> class. /// </summary> /// <param name='sess'> /// NessesManagerSession configured to connect to the nessus host. /// </param> public NessusManager (NessusManagerSession sess) { _session = sess; } /// <summary> /// Login the specified username, password and loggedIn. /// </summary> /// <param name='username'> /// Username. /// </param> /// <param name='password'> /// Password. /// </param> /// <param name='loggedIn'> /// Logged in. /// </param> public XmlDocument Login(string username, string password, out bool loggedIn) { return this.Login(username, password, this.RandomNumber, out loggedIn); } /// <summary> /// Login the specified username, password, seq and loggedIn. /// </summary> /// <param name='username'> /// Username. /// </param> /// <param name='password'> /// Password. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <param name='loggedIn'> /// Logged in. /// </param> public XmlDocument Login(string username, string password, int seq, out bool loggedIn) { return _session.Authenticate(username, password, seq, out loggedIn); } /// <summary> /// Logout this instance. /// </summary> public XmlDocument Logout () { return this.Logout(this.RandomNumber); } /// <summary> /// Logout the specified seq. /// </summary> /// <param name='seq'> /// Seq. /// </param> public XmlDocument Logout(int seq) { Hashtable options = new Hashtable(); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/logout", options); return response; } /// <summary> /// Adds the user. /// </summary> /// <returns> /// The user. /// </returns> /// <param name='username'> /// Username. /// </param> /// <param name='password'> /// Password. /// </param> /// <param name='isAdmin'> /// Is admin. /// </param> public XmlDocument AddUser(string username, string password, bool isAdmin) { return this.AddUser(username, password, isAdmin, this.RandomNumber); } /// <summary> /// Adds the user. /// </summary> /// <returns> /// The user. /// </returns> /// <param name='username'> /// Username. /// </param> /// <param name='password'> /// Password. /// </param> /// <param name='isAdmin'> /// Is admin. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument AddUser(string username, string password, bool isAdmin, int seq) { if (!_session.IsAuthenticated || !_session.IsAdministrator) throw new Exception("Not authenticated or not administrator"); Hashtable options = new Hashtable(); options.Add("seq", seq); options.Add("password", password); options.Add("admin", isAdmin ? "1" : "0"); options.Add("login", username); XmlDocument response = _session.ExecuteCommand("/users/add", options); return response; } /// <summary> /// Deletes the user. /// </summary> /// <returns> /// The user. /// </returns> /// <param name='username'> /// Username. /// </param> public XmlDocument DeleteUser(string username) { return this.DeleteUser(username, this.RandomNumber); } /// <summary> /// Deletes the user. /// </summary> /// <returns> /// The user. /// </returns> /// <param name='username'> /// Username. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument DeleteUser(string username, int seq) { if (!_session.IsAuthenticated || !_session.IsAdministrator) throw new Exception("Not authed or not admin"); Hashtable options = new Hashtable(); options.Add("login", username); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/users/delete", options); return response; } /// <summary> /// Edits the user. /// </summary> /// <returns> /// The user. /// </returns> /// <param name='username'> /// Username. /// </param> /// <param name='password'> /// Password. /// </param> /// <param name='isAdmin'> /// Is admin. /// </param> public XmlDocument EditUser(string username, string password, bool isAdmin) { return this.EditUser(username, password, isAdmin, this.RandomNumber); } /// <summary> /// Edits the user. /// </summary> /// <returns> /// The user. /// </returns> /// <param name='username'> /// Username. /// </param> /// <param name='password'> /// Password. /// </param> /// <param name='isAdmin'> /// Is admin. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument EditUser(string username, string password, bool isAdmin, int seq) { if (!_session.IsAuthenticated || !_session.IsAdministrator) throw new Exception("Not authed or not admin."); Hashtable options = new Hashtable(); options.Add("login", username); options.Add("password", password); options.Add("admin", isAdmin ? "1" : "0"); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/users/edit", options); return response; } /// <summary> /// Changes the user password. /// </summary> /// <returns> /// The user password. /// </returns> /// <param name='username'> /// Username. /// </param> /// <param name='password'> /// Password. /// </param> public XmlDocument ChangeUserPassword(string username, string password) { return this.ChangeUserPassword(username, password, this.RandomNumber); } /// <summary> /// Changes the user password. /// </summary> /// <returns> /// The user password. /// </returns> /// <param name='username'> /// Username. /// </param> /// <param name='password'> /// Password. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument ChangeUserPassword(string username, string password, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("login", username); options.Add("password", password); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/users/chpasswd", options); return response; } /// <summary> /// Lists the users. /// </summary> /// <returns> /// The users. /// </returns> public XmlDocument ListUsers() { return this.ListUsers(this.RandomNumber); } /// <summary> /// Lists the users. /// </summary> /// <returns> /// The users. /// </returns> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument ListUsers(int seq) { if (!_session.IsAuthenticated || !_session.IsAdministrator) throw new Exception("Not authed or not admin."); Hashtable options = new Hashtable(); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/users/list", options); return response; } /// <summary> /// Lists the plugin families. /// </summary> /// <returns> /// The plugin families. /// </returns> public XmlDocument ListPluginFamilies() { return this.ListPluginFamilies(this.RandomNumber); } /// <summary> /// Lists the plugin families. /// </summary> /// <returns> /// The plugin families. /// </returns> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument ListPluginFamilies(int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/plugins/list", options); return response; } /// <summary> /// Lists the plugins by family. /// </summary> /// <returns> /// The plugins by family. /// </returns> /// <param name='family'> /// Family. /// </param> public XmlDocument ListPluginsByFamily(string family) { return this.ListPluginsByFamily(family, this.RandomNumber); } /// <summary> /// Lists the plugins by family. /// </summary> /// <returns> /// The plugins by family. /// </returns> /// <param name='family'> /// Family. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument ListPluginsByFamily(string family, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("family", family); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/plugins/list/family", options); return response; } /// <summary> /// Gets the plugin descroption by filename. /// </summary> /// <returns> /// The plugin descroption by filename. /// </returns> /// <param name='filename'> /// Filename. /// </param> public XmlDocument GetPluginDescriptionByFilename(string filename) { return this.GetPluginDescriptionByFilename(filename, this.RandomNumber); } /// <summary> /// Gets the plugin description by filename. /// </summary> /// <returns> /// The plugin description by filename. /// </returns> /// <param name='filename'> /// Filename. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument GetPluginDescriptionByFilename(string filename, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("fname", filename); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/plugins/description", options); return response; } /// <summary> /// Lists the policies. /// </summary> /// <returns> /// The policies. /// </returns> public XmlDocument ListPolicies() { return this.ListPolicies(this.RandomNumber); } /// <summary> /// Lists the policies. /// </summary> /// <returns> /// The policies. /// </returns> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument ListPolicies(int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/policy/list", options); return response; } /// <summary> /// Deletes the policy. /// </summary> /// <returns> /// The policy. /// </returns> /// <param name='policyID'> /// Policy I. /// </param> public XmlDocument DeletePolicy(int policyID) { return this.DeletePolicy(policyID, this.RandomNumber); } /// <summary> /// Deletes the policy. /// </summary> /// <returns> /// The policy. /// </returns> /// <param name='policyID'> /// Policy ID. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument DeletePolicy(int policyID, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("policy_id", policyID); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/policy/delete", options); return response; } /// <summary> /// Copies the policy. /// </summary> /// <returns> /// The policy. /// </returns> /// <param name='policyID'> /// Policy ID. /// </param> public XmlDocument CopyPolicy(int policyID) { return this.CopyPolicy(policyID, this.RandomNumber); } /// <summary> /// Copies the policy. /// </summary> /// <returns> /// The policy. /// </returns> /// <param name='policyID'> /// Policy ID. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument CopyPolicy(int policyID, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("policy_id", policyID); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/policy/copy", options); return response; } /// <summary> /// Gets the feed information. /// </summary> /// <returns> /// The feed information. /// </returns> public XmlDocument GetFeedInformation() { return this.GetFeedInformation(this.RandomNumber); } /// <summary> /// Gets the feed information. /// </summary> /// <returns> /// The feed information. /// </returns> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument GetFeedInformation(int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed"); Hashtable options = new Hashtable(); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/feed/", options); return response; } /// <summary> /// Creates the scan. /// </summary> /// <returns> /// The scan. /// </returns> /// <param name='target'> /// Target. /// </param> /// <param name='policyID'> /// Policy ID. /// </param> /// <param name='name'> /// Name. /// </param> public XmlDocument CreateScan(string target, int policyID, string name) { return this.CreateScan(target, policyID, name, this.RandomNumber); } /// <summary> /// Creates the scan. /// </summary> /// <returns> /// The scan. /// </returns> /// <param name='target'> /// Target. /// </param> /// <param name='policyID'> /// Policy ID. /// </param> /// <param name='name'> /// Name. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument CreateScan(string target, int policyID, string name, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("target", target); options.Add("policy_id", policyID); options.Add("scan_name", name); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/scan/new", options); return response; } /// <summary> /// Stops the scan. /// </summary> /// <returns> /// The scan. /// </returns> /// <param name='scanID'> /// Scan ID. /// </param> public XmlDocument StopScan(Guid scanID) { return this.StopScan(scanID, this.RandomNumber); } /// <summary> /// Stops the scan. /// </summary> /// <returns> /// The scan. /// </returns> /// <param name='scanID'> /// Scan ID. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument StopScan(Guid scanID, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("scan_uuid", scanID.ToString()); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/scan/stop", options); return response; } /// <summary> /// Pauses the scan. /// </summary> /// <returns> /// The scan. /// </returns> /// <param name='scanID'> /// Scan ID. /// </param> public XmlDocument PauseScan(Guid scanID) { return this.PauseScan(scanID, this.RandomNumber); } /// <summary> /// Pauses the scan. /// </summary> /// <returns> /// The scan. /// </returns> /// <param name='scanID'> /// Scan ID. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument PauseScan(Guid scanID, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("scan_uuid", scanID.ToString()); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/scan/pause", options); return response; } /// <summary> /// Resumes the scan. /// </summary> /// <returns> /// The scan. /// </returns> /// <param name='scanID'> /// Scan ID. /// </param> public XmlDocument ResumeScan(Guid scanID) { return this.ResumeScan(scanID, this.RandomNumber); } /// <summary> /// Resumes the scan. /// </summary> /// <returns> /// The scan. /// </returns> /// <param name='scanID'> /// Scan ID. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument ResumeScan(Guid scanID, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("scan_uuid", scanID.ToString()); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/scan/resume", options); return response; } /// <summary> /// Lists the scans. /// </summary> /// <returns> /// The scans. /// </returns> public XmlDocument ListScans() { return this.ListScans(this.RandomNumber); } /// <summary> /// Lists the scans. /// </summary> /// <returns> /// The scans. /// </returns> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument ListScans(int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/scan/list", options); return response; } /// <summary> /// Creates the scan template. /// </summary> /// <returns> /// The scan template. /// </returns> /// <param name='name'> /// Name. /// </param> /// <param name='policyID'> /// Policy ID. /// </param> /// <param name='target'> /// Target. /// </param> public XmlDocument CreateScanTemplate(string name, int policyID, string target) { return this.CreateScanTemplate(name, policyID, target, this.RandomNumber); } /// <summary> /// Creates the scan template. /// </summary> /// <returns> /// The scan template. /// </returns> /// <param name='name'> /// Name. /// </param> /// <param name='policyID'> /// Policy ID. /// </param> /// <param name='target'> /// Target. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument CreateScanTemplate(string name, int policyID, string target, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("template_name", name); options.Add("policy_id", policyID); options.Add("target", target); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/scan/template/new", options); return response; } /// <summary> /// Edits the scan template. /// </summary> /// <returns> /// The scan template. /// </returns> /// <param name='name'> /// Name. /// </param> /// <param name='readableName'> /// Readable name. /// </param> /// <param name='policyID'> /// Policy ID. /// </param> /// <param name='target'> /// Target. /// </param> public XmlDocument EditScanTemplate(string name, string readableName, int policyID, string target) { return this.EditScanTemplate(name, readableName, policyID, target, this.RandomNumber); } /// <summary> /// Edits the scan template. /// </summary> /// <returns> /// The scan template. /// </returns> /// <param name='name'> /// Name. /// </param> /// <param name='readableName'> /// Readable name. /// </param> /// <param name='policyID'> /// Policy ID. /// </param> /// <param name='target'> /// Target. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument EditScanTemplate(string name, string readableName, int policyID, string target, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("template", name); options.Add("template_name", readableName); options.Add("policy_id", policyID); options.Add("target", target); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/scan/template/edit", options); return response; } /// <summary> /// Deletes the scan template. /// </summary> /// <returns> /// The scan template. /// </returns> /// <param name='name'> /// Name. /// </param> public XmlDocument DeleteScanTemplate(string name) { return this.DeleteScanTemplate(name, this.RandomNumber); } /// <summary> /// Deletes the scan template. /// </summary> /// <returns> /// The scan template. /// </returns> /// <param name='name'> /// Name. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument DeleteScanTemplate(string name, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("template", name); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/scan/template/delete", options); return response; } /// <summary> /// Launchs the scan template. /// </summary> /// <returns> /// The scan template. /// </returns> /// <param name='name'> /// Name. /// </param> public XmlDocument LaunchScanTemplate(string name) { return this.LaunchScanTemplate(name, this.RandomNumber); } /// <summary> /// Launchs the scan template. /// </summary> /// <returns> /// The scan template. /// </returns> /// <param name='name'> /// Name. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument LaunchScanTemplate(string name, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("template", name); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/scan/template/launch", options); return response; } /// <summary> /// Lists the reports. /// </summary> /// <returns> /// The reports. /// </returns> public XmlDocument ListReports() { return this.ListReports(this.RandomNumber); } /// <summary> /// Lists the reports. /// </summary> /// <returns> /// The reports. /// </returns> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument ListReports(int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/report/list", options); return response; } /// <summary> /// Deletes the report. /// </summary> /// <returns> /// The report. /// </returns> /// <param name='reportID'> /// Report ID. /// </param> public XmlDocument DeleteReport(string reportID) { return this.DeleteReport(reportID, this.RandomNumber); } /// <summary> /// Deletes the report. /// </summary> /// <returns> /// The report. /// </returns> /// <param name='reportID'> /// Report ID. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument DeleteReport(string reportID, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("report", reportID); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/report/delete", options); return response; } /// <summary> /// Gets the report hosts. /// </summary> /// <returns> /// The report hosts. /// </returns> /// <param name='reportID'> /// Report ID. /// </param> public XmlDocument GetReportHosts(string reportID) { return this.GetReportHosts(reportID, this.RandomNumber); } /// <summary> /// Gets the report hosts. /// </summary> /// <returns> /// The report hosts. /// </returns> /// <param name='reportID'> /// Report ID. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument GetReportHosts(string reportID, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("report", reportID); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/report/hosts", options); return response; } /// <summary> /// Gets the ports for host from report. /// </summary> /// <returns> /// The ports for host from report. /// </returns> /// <param name='reportID'> /// Report ID. /// </param> /// <param name='host'> /// Host. /// </param> public XmlDocument GetPortsForHostFromReport(string reportID, string host) { return this.GetPortsForHostFromReport(reportID, host, this.RandomNumber); } /// <summary> /// Gets the ports for host from report. /// </summary> /// <returns> /// The ports for host from report. /// </returns> /// <param name='reportID'> /// Report ID. /// </param> /// <param name='host'> /// Host. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument GetPortsForHostFromReport(string reportID, string host, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("report", reportID); options.Add("hostname", host); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/report/ports", options); return response; } /// <summary> /// Gets the report details by port and host. /// </summary> /// <returns> /// The report details by port and host. /// </returns> /// <param name='reportID'> /// Report ID. /// </param> /// <param name='host'> /// Host. /// </param> /// <param name='port'> /// Port. /// </param> /// <param name='protocol'> /// Protocol. /// </param> public XmlDocument GetReportDetailsByPortAndHost(string reportID, string host, int port, string protocol) { return this.GetReportDetailsByPortAndHost(reportID, host, port, protocol, this.RandomNumber); } /// <summary> /// Gets the report details by port and host. /// </summary> /// <returns> /// The report details by port and host. /// </returns> /// <param name='reportID'> /// Report ID. /// </param> /// <param name='host'> /// Host. /// </param> /// <param name='port'> /// Port. /// </param> /// <param name='protocol'> /// Protocol. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument GetReportDetailsByPortAndHost(string reportID, string host, int port, string protocol, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("report", reportID); options.Add("hostname", host); options.Add("port", port); options.Add("protocol", protocol); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/report/details", options); return response; } /// <summary> /// Gets the report tags. /// </summary> /// <returns> /// The report tags. /// </returns> /// <param name='reportID'> /// Report ID. /// </param> /// <param name='host'> /// Host. /// </param> public XmlDocument GetReportTags(Guid reportID, string host) { return this.GetReportTags(reportID, host, this.RandomNumber); } /// <summary> /// Gets the report tags. /// </summary> /// <returns> /// The report tags. /// </returns> /// <param name='reportID'> /// Report ID. /// </param> /// <param name='host'> /// Host. /// </param> /// <param name='seq'> /// Seq. /// </param> /// <exception cref='Exception'> /// Represents errors that occur during application execution. /// </exception> public XmlDocument GetReportTags(Guid reportID, string host, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("report", reportID.ToString()); options.Add("hostname", host); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/report/tags", options); return response; } public XmlDocument GetNessusV2Report(string reportID) { return this.GetNessusV2Report(reportID, this.RandomNumber); } public XmlDocument GetNessusV2Report(string reportID, int seq) { if (!_session.IsAuthenticated) throw new Exception("Not authed."); Hashtable options = new Hashtable(); options.Add("report", reportID); options.Add("seq", seq); XmlDocument response = _session.ExecuteCommand("/file/report/download", options); return response; } public void Dispose() {} } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Xunit; namespace System.IO.Pipelines.Tests { public class BackpressureTests : IDisposable { private const int PauseWriterThreshold = 64; private const int ResumeWriterThreshold = 32; public BackpressureTests() { _pool = new TestMemoryPool(); _pipe = new Pipe(new PipeOptions(_pool, resumeWriterThreshold: ResumeWriterThreshold, pauseWriterThreshold: PauseWriterThreshold, readerScheduler: PipeScheduler.Inline, writerScheduler: PipeScheduler.Inline, useSynchronizationContext: false)); } public void Dispose() { _pipe.Writer.Complete(); _pipe.Reader.Complete(); _pool?.Dispose(); } private readonly TestMemoryPool _pool; private readonly Pipe _pipe; [Fact] public void FlushAsyncAwaitableCompletesWhenReaderAdvancesUnderLow() { PipeWriter writableBuffer = _pipe.Writer.WriteEmpty(PauseWriterThreshold); ValueTask<FlushResult> flushAsync = writableBuffer.FlushAsync(); Assert.False(flushAsync.IsCompleted); ReadResult result = _pipe.Reader.ReadAsync().GetAwaiter().GetResult(); SequencePosition consumed = result.Buffer.GetPosition(33); _pipe.Reader.AdvanceTo(consumed, consumed); Assert.True(flushAsync.IsCompleted); FlushResult flushResult = flushAsync.GetAwaiter().GetResult(); Assert.False(flushResult.IsCompleted); } [Fact] public void FlushAsyncAwaitableCompletesWhenReaderAdvancesExaminedUnderLow() { PipeWriter writableBuffer = _pipe.Writer.WriteEmpty(PauseWriterThreshold); ValueTask<FlushResult> flushAsync = writableBuffer.FlushAsync(); Assert.False(flushAsync.IsCompleted); ReadResult result = _pipe.Reader.ReadAsync().GetAwaiter().GetResult(); SequencePosition examined = result.Buffer.GetPosition(33); _pipe.Reader.AdvanceTo(result.Buffer.Start, examined); Assert.True(flushAsync.IsCompleted); FlushResult flushResult = flushAsync.GetAwaiter().GetResult(); Assert.False(flushResult.IsCompleted); } [Fact] public async Task CanBufferPastPauseThresholdButGetPausedEachTime() { const int loops = 5; async Task WriteLoopAsync() { for (int i = 0; i < loops; i++) { _pipe.Writer.WriteEmpty(PauseWriterThreshold); ValueTask<FlushResult> flushTask = _pipe.Writer.FlushAsync(); Assert.False(flushTask.IsCompleted); await flushTask; } _pipe.Writer.Complete(); } Task writingTask = WriteLoopAsync(); while (true) { ReadResult result = await _pipe.Reader.ReadAsync(); if (result.IsCompleted) { _pipe.Reader.AdvanceTo(result.Buffer.End); Assert.Equal(PauseWriterThreshold * loops, result.Buffer.Length); break; } _pipe.Reader.AdvanceTo(result.Buffer.Start, result.Buffer.End); } await writingTask; } [Fact] public void FlushAsyncAwaitableDoesNotCompletesWhenReaderAdvancesUnderHight() { PipeWriter writableBuffer = _pipe.Writer.WriteEmpty(PauseWriterThreshold); ValueTask<FlushResult> flushAsync = writableBuffer.FlushAsync(); Assert.False(flushAsync.IsCompleted); ReadResult result = _pipe.Reader.ReadAsync().GetAwaiter().GetResult(); SequencePosition consumed = result.Buffer.GetPosition(ResumeWriterThreshold); _pipe.Reader.AdvanceTo(consumed, consumed); Assert.False(flushAsync.IsCompleted); } [Fact] public void FlushAsyncAwaitableResetsOnCommit() { PipeWriter writableBuffer = _pipe.Writer.WriteEmpty(PauseWriterThreshold); ValueTask<FlushResult> flushAsync = writableBuffer.FlushAsync(); Assert.False(flushAsync.IsCompleted); ReadResult result = _pipe.Reader.ReadAsync().GetAwaiter().GetResult(); SequencePosition consumed = result.Buffer.GetPosition(33); _pipe.Reader.AdvanceTo(consumed, consumed); Assert.True(flushAsync.IsCompleted); FlushResult flushResult = flushAsync.GetAwaiter().GetResult(); Assert.False(flushResult.IsCompleted); writableBuffer = _pipe.Writer.WriteEmpty(PauseWriterThreshold); flushAsync = writableBuffer.FlushAsync(); Assert.False(flushAsync.IsCompleted); } [Fact] public void FlushAsyncReturnsCompletedIfReaderCompletes() { PipeWriter writableBuffer = _pipe.Writer.WriteEmpty(PauseWriterThreshold); ValueTask<FlushResult> flushAsync = writableBuffer.FlushAsync(); Assert.False(flushAsync.IsCompleted); _pipe.Reader.Complete(); Assert.True(flushAsync.IsCompleted); FlushResult flushResult = flushAsync.GetAwaiter().GetResult(); Assert.True(flushResult.IsCompleted); writableBuffer = _pipe.Writer.WriteEmpty(PauseWriterThreshold); flushAsync = writableBuffer.FlushAsync(); flushResult = flushAsync.GetAwaiter().GetResult(); Assert.True(flushResult.IsCompleted); Assert.True(flushAsync.IsCompleted); } [Fact] public async Task FlushAsyncReturnsCompletedIfReaderCompletesWithoutAdvance() { PipeWriter writableBuffer = _pipe.Writer.WriteEmpty(PauseWriterThreshold); ValueTask<FlushResult> flushAsync = writableBuffer.FlushAsync(); Assert.False(flushAsync.IsCompleted); ReadResult result = await _pipe.Reader.ReadAsync(); _pipe.Reader.Complete(); Assert.True(flushAsync.IsCompleted); FlushResult flushResult = flushAsync.GetAwaiter().GetResult(); Assert.True(flushResult.IsCompleted); writableBuffer = _pipe.Writer.WriteEmpty(PauseWriterThreshold); flushAsync = writableBuffer.FlushAsync(); flushResult = flushAsync.GetAwaiter().GetResult(); Assert.True(flushResult.IsCompleted); Assert.True(flushAsync.IsCompleted); } [Fact] public void FlushAsyncReturnsCompletedTaskWhenSizeLessThenLimit() { PipeWriter writableBuffer = _pipe.Writer.WriteEmpty(ResumeWriterThreshold); ValueTask<FlushResult> flushAsync = writableBuffer.FlushAsync(); Assert.True(flushAsync.IsCompleted); FlushResult flushResult = flushAsync.GetAwaiter().GetResult(); Assert.False(flushResult.IsCompleted); } [Fact] public void FlushAsyncReturnsNonCompletedSizeWhenCommitOverTheLimit() { PipeWriter writableBuffer = _pipe.Writer.WriteEmpty(PauseWriterThreshold); ValueTask<FlushResult> flushAsync = writableBuffer.FlushAsync(); Assert.False(flushAsync.IsCompleted); } [Fact] public async Task FlushAsyncThrowsIfReaderCompletedWithException() { _pipe.Reader.Complete(new InvalidOperationException("Reader failed")); PipeWriter writableBuffer = _pipe.Writer.WriteEmpty(PauseWriterThreshold); InvalidOperationException invalidOperationException = await Assert.ThrowsAsync<InvalidOperationException>(async () => await writableBuffer.FlushAsync()); Assert.Equal("Reader failed", invalidOperationException.Message); invalidOperationException = await Assert.ThrowsAsync<InvalidOperationException>(async () => await writableBuffer.FlushAsync()); Assert.Equal("Reader failed", invalidOperationException.Message); } } }
//--------------------------------------------------------------------------- // // Copyright (c) Microsoft Corporation. All rights reserved. // // Description: BamlLocalizabilityResolver class // It resolves localizabilities of a class/element // //--------------------------------------------------------------------------- using System; using System.Windows; using System.Windows.Markup.Localizer; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Collections.Generic; using System.Security.Permissions; namespace BamlLocalization { /// <summary> /// </summary> public class BamlLocalizabilityByReflection : BamlLocalizabilityResolver { /// Take in an optional list of assemblies in addition to the /// default well-known WPF assemblies. The assemblies will be searched first /// in order before the well-known WPF assemblies. /// </summary> /// <param name="assemblies">additinal list of assemblies to search for Type information</param> public BamlLocalizabilityByReflection(params Assembly[] assemblies) { if (assemblies != null) { // create the table _assemblies = new Dictionary<string, Assembly>(assemblies.Length); try{ // Assert security permissions FileIOPermission permobj = new FileIOPermission(PermissionState.None); permobj.AllFiles = FileIOPermissionAccess.PathDiscovery; //CASRemoval:permobj.Assert(); for (int i = 0; i < assemblies.Length; i++) { // skip the null ones. if (assemblies[i] != null) { // index it by the name; _assemblies[assemblies[i].GetName().FullName] = assemblies[i]; } } } finally { // revert assert permission //CASRemoval:FileIOPermission.RevertAssert(); } } // create the cache for Type here _typeCache = new Dictionary<string, Type>(32); } /// <summary> /// Return the localizability of an element to the BamlLocalizer /// </summary> public override ElementLocalizability GetElementLocalizability( string assembly, string className ) { ElementLocalizability loc = new ElementLocalizability(); Type type = GetType(assembly, className); if (type != null) { // We found the type, now try to get the localizability attribte from the type loc.Attribute = GetLocalizabilityFromType(type); } // fill in the formatting tag int index = Array.IndexOf(FormattedElements, className); if (index >= 0) { loc.FormattingTag = FormattingTag[index]; } return loc; } /// <summary> /// return localizability of a property to the BamlLocalizer /// </summary> public override LocalizabilityAttribute GetPropertyLocalizability( string assembly, string className, string property ) { LocalizabilityAttribute attribute = null; Type type = GetType(assembly, className); if (type != null) { // type of the property. The type can be retrieved from CLR property, or Attached property. Type clrPropertyType = null, attachedPropertyType = null; // we found the type. try to get to the property as Clr property GetLocalizabilityForClrProperty( property, type, out attribute, out clrPropertyType ); if (attribute == null) { // we didn't find localizability as a Clr property on the type, // try to get the property as attached property GetLocalizabilityForAttachedProperty( property, type, out attribute, out attachedPropertyType ); } if (attribute == null) { // if attached property doesn't have [LocalizabilityAttribute] defined, // we get it from the type of the property. attribute =(clrPropertyType != null) ? GetLocalizabilityFromType(clrPropertyType) : GetLocalizabilityFromType(attachedPropertyType); } } return attribute; } /// <summary> /// Resolve a formatting tag back to the actual class name /// </summary> public override string ResolveFormattingTagToClass( string formattingTag ) { int index = Array.IndexOf(FormattingTag, formattingTag); if (index >= 0) return FormattedElements[index]; else return null; } /// <summary> /// Resolve a class name back to its containing assembly /// </summary> public override string ResolveAssemblyFromClass( string className ) { // search through the well-known assemblies for (int i = 0; i < _wellKnownAssemblies.Length; i++) { if (_wellKnownAssemblies[i] == null) { _wellKnownAssemblies[i] = Assembly.Load( GetCompatibleAssemblyName(_wellKnownAssemblyNames[i]) ); } if (_wellKnownAssemblies[i] != null && _wellKnownAssemblies[i].GetType(className) != null) { return _wellKnownAssemblies[i].GetName().FullName; } } // search through the custom assemblies if (_assemblies != null) { foreach (KeyValuePair<string, Assembly> pair in _assemblies) { if (pair.Value.GetType(className) != null) { return pair.Value.GetName().FullName; } } } return null; } //----------------------------------------------- // Private methods //----------------------------------------------- // get the type in a specified assembly private Type GetType(string assemblyName, string className) { Debug.Assert(className != null, "classname can't be null"); Debug.Assert(assemblyName != null, "Assembly name can't be null"); // combine assembly name and class name for unique indexing string fullName = assemblyName + ":" + className; Type type; if (_typeCache.ContainsKey(fullName)) { // we found it in the cache, so just return return _typeCache[fullName]; } // we didn't find it in the table. So let's get to the assembly first Assembly assembly = null; if (_assemblies != null && _assemblies.ContainsKey(assemblyName)) { // find the assembly in the hash table first assembly = _assemblies[assemblyName]; } if (assembly == null) { // we don't find the assembly in the hashtable // try to use the default well known assemblies int index; if ( (index = Array.BinarySearch( _wellKnownAssemblyNames, GetAssemblyShortName(assemblyName).ToLower(CultureInfo.InvariantCulture) ) ) >= 0 ) { // see if we already loaded the assembly if (_wellKnownAssemblies[index] == null) { // it is a well known name, load it from the gac _wellKnownAssemblies[index] = Assembly.Load(assemblyName); } assembly = _wellKnownAssemblies[index]; } } if (assembly != null) { // So, we found the assembly. Now get the type from the assembly type = assembly.GetType(className); } else { // Couldn't find the assembly. We will try to load it type = null; } // remember what we found out. _typeCache[fullName] = type; return type; // return } // returns the short name for the assembly private static string GetAssemblyShortName(string assemblyFullName) { int commaIndex = assemblyFullName.IndexOf(','); if (commaIndex > 0) { return assemblyFullName.Substring(0, commaIndex); } return assemblyFullName; } private static string GetCompatibleAssemblyName(string shortName) { AssemblyName asmName = null; for (int i = 0; i < _wellKnownAssemblies.Length; i++) { if (_wellKnownAssemblies[i] != null) { // create an assembly name with the same version and token info // as the WPF assembilies asmName = _wellKnownAssemblies[i].GetName(); asmName.Name = shortName; break; } } if (asmName == null) { // there is no WPF assembly loaded yet. We will just get the compatible version // of the current PresentationFramework Assembly presentationFramework = typeof(BamlLocalizer).Assembly; asmName = presentationFramework.GetName(); asmName.Name = shortName; } return asmName.ToString(); } /// <summary> /// gets the localizabiity attribute of a given the type /// </summary> private LocalizabilityAttribute GetLocalizabilityFromType(Type type) { if (type == null) return null; // let's get to its localizability attribute. object[] locAttributes = type.GetCustomAttributes( TypeOfLocalizabilityAttribute, // type of localizability true // search for inherited value ); if (locAttributes.Length == 0) { return DefaultAttributes.GetDefaultAttribute(type); } else { Debug.Assert(locAttributes.Length == 1, "Should have only 1 localizability attribute"); // use the one defined on the class return (LocalizabilityAttribute) locAttributes[0]; } } /// <summary> /// Get the localizability of a CLR property /// </summary> private void GetLocalizabilityForClrProperty( string propertyName, Type owner, out LocalizabilityAttribute localizability, out Type propertyType ) { localizability = null; propertyType = null; PropertyInfo info = owner.GetProperty(propertyName); if (info == null) { return; // couldn't find the Clr property } // we found the CLR property, set the type of the property propertyType = info.PropertyType; object[] locAttributes = info.GetCustomAttributes( TypeOfLocalizabilityAttribute, // type of the attribute true // search in base class ); if (locAttributes.Length == 0) { return; } else { Debug.Assert(locAttributes.Length == 1, "Should have only 1 localizability attribute"); // we found the attribute defined on the property localizability = (LocalizabilityAttribute) locAttributes[0]; } } /// <summary> /// Get localizability for attached property /// </summary> /// <param name="propertyName">property name</param> /// <param name="owner">owner type</param> /// <param name="localizability">out: localizability attribute</param> /// <param name="propertyType">out: type of the property</param> private void GetLocalizabilityForAttachedProperty( string propertyName, Type owner, out LocalizabilityAttribute localizability, out Type propertyType ) { localizability = null; propertyType = null; // if it is an attached property, it should have a dependency property with the name // <attached proeprty's name> + "Property" DependencyProperty attachedDp = DependencyPropertyFromName( propertyName, // property name owner ); // owner type if (attachedDp == null) return; // couldn't find the dp. // we found the Dp, set the type of the property propertyType = attachedDp.PropertyType; FieldInfo fieldInfo = attachedDp.OwnerType.GetField( attachedDp.Name + "Property", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.FlattenHierarchy); Debug.Assert(fieldInfo != null); object[] attributes = fieldInfo.GetCustomAttributes( TypeOfLocalizabilityAttribute, // type of localizability true ); // inherit if (attributes.Length == 0) { // didn't find it. return; } else { Debug.Assert(attributes.Length == 1, "Should have only 1 localizability attribute"); localizability = (LocalizabilityAttribute) attributes[0]; } } private DependencyProperty DependencyPropertyFromName(string propertyName, Type propertyType) { FieldInfo fi = propertyType.GetField(propertyName + "Property", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy); return (fi != null)?fi.GetValue(null) as DependencyProperty:null; } //--------------------------- // private members //--------------------------- private Dictionary<string, Assembly> _assemblies; // the _assemblies table private Dictionary<string, Type> _typeCache; // the types cache // well know assembly names, keep them sorted. private static readonly string[] _wellKnownAssemblyNames = new string[] { "presentationcore", "presentationframework", "windowsbase" }; // the well known assemblies private static Assembly[] _wellKnownAssemblies = new Assembly[_wellKnownAssemblyNames.Length]; private static Type TypeOfLocalizabilityAttribute= typeof(LocalizabilityAttribute); // supported elements that are formatted inline private static string[] FormattedElements = new string[]{ "System.Windows.Documents.Bold", "System.Windows.Documents.Hyperlink", "System.Windows.Documents.Inline", "System.Windows.Documents.Italic", "System.Windows.Documents.SmallCaps", "System.Windows.Documents.Subscript", "System.Windows.Documents.Superscript", "System.Windows.Documents.Underline" }; // corresponding tag private static string[] FormattingTag = new string[] { "b", "a", "in", "i", "small", "sub", "sup", "u" }; } }
using System; using System.Collections.Generic; using ModestTree; using Zenject.Internal; using System.Linq; #if !NOT_UNITY3D using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif #endif namespace Zenject { internal static class BindingUtil { #if !NOT_UNITY3D public static void AssertIsValidPrefab(UnityEngine.Object prefab) { Assert.That(!ZenUtilInternal.IsNull(prefab), "Received null prefab during bind command"); #if UNITY_EDITOR // This won't execute in dll builds sadly Assert.That(PrefabUtility.GetPrefabType(prefab) == PrefabType.Prefab, "Expected prefab but found game object with name '{0}' during bind command", prefab.name); #endif } public static void AssertIsValidGameObject(GameObject gameObject) { Assert.That(!ZenUtilInternal.IsNull(gameObject), "Received null game object during bind command"); #if UNITY_EDITOR Assert.That(PrefabUtility.GetPrefabType(gameObject) != PrefabType.Prefab, "Expected game object but found prefab instead with name '{0}' during bind command", gameObject.name); #endif } public static void AssertIsNotComponent(IEnumerable<Type> types) { foreach (var type in types) { AssertIsNotComponent(type); } } public static void AssertIsNotComponent<T>() { AssertIsNotComponent(typeof(T)); } public static void AssertIsNotComponent(Type type) { Assert.That(!type.DerivesFrom(typeof(Component)), "Invalid type given during bind command. Expected type '{0}' to NOT derive from UnityEngine.Component", type.Name()); } public static void AssertDerivesFromUnityObject(IEnumerable<Type> types) { foreach (var type in types) { AssertDerivesFromUnityObject(type); } } public static void AssertDerivesFromUnityObject<T>() { AssertDerivesFromUnityObject(typeof(T)); } public static void AssertDerivesFromUnityObject(Type type) { Assert.That(type.DerivesFrom<UnityEngine.Object>(), "Invalid type given during bind command. Expected type '{0}' to derive from UnityEngine.Object", type.Name()); } public static void AssertTypesAreNotComponents(IEnumerable<Type> types) { foreach (var type in types) { AssertIsNotComponent(type); } } public static void AssertIsValidResourcePath(string resourcePath) { Assert.That(!string.IsNullOrEmpty(resourcePath), "Null or empty resource path provided"); // We'd like to validate the path here but unfortunately there doesn't appear to be // a way to do this besides loading it } public static void AssertIsAbstractOrComponent(IEnumerable<Type> types) { foreach (var type in types) { AssertIsAbstractOrComponent(type); } } public static void AssertIsAbstractOrComponent<T>() { AssertIsAbstractOrComponent(typeof(T)); } public static void AssertIsAbstractOrComponent(Type type) { Assert.That(type.DerivesFrom(typeof(Component)) || type.IsInterface(), "Invalid type given during bind command. Expected type '{0}' to either derive from UnityEngine.Component or be an interface", type.Name()); } public static void AssertIsAbstractOrComponentOrGameObject(IEnumerable<Type> types) { foreach (var type in types) { AssertIsAbstractOrComponentOrGameObject(type); } } public static void AssertIsAbstractOrComponentOrGameObject<T>() { AssertIsAbstractOrComponentOrGameObject(typeof(T)); } public static void AssertIsAbstractOrComponentOrGameObject(Type type) { Assert.That(type.DerivesFrom(typeof(Component)) || type.IsInterface() || type == typeof(GameObject) || type == typeof(UnityEngine.Object), "Invalid type given during bind command. Expected type '{0}' to either derive from UnityEngine.Component or be an interface or be GameObject", type.Name()); } public static void AssertIsComponent(IEnumerable<Type> types) { foreach (var type in types) { AssertIsComponent(type); } } public static void AssertIsComponent<T>() { AssertIsComponent(typeof(T)); } public static void AssertIsComponent(Type type) { Assert.That(type.DerivesFrom(typeof(Component)), "Invalid type given during bind command. Expected type '{0}' to derive from UnityEngine.Component", type.Name()); } public static void AssertIsComponentOrGameObject(IEnumerable<Type> types) { foreach (var type in types) { AssertIsComponentOrGameObject(type); } } public static void AssertIsComponentOrGameObject<T>() { AssertIsComponentOrGameObject(typeof(T)); } public static void AssertIsComponentOrGameObject(Type type) { Assert.That(type.DerivesFrom(typeof(Component)) || type == typeof(GameObject), "Invalid type given during bind command. Expected type '{0}' to derive from UnityEngine.Component", type.Name()); } #else public static void AssertTypesAreNotComponents(IEnumerable<Type> types) { } public static void AssertIsNotComponent(Type type) { } public static void AssertIsNotComponent<T>() { } public static void AssertIsNotComponent(IEnumerable<Type> types) { } #endif public static void AssertTypesAreNotAbstract(IEnumerable<Type> types) { foreach (var type in types) { AssertIsNotAbstract(type); } } public static void AssertIsNotAbstract(IEnumerable<Type> types) { foreach (var type in types) { AssertIsNotAbstract(type); } } public static void AssertIsNotAbstract<T>() { AssertIsNotAbstract(typeof(T)); } public static void AssertIsNotAbstract(Type type) { Assert.That(!type.IsAbstract(), "Invalid type given during bind command. Expected type '{0}' to not be abstract.", type); } public static void AssertIsDerivedFromType(Type concreteType, Type parentType) { Assert.That(concreteType.DerivesFromOrEqual(parentType), "Invalid type given during bind command. Expected type '{0}' to derive from type '{1}'", concreteType.Name(), parentType.Name()); } public static void AssertConcreteTypeListIsNotEmpty(IEnumerable<Type> concreteTypes) { Assert.That(concreteTypes.Count() >= 1, "Must supply at least one concrete type to the current binding"); } public static void AssertIsIInstallerType(Type installerType) { Assert.That(installerType.DerivesFrom<IInstaller>(), "Invalid installer type given during bind command. Expected type '{0}' to derive from either 'MonoInstaller' or 'Installer'", installerType.Name()); } public static void AssertIsInstallerType(Type installerType) { Assert.That(installerType.DerivesFrom<Installer>(), "Invalid installer type given during bind command. Expected type '{0}' to derive from 'Installer'", installerType.Name()); } public static void AssertIsDerivedFromTypes( IEnumerable<Type> concreteTypes, IEnumerable<Type> parentTypes, InvalidBindResponses invalidBindResponse) { if (invalidBindResponse == InvalidBindResponses.Assert) { AssertIsDerivedFromTypes(concreteTypes, parentTypes); } else { Assert.IsEqual(invalidBindResponse, InvalidBindResponses.Skip); } } public static void AssertIsDerivedFromTypes(IEnumerable<Type> concreteTypes, IEnumerable<Type> parentTypes) { foreach (var concreteType in concreteTypes) { AssertIsDerivedFromTypes(concreteType, parentTypes); } } public static void AssertIsDerivedFromTypes(Type concreteType, IEnumerable<Type> parentTypes) { foreach (var parentType in parentTypes) { AssertIsDerivedFromType(concreteType, parentType); } } public static void AssertInstanceDerivesFromOrEqual(object instance, IEnumerable<Type> parentTypes) { if (!ZenUtilInternal.IsNull(instance)) { foreach (var baseType in parentTypes) { AssertInstanceDerivesFromOrEqual(instance, baseType); } } } public static void AssertInstanceDerivesFromOrEqual(object instance, Type baseType) { if (!ZenUtilInternal.IsNull(instance)) { Assert.That(instance.GetType().DerivesFromOrEqual(baseType), "Invalid type given during bind command. Expected type '{0}' to derive from type '{1}'", instance.GetType().Name(), baseType.Name()); } } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; using System.ComponentModel.DataAnnotations; using UsingLibrary; namespace TestProject.Business { /// <summary> /// Types of document (editable child object).<br/> /// This is a generated <see cref="DocTypeEdit"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="DocTypeEditColl"/> collection. /// This is a remark /// </remarks> [Attributable] [Serializable] public partial class DocTypeEdit : BusinessBase<DocTypeEdit>, IHaveInterface { #region Static Fields private static int _lastId; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="DocTypeID"/> property. /// </summary> [NotUndoable] public static readonly PropertyInfo<int> DocTypeIDProperty = RegisterProperty<int>(p => p.DocTypeID, "Doc Type ID"); /// <summary> /// Gets the Doc Type ID. /// </summary> /// <value>The Doc Type ID.</value> public int DocTypeID { get { return GetProperty(DocTypeIDProperty); } } /// <summary> /// Maintains metadata about <see cref="DocTypeName"/> property. /// </summary> public static readonly PropertyInfo<string> DocTypeNameProperty = RegisterProperty<string>(p => p.DocTypeName, "Doc Type Name"); /// <summary> /// Gets or sets the Doc Type Name. /// </summary> /// <value>The Doc Type Name.</value> [Required(AllowEmptyStrings = false, ErrorMessage = "Must fill.")] public string DocTypeName { get { return GetProperty(DocTypeNameProperty); } set { SetProperty(DocTypeNameProperty, value); } } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="DocTypeEdit"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public DocTypeEdit() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="DocTypeEdit"/> object properties. /// </summary> [RunLocal] protected override void Child_Create() { LoadProperty(DocTypeIDProperty, System.Threading.Interlocked.Decrement(ref _lastId)); var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="DocTypeEdit"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Child_Fetch(SafeDataReader dr) { // Value properties LoadProperty(DocTypeIDProperty, dr.GetInt32("DocTypeID")); LoadProperty(DocTypeNameProperty, dr.GetString("DocTypeName")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); // check all object rules and property rules BusinessRules.CheckRules(); } /// <summary> /// Inserts a new <see cref="DocTypeEdit"/> object in the database. /// </summary> private void Child_Insert() { using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.TestProjectConnection, false)) { using (var cmd = new SqlCommand("AddDocTypeEdit", ctx.Connection)) { cmd.Transaction = ctx.Transaction; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@DocTypeID", ReadProperty(DocTypeIDProperty)).Direction = ParameterDirection.Output; cmd.Parameters.AddWithValue("@DocTypeName", ReadProperty(DocTypeNameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); LoadProperty(DocTypeIDProperty, (int) cmd.Parameters["@DocTypeID"].Value); } } } /// <summary> /// Updates in the database all changes made to the <see cref="DocTypeEdit"/> object. /// </summary> private void Child_Update() { if (!IsDirty) return; using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.TestProjectConnection, false)) { using (var cmd = new SqlCommand("UpdateDocTypeEdit", ctx.Connection)) { cmd.Transaction = ctx.Transaction; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@DocTypeID", ReadProperty(DocTypeIDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@DocTypeName", ReadProperty(DocTypeNameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } } } /// <summary> /// Self deletes the <see cref="DocTypeEdit"/> object from database. /// </summary> private void Child_DeleteSelf() { using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.TestProjectConnection, false)) { using (var cmd = new SqlCommand("DeleteDocTypeEdit", ctx.Connection)) { cmd.Transaction = ctx.Transaction; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@DocTypeID", ReadProperty(DocTypeIDProperty)).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
/* ==================================================================== */ using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; namespace Oranikle.ReportDesigner { /// <summary> /// Summary description for FindTab. /// </summary> internal class FindTab : System.Windows.Forms.Form { private System.Windows.Forms.TabPage tabFind; private System.Windows.Forms.Label label1; private Oranikle.Studio.Controls.CustomTextControl txtFind; private System.Windows.Forms.RadioButton radioUp; private System.Windows.Forms.RadioButton radioDown; private System.Windows.Forms.GroupBox groupBox1; private Oranikle.Studio.Controls.StyledCheckBox chkCase; public System.Windows.Forms.TabPage tabGoTo; private System.Windows.Forms.Label label4; private Oranikle.Studio.Controls.CustomTextControl txtLine; private Oranikle.Studio.Controls.StyledButton btnNext; private RdlEditPreview rdlEdit; private Oranikle.Studio.Controls.StyledButton btnGoto; private Oranikle.Studio.Controls.StyledButton btnCancel; public System.Windows.Forms.TabPage tabReplace; private Oranikle.Studio.Controls.StyledButton btnFindNext; private Oranikle.Studio.Controls.StyledCheckBox chkMatchCase; private Oranikle.Studio.Controls.StyledButton btnReplaceAll; private Oranikle.Studio.Controls.StyledButton btnReplace; private Oranikle.Studio.Controls.CustomTextControl txtFindR; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label2; private Oranikle.Studio.Controls.CustomTextControl txtReplace; private Oranikle.Studio.Controls.StyledButton bCloseReplace; private Oranikle.Studio.Controls.StyledButton bCloseGoto; public Oranikle.Studio.Controls.CtrlStyledTab tcFRG; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public FindTab() { // // Required for Windows Form Designer support // InitializeComponent(); this.AcceptButton = btnNext; this.CancelButton = btnCancel; txtFind.Focus(); } internal FindTab(RdlEditPreview pad) { rdlEdit = pad; InitializeComponent(); this.AcceptButton = btnNext; this.CancelButton = btnCancel; txtFind.Focus(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.tcFRG = new Oranikle.Studio.Controls.CtrlStyledTab(); this.tabFind = new System.Windows.Forms.TabPage(); this.btnCancel = new Oranikle.Studio.Controls.StyledButton(); this.btnNext = new Oranikle.Studio.Controls.StyledButton(); this.chkCase = new Oranikle.Studio.Controls.StyledCheckBox(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.radioUp = new System.Windows.Forms.RadioButton(); this.radioDown = new System.Windows.Forms.RadioButton(); this.label1 = new System.Windows.Forms.Label(); this.txtFind = new Oranikle.Studio.Controls.CustomTextControl(); this.tabReplace = new System.Windows.Forms.TabPage(); this.bCloseReplace = new Oranikle.Studio.Controls.StyledButton(); this.btnFindNext = new Oranikle.Studio.Controls.StyledButton(); this.chkMatchCase = new Oranikle.Studio.Controls.StyledCheckBox(); this.btnReplaceAll = new Oranikle.Studio.Controls.StyledButton(); this.btnReplace = new Oranikle.Studio.Controls.StyledButton(); this.txtFindR = new Oranikle.Studio.Controls.CustomTextControl(); this.label3 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.txtReplace = new Oranikle.Studio.Controls.CustomTextControl(); this.tabGoTo = new System.Windows.Forms.TabPage(); this.bCloseGoto = new Oranikle.Studio.Controls.StyledButton(); this.txtLine = new Oranikle.Studio.Controls.CustomTextControl(); this.label4 = new System.Windows.Forms.Label(); this.btnGoto = new Oranikle.Studio.Controls.StyledButton(); this.tcFRG.SuspendLayout(); this.tabFind.SuspendLayout(); this.groupBox1.SuspendLayout(); this.tabReplace.SuspendLayout(); this.tabGoTo.SuspendLayout(); this.SuspendLayout(); // // tcFRG // this.tcFRG.BorderColor = System.Drawing.Color.DarkGray; this.tcFRG.Controls.Add(this.tabFind); this.tcFRG.Controls.Add(this.tabReplace); this.tcFRG.Controls.Add(this.tabGoTo); this.tcFRG.DontSlantMiddle = false; this.tcFRG.LeftSpacing = 0; this.tcFRG.Location = new System.Drawing.Point(8, 8); this.tcFRG.myBackColor = System.Drawing.Color.Transparent; this.tcFRG.Name = "tcFRG"; this.tcFRG.SelectedIndex = 0; this.tcFRG.Size = new System.Drawing.Size(432, 192); this.tcFRG.SizeMode = System.Windows.Forms.TabSizeMode.Fixed; this.tcFRG.TabFont = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.tcFRG.TabIndex = 0; this.tcFRG.TabSlant = 2; this.tcFRG.TabStop = false; this.tcFRG.TabTextColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64))))); this.tcFRG.TabTextHAlignment = System.Drawing.StringAlignment.Near; this.tcFRG.TabTextVAlignment = System.Drawing.StringAlignment.Center; this.tcFRG.TagPageSelectedColor = System.Drawing.Color.White; this.tcFRG.TagPageUnselectedColor = System.Drawing.Color.LightGray; this.tcFRG.Enter += new System.EventHandler(this.tcFRG_Enter); this.tcFRG.SelectedIndexChanged += new System.EventHandler(this.tcFRG_SelectedIndexChanged); // // tabFind // this.tabFind.BackColor = System.Drawing.Color.White; this.tabFind.Controls.Add(this.btnCancel); this.tabFind.Controls.Add(this.btnNext); this.tabFind.Controls.Add(this.chkCase); this.tabFind.Controls.Add(this.groupBox1); this.tabFind.Controls.Add(this.label1); this.tabFind.Controls.Add(this.txtFind); this.tabFind.Location = new System.Drawing.Point(4, 25); this.tabFind.Name = "tabFind"; this.tabFind.Size = new System.Drawing.Size(424, 163); this.tabFind.TabIndex = 0; this.tabFind.Tag = "find"; this.tabFind.Text = "Find"; // // btnCancel // this.btnCancel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245))))); this.btnCancel.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225))))); this.btnCancel.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.btnCancel.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200))))); this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.btnCancel.Font = new System.Drawing.Font("Arial", 9F); this.btnCancel.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90))))); this.btnCancel.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.btnCancel.Location = new System.Drawing.Point(344, 128); this.btnCancel.Name = "btnCancel"; this.btnCancel.OverriddenSize = null; this.btnCancel.Size = new System.Drawing.Size(75, 21); this.btnCancel.TabIndex = 3; this.btnCancel.Text = "Close"; this.btnCancel.UseVisualStyleBackColor = true; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // btnNext // this.btnNext.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245))))); this.btnNext.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225))))); this.btnNext.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.btnNext.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200))))); this.btnNext.Enabled = false; this.btnNext.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.btnNext.Font = new System.Drawing.Font("Arial", 9F); this.btnNext.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90))))); this.btnNext.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.btnNext.Location = new System.Drawing.Point(344, 16); this.btnNext.Name = "btnNext"; this.btnNext.OverriddenSize = null; this.btnNext.Size = new System.Drawing.Size(75, 21); this.btnNext.TabIndex = 1; this.btnNext.Text = "Find Next"; this.btnNext.UseVisualStyleBackColor = true; this.btnNext.Click += new System.EventHandler(this.btnNext_Click); // // chkCase // this.chkCase.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.chkCase.ForeColor = System.Drawing.Color.Black; this.chkCase.Location = new System.Drawing.Point(208, 72); this.chkCase.Name = "chkCase"; this.chkCase.Size = new System.Drawing.Size(88, 24); this.chkCase.TabIndex = 2; this.chkCase.Text = "Match Case"; // // groupBox1 // this.groupBox1.Controls.Add(this.radioUp); this.groupBox1.Controls.Add(this.radioDown); this.groupBox1.Location = new System.Drawing.Point(16, 48); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(176, 64); this.groupBox1.TabIndex = 2; this.groupBox1.TabStop = false; this.groupBox1.Text = "Search Direction"; // // radioUp // this.radioUp.Location = new System.Drawing.Point(16, 24); this.radioUp.Name = "radioUp"; this.radioUp.Size = new System.Drawing.Size(56, 24); this.radioUp.TabIndex = 0; this.radioUp.Text = "Up"; this.radioUp.CheckedChanged += new System.EventHandler(this.radioUp_CheckedChanged); // // radioDown // this.radioDown.Location = new System.Drawing.Point(104, 24); this.radioDown.Name = "radioDown"; this.radioDown.Size = new System.Drawing.Size(56, 24); this.radioDown.TabIndex = 1; this.radioDown.Text = "Down"; // // label1 // this.label1.Location = new System.Drawing.Point(12, 16); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(76, 23); this.label1.TabIndex = 0; this.label1.Text = "Find"; // // txtFind // this.txtFind.AddX = 0; this.txtFind.AddY = 0; this.txtFind.AllowSpace = false; this.txtFind.BorderColor = System.Drawing.Color.LightGray; this.txtFind.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtFind.ChangeVisibility = false; this.txtFind.ChildControl = null; this.txtFind.ConvertEnterToTab = true; this.txtFind.ConvertEnterToTabForDialogs = false; this.txtFind.Decimals = 0; this.txtFind.DisplayList = new object[0]; this.txtFind.HitText = Oranikle.Studio.Controls.HitText.String; this.txtFind.Location = new System.Drawing.Point(96, 16); this.txtFind.Name = "txtFind"; this.txtFind.OnDropDownCloseFocus = true; this.txtFind.SelectType = 0; this.txtFind.Size = new System.Drawing.Size(216, 20); this.txtFind.TabIndex = 0; this.txtFind.UseValueForChildsVisibilty = false; this.txtFind.Value = true; this.txtFind.TextChanged += new System.EventHandler(this.txtFind_TextChanged); // // tabReplace // this.tabReplace.BackColor = System.Drawing.Color.White; this.tabReplace.Controls.Add(this.bCloseReplace); this.tabReplace.Controls.Add(this.btnFindNext); this.tabReplace.Controls.Add(this.chkMatchCase); this.tabReplace.Controls.Add(this.btnReplaceAll); this.tabReplace.Controls.Add(this.btnReplace); this.tabReplace.Controls.Add(this.txtFindR); this.tabReplace.Controls.Add(this.label3); this.tabReplace.Controls.Add(this.label2); this.tabReplace.Controls.Add(this.txtReplace); this.tabReplace.Location = new System.Drawing.Point(4, 25); this.tabReplace.Name = "tabReplace"; this.tabReplace.Size = new System.Drawing.Size(424, 163); this.tabReplace.TabIndex = 1; this.tabReplace.Tag = "replace"; this.tabReplace.Text = "Replace"; // // bCloseReplace // this.bCloseReplace.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245))))); this.bCloseReplace.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225))))); this.bCloseReplace.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.bCloseReplace.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200))))); this.bCloseReplace.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.bCloseReplace.Font = new System.Drawing.Font("Arial", 9F); this.bCloseReplace.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90))))); this.bCloseReplace.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bCloseReplace.Location = new System.Drawing.Point(344, 128); this.bCloseReplace.Name = "bCloseReplace"; this.bCloseReplace.OverriddenSize = null; this.bCloseReplace.Size = new System.Drawing.Size(75, 21); this.bCloseReplace.TabIndex = 6; this.bCloseReplace.Text = "Close"; this.bCloseReplace.UseVisualStyleBackColor = true; this.bCloseReplace.Click += new System.EventHandler(this.btnCancel_Click); // // btnFindNext // this.btnFindNext.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245))))); this.btnFindNext.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225))))); this.btnFindNext.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.btnFindNext.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200))))); this.btnFindNext.Enabled = false; this.btnFindNext.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.btnFindNext.Font = new System.Drawing.Font("Arial", 9F); this.btnFindNext.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90))))); this.btnFindNext.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.btnFindNext.Location = new System.Drawing.Point(344, 16); this.btnFindNext.Name = "btnFindNext"; this.btnFindNext.OverriddenSize = null; this.btnFindNext.Size = new System.Drawing.Size(75, 21); this.btnFindNext.TabIndex = 3; this.btnFindNext.Text = "FindNext"; this.btnFindNext.UseVisualStyleBackColor = true; this.btnFindNext.Click += new System.EventHandler(this.btnFindNext_Click); // // chkMatchCase // this.chkMatchCase.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.chkMatchCase.ForeColor = System.Drawing.Color.Black; this.chkMatchCase.Location = new System.Drawing.Point(8, 88); this.chkMatchCase.Name = "chkMatchCase"; this.chkMatchCase.Size = new System.Drawing.Size(104, 24); this.chkMatchCase.TabIndex = 2; this.chkMatchCase.Text = "Match Case"; // // btnReplaceAll // this.btnReplaceAll.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245))))); this.btnReplaceAll.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225))))); this.btnReplaceAll.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.btnReplaceAll.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200))))); this.btnReplaceAll.Enabled = false; this.btnReplaceAll.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.btnReplaceAll.Font = new System.Drawing.Font("Arial", 9F); this.btnReplaceAll.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90))))); this.btnReplaceAll.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.btnReplaceAll.Location = new System.Drawing.Point(344, 80); this.btnReplaceAll.Name = "btnReplaceAll"; this.btnReplaceAll.OverriddenSize = null; this.btnReplaceAll.Size = new System.Drawing.Size(75, 21); this.btnReplaceAll.TabIndex = 5; this.btnReplaceAll.Text = "ReplaceAll"; this.btnReplaceAll.UseVisualStyleBackColor = true; this.btnReplaceAll.Click += new System.EventHandler(this.btnReplaceAll_Click); // // btnReplace // this.btnReplace.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245))))); this.btnReplace.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225))))); this.btnReplace.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.btnReplace.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200))))); this.btnReplace.Enabled = false; this.btnReplace.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.btnReplace.Font = new System.Drawing.Font("Arial", 9F); this.btnReplace.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90))))); this.btnReplace.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.btnReplace.Location = new System.Drawing.Point(344, 48); this.btnReplace.Name = "btnReplace"; this.btnReplace.OverriddenSize = null; this.btnReplace.Size = new System.Drawing.Size(75, 21); this.btnReplace.TabIndex = 4; this.btnReplace.Text = "Replace"; this.btnReplace.UseVisualStyleBackColor = true; this.btnReplace.Click += new System.EventHandler(this.btnReplace_Click); // // txtFindR // this.txtFindR.AddX = 0; this.txtFindR.AddY = 0; this.txtFindR.AllowSpace = false; this.txtFindR.BorderColor = System.Drawing.Color.LightGray; this.txtFindR.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtFindR.ChangeVisibility = false; this.txtFindR.ChildControl = null; this.txtFindR.ConvertEnterToTab = true; this.txtFindR.ConvertEnterToTabForDialogs = false; this.txtFindR.Decimals = 0; this.txtFindR.DisplayList = new object[0]; this.txtFindR.HitText = Oranikle.Studio.Controls.HitText.String; this.txtFindR.Location = new System.Drawing.Point(96, 16); this.txtFindR.Name = "txtFindR"; this.txtFindR.OnDropDownCloseFocus = true; this.txtFindR.SelectType = 0; this.txtFindR.Size = new System.Drawing.Size(224, 20); this.txtFindR.TabIndex = 0; this.txtFindR.UseValueForChildsVisibilty = false; this.txtFindR.Value = true; this.txtFindR.TextChanged += new System.EventHandler(this.txtFindR_TextChanged); // // label3 // this.label3.Location = new System.Drawing.Point(14, 16); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(76, 23); this.label3.TabIndex = 0; this.label3.Text = "Find"; // // label2 // this.label2.Location = new System.Drawing.Point(14, 56); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(76, 23); this.label2.TabIndex = 5; this.label2.Text = "Replace With"; // // txtReplace // this.txtReplace.AddX = 0; this.txtReplace.AddY = 0; this.txtReplace.AllowSpace = false; this.txtReplace.BorderColor = System.Drawing.Color.LightGray; this.txtReplace.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtReplace.ChangeVisibility = false; this.txtReplace.ChildControl = null; this.txtReplace.ConvertEnterToTab = true; this.txtReplace.ConvertEnterToTabForDialogs = false; this.txtReplace.Decimals = 0; this.txtReplace.DisplayList = new object[0]; this.txtReplace.HitText = Oranikle.Studio.Controls.HitText.String; this.txtReplace.Location = new System.Drawing.Point(96, 56); this.txtReplace.Name = "txtReplace"; this.txtReplace.OnDropDownCloseFocus = true; this.txtReplace.SelectType = 0; this.txtReplace.Size = new System.Drawing.Size(224, 20); this.txtReplace.TabIndex = 1; this.txtReplace.UseValueForChildsVisibilty = false; this.txtReplace.Value = true; // // tabGoTo // this.tabGoTo.BackColor = System.Drawing.Color.White; this.tabGoTo.Controls.Add(this.bCloseGoto); this.tabGoTo.Controls.Add(this.txtLine); this.tabGoTo.Controls.Add(this.label4); this.tabGoTo.Controls.Add(this.btnGoto); this.tabGoTo.Location = new System.Drawing.Point(4, 25); this.tabGoTo.Name = "tabGoTo"; this.tabGoTo.Size = new System.Drawing.Size(424, 163); this.tabGoTo.TabIndex = 2; this.tabGoTo.Tag = "goto"; this.tabGoTo.Text = "GoTo"; // // bCloseGoto // this.bCloseGoto.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245))))); this.bCloseGoto.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225))))); this.bCloseGoto.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.bCloseGoto.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200))))); this.bCloseGoto.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.bCloseGoto.Font = new System.Drawing.Font("Arial", 9F); this.bCloseGoto.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90))))); this.bCloseGoto.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bCloseGoto.Location = new System.Drawing.Point(344, 128); this.bCloseGoto.Name = "bCloseGoto"; this.bCloseGoto.OverriddenSize = null; this.bCloseGoto.Size = new System.Drawing.Size(75, 21); this.bCloseGoto.TabIndex = 2; this.bCloseGoto.Text = "Close"; this.bCloseGoto.UseVisualStyleBackColor = true; this.bCloseGoto.Click += new System.EventHandler(this.btnCancel_Click); // // txtLine // this.txtLine.AddX = 0; this.txtLine.AddY = 0; this.txtLine.AllowSpace = false; this.txtLine.BorderColor = System.Drawing.Color.LightGray; this.txtLine.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtLine.ChangeVisibility = false; this.txtLine.ChildControl = null; this.txtLine.ConvertEnterToTab = true; this.txtLine.ConvertEnterToTabForDialogs = false; this.txtLine.Decimals = 0; this.txtLine.DisplayList = new object[0]; this.txtLine.HitText = Oranikle.Studio.Controls.HitText.String; this.txtLine.Location = new System.Drawing.Point(96, 16); this.txtLine.Name = "txtLine"; this.txtLine.OnDropDownCloseFocus = true; this.txtLine.SelectType = 0; this.txtLine.Size = new System.Drawing.Size(100, 20); this.txtLine.TabIndex = 0; this.txtLine.UseValueForChildsVisibilty = false; this.txtLine.Value = true; // // label4 // this.label4.Location = new System.Drawing.Point(16, 16); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(100, 23); this.label4.TabIndex = 2; this.label4.Text = "Line Number"; // // btnGoto // this.btnGoto.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245))))); this.btnGoto.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225))))); this.btnGoto.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.btnGoto.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200))))); this.btnGoto.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.btnGoto.Font = new System.Drawing.Font("Arial", 9F); this.btnGoto.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90))))); this.btnGoto.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.btnGoto.Location = new System.Drawing.Point(344, 16); this.btnGoto.Name = "btnGoto"; this.btnGoto.OverriddenSize = null; this.btnGoto.Size = new System.Drawing.Size(75, 21); this.btnGoto.TabIndex = 1; this.btnGoto.Text = "GoTo"; this.btnGoto.UseVisualStyleBackColor = true; this.btnGoto.Click += new System.EventHandler(this.btnGoto_Click); // // FindTab // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(228)))), ((int)(((byte)(241)))), ((int)(((byte)(249))))); this.CancelButton = this.btnCancel; this.ClientSize = new System.Drawing.Size(445, 206); this.Controls.Add(this.tcFRG); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "FindTab"; this.Text = "Find"; this.TopMost = true; this.tcFRG.ResumeLayout(false); this.tabFind.ResumeLayout(false); this.tabFind.PerformLayout(); this.groupBox1.ResumeLayout(false); this.tabReplace.ResumeLayout(false); this.tabReplace.PerformLayout(); this.tabGoTo.ResumeLayout(false); this.tabGoTo.PerformLayout(); this.ResumeLayout(false); } #endregion private void radioUp_CheckedChanged(object sender, System.EventArgs e) { } private void btnNext_Click(object sender, System.EventArgs e) { rdlEdit.FindNext(this, txtFind.Text, chkCase.Checked); } private void txtFind_TextChanged(object sender, System.EventArgs e) { if (txtFind.Text == "") btnNext.Enabled = false; else btnNext.Enabled = true; } private void btnFindNext_Click(object sender, System.EventArgs e) { rdlEdit.FindNext(this, txtFindR.Text, chkCase.Checked); txtFind.Focus(); } private void btnReplace_Click(object sender, System.EventArgs e) { rdlEdit.FindNext(this, txtFindR.Text, chkCase.Checked); rdlEdit.ReplaceNext(this, txtFindR.Text, txtReplace.Text, chkCase.Checked); txtFindR.Focus(); } private void txtFindR_TextChanged(object sender, System.EventArgs e) { bool bEnable = (txtFindR.Text == "") ? false : true; btnFindNext.Enabled = bEnable; btnReplace.Enabled = bEnable; btnReplaceAll.Enabled = bEnable; } private void btnReplaceAll_Click(object sender, System.EventArgs e) { rdlEdit.ReplaceAll(this, txtFindR.Text, txtReplace.Text, chkCase.Checked); txtFindR.Focus(); } private void btnGoto_Click(object sender, System.EventArgs e) { try { try { int nLine = Int32.Parse(txtLine.Text); rdlEdit.Goto(this, nLine); } catch (Exception ex) { MessageBox.Show(this, ex.Message, "Invalid Line Number"); } txtLine.Focus(); } catch(Exception er) { er.ToString(); } } private void btnCancel_Click(object sender, System.EventArgs e) { Close(); } private void tcFRG_SelectedIndexChanged(object sender, System.EventArgs e) { TabControl tc = (TabControl) sender; string tag = (string) tc.TabPages[tc.SelectedIndex].Tag; switch (tag) { case "find": this.AcceptButton = btnNext; this.CancelButton = btnCancel; txtFind.Focus(); break; case "replace": this.AcceptButton = this.btnFindNext; this.CancelButton = this.bCloseReplace; txtFindR.Focus(); break; case "goto": this.AcceptButton = btnGoto; this.CancelButton = this.bCloseGoto; txtLine.Focus(); break; } } private void tcFRG_Enter(object sender, System.EventArgs e) { tcFRG_SelectedIndexChanged(this.tcFRG, new EventArgs()); } } }
/* * CP20905.cs - IBM EBCDIC (Turkish) code page. * * Copyright (c) 2002 Southern Storm Software, Pty Ltd * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // Generated from "ibm-1026.ucm". namespace I18N.Rare { using System; using I18N.Common; public class CP20905 : ByteEncoding { public CP20905() : base(20905, ToChars, "IBM EBCDIC (Turkish)", "IBM905", "IBM905", "IBM905", false, false, false, false, 1254) {} private static readonly char[] ToChars = { '\u0000', '\u0001', '\u0002', '\u0003', '\u009C', '\u0009', '\u0086', '\u007F', '\u0097', '\u008D', '\u008E', '\u000B', '\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011', '\u0012', '\u0013', '\u009D', '\u0085', '\u0008', '\u0087', '\u0018', '\u0019', '\u0092', '\u008F', '\u001C', '\u001D', '\u001E', '\u001F', '\u0080', '\u0081', '\u0082', '\u0083', '\u0084', '\u000A', '\u0017', '\u001B', '\u0088', '\u0089', '\u008A', '\u008B', '\u008C', '\u0005', '\u0006', '\u0007', '\u0090', '\u0091', '\u0016', '\u0093', '\u0094', '\u0095', '\u0096', '\u0004', '\u0098', '\u0099', '\u009A', '\u009B', '\u0014', '\u0015', '\u009E', '\u001A', '\u0020', '\u00A0', '\u00E2', '\u00E4', '\u00E0', '\u00E1', '\u00E3', '\u00E5', '\u007B', '\u00F1', '\u00C7', '\u002E', '\u003C', '\u0028', '\u002B', '\u0021', '\u0026', '\u00E9', '\u00EA', '\u00EB', '\u00E8', '\u00ED', '\u00EE', '\u00EF', '\u00EC', '\u00DF', '\u011E', '\u0130', '\u002A', '\u0029', '\u003B', '\u005E', '\u002D', '\u002F', '\u00C2', '\u00C4', '\u00C0', '\u00C1', '\u00C3', '\u00C5', '\u005B', '\u00D1', '\u015F', '\u002C', '\u0025', '\u005F', '\u003E', '\u003F', '\u00F8', '\u00C9', '\u00CA', '\u00CB', '\u00C8', '\u00CD', '\u00CE', '\u00CF', '\u00CC', '\u0131', '\u003A', '\u00D6', '\u015E', '\u0027', '\u003D', '\u00DC', '\u00D8', '\u0061', '\u0062', '\u0063', '\u0064', '\u0065', '\u0066', '\u0067', '\u0068', '\u0069', '\u00AB', '\u00BB', '\u007D', '\u0060', '\u00A6', '\u00B1', '\u00B0', '\u006A', '\u006B', '\u006C', '\u006D', '\u006E', '\u006F', '\u0070', '\u0071', '\u0072', '\u00AA', '\u00BA', '\u00E6', '\u00B8', '\u00C6', '\u00A4', '\u00B5', '\u00F6', '\u0073', '\u0074', '\u0075', '\u0076', '\u0077', '\u0078', '\u0079', '\u007A', '\u00A1', '\u00BF', '\u005D', '\u0024', '\u0040', '\u00AE', '\u00A2', '\u00A3', '\u00A5', '\u00B7', '\u00A9', '\u00A7', '\u00B6', '\u00BC', '\u00BD', '\u00BE', '\u00AC', '\u007C', '\u00AF', '\u00A8', '\u00B4', '\u00D7', '\u00E7', '\u0041', '\u0042', '\u0043', '\u0044', '\u0045', '\u0046', '\u0047', '\u0048', '\u0049', '\u00AD', '\u00F4', '\u007E', '\u00F2', '\u00F3', '\u00F5', '\u011F', '\u004A', '\u004B', '\u004C', '\u004D', '\u004E', '\u004F', '\u0050', '\u0051', '\u0052', '\u00B9', '\u00FB', '\u005C', '\u00F9', '\u00FA', '\u00FF', '\u00FC', '\u00F7', '\u0053', '\u0054', '\u0055', '\u0056', '\u0057', '\u0058', '\u0059', '\u005A', '\u00B2', '\u00D4', '\u0023', '\u00D2', '\u00D3', '\u00D5', '\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035', '\u0036', '\u0037', '\u0038', '\u0039', '\u00B3', '\u00DB', '\u0022', '\u00D9', '\u00DA', '\u009F', }; protected override void ToBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { int ch; while(charCount > 0) { ch = (int)(chars[charIndex++]); if(ch >= 4) switch(ch) { case 0x000B: case 0x000C: case 0x000D: case 0x000E: case 0x000F: case 0x0010: case 0x0011: case 0x0012: case 0x0013: case 0x0018: case 0x0019: case 0x001C: case 0x001D: case 0x001E: case 0x001F: case 0x00B6: break; case 0x0004: ch = 0x37; break; case 0x0005: ch = 0x2D; break; case 0x0006: ch = 0x2E; break; case 0x0007: ch = 0x2F; break; case 0x0008: ch = 0x16; break; case 0x0009: ch = 0x05; break; case 0x000A: ch = 0x25; break; case 0x0014: ch = 0x3C; break; case 0x0015: ch = 0x3D; break; case 0x0016: ch = 0x32; break; case 0x0017: ch = 0x26; break; case 0x001A: ch = 0x3F; break; case 0x001B: ch = 0x27; break; case 0x0020: ch = 0x40; break; case 0x0021: ch = 0x4F; break; case 0x0022: ch = 0xFC; break; case 0x0023: ch = 0xEC; break; case 0x0024: ch = 0xAD; break; case 0x0025: ch = 0x6C; break; case 0x0026: ch = 0x50; break; case 0x0027: ch = 0x7D; break; case 0x0028: ch = 0x4D; break; case 0x0029: ch = 0x5D; break; case 0x002A: ch = 0x5C; break; case 0x002B: ch = 0x4E; break; case 0x002C: ch = 0x6B; break; case 0x002D: ch = 0x60; break; case 0x002E: ch = 0x4B; break; case 0x002F: ch = 0x61; break; case 0x0030: case 0x0031: case 0x0032: case 0x0033: case 0x0034: case 0x0035: case 0x0036: case 0x0037: case 0x0038: case 0x0039: ch += 0x00C0; break; case 0x003A: ch = 0x7A; break; case 0x003B: ch = 0x5E; break; case 0x003C: ch = 0x4C; break; case 0x003D: ch = 0x7E; break; case 0x003E: ch = 0x6E; break; case 0x003F: ch = 0x6F; break; case 0x0040: ch = 0xAE; break; case 0x0041: case 0x0042: case 0x0043: case 0x0044: case 0x0045: case 0x0046: case 0x0047: case 0x0048: case 0x0049: ch += 0x0080; break; case 0x004A: case 0x004B: case 0x004C: case 0x004D: case 0x004E: case 0x004F: case 0x0050: case 0x0051: case 0x0052: ch += 0x0087; break; case 0x0053: case 0x0054: case 0x0055: case 0x0056: case 0x0057: case 0x0058: case 0x0059: case 0x005A: ch += 0x008F; break; case 0x005B: ch = 0x68; break; case 0x005C: ch = 0xDC; break; case 0x005D: ch = 0xAC; break; case 0x005E: ch = 0x5F; break; case 0x005F: ch = 0x6D; break; case 0x0060: ch = 0x8D; break; case 0x0061: case 0x0062: case 0x0063: case 0x0064: case 0x0065: case 0x0066: case 0x0067: case 0x0068: case 0x0069: ch += 0x0020; break; case 0x006A: case 0x006B: case 0x006C: case 0x006D: case 0x006E: case 0x006F: case 0x0070: case 0x0071: case 0x0072: ch += 0x0027; break; case 0x0073: case 0x0074: case 0x0075: case 0x0076: case 0x0077: case 0x0078: case 0x0079: case 0x007A: ch += 0x002F; break; case 0x007B: ch = 0x48; break; case 0x007C: ch = 0xBB; break; case 0x007D: ch = 0x8C; break; case 0x007E: ch = 0xCC; break; case 0x007F: ch = 0x07; break; case 0x0080: case 0x0081: case 0x0082: case 0x0083: case 0x0084: ch -= 0x0060; break; case 0x0085: ch = 0x15; break; case 0x0086: ch = 0x06; break; case 0x0087: ch = 0x17; break; case 0x0088: case 0x0089: case 0x008A: case 0x008B: case 0x008C: ch -= 0x0060; break; case 0x008D: ch = 0x09; break; case 0x008E: ch = 0x0A; break; case 0x008F: ch = 0x1B; break; case 0x0090: ch = 0x30; break; case 0x0091: ch = 0x31; break; case 0x0092: ch = 0x1A; break; case 0x0093: case 0x0094: case 0x0095: case 0x0096: ch -= 0x0060; break; case 0x0097: ch = 0x08; break; case 0x0098: case 0x0099: case 0x009A: case 0x009B: ch -= 0x0060; break; case 0x009C: ch = 0x04; break; case 0x009D: ch = 0x14; break; case 0x009E: ch = 0x3E; break; case 0x009F: ch = 0xFF; break; case 0x00A0: ch = 0x41; break; case 0x00A1: ch = 0xAA; break; case 0x00A2: ch = 0xB0; break; case 0x00A3: ch = 0xB1; break; case 0x00A4: ch = 0x9F; break; case 0x00A5: ch = 0xB2; break; case 0x00A6: ch = 0x8E; break; case 0x00A7: ch = 0xB5; break; case 0x00A8: ch = 0xBD; break; case 0x00A9: ch = 0xB4; break; case 0x00AA: ch = 0x9A; break; case 0x00AB: ch = 0x8A; break; case 0x00AC: ch = 0xBA; break; case 0x00AD: ch = 0xCA; break; case 0x00AE: ch = 0xAF; break; case 0x00AF: ch = 0xBC; break; case 0x00B0: ch = 0x90; break; case 0x00B1: ch = 0x8F; break; case 0x00B2: ch = 0xEA; break; case 0x00B3: ch = 0xFA; break; case 0x00B4: ch = 0xBE; break; case 0x00B5: ch = 0xA0; break; case 0x00B7: ch = 0xB3; break; case 0x00B8: ch = 0x9D; break; case 0x00B9: ch = 0xDA; break; case 0x00BA: ch = 0x9B; break; case 0x00BB: ch = 0x8B; break; case 0x00BC: ch = 0xB7; break; case 0x00BD: ch = 0xB8; break; case 0x00BE: ch = 0xB9; break; case 0x00BF: ch = 0xAB; break; case 0x00C0: ch = 0x64; break; case 0x00C1: ch = 0x65; break; case 0x00C2: ch = 0x62; break; case 0x00C3: ch = 0x66; break; case 0x00C4: ch = 0x63; break; case 0x00C5: ch = 0x67; break; case 0x00C6: ch = 0x9E; break; case 0x00C7: ch = 0x4A; break; case 0x00C8: ch = 0x74; break; case 0x00C9: ch = 0x71; break; case 0x00CA: ch = 0x72; break; case 0x00CB: ch = 0x73; break; case 0x00CC: ch = 0x78; break; case 0x00CD: ch = 0x75; break; case 0x00CE: ch = 0x76; break; case 0x00CF: ch = 0x77; break; case 0x00D1: ch = 0x69; break; case 0x00D2: ch = 0xED; break; case 0x00D3: ch = 0xEE; break; case 0x00D4: ch = 0xEB; break; case 0x00D5: ch = 0xEF; break; case 0x00D6: ch = 0x7B; break; case 0x00D7: ch = 0xBF; break; case 0x00D8: ch = 0x80; break; case 0x00D9: ch = 0xFD; break; case 0x00DA: ch = 0xFE; break; case 0x00DB: ch = 0xFB; break; case 0x00DC: ch = 0x7F; break; case 0x00DF: ch = 0x59; break; case 0x00E0: ch = 0x44; break; case 0x00E1: ch = 0x45; break; case 0x00E2: ch = 0x42; break; case 0x00E3: ch = 0x46; break; case 0x00E4: ch = 0x43; break; case 0x00E5: ch = 0x47; break; case 0x00E6: ch = 0x9C; break; case 0x00E7: ch = 0xC0; break; case 0x00E8: ch = 0x54; break; case 0x00E9: ch = 0x51; break; case 0x00EA: ch = 0x52; break; case 0x00EB: ch = 0x53; break; case 0x00EC: ch = 0x58; break; case 0x00ED: ch = 0x55; break; case 0x00EE: ch = 0x56; break; case 0x00EF: ch = 0x57; break; case 0x00F1: ch = 0x49; break; case 0x00F2: ch = 0xCD; break; case 0x00F3: ch = 0xCE; break; case 0x00F4: ch = 0xCB; break; case 0x00F5: ch = 0xCF; break; case 0x00F6: ch = 0xA1; break; case 0x00F7: ch = 0xE1; break; case 0x00F8: ch = 0x70; break; case 0x00F9: ch = 0xDD; break; case 0x00FA: ch = 0xDE; break; case 0x00FB: ch = 0xDB; break; case 0x00FC: ch = 0xE0; break; case 0x00FF: ch = 0xDF; break; case 0x011E: ch = 0x5A; break; case 0x011F: ch = 0xD0; break; case 0x0130: ch = 0x5B; break; case 0x0131: ch = 0x79; break; case 0x015E: ch = 0x7C; break; case 0x015F: ch = 0x6A; break; case 0x203E: ch = 0xBC; break; case 0xFF01: ch = 0x4F; break; case 0xFF02: ch = 0xFC; break; case 0xFF03: ch = 0xEC; break; case 0xFF04: ch = 0xAD; break; case 0xFF05: ch = 0x6C; break; case 0xFF06: ch = 0x50; break; case 0xFF07: ch = 0x7D; break; case 0xFF08: ch = 0x4D; break; case 0xFF09: ch = 0x5D; break; case 0xFF0A: ch = 0x5C; break; case 0xFF0B: ch = 0x4E; break; case 0xFF0C: ch = 0x6B; break; case 0xFF0D: ch = 0x60; break; case 0xFF0E: ch = 0x4B; break; case 0xFF0F: ch = 0x61; break; case 0xFF10: case 0xFF11: case 0xFF12: case 0xFF13: case 0xFF14: case 0xFF15: case 0xFF16: case 0xFF17: case 0xFF18: case 0xFF19: ch -= 0xFE20; break; case 0xFF1A: ch = 0x7A; break; case 0xFF1B: ch = 0x5E; break; case 0xFF1C: ch = 0x4C; break; case 0xFF1D: ch = 0x7E; break; case 0xFF1E: ch = 0x6E; break; case 0xFF1F: ch = 0x6F; break; case 0xFF20: ch = 0xAE; break; case 0xFF21: case 0xFF22: case 0xFF23: case 0xFF24: case 0xFF25: case 0xFF26: case 0xFF27: case 0xFF28: case 0xFF29: ch -= 0xFE60; break; case 0xFF2A: case 0xFF2B: case 0xFF2C: case 0xFF2D: case 0xFF2E: case 0xFF2F: case 0xFF30: case 0xFF31: case 0xFF32: ch -= 0xFE59; break; case 0xFF33: case 0xFF34: case 0xFF35: case 0xFF36: case 0xFF37: case 0xFF38: case 0xFF39: case 0xFF3A: ch -= 0xFE51; break; case 0xFF3B: ch = 0x68; break; case 0xFF3C: ch = 0xDC; break; case 0xFF3D: ch = 0xAC; break; case 0xFF3E: ch = 0x5F; break; case 0xFF3F: ch = 0x6D; break; case 0xFF40: ch = 0x8D; break; case 0xFF41: case 0xFF42: case 0xFF43: case 0xFF44: case 0xFF45: case 0xFF46: case 0xFF47: case 0xFF48: case 0xFF49: ch -= 0xFEC0; break; case 0xFF4A: case 0xFF4B: case 0xFF4C: case 0xFF4D: case 0xFF4E: case 0xFF4F: case 0xFF50: case 0xFF51: case 0xFF52: ch -= 0xFEB9; break; case 0xFF53: case 0xFF54: case 0xFF55: case 0xFF56: case 0xFF57: case 0xFF58: case 0xFF59: case 0xFF5A: ch -= 0xFEB1; break; case 0xFF5B: ch = 0x48; break; case 0xFF5C: ch = 0xBB; break; case 0xFF5D: ch = 0x8C; break; case 0xFF5E: ch = 0xCC; break; default: ch = 0x3F; break; } bytes[byteIndex++] = (byte)ch; --charCount; } } protected override void ToBytes(String s, int charIndex, int charCount, byte[] bytes, int byteIndex) { int ch; while(charCount > 0) { ch = (int)(s[charIndex++]); if(ch >= 4) switch(ch) { case 0x000B: case 0x000C: case 0x000D: case 0x000E: case 0x000F: case 0x0010: case 0x0011: case 0x0012: case 0x0013: case 0x0018: case 0x0019: case 0x001C: case 0x001D: case 0x001E: case 0x001F: case 0x00B6: break; case 0x0004: ch = 0x37; break; case 0x0005: ch = 0x2D; break; case 0x0006: ch = 0x2E; break; case 0x0007: ch = 0x2F; break; case 0x0008: ch = 0x16; break; case 0x0009: ch = 0x05; break; case 0x000A: ch = 0x25; break; case 0x0014: ch = 0x3C; break; case 0x0015: ch = 0x3D; break; case 0x0016: ch = 0x32; break; case 0x0017: ch = 0x26; break; case 0x001A: ch = 0x3F; break; case 0x001B: ch = 0x27; break; case 0x0020: ch = 0x40; break; case 0x0021: ch = 0x4F; break; case 0x0022: ch = 0xFC; break; case 0x0023: ch = 0xEC; break; case 0x0024: ch = 0xAD; break; case 0x0025: ch = 0x6C; break; case 0x0026: ch = 0x50; break; case 0x0027: ch = 0x7D; break; case 0x0028: ch = 0x4D; break; case 0x0029: ch = 0x5D; break; case 0x002A: ch = 0x5C; break; case 0x002B: ch = 0x4E; break; case 0x002C: ch = 0x6B; break; case 0x002D: ch = 0x60; break; case 0x002E: ch = 0x4B; break; case 0x002F: ch = 0x61; break; case 0x0030: case 0x0031: case 0x0032: case 0x0033: case 0x0034: case 0x0035: case 0x0036: case 0x0037: case 0x0038: case 0x0039: ch += 0x00C0; break; case 0x003A: ch = 0x7A; break; case 0x003B: ch = 0x5E; break; case 0x003C: ch = 0x4C; break; case 0x003D: ch = 0x7E; break; case 0x003E: ch = 0x6E; break; case 0x003F: ch = 0x6F; break; case 0x0040: ch = 0xAE; break; case 0x0041: case 0x0042: case 0x0043: case 0x0044: case 0x0045: case 0x0046: case 0x0047: case 0x0048: case 0x0049: ch += 0x0080; break; case 0x004A: case 0x004B: case 0x004C: case 0x004D: case 0x004E: case 0x004F: case 0x0050: case 0x0051: case 0x0052: ch += 0x0087; break; case 0x0053: case 0x0054: case 0x0055: case 0x0056: case 0x0057: case 0x0058: case 0x0059: case 0x005A: ch += 0x008F; break; case 0x005B: ch = 0x68; break; case 0x005C: ch = 0xDC; break; case 0x005D: ch = 0xAC; break; case 0x005E: ch = 0x5F; break; case 0x005F: ch = 0x6D; break; case 0x0060: ch = 0x8D; break; case 0x0061: case 0x0062: case 0x0063: case 0x0064: case 0x0065: case 0x0066: case 0x0067: case 0x0068: case 0x0069: ch += 0x0020; break; case 0x006A: case 0x006B: case 0x006C: case 0x006D: case 0x006E: case 0x006F: case 0x0070: case 0x0071: case 0x0072: ch += 0x0027; break; case 0x0073: case 0x0074: case 0x0075: case 0x0076: case 0x0077: case 0x0078: case 0x0079: case 0x007A: ch += 0x002F; break; case 0x007B: ch = 0x48; break; case 0x007C: ch = 0xBB; break; case 0x007D: ch = 0x8C; break; case 0x007E: ch = 0xCC; break; case 0x007F: ch = 0x07; break; case 0x0080: case 0x0081: case 0x0082: case 0x0083: case 0x0084: ch -= 0x0060; break; case 0x0085: ch = 0x15; break; case 0x0086: ch = 0x06; break; case 0x0087: ch = 0x17; break; case 0x0088: case 0x0089: case 0x008A: case 0x008B: case 0x008C: ch -= 0x0060; break; case 0x008D: ch = 0x09; break; case 0x008E: ch = 0x0A; break; case 0x008F: ch = 0x1B; break; case 0x0090: ch = 0x30; break; case 0x0091: ch = 0x31; break; case 0x0092: ch = 0x1A; break; case 0x0093: case 0x0094: case 0x0095: case 0x0096: ch -= 0x0060; break; case 0x0097: ch = 0x08; break; case 0x0098: case 0x0099: case 0x009A: case 0x009B: ch -= 0x0060; break; case 0x009C: ch = 0x04; break; case 0x009D: ch = 0x14; break; case 0x009E: ch = 0x3E; break; case 0x009F: ch = 0xFF; break; case 0x00A0: ch = 0x41; break; case 0x00A1: ch = 0xAA; break; case 0x00A2: ch = 0xB0; break; case 0x00A3: ch = 0xB1; break; case 0x00A4: ch = 0x9F; break; case 0x00A5: ch = 0xB2; break; case 0x00A6: ch = 0x8E; break; case 0x00A7: ch = 0xB5; break; case 0x00A8: ch = 0xBD; break; case 0x00A9: ch = 0xB4; break; case 0x00AA: ch = 0x9A; break; case 0x00AB: ch = 0x8A; break; case 0x00AC: ch = 0xBA; break; case 0x00AD: ch = 0xCA; break; case 0x00AE: ch = 0xAF; break; case 0x00AF: ch = 0xBC; break; case 0x00B0: ch = 0x90; break; case 0x00B1: ch = 0x8F; break; case 0x00B2: ch = 0xEA; break; case 0x00B3: ch = 0xFA; break; case 0x00B4: ch = 0xBE; break; case 0x00B5: ch = 0xA0; break; case 0x00B7: ch = 0xB3; break; case 0x00B8: ch = 0x9D; break; case 0x00B9: ch = 0xDA; break; case 0x00BA: ch = 0x9B; break; case 0x00BB: ch = 0x8B; break; case 0x00BC: ch = 0xB7; break; case 0x00BD: ch = 0xB8; break; case 0x00BE: ch = 0xB9; break; case 0x00BF: ch = 0xAB; break; case 0x00C0: ch = 0x64; break; case 0x00C1: ch = 0x65; break; case 0x00C2: ch = 0x62; break; case 0x00C3: ch = 0x66; break; case 0x00C4: ch = 0x63; break; case 0x00C5: ch = 0x67; break; case 0x00C6: ch = 0x9E; break; case 0x00C7: ch = 0x4A; break; case 0x00C8: ch = 0x74; break; case 0x00C9: ch = 0x71; break; case 0x00CA: ch = 0x72; break; case 0x00CB: ch = 0x73; break; case 0x00CC: ch = 0x78; break; case 0x00CD: ch = 0x75; break; case 0x00CE: ch = 0x76; break; case 0x00CF: ch = 0x77; break; case 0x00D1: ch = 0x69; break; case 0x00D2: ch = 0xED; break; case 0x00D3: ch = 0xEE; break; case 0x00D4: ch = 0xEB; break; case 0x00D5: ch = 0xEF; break; case 0x00D6: ch = 0x7B; break; case 0x00D7: ch = 0xBF; break; case 0x00D8: ch = 0x80; break; case 0x00D9: ch = 0xFD; break; case 0x00DA: ch = 0xFE; break; case 0x00DB: ch = 0xFB; break; case 0x00DC: ch = 0x7F; break; case 0x00DF: ch = 0x59; break; case 0x00E0: ch = 0x44; break; case 0x00E1: ch = 0x45; break; case 0x00E2: ch = 0x42; break; case 0x00E3: ch = 0x46; break; case 0x00E4: ch = 0x43; break; case 0x00E5: ch = 0x47; break; case 0x00E6: ch = 0x9C; break; case 0x00E7: ch = 0xC0; break; case 0x00E8: ch = 0x54; break; case 0x00E9: ch = 0x51; break; case 0x00EA: ch = 0x52; break; case 0x00EB: ch = 0x53; break; case 0x00EC: ch = 0x58; break; case 0x00ED: ch = 0x55; break; case 0x00EE: ch = 0x56; break; case 0x00EF: ch = 0x57; break; case 0x00F1: ch = 0x49; break; case 0x00F2: ch = 0xCD; break; case 0x00F3: ch = 0xCE; break; case 0x00F4: ch = 0xCB; break; case 0x00F5: ch = 0xCF; break; case 0x00F6: ch = 0xA1; break; case 0x00F7: ch = 0xE1; break; case 0x00F8: ch = 0x70; break; case 0x00F9: ch = 0xDD; break; case 0x00FA: ch = 0xDE; break; case 0x00FB: ch = 0xDB; break; case 0x00FC: ch = 0xE0; break; case 0x00FF: ch = 0xDF; break; case 0x011E: ch = 0x5A; break; case 0x011F: ch = 0xD0; break; case 0x0130: ch = 0x5B; break; case 0x0131: ch = 0x79; break; case 0x015E: ch = 0x7C; break; case 0x015F: ch = 0x6A; break; case 0x203E: ch = 0xBC; break; case 0xFF01: ch = 0x4F; break; case 0xFF02: ch = 0xFC; break; case 0xFF03: ch = 0xEC; break; case 0xFF04: ch = 0xAD; break; case 0xFF05: ch = 0x6C; break; case 0xFF06: ch = 0x50; break; case 0xFF07: ch = 0x7D; break; case 0xFF08: ch = 0x4D; break; case 0xFF09: ch = 0x5D; break; case 0xFF0A: ch = 0x5C; break; case 0xFF0B: ch = 0x4E; break; case 0xFF0C: ch = 0x6B; break; case 0xFF0D: ch = 0x60; break; case 0xFF0E: ch = 0x4B; break; case 0xFF0F: ch = 0x61; break; case 0xFF10: case 0xFF11: case 0xFF12: case 0xFF13: case 0xFF14: case 0xFF15: case 0xFF16: case 0xFF17: case 0xFF18: case 0xFF19: ch -= 0xFE20; break; case 0xFF1A: ch = 0x7A; break; case 0xFF1B: ch = 0x5E; break; case 0xFF1C: ch = 0x4C; break; case 0xFF1D: ch = 0x7E; break; case 0xFF1E: ch = 0x6E; break; case 0xFF1F: ch = 0x6F; break; case 0xFF20: ch = 0xAE; break; case 0xFF21: case 0xFF22: case 0xFF23: case 0xFF24: case 0xFF25: case 0xFF26: case 0xFF27: case 0xFF28: case 0xFF29: ch -= 0xFE60; break; case 0xFF2A: case 0xFF2B: case 0xFF2C: case 0xFF2D: case 0xFF2E: case 0xFF2F: case 0xFF30: case 0xFF31: case 0xFF32: ch -= 0xFE59; break; case 0xFF33: case 0xFF34: case 0xFF35: case 0xFF36: case 0xFF37: case 0xFF38: case 0xFF39: case 0xFF3A: ch -= 0xFE51; break; case 0xFF3B: ch = 0x68; break; case 0xFF3C: ch = 0xDC; break; case 0xFF3D: ch = 0xAC; break; case 0xFF3E: ch = 0x5F; break; case 0xFF3F: ch = 0x6D; break; case 0xFF40: ch = 0x8D; break; case 0xFF41: case 0xFF42: case 0xFF43: case 0xFF44: case 0xFF45: case 0xFF46: case 0xFF47: case 0xFF48: case 0xFF49: ch -= 0xFEC0; break; case 0xFF4A: case 0xFF4B: case 0xFF4C: case 0xFF4D: case 0xFF4E: case 0xFF4F: case 0xFF50: case 0xFF51: case 0xFF52: ch -= 0xFEB9; break; case 0xFF53: case 0xFF54: case 0xFF55: case 0xFF56: case 0xFF57: case 0xFF58: case 0xFF59: case 0xFF5A: ch -= 0xFEB1; break; case 0xFF5B: ch = 0x48; break; case 0xFF5C: ch = 0xBB; break; case 0xFF5D: ch = 0x8C; break; case 0xFF5E: ch = 0xCC; break; default: ch = 0x3F; break; } bytes[byteIndex++] = (byte)ch; --charCount; } } }; // class CP20905 public class ENCibm905 : CP20905 { public ENCibm905() : base() {} }; // class ENCibm905 }; // namespace I18N.Rare
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Concurrent; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.Isam.Esent; using Microsoft.Isam.Esent.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Esent { internal partial class EsentPersistentStorage : AbstractPersistentStorage { private const string StorageExtension = "vbcs.cache"; private const string PersistentStorageFileName = "storage.ide"; private readonly ConcurrentDictionary<string, int> _nameTableCache; private readonly EsentStorage _esentStorage; public EsentPersistentStorage( IOptionService optionService, string workingFolderPath, string solutionFilePath, Action<AbstractPersistentStorage> disposer) : base(optionService, workingFolderPath, solutionFilePath, disposer) { // solution must exist in disk. otherwise, we shouldn't be here at all. Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(solutionFilePath)); var databaseFile = GetDatabaseFile(workingFolderPath); this.EsentDirectory = Path.GetDirectoryName(databaseFile); if (!Directory.Exists(this.EsentDirectory)) { Directory.CreateDirectory(this.EsentDirectory); } _nameTableCache = new ConcurrentDictionary<string, int>(StringComparer.OrdinalIgnoreCase); var enablePerformanceMonitor = optionService.GetOption(InternalFeatureOnOffOptions.EsentPerformanceMonitor); _esentStorage = new EsentStorage(databaseFile, enablePerformanceMonitor); } public static string GetDatabaseFile(string workingFolderPath) { Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(workingFolderPath)); return Path.Combine(workingFolderPath, StorageExtension, PersistentStorageFileName); } public void Initialize() { _esentStorage.Initialize(); } public string EsentDirectory { get; } public override Task<Stream> ReadStreamAsync(Document document, string name, CancellationToken cancellationToken = default(CancellationToken)) { Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(name)); if (!PersistenceEnabled) { return SpecializedTasks.Default<Stream>(); } int nameId; EsentStorage.Key key; if (!TryGetProjectAndDocumentKey(document, out key) || !TryGetUniqueNameId(name, out nameId)) { return SpecializedTasks.Default<Stream>(); } var stream = EsentExceptionWrapper(key, nameId, ReadStream, cancellationToken); return Task.FromResult(stream); } public override Task<Stream> ReadStreamAsync(Project project, string name, CancellationToken cancellationToken = default(CancellationToken)) { Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(name)); if (!PersistenceEnabled) { return SpecializedTasks.Default<Stream>(); } int nameId; EsentStorage.Key key; if (!TryGetProjectKey(project, out key) || !TryGetUniqueNameId(name, out nameId)) { return SpecializedTasks.Default<Stream>(); } var stream = EsentExceptionWrapper(key, nameId, ReadStream, cancellationToken); return Task.FromResult(stream); } public override Task<Stream> ReadStreamAsync(string name, CancellationToken cancellationToken = default(CancellationToken)) { Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(name)); if (!PersistenceEnabled) { return SpecializedTasks.Default<Stream>(); } int nameId; if (!TryGetUniqueNameId(name, out nameId)) { return SpecializedTasks.Default<Stream>(); } var stream = EsentExceptionWrapper(nameId, ReadStream, cancellationToken); return Task.FromResult(stream); } private Stream ReadStream(EsentStorage.Key key, int nameId, object unused1, object unused2, CancellationToken cancellationToken) { using (var accessor = GetAccessor(key)) using (var esentStream = accessor.GetReadStream(key, nameId)) { if (esentStream == null) { return null; } // this will copy over esent stream and let it go. return SerializableBytes.CreateReadableStream(esentStream, cancellationToken); } } private Stream ReadStream(int nameId, object unused1, object unused2, object unused3, CancellationToken cancellationToken) { using (var accessor = _esentStorage.GetSolutionTableAccessor()) using (var esentStream = accessor.GetReadStream(nameId)) { if (esentStream == null) { return null; } // this will copy over esent stream and let it go. return SerializableBytes.CreateReadableStream(esentStream, cancellationToken); } } public override Task<bool> WriteStreamAsync(Document document, string name, Stream stream, CancellationToken cancellationToken = default(CancellationToken)) { Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(name)); Contract.ThrowIfNull(stream); if (!PersistenceEnabled) { return SpecializedTasks.False; } int nameId; EsentStorage.Key key; if (!TryGetProjectAndDocumentKey(document, out key) || !TryGetUniqueNameId(name, out nameId)) { return SpecializedTasks.False; } var success = EsentExceptionWrapper(key, nameId, stream, WriteStream, cancellationToken); return success ? SpecializedTasks.True : SpecializedTasks.False; } public override Task<bool> WriteStreamAsync(Project project, string name, Stream stream, CancellationToken cancellationToken = default(CancellationToken)) { Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(name)); Contract.ThrowIfNull(stream); if (!PersistenceEnabled) { return SpecializedTasks.False; } int nameId; EsentStorage.Key key; if (!TryGetProjectKey(project, out key) || !TryGetUniqueNameId(name, out nameId)) { return SpecializedTasks.False; } var success = EsentExceptionWrapper(key, nameId, stream, WriteStream, cancellationToken); return success ? SpecializedTasks.True : SpecializedTasks.False; } public override Task<bool> WriteStreamAsync(string name, Stream stream, CancellationToken cancellationToken = default(CancellationToken)) { Contract.ThrowIfTrue(string.IsNullOrWhiteSpace(name)); Contract.ThrowIfNull(stream); if (!PersistenceEnabled) { return SpecializedTasks.False; } int nameId; if (!TryGetUniqueNameId(name, out nameId)) { return SpecializedTasks.False; } var success = EsentExceptionWrapper(nameId, stream, WriteStream, cancellationToken); return success ? SpecializedTasks.True : SpecializedTasks.False; } private bool WriteStream(EsentStorage.Key key, int nameId, Stream stream, object unused1, CancellationToken cancellationToken) { using (var accessor = GetAccessor(key)) using (var esentStream = accessor.GetWriteStream(key, nameId)) { WriteToStream(stream, esentStream, cancellationToken); return accessor.ApplyChanges(); } } private bool WriteStream(int nameId, Stream stream, object unused1, object unused2, CancellationToken cancellationToken) { using (var accessor = _esentStorage.GetSolutionTableAccessor()) using (var esentStream = accessor.GetWriteStream(nameId)) { WriteToStream(stream, esentStream, cancellationToken); return accessor.ApplyChanges(); } } public override void Close() { _esentStorage.Close(); } private bool TryGetUniqueNameId(string name, out int id) { return TryGetUniqueId(name, false, out id); } private bool TryGetUniqueFileId(string path, out int id) { return TryGetUniqueId(path, true, out id); } private bool TryGetUniqueId(string value, bool fileCheck, out int id) { id = default(int); if (string.IsNullOrWhiteSpace(value)) { return false; } // if we already know, get the id if (_nameTableCache.TryGetValue(value, out id)) { return true; } // we only persist for things that actually exist if (fileCheck && !File.Exists(value)) { return false; } try { var uniqueIdValue = fileCheck ? FilePathUtilities.GetRelativePath(Path.GetDirectoryName(SolutionFilePath), value) : value; id = _nameTableCache.GetOrAdd(value, _esentStorage.GetUniqueId(uniqueIdValue)); return true; } catch (Exception ex) { // if we get fatal errors from esent such as disk out of space or log file corrupted by other process and etc // don't crash VS, but let VS know it can't use esent. we will gracefully recover issue by using memory. EsentLogger.LogException(ex); return false; } } private static void WriteToStream(Stream inputStream, Stream esentStream, CancellationToken cancellationToken) { var buffer = SharedPools.ByteArray.Allocate(); try { int bytesRead; do { cancellationToken.ThrowIfCancellationRequested(); bytesRead = inputStream.Read(buffer, 0, buffer.Length); if (bytesRead > 0) { esentStream.Write(buffer, 0, bytesRead); } } while (bytesRead > 0); // flush the data and trim column size of necessary esentStream.Flush(); } finally { SharedPools.ByteArray.Free(buffer); } } private EsentStorage.ProjectDocumentTableAccessor GetAccessor(EsentStorage.Key key) { return key.DocumentIdOpt.HasValue ? _esentStorage.GetDocumentTableAccessor() : (EsentStorage.ProjectDocumentTableAccessor)_esentStorage.GetProjectTableAccessor(); } private bool TryGetProjectAndDocumentKey(Document document, out EsentStorage.Key key) { key = default(EsentStorage.Key); int projectId; int projectNameId; int documentId; if (!TryGetProjectId(document.Project, out projectId, out projectNameId) || !TryGetUniqueFileId(document.FilePath, out documentId)) { return false; } key = new EsentStorage.Key(projectId, projectNameId, documentId); return true; } private bool TryGetProjectKey(Project project, out EsentStorage.Key key) { key = default(EsentStorage.Key); int projectId; int projectNameId; if (!TryGetProjectId(project, out projectId, out projectNameId)) { return false; } key = new EsentStorage.Key(projectId, projectNameId); return true; } private bool TryGetProjectId(Project project, out int projectId, out int projectNameId) { projectId = default(int); projectNameId = default(int); return TryGetUniqueFileId(project.FilePath, out projectId) && TryGetUniqueNameId(project.Name, out projectNameId); } private TResult EsentExceptionWrapper<TArg1, TResult>(TArg1 arg1, Func<TArg1, object, object, object, CancellationToken, TResult> func, CancellationToken cancellationToken) { return EsentExceptionWrapper(arg1, (object)null, func, cancellationToken); } private TResult EsentExceptionWrapper<TArg1, TArg2, TResult>( TArg1 arg1, TArg2 arg2, Func<TArg1, TArg2, object, object, CancellationToken, TResult> func, CancellationToken cancellationToken) { return EsentExceptionWrapper(arg1, arg2, (object)null, func, cancellationToken); } private TResult EsentExceptionWrapper<TArg1, TArg2, TArg3, TResult>( TArg1 arg1, TArg2 arg2, TArg3 arg3, Func<TArg1, TArg2, TArg3, object, CancellationToken, TResult> func, CancellationToken cancellationToken) { return EsentExceptionWrapper(arg1, arg2, arg3, (object)null, func, cancellationToken); } private TResult EsentExceptionWrapper<TArg1, TArg2, TArg3, TArg4, TResult>( TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, Func<TArg1, TArg2, TArg3, TArg4, CancellationToken, TResult> func, CancellationToken cancellationToken) { try { return func(arg1, arg2, arg3, arg4, cancellationToken); } catch (EsentInvalidSesidException) { // operation was in-fly when Esent instance was shutdown - ignore the error } catch (OperationCanceledException) { } catch (EsentException ex) { if (!_esentStorage.IsClosed) { // ignore esent exception if underlying storage was closed // there is not much we can do here. // internally we use it as a way to cache information between sessions anyway. // no functionality will be affected by this except perf Logger.Log(FunctionId.PersistenceService_WriteAsyncFailed, "Esent Failed : " + ex.Message); } } catch (Exception ex) { // ignore exception // there is not much we can do here. // internally we use it as a way to cache information between sessions anyway. // no functionality will be affected by this except perf Logger.Log(FunctionId.PersistenceService_WriteAsyncFailed, "Failed : " + ex.Message); } return default(TResult); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: tenancy_config/rpc/tax_exempt_category_svc.proto #pragma warning disable 1591 #region Designer generated code using System; using System.Threading; using System.Threading.Tasks; using grpc = global::Grpc.Core; namespace HOLMS.Types.TenancyConfig.RPC { public static partial class TaxExemptCategorySvc { static readonly string __ServiceName = "holms.types.tenancy_config.rpc.TaxExemptCategorySvc"; static readonly grpc::Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.TenancyConfig.RPC.TaxExemptCategorySvcAllResponse> __Marshaller_TaxExemptCategorySvcAllResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.TenancyConfig.RPC.TaxExemptCategorySvcAllResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.TenancyConfig.Indicators.TaxExemptCategoryIndicator> __Marshaller_TaxExemptCategoryIndicator = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.TenancyConfig.Indicators.TaxExemptCategoryIndicator.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.TenancyConfig.TaxExemptCategory> __Marshaller_TaxExemptCategory = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.TenancyConfig.TaxExemptCategory.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Primitive.ServerActionConfirmation> __Marshaller_ServerActionConfirmation = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Primitive.ServerActionConfirmation.Parser.ParseFrom); static readonly grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::HOLMS.Types.TenancyConfig.RPC.TaxExemptCategorySvcAllResponse> __Method_All = new grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::HOLMS.Types.TenancyConfig.RPC.TaxExemptCategorySvcAllResponse>( grpc::MethodType.Unary, __ServiceName, "All", __Marshaller_Empty, __Marshaller_TaxExemptCategorySvcAllResponse); static readonly grpc::Method<global::HOLMS.Types.TenancyConfig.Indicators.TaxExemptCategoryIndicator, global::HOLMS.Types.TenancyConfig.TaxExemptCategory> __Method_GetById = new grpc::Method<global::HOLMS.Types.TenancyConfig.Indicators.TaxExemptCategoryIndicator, global::HOLMS.Types.TenancyConfig.TaxExemptCategory>( grpc::MethodType.Unary, __ServiceName, "GetById", __Marshaller_TaxExemptCategoryIndicator, __Marshaller_TaxExemptCategory); static readonly grpc::Method<global::HOLMS.Types.TenancyConfig.TaxExemptCategory, global::HOLMS.Types.TenancyConfig.TaxExemptCategory> __Method_Create = new grpc::Method<global::HOLMS.Types.TenancyConfig.TaxExemptCategory, global::HOLMS.Types.TenancyConfig.TaxExemptCategory>( grpc::MethodType.Unary, __ServiceName, "Create", __Marshaller_TaxExemptCategory, __Marshaller_TaxExemptCategory); static readonly grpc::Method<global::HOLMS.Types.TenancyConfig.TaxExemptCategory, global::HOLMS.Types.TenancyConfig.TaxExemptCategory> __Method_Update = new grpc::Method<global::HOLMS.Types.TenancyConfig.TaxExemptCategory, global::HOLMS.Types.TenancyConfig.TaxExemptCategory>( grpc::MethodType.Unary, __ServiceName, "Update", __Marshaller_TaxExemptCategory, __Marshaller_TaxExemptCategory); static readonly grpc::Method<global::HOLMS.Types.TenancyConfig.TaxExemptCategory, global::HOLMS.Types.Primitive.ServerActionConfirmation> __Method_Delete = new grpc::Method<global::HOLMS.Types.TenancyConfig.TaxExemptCategory, global::HOLMS.Types.Primitive.ServerActionConfirmation>( grpc::MethodType.Unary, __ServiceName, "Delete", __Marshaller_TaxExemptCategory, __Marshaller_ServerActionConfirmation); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::HOLMS.Types.TenancyConfig.RPC.TaxExemptCategorySvcReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of TaxExemptCategorySvc</summary> public abstract partial class TaxExemptCategorySvcBase { public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.TenancyConfig.RPC.TaxExemptCategorySvcAllResponse> All(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.TenancyConfig.TaxExemptCategory> GetById(global::HOLMS.Types.TenancyConfig.Indicators.TaxExemptCategoryIndicator request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.TenancyConfig.TaxExemptCategory> Create(global::HOLMS.Types.TenancyConfig.TaxExemptCategory request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.TenancyConfig.TaxExemptCategory> Update(global::HOLMS.Types.TenancyConfig.TaxExemptCategory request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Primitive.ServerActionConfirmation> Delete(global::HOLMS.Types.TenancyConfig.TaxExemptCategory request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } } /// <summary>Client for TaxExemptCategorySvc</summary> public partial class TaxExemptCategorySvcClient : grpc::ClientBase<TaxExemptCategorySvcClient> { /// <summary>Creates a new client for TaxExemptCategorySvc</summary> /// <param name="channel">The channel to use to make remote calls.</param> public TaxExemptCategorySvcClient(grpc::Channel channel) : base(channel) { } /// <summary>Creates a new client for TaxExemptCategorySvc that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public TaxExemptCategorySvcClient(grpc::CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected TaxExemptCategorySvcClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected TaxExemptCategorySvcClient(ClientBaseConfiguration configuration) : base(configuration) { } public virtual global::HOLMS.Types.TenancyConfig.RPC.TaxExemptCategorySvcAllResponse All(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return All(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.TenancyConfig.RPC.TaxExemptCategorySvcAllResponse All(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_All, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.TenancyConfig.RPC.TaxExemptCategorySvcAllResponse> AllAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return AllAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.TenancyConfig.RPC.TaxExemptCategorySvcAllResponse> AllAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_All, null, options, request); } public virtual global::HOLMS.Types.TenancyConfig.TaxExemptCategory GetById(global::HOLMS.Types.TenancyConfig.Indicators.TaxExemptCategoryIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetById(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.TenancyConfig.TaxExemptCategory GetById(global::HOLMS.Types.TenancyConfig.Indicators.TaxExemptCategoryIndicator request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetById, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.TenancyConfig.TaxExemptCategory> GetByIdAsync(global::HOLMS.Types.TenancyConfig.Indicators.TaxExemptCategoryIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetByIdAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.TenancyConfig.TaxExemptCategory> GetByIdAsync(global::HOLMS.Types.TenancyConfig.Indicators.TaxExemptCategoryIndicator request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetById, null, options, request); } public virtual global::HOLMS.Types.TenancyConfig.TaxExemptCategory Create(global::HOLMS.Types.TenancyConfig.TaxExemptCategory request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return Create(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.TenancyConfig.TaxExemptCategory Create(global::HOLMS.Types.TenancyConfig.TaxExemptCategory request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_Create, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.TenancyConfig.TaxExemptCategory> CreateAsync(global::HOLMS.Types.TenancyConfig.TaxExemptCategory request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CreateAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.TenancyConfig.TaxExemptCategory> CreateAsync(global::HOLMS.Types.TenancyConfig.TaxExemptCategory request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_Create, null, options, request); } public virtual global::HOLMS.Types.TenancyConfig.TaxExemptCategory Update(global::HOLMS.Types.TenancyConfig.TaxExemptCategory request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return Update(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.TenancyConfig.TaxExemptCategory Update(global::HOLMS.Types.TenancyConfig.TaxExemptCategory request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_Update, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.TenancyConfig.TaxExemptCategory> UpdateAsync(global::HOLMS.Types.TenancyConfig.TaxExemptCategory request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UpdateAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.TenancyConfig.TaxExemptCategory> UpdateAsync(global::HOLMS.Types.TenancyConfig.TaxExemptCategory request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_Update, null, options, request); } public virtual global::HOLMS.Types.Primitive.ServerActionConfirmation Delete(global::HOLMS.Types.TenancyConfig.TaxExemptCategory request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return Delete(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Primitive.ServerActionConfirmation Delete(global::HOLMS.Types.TenancyConfig.TaxExemptCategory request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_Delete, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Primitive.ServerActionConfirmation> DeleteAsync(global::HOLMS.Types.TenancyConfig.TaxExemptCategory request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DeleteAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Primitive.ServerActionConfirmation> DeleteAsync(global::HOLMS.Types.TenancyConfig.TaxExemptCategory request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_Delete, null, options, request); } /// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary> protected override TaxExemptCategorySvcClient NewInstance(ClientBaseConfiguration configuration) { return new TaxExemptCategorySvcClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> public static grpc::ServerServiceDefinition BindService(TaxExemptCategorySvcBase serviceImpl) { return grpc::ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_All, serviceImpl.All) .AddMethod(__Method_GetById, serviceImpl.GetById) .AddMethod(__Method_Create, serviceImpl.Create) .AddMethod(__Method_Update, serviceImpl.Update) .AddMethod(__Method_Delete, serviceImpl.Delete).Build(); } } } #endregion
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Threading; using Microsoft.Scripting.Utils; namespace Microsoft.Scripting.Runtime { /// <summary> /// Singleton for each language. /// </summary> internal sealed class LanguageConfiguration { private readonly IDictionary<string, object> _options; private LanguageContext _context; public LanguageContext LanguageContext => _context; public AssemblyQualifiedTypeName ProviderName { get; } public string DisplayName { get; } public LanguageConfiguration(AssemblyQualifiedTypeName providerName, string displayName, IDictionary<string, object> options) { ProviderName = providerName; DisplayName = displayName; _options = options; } /// <summary> /// Must not be called under a lock as it can potentially call a user code. /// </summary> /// <exception cref="InvalidImplementationException">The language context's implementation failed to instantiate.</exception> internal LanguageContext LoadLanguageContext(ScriptDomainManager domainManager, out bool alreadyLoaded) { if (_context == null) { // Let assembly load errors bubble out var assembly = domainManager.Platform.LoadAssembly(ProviderName.AssemblyName.FullName); Type type = assembly.GetType(ProviderName.TypeName); if (type == null) { throw new InvalidOperationException( String.Format( "Failed to load language '{0}': assembly '{1}' does not contain type '{2}'", DisplayName, #if FEATURE_FILESYSTEM assembly.Location, #else assembly.FullName, #endif ProviderName.TypeName )); } if (!type.IsSubclassOf(typeof(LanguageContext))) { throw new InvalidOperationException( $"Failed to load language '{DisplayName}': type '{type}' is not a valid language provider because it does not inherit from LanguageContext"); } LanguageContext context; try { context = (LanguageContext)Activator.CreateInstance(type, new object[] { domainManager, _options }); } catch (TargetInvocationException e) { throw new TargetInvocationException( $"Failed to load language '{DisplayName}': {e.InnerException.Message}", e.InnerException ); } catch (Exception e) { throw new InvalidImplementationException(Strings.InvalidCtorImplementation(type, e.Message), e); } alreadyLoaded = Interlocked.CompareExchange(ref _context, context, null) != null; } else { alreadyLoaded = true; } return _context; } } public sealed class DlrConfiguration { private bool _frozen; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly StringComparer FileExtensionComparer = StringComparer.OrdinalIgnoreCase; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly StringComparer LanguageNameComparer = StringComparer.OrdinalIgnoreCase; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly StringComparer OptionNameComparer = StringComparer.Ordinal; private readonly Dictionary<string, LanguageConfiguration> _languageNames; private readonly Dictionary<string, LanguageConfiguration> _languageExtensions; private readonly Dictionary<AssemblyQualifiedTypeName, LanguageConfiguration> _languageConfigurations; private readonly Dictionary<Type, LanguageConfiguration> _loadedProviderTypes; public DlrConfiguration(bool debugMode, bool privateBinding, IDictionary<string, object> options) { ContractUtils.RequiresNotNull(options, nameof(options)); DebugMode = debugMode; PrivateBinding = privateBinding; Options = options; _languageNames = new Dictionary<string, LanguageConfiguration>(LanguageNameComparer); _languageExtensions = new Dictionary<string, LanguageConfiguration>(FileExtensionComparer); _languageConfigurations = new Dictionary<AssemblyQualifiedTypeName, LanguageConfiguration>(); _loadedProviderTypes = new Dictionary<Type, LanguageConfiguration>(); } /// <summary> /// Gets a value indicating whether the application is in debug mode. /// This means: /// /// 1) Symbols are emitted for debuggable methods (methods associated with SourceUnit). /// 2) Debuggable methods are emitted to non-collectable types (this is due to CLR limitations on dynamic method debugging). /// 3) JIT optimization is disabled for all methods /// 4) Languages may disable optimizations based on this value. /// </summary> public bool DebugMode { get; } /// <summary> /// Ignore CLR visibility checks. /// </summary> public bool PrivateBinding { get; } internal IDictionary<string, object> Options { get; } internal IDictionary<AssemblyQualifiedTypeName, LanguageConfiguration> Languages => _languageConfigurations; public void AddLanguage(string languageTypeName, string displayName, IList<string> names, IList<string> fileExtensions, IDictionary<string, object> options) { AddLanguage(languageTypeName, displayName, names, fileExtensions, options, null); } internal void AddLanguage(string languageTypeName, string displayName, IList<string> names, IList<string> fileExtensions, IDictionary<string, object> options, string paramName) { ContractUtils.Requires(!_frozen, "Configuration cannot be modified once the runtime is initialized"); ContractUtils.Requires( names.TrueForAll((id) => !String.IsNullOrEmpty(id) && !_languageNames.ContainsKey(id)), paramName ?? "names", "Language name should not be null, empty or duplicated between languages" ); ContractUtils.Requires( fileExtensions.TrueForAll((ext) => !String.IsNullOrEmpty(ext) && !_languageExtensions.ContainsKey(ext)), paramName ?? "fileExtensions", "File extension should not be null, empty or duplicated between languages" ); ContractUtils.RequiresNotNull(displayName, paramName ?? nameof(displayName)); if (string.IsNullOrEmpty(displayName)) { ContractUtils.Requires(names.Count > 0, paramName ?? nameof(displayName), "Must have a non-empty display name or a a non-empty list of language names"); displayName = names[0]; } var aqtn = AssemblyQualifiedTypeName.ParseArgument(languageTypeName, paramName ?? "languageTypeName"); if (_languageConfigurations.ContainsKey(aqtn)) { throw new ArgumentException($"Duplicate language with type name '{aqtn}'", nameof(languageTypeName)); } // Add global language options first, they can be rewritten by language specific ones: var mergedOptions = new Dictionary<string, object>(Options); // Replace global options with language-specific options foreach (var option in options) { mergedOptions[option.Key] = option.Value; } var config = new LanguageConfiguration(aqtn, displayName, mergedOptions); _languageConfigurations.Add(aqtn, config); // allow duplicate ids in identifiers and extensions lists: foreach (var name in names) { _languageNames[name] = config; } foreach (var ext in fileExtensions) { _languageExtensions[NormalizeExtension(ext)] = config; } } internal static string NormalizeExtension(string extension) { return extension[0] == '.' ? extension : "." + extension; } internal void Freeze() { Debug.Assert(!_frozen); _frozen = true; } internal bool TryLoadLanguage(ScriptDomainManager manager, in AssemblyQualifiedTypeName providerName, out LanguageContext language) { Assert.NotNull(manager); if (_languageConfigurations.TryGetValue(providerName, out LanguageConfiguration config)) { language = LoadLanguageContext(manager, config); return true; } language = null; return false; } internal bool TryLoadLanguage(ScriptDomainManager manager, string str, bool isExtension, out LanguageContext language) { Assert.NotNull(manager, str); var dict = isExtension ? _languageExtensions : _languageNames; if (dict.TryGetValue(str, out LanguageConfiguration config)) { language = LoadLanguageContext(manager, config); return true; } language = null; return false; } private LanguageContext LoadLanguageContext(ScriptDomainManager manager, LanguageConfiguration config) { var language = config.LoadLanguageContext(manager, out bool alreadyLoaded); if (!alreadyLoaded) { // Checks whether a single language is not registered under two different AQTNs. // We can only do it now because there is no way how to ensure that two AQTNs don't refer to the same type w/o loading the type. // The check takes place after config.LoadLanguageContext is called to avoid calling user code while holding a lock. lock (_loadedProviderTypes) { Type type = language.GetType(); if (_loadedProviderTypes.TryGetValue(type, out LanguageConfiguration existingConfig)) { throw new InvalidOperationException( $"Language implemented by type '{config.ProviderName}' has already been loaded using name '{existingConfig.ProviderName}'"); } _loadedProviderTypes.Add(type, config); } } return language; } public string[] GetLanguageNames(LanguageContext context) { ContractUtils.RequiresNotNull(context, nameof(context)); List<string> result = new List<string>(); foreach (var entry in _languageNames) { if (entry.Value.LanguageContext == context) { result.Add(entry.Key); } } return result.ToArray(); } internal string[] GetLanguageNames(LanguageConfiguration config) { List<string> result = new List<string>(); foreach (var entry in _languageNames) { if (entry.Value == config) { result.Add(entry.Key); } } return result.ToArray(); } public string[] GetLanguageNames() { return ArrayUtils.MakeArray<string>(_languageNames.Keys); } public string[] GetFileExtensions(LanguageContext context) { var result = new List<string>(); foreach (var entry in _languageExtensions) { if (entry.Value.LanguageContext == context) { result.Add(entry.Key); } } return result.ToArray(); } internal string[] GetFileExtensions(LanguageConfiguration config) { var result = new List<string>(); foreach (var entry in _languageExtensions) { if (entry.Value == config) { result.Add(entry.Key); } } return result.ToArray(); } public string[] GetFileExtensions() { return ArrayUtils.MakeArray<string>(_languageExtensions.Keys); } internal LanguageConfiguration GetLanguageConfig(LanguageContext context) { foreach (var config in _languageConfigurations.Values) { if (config.LanguageContext == context) { return config; } } return null; } } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using InputController; // Actions needing a key binding. public enum GameButton { Menu, Walk, WalkToggle, Jump, Lock, Primary, Secondary, TK, SwitchCharacter, ConsiderSuicide, } // Actions needing an axis binding. public enum GameAxis { LookX, LookY, LockX, LockY, MoveX, MoveY, Zoom, TKDistance, TKRotateX, TKRotateY } [RequireComponent(typeof(ControlsEarlyUpdate))] /* * Stores and maintains user constrols. */ public class Controls : MonoBehaviour { private static Dictionary<GameButton, BufferedButton> m_buttons; public static Dictionary<GameButton, BufferedButton> Buttons { get { return m_buttons; } } private static Dictionary<GameAxis, BufferedAxis> m_axis; public static Dictionary<GameAxis, BufferedAxis> Axis { get { return m_axis; } } private static bool m_isMuted = false; public static bool IsMuted { get { return m_isMuted; } set { m_isMuted = value; } } void Awake() { loadDefaultControls(); } /* * Needs to run at the end of every FixedUpdate frame to handle the input buffers. */ private void FixedUpdate() { foreach (BufferedButton button in m_buttons.Values) { button.RecordFixedUpdateState(); } foreach (BufferedAxis axis in m_axis.Values) { axis.RecordFixedUpdateState(); } } /* * Needs to run at the start of every Update frame to buffer new inputs. */ public void EarlyUpdate() { foreach (BufferedButton button in m_buttons.Values) { button.RecordUpdateState(); } foreach (BufferedAxis axis in m_axis.Values) { axis.RecordUpdateState(); } } /* * Clears the current controls and replaces them with the default set. */ public static void loadDefaultControls() { m_buttons = new Dictionary<GameButton, BufferedButton>(); m_buttons.Add(GameButton.Menu, new BufferedButton(false, new List<ButtonSource> { new KeyButton(KeyCode.Escape), new JoystickButton(GamepadButton.Start) })); m_buttons.Add(GameButton.Walk, new BufferedButton(true, new List<ButtonSource> { new KeyButton(KeyCode.LeftShift), })); m_buttons.Add(GameButton.WalkToggle, new BufferedButton(true, new List<ButtonSource> { new KeyButton(KeyCode.LeftControl), })); m_buttons.Add(GameButton.Jump, new BufferedButton(true, new List<ButtonSource> { new KeyButton(KeyCode.Space), new JoystickButton(GamepadButton.A) })); m_buttons.Add(GameButton.Lock, new BufferedButton(true, new List<ButtonSource> { new KeyButton(KeyCode.Q), new JoystickButton(GamepadButton.RStick) })); m_buttons.Add(GameButton.Primary, new BufferedButton(true, new List<ButtonSource> { new KeyButton(KeyCode.Mouse0), new JoystickButton(GamepadButton.RTrigger) })); m_buttons.Add(GameButton.Secondary, new BufferedButton(true, new List<ButtonSource> { new KeyButton(KeyCode.Mouse1), new JoystickButton(GamepadButton.LTrigger) })); m_buttons.Add(GameButton.TK, new BufferedButton(true, new List<ButtonSource> { new KeyButton(KeyCode.Z), new JoystickButton(GamepadButton.Y) })); m_buttons.Add(GameButton.SwitchCharacter, new BufferedButton(true, new List<ButtonSource> { new KeyButton(KeyCode.Tab), new JoystickButton(GamepadButton.Back) })); m_buttons.Add(GameButton.ConsiderSuicide, new BufferedButton(true, new List<ButtonSource> { new KeyButton(KeyCode.K), })); m_axis = new Dictionary<GameAxis, BufferedAxis>(); m_axis.Add(GameAxis.LookX, new BufferedAxis(new List<AxisSource> { new MouseAxis(MouseAxis.Axis.MouseX), new JoystickAxis(GamepadAxis.RStickX, 2.0f, 0.2f) })); m_axis.Add(GameAxis.LookY,new BufferedAxis(new List<AxisSource> { new MouseAxis(MouseAxis.Axis.MouseY), new JoystickAxis(GamepadAxis.RStickY, 2.0f, 0.2f) })); m_axis.Add(GameAxis.LockX, new BufferedAxis(new List<AxisSource> { new MouseAxis(MouseAxis.Axis.MouseX, 2.0f), new KeyAxis(KeyCode.RightArrow, KeyCode.LeftArrow), new JoystickAxis(GamepadAxis.RStickX, 1.0f, 0.3f) })); m_axis.Add(GameAxis.LockY, new BufferedAxis(new List<AxisSource> { new MouseAxis(MouseAxis.Axis.MouseY, 2.0f), new KeyAxis(KeyCode.UpArrow, KeyCode.DownArrow), new JoystickAxis(GamepadAxis.RStickY, 1.0f, 0.3f) })); m_axis.Add(GameAxis.MoveX, new BufferedAxis(new List<AxisSource> { new KeyAxis(KeyCode.D, KeyCode.A), new JoystickAxis(GamepadAxis.LStickX, 1.0f, 1.0f) })); m_axis.Add(GameAxis.MoveY, new BufferedAxis(new List<AxisSource> { new KeyAxis(KeyCode.W, KeyCode.S), new JoystickAxis(GamepadAxis.LStickY, 1.0f, 1.0f) })); m_axis.Add(GameAxis.Zoom, new BufferedAxis(new List<AxisSource> { new KeyAxis(KeyCode.Equals, KeyCode.Minus), new KeyAxis(KeyCode.KeypadPlus, KeyCode.KeypadMinus), })); m_axis.Add(GameAxis.TKDistance, new BufferedAxis(new List<AxisSource> { new MouseAxis(MouseAxis.Axis.ScrollWheel), new JoystickButtonAxis(GamepadButton.RShoulder, GamepadButton.LShoulder, 0.1f) })); m_axis.Add(GameAxis.TKRotateX, new BufferedAxis(new List<AxisSource> { new MouseAxis(MouseAxis.Axis.MouseX), new JoystickAxis(GamepadAxis.RStickX, 2.0f, 1.0f) })); m_axis.Add(GameAxis.TKRotateY, new BufferedAxis(new List<AxisSource> { new MouseAxis(MouseAxis.Axis.MouseY), new JoystickAxis(GamepadAxis.RStickY, 2.0f, 1.0f) })); } /* * Returns true if any of the relevant keyboard or joystick buttons are held down. */ public static bool IsDown(GameButton button) { BufferedButton bufferedButton = m_buttons[button]; return !(m_isMuted && bufferedButton.CanBeMuted) && bufferedButton.IsDown(); } /* * Returns true if a relevant keyboard or joystick key was pressed since the last appropriate update. */ public static bool JustDown(GameButton button) { BufferedButton bufferedButton = m_buttons[button]; bool isFixed = (Time.deltaTime == Time.fixedDeltaTime); return !(m_isMuted && bufferedButton.CanBeMuted) && (isFixed ? bufferedButton.JustDown() : bufferedButton.VisualJustDown()); } /* * Returns true if a relevant keyboard or joystick key was released since the last appropriate update. */ public static bool JustUp(GameButton button) { BufferedButton bufferedButton = m_buttons[button]; bool isFixed = (Time.deltaTime == Time.fixedDeltaTime); return !(m_isMuted && bufferedButton.CanBeMuted) && (isFixed ? bufferedButton.JustUp() : bufferedButton.VisualJustUp()); } /* * Returns the average value of an axis from all Update frames since the last FixedUpdate. */ public static float AverageValue(GameAxis axis) { return m_isMuted ? 0 : m_axis[axis].AverageValue(); } /* * Returns the cumulative value of an axis from all Update frames since the last FixedUpdate. */ public static float CumulativeValue(GameAxis axis) { return m_isMuted ? 0 : m_axis[axis].CumulativeValue(); } }
// 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.ComponentModel.Composition; using System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.RQName; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation { [Export(typeof(IRefactorNotifyService))] internal sealed class VsRefactorNotifyService : ForegroundThreadAffinitizedObject, IRefactorNotifyService { public bool TryOnBeforeGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, ISymbol symbol, string newName, bool throwOnFailure) { AssertIsForeground(); Dictionary<IVsHierarchy, List<uint>> hierarchyToItemIDsMap; string[] rqnames; if (TryGetRenameAPIRequiredArguments(workspace, changedDocumentIDs, symbol, out hierarchyToItemIDsMap, out rqnames)) { foreach (var hierarchy in hierarchyToItemIDsMap.Keys) { var itemIDs = hierarchyToItemIDsMap[hierarchy]; var refactorNotify = hierarchy as IVsHierarchyRefactorNotify; if (refactorNotify != null) { var hresult = refactorNotify.OnBeforeGlobalSymbolRenamed( (uint)itemIDs.Count, itemIDs.ToArray(), (uint)rqnames.Length, rqnames, newName, promptContinueOnFail: 1); if (hresult < 0) { if (throwOnFailure) { Marshal.ThrowExceptionForHR(hresult); } else { return false; } } } } } return true; } public bool TryOnAfterGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, ISymbol symbol, string newName, bool throwOnFailure) { AssertIsForeground(); Dictionary<IVsHierarchy, List<uint>> hierarchyToItemIDsMap; string[] rqnames; if (TryGetRenameAPIRequiredArguments(workspace, changedDocumentIDs, symbol, out hierarchyToItemIDsMap, out rqnames)) { foreach (var hierarchy in hierarchyToItemIDsMap.Keys) { var itemIDs = hierarchyToItemIDsMap[hierarchy]; var refactorNotify = hierarchy as IVsHierarchyRefactorNotify; if (refactorNotify != null) { var hresult = refactorNotify.OnGlobalSymbolRenamed( (uint)itemIDs.Count, itemIDs.ToArray(), (uint)rqnames.Length, rqnames, newName); if (hresult < 0) { if (throwOnFailure) { Marshal.ThrowExceptionForHR(hresult); } else { return false; } } } } } return true; } private bool TryGetRenameAPIRequiredArguments( Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, ISymbol symbol, out Dictionary<IVsHierarchy, List<uint>> hierarchyToItemIDsMap, out string[] rqnames) { AssertIsForeground(); hierarchyToItemIDsMap = null; rqnames = null; string rqname; VisualStudioWorkspaceImpl visualStudioWorkspace; if (!TryGetItemIDsAndRQName(workspace, changedDocumentIDs, symbol, out visualStudioWorkspace, out hierarchyToItemIDsMap, out rqname)) { return false; } rqnames = new string[1] { rqname }; return true; } private bool TryGetItemIDsAndRQName( Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, ISymbol symbol, out VisualStudioWorkspaceImpl visualStudioWorkspace, out Dictionary<IVsHierarchy, List<uint>> hierarchyToItemIDsMap, out string rqname) { AssertIsForeground(); visualStudioWorkspace = null; hierarchyToItemIDsMap = null; rqname = null; if (!changedDocumentIDs.Any()) { return false; } visualStudioWorkspace = workspace as VisualStudioWorkspaceImpl; if (visualStudioWorkspace == null) { return false; } if (!TryGetRenamingRQNameForSymbol(symbol, out rqname)) { return false; } hierarchyToItemIDsMap = GetHierarchiesAndItemIDsFromDocumentIDs(visualStudioWorkspace, changedDocumentIDs); return true; } private bool TryGetRenamingRQNameForSymbol(ISymbol symbol, out string rqname) { if (symbol.Kind == SymbolKind.Method) { var methodSymbol = symbol as IMethodSymbol; if (methodSymbol.MethodKind == MethodKind.Constructor || methodSymbol.MethodKind == MethodKind.Destructor) { symbol = symbol.ContainingType; } } rqname = LanguageServices.RQName.From(symbol); return rqname != null; } private Dictionary<IVsHierarchy, List<uint>> GetHierarchiesAndItemIDsFromDocumentIDs(VisualStudioWorkspaceImpl visualStudioWorkspace, IEnumerable<DocumentId> changedDocumentIDs) { AssertIsForeground(); var hierarchyToItemIDsMap = new Dictionary<IVsHierarchy, List<uint>>(); foreach (var docID in changedDocumentIDs) { var project = visualStudioWorkspace.GetHostProject(docID.ProjectId); var itemID = project.GetDocumentOrAdditionalDocument(docID).GetItemId(); if (itemID == (uint)VSConstants.VSITEMID.Nil) { continue; } List<uint> itemIDsForCurrentHierarchy; if (!hierarchyToItemIDsMap.TryGetValue(project.Hierarchy, out itemIDsForCurrentHierarchy)) { itemIDsForCurrentHierarchy = new List<uint>(); hierarchyToItemIDsMap.Add(project.Hierarchy, itemIDsForCurrentHierarchy); } if (!itemIDsForCurrentHierarchy.Contains(itemID)) { itemIDsForCurrentHierarchy.Add(itemID); } } return hierarchyToItemIDsMap; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Packaging; using System.Linq; using System.Net.Mime; using System.Text; using System.Xml.Serialization; namespace ClosedXML_Tests { public static class PackageHelper { public static void WriteXmlPart(Package package, Uri uri, object content, XmlSerializer serializer) { if (package.PartExists(uri)) { package.DeletePart(uri); } PackagePart part = package.CreatePart(uri, MediaTypeNames.Text.Xml, CompressionOption.Fast); using (Stream stream = part.GetStream()) { serializer.Serialize(stream, content); } } public static object ReadXmlPart(Package package, Uri uri, XmlSerializer serializer) { if (!package.PartExists(uri)) { throw new ApplicationException(string.Format("Package part '{0}' doesn't exists!", uri.OriginalString)); } PackagePart part = package.GetPart(uri); using (Stream stream = part.GetStream()) { return serializer.Deserialize(stream); } } public static void WriteBinaryPart(Package package, Uri uri, Stream content) { if (package.PartExists(uri)) { package.DeletePart(uri); } PackagePart part = package.CreatePart(uri, MediaTypeNames.Application.Octet, CompressionOption.Fast); using (Stream stream = part.GetStream()) { StreamHelper.StreamToStreamAppend(content, stream); } } /// <summary> /// Returns part's stream /// </summary> /// <param name="package"></param> /// <param name="uri"></param> /// <returns></returns> public static Stream ReadBinaryPart(Package package, Uri uri) { if (!package.PartExists(uri)) { throw new ApplicationException("Package part doesn't exists!"); } PackagePart part = package.GetPart(uri); return part.GetStream(); } public static void CopyPart(Uri uri, Package source, Package dest) { CopyPart(uri, source, dest, true); } public static void CopyPart(Uri uri, Package source, Package dest, bool overwrite) { #region Check if (ReferenceEquals(uri, null)) { throw new ArgumentNullException("uri"); } if (ReferenceEquals(source, null)) { throw new ArgumentNullException("source"); } if (ReferenceEquals(dest, null)) { throw new ArgumentNullException("dest"); } #endregion if (dest.PartExists(uri)) { if (!overwrite) { throw new ArgumentException("Specified part already exists", "uri"); } dest.DeletePart(uri); } PackagePart sourcePart = source.GetPart(uri); PackagePart destPart = dest.CreatePart(uri, sourcePart.ContentType, sourcePart.CompressionOption); using (Stream sourceStream = sourcePart.GetStream()) { using (Stream destStream = destPart.GetStream()) { StreamHelper.StreamToStreamAppend(sourceStream, destStream); } } } public static void WritePart<T>(Package package, PackagePartDescriptor descriptor, T content, Action<Stream, T> serializeAction) { #region Check if (ReferenceEquals(package, null)) { throw new ArgumentNullException("package"); } if (ReferenceEquals(descriptor, null)) { throw new ArgumentNullException("descriptor"); } if (ReferenceEquals(serializeAction, null)) { throw new ArgumentNullException("serializeAction"); } #endregion if (package.PartExists(descriptor.Uri)) { package.DeletePart(descriptor.Uri); } PackagePart part = package.CreatePart(descriptor.Uri, descriptor.ContentType, descriptor.CompressOption); using (Stream stream = part.GetStream()) { serializeAction(stream, content); } } public static void WritePart(Package package, PackagePartDescriptor descriptor, Action<Stream> serializeAction) { #region Check if (ReferenceEquals(package, null)) { throw new ArgumentNullException("package"); } if (ReferenceEquals(descriptor, null)) { throw new ArgumentNullException("descriptor"); } if (ReferenceEquals(serializeAction, null)) { throw new ArgumentNullException("serializeAction"); } #endregion if (package.PartExists(descriptor.Uri)) { package.DeletePart(descriptor.Uri); } PackagePart part = package.CreatePart(descriptor.Uri, descriptor.ContentType, descriptor.CompressOption); using (Stream stream = part.GetStream()) { serializeAction(stream); } } public static T ReadPart<T>(Package package, Uri uri, Func<Stream, T> deserializeFunc) { #region Check if (ReferenceEquals(package, null)) { throw new ArgumentNullException("package"); } if (ReferenceEquals(uri, null)) { throw new ArgumentNullException("uri"); } if (ReferenceEquals(deserializeFunc, null)) { throw new ArgumentNullException("deserializeFunc"); } #endregion if (!package.PartExists(uri)) { throw new ApplicationException(string.Format("Package part '{0}' doesn't exists!", uri.OriginalString)); } PackagePart part = package.GetPart(uri); using (Stream stream = part.GetStream()) { return deserializeFunc(stream); } } public static void ReadPart(Package package, Uri uri, Action<Stream> deserializeAction) { #region Check if (ReferenceEquals(package, null)) { throw new ArgumentNullException("package"); } if (ReferenceEquals(uri, null)) { throw new ArgumentNullException("uri"); } if (ReferenceEquals(deserializeAction, null)) { throw new ArgumentNullException("deserializeAction"); } #endregion if (!package.PartExists(uri)) { throw new ApplicationException(string.Format("Package part '{0}' doesn't exists!", uri.OriginalString)); } PackagePart part = package.GetPart(uri); using (Stream stream = part.GetStream()) { deserializeAction(stream); } } public static bool TryReadPart(Package package, Uri uri, Action<Stream> deserializeAction) { #region Check if (ReferenceEquals(package, null)) { throw new ArgumentNullException("package"); } if (ReferenceEquals(uri, null)) { throw new ArgumentNullException("uri"); } if (ReferenceEquals(deserializeAction, null)) { throw new ArgumentNullException("deserializeAction"); } #endregion if (!package.PartExists(uri)) { return false; } PackagePart part = package.GetPart(uri); using (Stream stream = part.GetStream()) { deserializeAction(stream); } return true; } /// <summary> /// Compare to packages by parts like streams /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <param name="compareToFirstDifference"></param> /// <param name="excludeMethod"></param> /// <param name="message"></param> /// <returns></returns> public static bool Compare(Package left, Package right, bool compareToFirstDifference, bool stripColumnWidths, out string message) { return Compare(left, right, compareToFirstDifference, null, stripColumnWidths, out message); } /// <summary> /// Compare to packages by parts like streams /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <param name="compareToFirstDifference"></param> /// <param name="excludeMethod"></param> /// <param name="message"></param> /// <returns></returns> public static bool Compare(Package left, Package right, bool compareToFirstDifference, Func<Uri, bool> excludeMethod, bool stripColumnWidths, out string message) { #region Check if (left == null) { throw new ArgumentNullException("left"); } if (right == null) { throw new ArgumentNullException("right"); } #endregion excludeMethod = excludeMethod ?? (uri => false); PackagePartCollection leftParts = left.GetParts(); PackagePartCollection rightParts = right.GetParts(); var pairs = new Dictionary<Uri, PartPair>(); foreach (PackagePart part in leftParts) { if (excludeMethod(part.Uri)) { continue; } pairs.Add(part.Uri, new PartPair(part.Uri, CompareStatus.OnlyOnLeft)); } foreach (PackagePart part in rightParts) { if (excludeMethod(part.Uri)) { continue; } PartPair pair; if (pairs.TryGetValue(part.Uri, out pair)) { pair.Status = CompareStatus.Equal; } else { pairs.Add(part.Uri, new PartPair(part.Uri, CompareStatus.OnlyOnRight)); } } if (compareToFirstDifference && pairs.Any(pair => pair.Value.Status != CompareStatus.Equal)) { goto EXIT; } foreach (PartPair pair in pairs.Values) { if (pair.Status != CompareStatus.Equal) { continue; } var leftPart = left.GetPart(pair.Uri); var rightPart = right.GetPart(pair.Uri); using (Stream oneStream = leftPart.GetStream(FileMode.Open, FileAccess.Read)) using (Stream otherStream = rightPart.GetStream(FileMode.Open, FileAccess.Read)) { bool stripColumnWidthsFromSheet = stripColumnWidths && leftPart.ContentType == @"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml" && rightPart.ContentType == @"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"; if (!StreamHelper.Compare(oneStream, otherStream, stripColumnWidthsFromSheet)) { pair.Status = CompareStatus.NonEqual; if (compareToFirstDifference) { goto EXIT; } } } } EXIT: List<PartPair> sortedPairs = pairs.Values.ToList(); sortedPairs.Sort((one, other) => one.Uri.OriginalString.CompareTo(other.Uri.OriginalString)); var sbuilder = new StringBuilder(); foreach (PartPair pair in sortedPairs) { if (pair.Status == CompareStatus.Equal) { continue; } sbuilder.AppendFormat("{0} :{1}", pair.Uri, pair.Status); sbuilder.AppendLine(); } message = sbuilder.ToString(); return message.Length == 0; } #region Nested type: PackagePartDescriptor public sealed class PackagePartDescriptor { #region Private fields [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly CompressionOption _compressOption; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly string _contentType; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly Uri _uri; #endregion #region Constructor /// <summary> /// Instance constructor /// </summary> /// <param name="uri">Part uri</param> /// <param name="contentType">Content type from <see cref="MediaTypeNames" /></param> /// <param name="compressOption"></param> public PackagePartDescriptor(Uri uri, string contentType, CompressionOption compressOption) { #region Check if (ReferenceEquals(uri, null)) { throw new ArgumentNullException("uri"); } if (string.IsNullOrEmpty(contentType)) { throw new ArgumentNullException("contentType"); } #endregion _uri = uri; _contentType = contentType; _compressOption = compressOption; } #endregion #region Public properties public Uri Uri { [DebuggerStepThrough] get { return _uri; } } public string ContentType { [DebuggerStepThrough] get { return _contentType; } } public CompressionOption CompressOption { [DebuggerStepThrough] get { return _compressOption; } } #endregion #region Public methods public override string ToString() { return string.Format("Uri:{0} ContentType: {1}, Compression: {2}", _uri, _contentType, _compressOption); } #endregion } #endregion #region Nested type: CompareStatus private enum CompareStatus { OnlyOnLeft, OnlyOnRight, Equal, NonEqual } #endregion #region Nested type: PartPair private sealed class PartPair { #region Private fields [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly Uri _uri; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private CompareStatus _status; #endregion #region Constructor public PartPair(Uri uri, CompareStatus status) { _uri = uri; _status = status; } #endregion #region Public properties public Uri Uri { [DebuggerStepThrough] get { return _uri; } } public CompareStatus Status { [DebuggerStepThrough] get { return _status; } [DebuggerStepThrough] set { _status = value; } } #endregion } #endregion //-- } }
using System; using System.Collections.Generic; using System.Text; using BTDB.FieldHandler; using BTDB.KVDBLayer; using BTDB.ODBLayer; using Xunit; namespace BTDBTest { public class ObjectDbTableFreeContentTest : IDisposable { IKeyValueDB _lowDb; IObjectDB _db; public ObjectDbTableFreeContentTest() { _lowDb = new InMemoryKeyValueDB(); OpenDb(); } void OpenDb() { _db = new ObjectDB(); _db.Open(_lowDb, false, new DBOptions().WithoutAutoRegistration()); } void ReopenDb() { _db.Dispose(); OpenDb(); } public class Link { [PrimaryKey] public ulong Id { get; set; } public IDictionary<ulong, ulong> Edges { get; set; } } public interface ILinks : IRelation<Link> { void Insert(Link link); void Update(Link link); void ShallowUpdate(Link link); bool ShallowUpsert(Link link); bool RemoveById(ulong id); bool ShallowRemoveById(ulong id); Link FindById(ulong id); } [Fact] public void FreeIDictionary() { var creator = InitILinks(); using (var tr = _db.StartTransaction()) { var links = creator(tr); Assert.True(links.RemoveById(1)); tr.Commit(); } AssertNoLeaksInDb(); } Func<IObjectDBTransaction, ILinks> InitILinks() { Func<IObjectDBTransaction, ILinks> creator; using (var tr = _db.StartTransaction()) { creator = tr.InitRelation<ILinks>("LinksRelation"); var links = creator(tr); var link = new Link { Id = 1, Edges = new Dictionary<ulong, ulong> { [0] = 1, [1] = 2, [2] = 3 } }; links.Insert(link); tr.Commit(); } return creator; } [Fact] public void FreeIDictionaryInUpdate() { var creator = InitILinks(); using (var tr = _db.StartTransaction()) { var links = creator(tr); links.Insert(new Link { Id = 2, Edges = new Dictionary<ulong, ulong> { [10] = 20 } }); var link = new Link { Id = 1, Edges = new Dictionary<ulong, ulong>() }; links.Update(link); //replace dict link = links.FindById(2); link.Edges.Add(20, 30); links.Update(link); //update dict, must not free link = links.FindById(2); Assert.Equal(2, link.Edges.Count); tr.Commit(); } AssertNoLeaksInDb(); } [Fact] public void LeakingIDictionaryInShallowUpdate() { var creator = InitILinks(); using (var tr = _db.StartTransaction()) { var links = creator(tr); links.Insert(new Link { Id = 2, Edges = new Dictionary<ulong, ulong> { [10] = 20 } }); var link = new Link { Id = 1, Edges = new Dictionary<ulong, ulong>() }; links.ShallowUpdate(link); //replace dict link = links.FindById(2); link.Edges.Add(20, 30); links.ShallowUpdate(link); //update dict, must not free link = links.FindById(2); Assert.Equal(2, link.Edges.Count); tr.Commit(); } Assert.NotEmpty(FindLeaks()); } [Fact] public void LeakingIDictionaryInShallowRemove() { var creator = InitILinks(); using (var tr = _db.StartTransaction()) { var links = creator(tr); Assert.True(links.ShallowRemoveById(1)); //remove without free Assert.Equal(0, links.Count); tr.Commit(); } Assert.NotEmpty(FindLeaks()); } [Fact] public void ReuseIDictionaryAfterShallowRemove() { var creator = InitILinks(); using (var tr = _db.StartTransaction()) { var links = creator(tr); var value = links.FindById(1); links.ShallowRemoveById(1); //remove without free Assert.Equal(0, links.Count); links.Insert(value); Assert.Equal(3, value.Edges.Count); tr.Commit(); } AssertNoLeaksInDb(); } [Fact] public void FreeIDictionaryInUpsert() { var creator = InitILinks(); using (var tr = _db.StartTransaction()) { var links = creator(tr); var link = new Link { Id = 1, Edges = new Dictionary<ulong, ulong>() }; links.Upsert(link); //replace dict tr.Commit(); } AssertNoLeaksInDb(); } [Fact] public void LeakingIDictionaryInShallowUpsert() { var creator = InitILinks(); using (var tr = _db.StartTransaction()) { var links = creator(tr); var link = new Link { Id = 1, Edges = new Dictionary<ulong, ulong>() }; links.ShallowUpsert(link); //replace dict tr.Commit(); } Assert.NotEmpty(FindLeaks()); } public class LinkInList { [PrimaryKey] public ulong Id { get; set; } public List<IDictionary<ulong, ulong>> EdgesList { get; set; } } public interface ILinksInList : IRelation<LinkInList> { void Insert(LinkInList link); void Update(LinkInList link); LinkInList FindById(ulong id); bool RemoveById(ulong id); } [Fact] public void FreeIDictionaryInList() { Func<IObjectDBTransaction, ILinksInList> creator; using (var tr = _db.StartTransaction()) { creator = tr.InitRelation<ILinksInList>("ListLinksRelation"); var links = creator(tr); var link = new LinkInList { Id = 1, EdgesList = new List<IDictionary<ulong, ulong>> { new Dictionary<ulong, ulong> {[0] = 1, [1] = 2, [2] = 3}, new Dictionary<ulong, ulong> {[0] = 1, [1] = 2, [2] = 3} } }; links.Insert(link); tr.Commit(); } AssertNoLeaksInDb(); using (var tr = _db.StartTransaction()) { var links = creator(tr); Assert.True(links.RemoveById(1)); tr.Commit(); } AssertNoLeaksInDb(); } [Fact] public void FreeIDictionaryInListInUpdate() { Func<IObjectDBTransaction, ILinksInList> creator; using (var tr = _db.StartTransaction()) { creator = tr.InitRelation<ILinksInList>("ListLinksRelation"); var links = creator(tr); var link = new LinkInList { Id = 1, EdgesList = new List<IDictionary<ulong, ulong>> { new Dictionary<ulong, ulong> {[0] = 1, [1] = 2, [2] = 3}, new Dictionary<ulong, ulong> {[0] = 1, [1] = 2, [2] = 3} } }; links.Insert(link); tr.Commit(); } AssertNoLeaksInDb(); using (var tr = _db.StartTransaction()) { var links = creator(tr); var link = links.FindById(1); for (int i = 0; i < 20; i++) link.EdgesList.Add(new Dictionary<ulong, ulong> { [10] = 20 }); links.Update(link); tr.Commit(); } AssertNoLeaksInDb(); } public class LinkInDict { [PrimaryKey] public ulong Id { get; set; } public Dictionary<int, IDictionary<ulong, ulong>> EdgesIDict { get; set; } public string Name { get; set; } } public interface ILinksInDict : IRelation<LinkInDict> { void Insert(LinkInDict link); bool RemoveById(ulong id); } [Fact] public void FreeIDictionaryInDictionary() { Func<IObjectDBTransaction, ILinksInDict> creator; using (var tr = _db.StartTransaction()) { creator = tr.InitRelation<ILinksInDict>("DictLinksRelation"); var links = creator(tr); var link = new LinkInDict { Id = 1, EdgesIDict = new Dictionary<int, IDictionary<ulong, ulong>> { [0] = new Dictionary<ulong, ulong> { [0] = 1, [1] = 2, [2] = 3 }, [1] = new Dictionary<ulong, ulong> { [0] = 1, [1] = 2, [2] = 3 } } }; links.Insert(link); tr.Commit(); } AssertNoLeaksInDb(); using (var tr = _db.StartTransaction()) { var links = creator(tr); Assert.True(links.RemoveById(1)); tr.Commit(); } AssertNoLeaksInDb(); } public class LinkInIDict { [PrimaryKey] public ulong Id { get; set; } public IDictionary<int, IDictionary<ulong, ulong>> EdgesIDict { get; set; } } public interface ILinksInIDict : IRelation<LinkInIDict> { void Insert(LinkInIDict link); bool RemoveById(ulong id); } [Fact] public void FreeIDictionaryInIDictionary() { Func<IObjectDBTransaction, ILinksInIDict> creator; using (var tr = _db.StartTransaction()) { creator = tr.InitRelation<ILinksInIDict>("IDictLinksRelation"); var links = creator(tr); var link = new LinkInIDict { Id = 1, EdgesIDict = new Dictionary<int, IDictionary<ulong, ulong>> { [0] = new Dictionary<ulong, ulong> { [0] = 1, [1] = 2, [2] = 3 }, [1] = new Dictionary<ulong, ulong> { [0] = 1, [1] = 2, [2] = 3 } } }; links.Insert(link); tr.Commit(); } AssertNoLeaksInDb(); using (var tr = _db.StartTransaction()) { var links = creator(tr); Assert.True(links.RemoveById(1)); tr.Commit(); } AssertNoLeaksInDb(); } public class Nodes { public IDictionary<ulong, ulong> Edges { get; set; } } public class Links { [PrimaryKey] public ulong Id { get; set; } public Nodes Nodes { get; set; } } public interface ILinksWithNodes : IRelation<Links> { void Insert(Links link); Links FindByIdOrDefault(ulong id); bool RemoveById(ulong id); } [Fact] public void FreeIDictionaryInInlineObject() { Func<IObjectDBTransaction, ILinksWithNodes> creator; using (var tr = _db.StartTransaction()) { creator = tr.InitRelation<ILinksWithNodes>("IDictObjLinksRelation"); var links = creator(tr); var link = new Links { Id = 1, Nodes = new Nodes { Edges = new Dictionary<ulong, ulong> { [0] = 1, [1] = 2, [2] = 3 } } }; links.Insert(link); tr.Commit(); } AssertNoLeaksInDb(); using (var tr = _db.StartTransaction()) { var links = creator(tr); var l = links.FindByIdOrDefault(1); Assert.Equal(2ul, l.Nodes.Edges[1]); Assert.True(links.RemoveById(1)); tr.Commit(); } AssertNoLeaksInDb(); } public class BlobLocation { public string Name { get; set; } } public class LicenseFileDb { public string FileName { get; set; } public BlobLocation Location { get; set; } } public class LicenseDb { [PrimaryKey(1)] public ulong ItemId { get; set; } public LicenseFileDb LicenseFile { get; set; } } public interface ILicenseTable : IRelation<LicenseDb> { void Insert(LicenseDb license); void Update(LicenseDb license); } [Fact] public void DoNotCrashOnUnknownType() { Func<IObjectDBTransaction, ILicenseTable> creator; using (var tr = _db.StartTransaction()) { creator = tr.InitRelation<ILicenseTable>("LicRel"); var lics = creator(tr); var license = new LicenseDb { ItemId = 1 }; //no LicenseFileDb inserted lics.Insert(license); tr.Commit(); } using (var tr = _db.StartTransaction()) { var lics = creator(tr); var license = new LicenseDb { ItemId = 1 }; lics.Update(license); tr.Commit(); } AssertNoLeaksInDb(); } public class License { [PrimaryKey(1)] public ulong CompanyId { get; set; } [PrimaryKey(2)] public ulong UserId { get; set; } public IDictionary<ulong, IDictionary<ulong, ConcurrentFeatureItemInfo>> ConcurrentFeautureItemsSessions { get; set; } } public class ConcurrentFeatureItemInfo { public DateTime UsedFrom { get; set; } } public interface ILicenses : IRelation<License> { void Insert(License license); bool RemoveById(ulong companyId, ulong userId); int RemoveById(ulong companyId); } [Fact] public void AlsoFieldsInsideIDictionaryAreStoredInlineByDefault() { Func<IObjectDBTransaction, ILicenses> creator; using (var tr = _db.StartTransaction()) { creator = tr.InitRelation<ILicenses>("LicenseRel"); var lics = creator(tr); lics.Insert(new License()); var license = new License { CompanyId = 1, UserId = 1, ConcurrentFeautureItemsSessions = new Dictionary<ulong, IDictionary<ulong, ConcurrentFeatureItemInfo>> { [4] = new Dictionary<ulong, ConcurrentFeatureItemInfo> { [2] = new ConcurrentFeatureItemInfo() } } }; lics.Insert(license); tr.Commit(); } AssertNoLeaksInDb(); ReopenDb(); using (var tr = _db.StartTransaction()) { creator = tr.InitRelation<ILicenses>("LicenseRel"); var lics = creator(tr); lics.RemoveById(0, 1); lics.RemoveById(1, 1); tr.Commit(); } AssertNoLeaksInDb(); } public class File { [PrimaryKey] public ulong Id { get; set; } public IIndirect<RawData> Data { get; set; } } public class RawData { public byte[] Data { get; set; } public IDictionary<ulong, ulong> Edges { get; set; } } public interface IHddRelation : IRelation<File> { void Insert(File file); void RemoveById(ulong id); File FindById(ulong id); } [Fact] public void IIndirectIsNotFreedAutomatically() { Func<IObjectDBTransaction, IHddRelation> creator; using (var tr = _db.StartTransaction()) { creator = tr.InitRelation<IHddRelation>("HddRelation"); var files = creator(tr); var file = new File { Id = 1, Data = new DBIndirect<RawData>(new RawData { Data = new byte[] { 1, 2, 3 }, Edges = new Dictionary<ulong, ulong> { [10] = 20 } }) }; files.Insert(file); tr.Commit(); } using (var tr = _db.StartTransaction()) { var files = creator(tr); var file = files.FindById(1); Assert.Equal(file.Data.Value.Data, new byte[] { 1, 2, 3 }); files.RemoveById(1); tr.Commit(); } Assert.NotEmpty(FindLeaks()); } [Fact] public void IIndirectMustBeFreedManually() { Func<IObjectDBTransaction, IHddRelation> creator; using (var tr = _db.StartTransaction()) { creator = tr.InitRelation<IHddRelation>("HddRelation"); var files = creator(tr); var file = new File { Id = 1, Data = new DBIndirect<RawData>(new RawData { Data = new byte[] { 1, 2, 3 }, Edges = new Dictionary<ulong, ulong> { [10] = 20 } }) }; files.Insert(file); tr.Commit(); } using (var tr = _db.StartTransaction()) { var files = creator(tr); var file = files.FindById(1); Assert.Equal(file.Data.Value.Data, new byte[] { 1, 2, 3 }); file.Data.Value.Edges.Clear(); tr.Delete(file.Data); files.RemoveById(1); tr.Commit(); } AssertNoLeaksInDb(); } public class Setting { [PrimaryKey] public ulong Id { get; set; } public License License { get; set; } } public interface ISettings : IRelation<Setting> { void Insert(Setting license); bool RemoveById(ulong id); } [Fact] public void PreferInlineIsTransferredThroughDBObject() { using (var tr = _db.StartTransaction()) { var creator = tr.InitRelation<ISettings>("SettingRel"); var settings = creator(tr); var setting = new Setting { Id = 1, License = new License { CompanyId = 1, ConcurrentFeautureItemsSessions = new Dictionary<ulong, IDictionary<ulong, ConcurrentFeatureItemInfo>> { [4] = new Dictionary<ulong, ConcurrentFeatureItemInfo> { [2] = new ConcurrentFeatureItemInfo() } } } }; settings.Insert(setting); settings.RemoveById(1); tr.Commit(); } AssertNoLeaksInDb(); } public interface INodes { } public class NodesA : INodes { public string F { get; set; } public IDictionary<ulong, ulong> A { get; set; } } public class NodesB : INodes { public IDictionary<ulong, ulong> B { get; set; } public string E { get; set; } } public class Graph { [PrimaryKey] public ulong Id { get; set; } public INodes Nodes { get; set; } } public interface IGraph : IRelation<Graph> { void Insert(Graph license); Graph FindById(ulong id); bool RemoveById(ulong id); } [Fact] public void FreeWorksAlsoForDifferentSubObjects() { _db.RegisterType(typeof(NodesA)); _db.RegisterType(typeof(NodesB)); using (var tr = _db.StartTransaction()) { var creator = tr.InitRelation<IGraph>("Graph"); var table = creator(tr); var graph = new Graph { Id = 1, Nodes = new NodesA { A = new Dictionary<ulong, ulong> { [0] = 1, [1] = 2, [2] = 3 }, F = "f" } }; table.Insert(graph); graph = new Graph { Id = 2, Nodes = new NodesB { B = new Dictionary<ulong, ulong> { [0] = 1, [1] = 2, [2] = 3 }, E = "e" } }; table.Insert(graph); Assert.True(table.FindById(1).Nodes is NodesA); Assert.True(table.FindById(2).Nodes is NodesB); table.RemoveById(1); table.RemoveById(2); tr.Commit(); } AssertNoLeaksInDb(); } public class Component { public IList<Component> Children { get; set; } public IDictionary<string, string> Props { get; set; } } public class View { [PrimaryKey(1)] public ulong Id { get; set; } public Component Component { get; set; } } public interface IViewTable : IRelation<View> { void Insert(View license); void RemoveById(ulong id); } [Fact] public void FreeWorksInRecursiveStructures() { using (var tr = _db.StartTransaction()) { var creator = tr.InitRelation<IViewTable>("View"); var table = creator(tr); table.Insert(new View { Id = 1, Component = new Component { Children = new List<Component> { new Component {Props = new Dictionary<string, string> {["a"] = "A"}}, new Component {Props = new Dictionary<string, string> {["b"] = "B"}} } } }); table.RemoveById(1); AssertNoLeaksInDb(); } } [Fact] public void FreeWorksTogetherWithRemoveByPrefix() { Func<IObjectDBTransaction, ILicenses> creator; using (var tr = _db.StartTransaction()) { creator = tr.InitRelation<ILicenses>("LicenseRel2"); var lics = creator(tr); lics.Insert(new License()); var license = new License { CompanyId = 1, UserId = 1, ConcurrentFeautureItemsSessions = new Dictionary<ulong, IDictionary<ulong, ConcurrentFeatureItemInfo>> { [4] = new Dictionary<ulong, ConcurrentFeatureItemInfo> { [2] = new ConcurrentFeatureItemInfo() } } }; lics.Insert(license); tr.Commit(); } AssertNoLeaksInDb(); ReopenDb(); using (var tr = _db.StartTransaction()) { creator = tr.InitRelation<ILicenses>("LicenseRel2"); var lics = creator(tr); Assert.Equal(1, lics.RemoveById(1)); tr.Commit(); } AssertNoLeaksInDb(); } public abstract class UploadDataBase { public BlobLocation Location { get; set; } public string FileName { get; set; } } public class SharedImageFile : UploadDataBase { [PrimaryKey(1)] [SecondaryKey("CompanyId")] public ulong CompanyId { get; set; } [PrimaryKey(2)] public ulong Id { get; set; } public new BlobLocation Location { get => base.Location; set => base.Location = value; } public BlobLocation TempLocation { get; set; } public int Width { get; set; } public int Height { get; set; } public IDictionary<int, bool> Dict { get; set; } } public interface IFileTable : IRelation<SharedImageFile> { void Insert(SharedImageFile license); void RemoveById(ulong companyId, ulong id); } [Fact] public void IterateWellObjectsWithSharedInstance() { using (var tr = _db.StartTransaction()) { var creator = tr.InitRelation<IFileTable>("IFileTable"); var files = creator(tr); var loc = new BlobLocation(); files.Insert(new SharedImageFile { Location = loc, TempLocation = loc, Dict = new Dictionary<int, bool> { [1] = true } }); files.RemoveById(0, 0); tr.Commit(); } AssertNoLeaksInDb(); } public class ImportData { [PrimaryKey] public ulong CompanyId { get; set; } [PrimaryKey(Order = 1)] public ulong Id { get; set; } public IDictionary<ObjectId, ObjectNode> Items { get; set; } } public interface IImportDataTable : IRelation<ImportData> { bool Insert(ImportData item); void Update(ImportData item); int RemoveById(ulong companyId); } public class ObjectNode { public string Sample { get; set; } } public class ObjectId { public ulong Id { get; set; } } [Fact] public void DoNotPanicWhenUnknownStatusInIDictionaryKey() { using (var tr = _db.StartTransaction()) { var creator = tr.InitRelation<IImportDataTable>("ImportData"); var table = creator(tr); table.Insert(new ImportData { Items = new Dictionary<ObjectId, ObjectNode> { [new ObjectId()] = new ObjectNode() } }); tr.Commit(); } } public class NodesBase { } public class NodesOne : NodesBase { public string F { get; set; } public IDictionary<ulong, ulong> A { get; set; } } public class NodesTwo : NodesBase { public IDictionary<ulong, ulong> B { get; set; } public string E { get; set; } } public class NodesGraph { [PrimaryKey] public ulong Id { get; set; } public NodesBase Nodes { get; set; } } public interface IGraphTable : IRelation<NodesGraph> { void Insert(NodesGraph license); NodesGraph FindById(ulong id); bool RemoveById(ulong id); } [Fact] public void FreeWorksAlsoForDifferentSubObjectsWithoutIface() { _db.RegisterType(typeof(NodesOne)); _db.RegisterType(typeof(NodesTwo)); using (var tr = _db.StartTransaction()) { var creator = tr.InitRelation<IGraphTable>("GraphTable"); var table = creator(tr); var graph = new NodesGraph { Id = 1, Nodes = new NodesOne { A = new Dictionary<ulong, ulong> { [0] = 1, [1] = 2, [2] = 3 }, F = "f" } }; table.Insert(graph); graph = new NodesGraph { Id = 2, Nodes = new NodesTwo { B = new Dictionary<ulong, ulong> { [0] = 1, [1] = 2, [2] = 3 }, E = "e" } }; table.Insert(graph); graph = new NodesGraph { Id = 3, Nodes = new NodesBase() }; table.Insert(graph); Assert.True(table.FindById(1).Nodes is NodesOne); Assert.True(table.FindById(2).Nodes is NodesTwo); table.RemoveById(1); table.RemoveById(2); tr.Commit(); } AssertNoLeaksInDb(); } public class EmailMessage { public IDictionary<string, string> Bcc { get; set; } public IDictionary<string, string> Cc { get; set; } public IDictionary<string, string> To { get; set; } public IOrderedSet<string> Tags { get; set; } } public class EmailDb { public EmailMessage Content { get; set; } } public class BatchDb { [PrimaryKey(1)] public Guid ItemId { get; set; } public IDictionary<Guid, EmailDb> MailPieces { get; set; } } public interface IBatchTable : IRelation<BatchDb> { void Insert(BatchDb batch); void Update(BatchDb batch); BatchDb FindByIdOrDefault(Guid itemId); } [Fact(Skip = "prepared for discussion")] public void LeakCanBeMade() { Func<IObjectDBTransaction, IBatchTable> creator = null; var guid = Guid.NewGuid(); var mailGuid = Guid.NewGuid(); using (var tr = _db.StartTransaction()) { creator = tr.InitRelation<IBatchTable>("IBatchTable"); var table = creator(tr); var batch = new BatchDb { ItemId = guid, MailPieces = new Dictionary<Guid, EmailDb> { [mailGuid] = new EmailDb { Content = new EmailMessage { Bcc = new Dictionary<string, string> { ["a"] = "b" }, Cc = new Dictionary<string, string> { ["c"] = "d" }, To = new Dictionary<string, string> { ["e"] = "f" } } } } }; table.Insert(batch); batch = table.FindByIdOrDefault(guid); batch.MailPieces[mailGuid].Content.Tags.Add("Important"); tr.Commit(); } using (var tr = _db.StartTransaction()) { var table = creator(tr); var batch = table.FindByIdOrDefault(guid); batch.MailPieces[mailGuid] = null; //LEAK - removed immediately from db, in table.Update don't have previous value table.Update(batch); tr.Commit(); } AssertNoLeaksInDb(); } void AssertNoLeaksInDb() { var leaks = FindLeaks(); Assert.Equal("", leaks); } string FindLeaks() { using (var visitor = new FindUnusedKeysVisitor()) { using (var tr = _db.StartReadOnlyTransaction()) { visitor.ImportAllKeys(tr); visitor.Iterate(tr); return DumpUnseenKeys(visitor, " "); } } } static string DumpUnseenKeys(FindUnusedKeysVisitor visitor, string concat) { var builder = new StringBuilder(); foreach (var unseenKey in visitor.UnseenKeys()) { if (builder.Length > 0) builder.Append(concat); foreach (var b in unseenKey.Key) builder.Append(b.ToString("X2")); builder.Append(" Value len:"); builder.Append(unseenKey.ValueSize); } return builder.ToString(); } public void Dispose() { _db.Dispose(); _lowDb.Dispose(); } } }
#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.Text; using System.IO; using PlayFab.Json.Utilities; using PlayFab.Json.Linq; using System.Globalization; namespace PlayFab.Json { /// <summary> /// Specifies the state of the <see cref="JsonWriter"/>. /// </summary> public enum WriteState { /// <summary> /// An exception has been thrown, which has left the <see cref="JsonWriter"/> in an invalid state. /// You may call the <see cref="JsonWriter.Close"/> method to put the <see cref="JsonWriter"/> in the <c>Closed</c> state. /// Any other <see cref="JsonWriter"/> method calls results in an <see cref="InvalidOperationException"/> being thrown. /// </summary> Error, /// <summary> /// The <see cref="JsonWriter.Close"/> method has been called. /// </summary> Closed, /// <summary> /// An object is being written. /// </summary> Object, /// <summary> /// A array is being written. /// </summary> Array, /// <summary> /// A constructor is being written. /// </summary> Constructor, /// <summary> /// A property is being written. /// </summary> Property, /// <summary> /// A write method has not been called. /// </summary> Start } /// <summary> /// Specifies formatting options for the <see cref="JsonTextWriter"/>. /// </summary> public enum Formatting { /// <summary> /// No special formatting is applied. This is the default. /// </summary> None, /// <summary> /// Causes child objects to be indented according to the <see cref="JsonTextWriter.Indentation"/> and <see cref="JsonTextWriter.IndentChar"/> settings. /// </summary> Indented } /// <summary> /// Represents a writer that provides a fast, non-cached, forward-only way of generating Json data. /// </summary> public abstract class JsonWriter : IDisposable { private enum State { Start, Property, ObjectStart, Object, ArrayStart, Array, ConstructorStart, Constructor, Bytes, Closed, Error } // array that gives a new state based on the current state an the token being written private static readonly State[][] stateArray = new[] { // Start PropertyName ObjectStart Object ArrayStart Array ConstructorStart Constructor Closed Error // /* None */new[]{ State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error }, /* StartObject */new[]{ State.ObjectStart, State.ObjectStart, State.Error, State.Error, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.Error, State.Error }, /* StartArray */new[]{ State.ArrayStart, State.ArrayStart, State.Error, State.Error, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.Error, State.Error }, /* StartConstructor */new[]{ State.ConstructorStart, State.ConstructorStart, State.Error, State.Error, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.Error, State.Error }, /* StartProperty */new[]{ State.Property, State.Error, State.Property, State.Property, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error }, /* Comment */new[]{ State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error }, /* Raw */new[]{ State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error }, /* Value */new[]{ State.Start, State.Object, State.Error, State.Error, State.Array, State.Array, State.Constructor, State.Constructor, State.Error, State.Error }, }; private int _top; private readonly List<JTokenType> _stack; private State _currentState; private Formatting _formatting; /// <summary> /// Gets or sets a value indicating whether the underlying stream or /// <see cref="TextReader"/> should be closed when the writer is closed. /// </summary> /// <value> /// true to close the underlying stream or <see cref="TextReader"/> when /// the writer is closed; otherwise false. The default is true. /// </value> public bool CloseOutput { get; set; } /// <summary> /// Gets the top. /// </summary> /// <value>The top.</value> protected internal int Top { get { return _top; } } /// <summary> /// Gets the state of the writer. /// </summary> public WriteState WriteState { get { switch (_currentState) { case State.Error: return WriteState.Error; case State.Closed: return WriteState.Closed; case State.Object: case State.ObjectStart: return WriteState.Object; case State.Array: case State.ArrayStart: return WriteState.Array; case State.Constructor: case State.ConstructorStart: return WriteState.Constructor; case State.Property: return WriteState.Property; case State.Start: return WriteState.Start; default: throw new JsonWriterException("Invalid state: " + _currentState); } } } /// <summary> /// Indicates how the output is formatted. /// </summary> public Formatting Formatting { get { return _formatting; } set { _formatting = value; } } /// <summary> /// Creates an instance of the <c>JsonWriter</c> class. /// </summary> protected JsonWriter() { _stack = new List<JTokenType>(8); _stack.Add(JTokenType.None); _currentState = State.Start; _formatting = Formatting.None; CloseOutput = true; } private void Push(JTokenType value) { _top++; if (_stack.Count <= _top) _stack.Add(value); else _stack[_top] = value; } private JTokenType Pop() { JTokenType value = Peek(); _top--; return value; } private JTokenType Peek() { return _stack[_top]; } /// <summary> /// Flushes whatever is in the buffer to the underlying streams and also flushes the underlying stream. /// </summary> public abstract void Flush(); /// <summary> /// Closes this stream and the underlying stream. /// </summary> public virtual void Close() { AutoCompleteAll(); } /// <summary> /// Writes the beginning of a Json object. /// </summary> public virtual void WriteStartObject() { AutoComplete(JsonToken.StartObject); Push(JTokenType.Object); } /// <summary> /// Writes the end of a Json object. /// </summary> public virtual void WriteEndObject() { AutoCompleteClose(JsonToken.EndObject); } /// <summary> /// Writes the beginning of a Json array. /// </summary> public virtual void WriteStartArray() { AutoComplete(JsonToken.StartArray); Push(JTokenType.Array); } /// <summary> /// Writes the end of an array. /// </summary> public virtual void WriteEndArray() { AutoCompleteClose(JsonToken.EndArray); } /// <summary> /// Writes the start of a constructor with the given name. /// </summary> /// <param name="name">The name of the constructor.</param> public virtual void WriteStartConstructor(string name) { AutoComplete(JsonToken.StartConstructor); Push(JTokenType.Constructor); } /// <summary> /// Writes the end constructor. /// </summary> public virtual void WriteEndConstructor() { AutoCompleteClose(JsonToken.EndConstructor); } /// <summary> /// Writes the property name of a name/value pair on a Json object. /// </summary> /// <param name="name">The name of the property.</param> public virtual void WritePropertyName(string name) { AutoComplete(JsonToken.PropertyName); } /// <summary> /// Writes the end of the current Json object or array. /// </summary> public virtual void WriteEnd() { WriteEnd(Peek()); } /// <summary> /// Writes the current <see cref="JsonReader"/> token. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> to read the token from.</param> public void WriteToken(JsonReader reader) { ValidationUtils.ArgumentNotNull(reader, "reader"); int initialDepth; if (reader.TokenType == JsonToken.None) initialDepth = -1; else if (!IsStartToken(reader.TokenType)) initialDepth = reader.Depth + 1; else initialDepth = reader.Depth; WriteToken(reader, initialDepth); } internal void WriteToken(JsonReader reader, int initialDepth) { do { switch (reader.TokenType) { case JsonToken.None: // read to next break; case JsonToken.StartObject: WriteStartObject(); break; case JsonToken.StartArray: WriteStartArray(); break; case JsonToken.StartConstructor: string constructorName = reader.Value.ToString(); // write a JValue date when the constructor is for a date if (string.Compare(constructorName, "Date", StringComparison.Ordinal) == 0) WriteConstructorDate(reader); else WriteStartConstructor(reader.Value.ToString()); break; case JsonToken.PropertyName: WritePropertyName(reader.Value.ToString()); break; case JsonToken.Comment: WriteComment(reader.Value.ToString()); break; case JsonToken.Integer: WriteValue(Convert.ToInt64(reader.Value, CultureInfo.InvariantCulture)); break; case JsonToken.Float: WriteValue(Convert.ToDouble(reader.Value, CultureInfo.InvariantCulture)); break; case JsonToken.String: WriteValue(reader.Value.ToString()); break; case JsonToken.Boolean: WriteValue(Convert.ToBoolean(reader.Value, CultureInfo.InvariantCulture)); break; case JsonToken.Null: WriteNull(); break; case JsonToken.Undefined: WriteUndefined(); break; case JsonToken.EndObject: WriteEndObject(); break; case JsonToken.EndArray: WriteEndArray(); break; case JsonToken.EndConstructor: WriteEndConstructor(); break; case JsonToken.Date: WriteValue((DateTime)reader.Value); break; case JsonToken.Raw: WriteRawValue((string)reader.Value); break; case JsonToken.Bytes: WriteValue((byte[])reader.Value); break; default: throw MiscellaneousUtils.CreateArgumentOutOfRangeException("TokenType", reader.TokenType, "Unexpected token type."); } } while ( // stop if we have reached the end of the token being read initialDepth - 1 < reader.Depth - (IsEndToken(reader.TokenType) ? 1 : 0) && reader.Read()); } private void WriteConstructorDate(JsonReader reader) { if (!reader.Read()) throw new Exception("Unexpected end while reading date constructor."); if (reader.TokenType != JsonToken.Integer) throw new Exception("Unexpected token while reading date constructor. Expected Integer, got " + reader.TokenType); long ticks = (long)reader.Value; DateTime date = JsonConvert.ConvertJavaScriptTicksToDateTime(ticks); if (!reader.Read()) throw new Exception("Unexpected end while reading date constructor."); if (reader.TokenType != JsonToken.EndConstructor) throw new Exception("Unexpected token while reading date constructor. Expected EndConstructor, got " + reader.TokenType); WriteValue(date); } private bool IsEndToken(JsonToken token) { switch (token) { case JsonToken.EndObject: case JsonToken.EndArray: case JsonToken.EndConstructor: return true; default: return false; } } private bool IsStartToken(JsonToken token) { switch (token) { case JsonToken.StartObject: case JsonToken.StartArray: case JsonToken.StartConstructor: return true; default: return false; } } private void WriteEnd(JTokenType type) { switch (type) { case JTokenType.Object: WriteEndObject(); break; case JTokenType.Array: WriteEndArray(); break; case JTokenType.Constructor: WriteEndConstructor(); break; default: throw new JsonWriterException("Unexpected type when writing end: " + type); } } private void AutoCompleteAll() { while (_top > 0) { WriteEnd(); } } private JTokenType GetTypeForCloseToken(JsonToken token) { switch (token) { case JsonToken.EndObject: return JTokenType.Object; case JsonToken.EndArray: return JTokenType.Array; case JsonToken.EndConstructor: return JTokenType.Constructor; default: throw new JsonWriterException("No type for token: " + token); } } private JsonToken GetCloseTokenForType(JTokenType type) { switch (type) { case JTokenType.Object: return JsonToken.EndObject; case JTokenType.Array: return JsonToken.EndArray; case JTokenType.Constructor: return JsonToken.EndConstructor; default: throw new JsonWriterException("No close token for type: " + type); } } private void AutoCompleteClose(JsonToken tokenBeingClosed) { // write closing symbol and calculate new state int levelsToComplete = 0; for (int i = 0; i < _top; i++) { int currentLevel = _top - i; if (_stack[currentLevel] == GetTypeForCloseToken(tokenBeingClosed)) { levelsToComplete = i + 1; break; } } if (levelsToComplete == 0) throw new JsonWriterException("No token to close."); for (int i = 0; i < levelsToComplete; i++) { JsonToken token = GetCloseTokenForType(Pop()); if (_currentState != State.ObjectStart && _currentState != State.ArrayStart) WriteIndent(); WriteEnd(token); } JTokenType currentLevelType = Peek(); switch (currentLevelType) { case JTokenType.Object: _currentState = State.Object; break; case JTokenType.Array: _currentState = State.Array; break; case JTokenType.Constructor: _currentState = State.Array; break; case JTokenType.None: _currentState = State.Start; break; default: throw new JsonWriterException("Unknown JsonType: " + currentLevelType); } } /// <summary> /// Writes the specified end token. /// </summary> /// <param name="token">The end token to write.</param> protected virtual void WriteEnd(JsonToken token) { } /// <summary> /// Writes indent characters. /// </summary> protected virtual void WriteIndent() { } /// <summary> /// Writes the JSON value delimiter. /// </summary> protected virtual void WriteValueDelimiter() { } /// <summary> /// Writes an indent space. /// </summary> protected virtual void WriteIndentSpace() { } internal void AutoComplete(JsonToken tokenBeingWritten) { int token; switch (tokenBeingWritten) { default: token = (int)tokenBeingWritten; break; case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Null: case JsonToken.Undefined: case JsonToken.Date: case JsonToken.Bytes: // a value is being written token = 7; break; } // gets new state based on the current state and what is being written State newState = stateArray[token][(int)_currentState]; if (newState == State.Error) throw new JsonWriterException("Token {0} in state {1} would result in an invalid JavaScript object.".FormatWith(CultureInfo.InvariantCulture, tokenBeingWritten.ToString(), _currentState.ToString())); if ((_currentState == State.Object || _currentState == State.Array || _currentState == State.Constructor) && tokenBeingWritten != JsonToken.Comment) { WriteValueDelimiter(); } else if (_currentState == State.Property) { if (_formatting == Formatting.Indented) WriteIndentSpace(); } WriteState writeState = WriteState; // don't indent a property when it is the first token to be written (i.e. at the start) if ((tokenBeingWritten == JsonToken.PropertyName && writeState != WriteState.Start) || writeState == WriteState.Array || writeState == WriteState.Constructor) { WriteIndent(); } _currentState = newState; } #region WriteValue methods /// <summary> /// Writes a null value. /// </summary> public virtual void WriteNull() { AutoComplete(JsonToken.Null); } /// <summary> /// Writes an undefined value. /// </summary> public virtual void WriteUndefined() { AutoComplete(JsonToken.Undefined); } /// <summary> /// Writes raw JSON without changing the writer's state. /// </summary> /// <param name="json">The raw JSON to write.</param> public virtual void WriteRaw(string json) { } /// <summary> /// Writes raw JSON where a value is expected and updates the writer's state. /// </summary> /// <param name="json">The raw JSON to write.</param> public virtual void WriteRawValue(string json) { // hack. want writer to change state as if a value had been written AutoComplete(JsonToken.Undefined); WriteRaw(json); } /// <summary> /// Writes a <see cref="String"/> value. /// </summary> /// <param name="value">The <see cref="String"/> value to write.</param> public virtual void WriteValue(string value) { AutoComplete(JsonToken.String); } /// <summary> /// Writes a <see cref="Int32"/> value. /// </summary> /// <param name="value">The <see cref="Int32"/> value to write.</param> public virtual void WriteValue(int value) { AutoComplete(JsonToken.Integer); } /// <summary> /// Writes a <see cref="UInt32"/> value. /// </summary> /// <param name="value">The <see cref="UInt32"/> value to write.</param> // public virtual void WriteValue(uint value) { AutoComplete(JsonToken.Integer); } /// <summary> /// Writes a <see cref="Int64"/> value. /// </summary> /// <param name="value">The <see cref="Int64"/> value to write.</param> public virtual void WriteValue(long value) { AutoComplete(JsonToken.Integer); } /// <summary> /// Writes a <see cref="UInt64"/> value. /// </summary> /// <param name="value">The <see cref="UInt64"/> value to write.</param> // public virtual void WriteValue(ulong value) { AutoComplete(JsonToken.Integer); } /// <summary> /// Writes a <see cref="Single"/> value. /// </summary> /// <param name="value">The <see cref="Single"/> value to write.</param> public virtual void WriteValue(float value) { AutoComplete(JsonToken.Float); } /// <summary> /// Writes a <see cref="Double"/> value. /// </summary> /// <param name="value">The <see cref="Double"/> value to write.</param> public virtual void WriteValue(double value) { AutoComplete(JsonToken.Float); } /// <summary> /// Writes a <see cref="Boolean"/> value. /// </summary> /// <param name="value">The <see cref="Boolean"/> value to write.</param> public virtual void WriteValue(bool value) { AutoComplete(JsonToken.Boolean); } /// <summary> /// Writes a <see cref="Int16"/> value. /// </summary> /// <param name="value">The <see cref="Int16"/> value to write.</param> public virtual void WriteValue(short value) { AutoComplete(JsonToken.Integer); } /// <summary> /// Writes a <see cref="UInt16"/> value. /// </summary> /// <param name="value">The <see cref="UInt16"/> value to write.</param> // public virtual void WriteValue(ushort value) { AutoComplete(JsonToken.Integer); } /// <summary> /// Writes a <see cref="Char"/> value. /// </summary> /// <param name="value">The <see cref="Char"/> value to write.</param> public virtual void WriteValue(char value) { AutoComplete(JsonToken.String); } /// <summary> /// Writes a <see cref="Byte"/> value. /// </summary> /// <param name="value">The <see cref="Byte"/> value to write.</param> public virtual void WriteValue(byte value) { AutoComplete(JsonToken.Integer); } /// <summary> /// Writes a <see cref="SByte"/> value. /// </summary> /// <param name="value">The <see cref="SByte"/> value to write.</param> // public virtual void WriteValue(sbyte value) { AutoComplete(JsonToken.Integer); } /// <summary> /// Writes a <see cref="Decimal"/> value. /// </summary> /// <param name="value">The <see cref="Decimal"/> value to write.</param> public virtual void WriteValue(decimal value) { AutoComplete(JsonToken.Float); } /// <summary> /// Writes a <see cref="DateTime"/> value. /// </summary> /// <param name="value">The <see cref="DateTime"/> value to write.</param> public virtual void WriteValue(DateTime value) { AutoComplete(JsonToken.Date); } /// <summary> /// Writes a <see cref="DateTimeOffset"/> value. /// </summary> /// <param name="value">The <see cref="DateTimeOffset"/> value to write.</param> public virtual void WriteValue(DateTimeOffset value) { AutoComplete(JsonToken.Date); } /// <summary> /// Writes a <see cref="Guid"/> value. /// </summary> /// <param name="value">The <see cref="Guid"/> value to write.</param> public virtual void WriteValue(Guid value) { AutoComplete(JsonToken.String); } /// <summary> /// Writes a <see cref="TimeSpan"/> value. /// </summary> /// <param name="value">The <see cref="TimeSpan"/> value to write.</param> public virtual void WriteValue(TimeSpan value) { AutoComplete(JsonToken.String); } /// <summary> /// Writes a <see cref="Nullable{Int32}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{Int32}"/> value to write.</param> public virtual void WriteValue(int? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{UInt32}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{UInt32}"/> value to write.</param> // public virtual void WriteValue(uint? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{Int64}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{Int64}"/> value to write.</param> public virtual void WriteValue(long? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{UInt64}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{UInt64}"/> value to write.</param> // public virtual void WriteValue(ulong? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{Single}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{Single}"/> value to write.</param> public virtual void WriteValue(float? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{Double}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{Double}"/> value to write.</param> public virtual void WriteValue(double? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{Boolean}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{Boolean}"/> value to write.</param> public virtual void WriteValue(bool? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{Int16}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{Int16}"/> value to write.</param> public virtual void WriteValue(short? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{UInt16}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{UInt16}"/> value to write.</param> // public virtual void WriteValue(ushort? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{Char}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{Char}"/> value to write.</param> public virtual void WriteValue(char? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{Byte}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{Byte}"/> value to write.</param> public virtual void WriteValue(byte? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{SByte}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{SByte}"/> value to write.</param> // public virtual void WriteValue(sbyte? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{Decimal}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{Decimal}"/> value to write.</param> public virtual void WriteValue(decimal? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{DateTime}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{DateTime}"/> value to write.</param> public virtual void WriteValue(DateTime? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{DateTimeOffset}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{DateTimeOffset}"/> value to write.</param> public virtual void WriteValue(DateTimeOffset? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{Guid}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{Guid}"/> value to write.</param> public virtual void WriteValue(Guid? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="Nullable{TimeSpan}"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{TimeSpan}"/> value to write.</param> public virtual void WriteValue(TimeSpan? value) { if (value == null) WriteNull(); else WriteValue(value.Value); } /// <summary> /// Writes a <see cref="T:Byte[]"/> value. /// </summary> /// <param name="value">The <see cref="T:Byte[]"/> value to write.</param> public virtual void WriteValue(byte[] value) { if (value == null) WriteNull(); else AutoComplete(JsonToken.Bytes); } /// <summary> /// Writes a <see cref="Uri"/> value. /// </summary> /// <param name="value">The <see cref="Uri"/> value to write.</param> public virtual void WriteValue(Uri value) { if (value == null) WriteNull(); else AutoComplete(JsonToken.String); } /// <summary> /// Writes a <see cref="Object"/> value. /// An error will raised if the value cannot be written as a single JSON token. /// </summary> /// <param name="value">The <see cref="Object"/> value to write.</param> public virtual void WriteValue(object value) { if (value == null) { WriteNull(); return; } else if (value is IConvertible) { IConvertible convertible = value as IConvertible; switch (convertible.GetTypeCode()) { case TypeCode.String: WriteValue(convertible.ToString(CultureInfo.InvariantCulture)); return; case TypeCode.Char: WriteValue(convertible.ToChar(CultureInfo.InvariantCulture)); return; case TypeCode.Boolean: WriteValue(convertible.ToBoolean(CultureInfo.InvariantCulture)); return; case TypeCode.SByte: WriteValue(convertible.ToSByte(CultureInfo.InvariantCulture)); return; case TypeCode.Int16: WriteValue(convertible.ToInt16(CultureInfo.InvariantCulture)); return; case TypeCode.UInt16: WriteValue(convertible.ToUInt16(CultureInfo.InvariantCulture)); return; case TypeCode.Int32: WriteValue(convertible.ToInt32(CultureInfo.InvariantCulture)); return; case TypeCode.Byte: WriteValue(convertible.ToByte(CultureInfo.InvariantCulture)); return; case TypeCode.UInt32: WriteValue(convertible.ToUInt32(CultureInfo.InvariantCulture)); return; case TypeCode.Int64: WriteValue(convertible.ToInt64(CultureInfo.InvariantCulture)); return; case TypeCode.UInt64: WriteValue(convertible.ToUInt64(CultureInfo.InvariantCulture)); return; case TypeCode.Single: WriteValue(convertible.ToSingle(CultureInfo.InvariantCulture)); return; case TypeCode.Double: WriteValue(convertible.ToDouble(CultureInfo.InvariantCulture)); return; case TypeCode.DateTime: WriteValue(convertible.ToDateTime(CultureInfo.InvariantCulture)); return; case TypeCode.Decimal: WriteValue(convertible.ToDecimal(CultureInfo.InvariantCulture)); return; case TypeCode.DBNull: WriteNull(); return; } } else if (value is DateTimeOffset) { WriteValue((DateTimeOffset)value); return; } else if (value is byte[]) { WriteValue((byte[])value); return; } else if (value is Guid) { WriteValue((Guid)value); return; } else if (value is Uri) { WriteValue((Uri)value); return; } else if (value is TimeSpan) { WriteValue((TimeSpan)value); return; } throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType())); } #endregion /// <summary> /// Writes out a comment <code>/*...*/</code> containing the specified text. /// </summary> /// <param name="text">Text to place inside the comment.</param> public virtual void WriteComment(string text) { AutoComplete(JsonToken.Comment); } /// <summary> /// Writes out the given white space. /// </summary> /// <param name="ws">The string of white space characters.</param> public virtual void WriteWhitespace(string ws) { if (ws != null) { if (!StringUtils.IsWhiteSpace(ws)) throw new JsonWriterException("Only white space characters should be used."); } } void IDisposable.Dispose() { Dispose(true); } private void Dispose(bool disposing) { if (WriteState != WriteState.Closed) Close(); } } } #endif
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Sample.WebApi.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); } } } }
//+----------------------------------------------------------------------- // // Copyright (c) Microsoft Corporation. All rights reserved. // // Description: // Helper class for handling all web requests/responses in the framework. Using it ensures consisent // handling and support for special features: cookies, NTLM authentication, caching, inferring MIME // type from filename. // // History: // 2007/04/11 [....] Created // //------------------------------------------------------------------------ using System; using System.Net; using System.Net.Cache; using System.Security; using System.Security.Permissions; using System.IO; using System.Windows.Navigation; using System.IO.Packaging; using MS.Internal.AppModel; using MS.Internal.Utility; using MS.Internal.PresentationCore; //From Presharp documentation: //In order to avoid generating warnings about unknown message numbers and //unknown pragmas when compiling your C# source code with the actual C# compiler, //you need to disable warnings 1634 and 1691. #pragma warning disable 1634, 1691 namespace MS.Internal { /// <summary> /// Helper class for handling all web requests/responses in the framework. Using it ensures consisent handling /// and support for special features: cookies, NTLM authentication, caching, inferring MIME type from filename. /// /// Only two methods are mandatory: /// - CreateRequest. (PackWebRequestFactory.CreateWebRequest is an allowed alternative. It delegates to /// this CreateRequest for non-pack URIs.) /// - HandleWebResponse. /// The remaining methods just automate the entire request process, up to the point of getting the response /// stream. Using the SecurityTreatAsSafe ones helps avoid making other code SecurityCritical. /// /// Related types: /// - BaseUriHelper /// - BindUriHelper (built into Framework, subset into Core) /// - PackWebRequestFactory /// - MimeObjectFactory /// </summary> static class WpfWebRequestHelper { /// <SecurityNote> /// Critical: Elevates to set WebRequest.UseDefaultCredentials. /// Safe: Activates the CustomCredentialPolicy, which makes sure the user's system credentials are not /// sent across the Internet. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] [FriendAccessAllowed] internal static WebRequest CreateRequest(Uri uri) { // Ideally we would want to use RegisterPrefix and WebRequest.Create. // However, these two functions regress 700k working set in System.dll and System.xml.dll // which is mostly for logging and config. // Call PackWebRequestFactory.CreateWebRequest to bypass the regression if possible // by calling Create on PackWebRequest if uri is pack scheme if (string.Compare(uri.Scheme, PackUriHelper.UriSchemePack, StringComparison.Ordinal) == 0) { return PackWebRequestFactory.CreateWebRequest(uri); // The PackWebRequest may end up creating a "real" web request as its inner request. // It will then call this method again. } // Work around the issue with FileWebRequest not handling #. Details in bug 1096304. // FileWebRequest doesn't support the concept of query and fragment. if (uri.IsFile) { uri = new Uri(uri.GetLeftPart(UriPartial.Path)); } WebRequest request = WebRequest.Create(uri); // It is not clear whether WebRequest.Create() can ever return null, but v1 code make this check in // a couple of places, so it is still done here, just in case. if(request == null) { // Unfortunately, there is no appropriate exception string in PresentationCore, and for v3.5 // we have a total resource freeze. So just report WebExceptionStatus.RequestCanceled: // "The request was canceled, the WebRequest.Abort method was called, or an unclassifiable error // occurred. This is the default value for Status." Uri requestUri = BaseUriHelper.PackAppBaseUri.MakeRelativeUri(uri); throw new WebException(requestUri.ToString(), WebExceptionStatus.RequestCanceled); //throw new IOException(SR.Get(SRID.GetResponseFailed, requestUri.ToString())); } HttpWebRequest httpRequest = request as HttpWebRequest; if (httpRequest != null) { if (string.IsNullOrEmpty(httpRequest.UserAgent)) { httpRequest.UserAgent = DefaultUserAgent; } CookieHandler.HandleWebRequest(httpRequest); if (String.IsNullOrEmpty(httpRequest.Referer)) { httpRequest.Referer = BindUriHelper.GetReferer(uri); } CustomCredentialPolicy.EnsureCustomCredentialPolicy(); // Enable NTLM authentication. // This is safe to do thanks to the CustomCredentialPolicy. (new EnvironmentPermission(EnvironmentPermissionAccess.Read, "USERNAME")).Assert(); // BlessedAssert try { httpRequest.UseDefaultCredentials = true; } finally { EnvironmentPermission.RevertAssert(); } } return request; } /// <remarks> ****** /// This method was factored out of the defunct BindUriHelper.ConfigHttpWebRequest(). /// Ideally, all framework-created web requests should use the same caching settings, but in order not to /// change behavior in SP1/v3.5, ConfigCachePolicy() is called separately by the code that previously /// relied on ConfigHttpWebRequest(). /// </remarks> [FriendAccessAllowed] static internal void ConfigCachePolicy(WebRequest request, bool isRefresh) { HttpWebRequest httpRequest = request as HttpWebRequest; if (httpRequest != null) { // Setting CachePolicy to the default level if it is null. if (request.CachePolicy == null || request.CachePolicy.Level != RequestCacheLevel.Default) { if (isRefresh) { if (_httpRequestCachePolicyRefresh == null) { _httpRequestCachePolicyRefresh = new HttpRequestCachePolicy(HttpRequestCacheLevel.Refresh); } request.CachePolicy = _httpRequestCachePolicyRefresh; } else { if (_httpRequestCachePolicy == null) { _httpRequestCachePolicy = new HttpRequestCachePolicy(); } request.CachePolicy = _httpRequestCachePolicy; } } } } private static HttpRequestCachePolicy _httpRequestCachePolicy; private static HttpRequestCachePolicy _httpRequestCachePolicyRefresh; /// <SecurityNote> /// Critical (getter): Calls the native ObtainUserAgentString(). /// Safe: User-agent string is safe to expose. An XBAP could get it by asking the server what the browser /// sent it initially. /// </SecurityNote> internal static string DefaultUserAgent { [SecurityCritical, SecurityTreatAsSafe] get { if (_defaultUserAgent == null) { _defaultUserAgent = MS.Win32.UnsafeNativeMethods.ObtainUserAgentString(); } return _defaultUserAgent; } set // set by ApplicationProxyInternal for browser hosting { _defaultUserAgent = value; } } private static string _defaultUserAgent; /// <SecurityNote> /// Critical: Calls the critical CookieHandler.HandleWebResponse(). /// We need a secure path for passing authentic, unaltered HttpWebRespones. /// CAUTION: Presently, callers of this method are not required to make any security guarantee about /// non-HTTP web responses. They will all need to be revised if secure handling of other types of /// requests/responses becomes necessary. /// </SecurityNote> [SecurityCritical] [FriendAccessAllowed] internal static void HandleWebResponse(WebResponse response) { CookieHandler.HandleWebResponse(response); } [FriendAccessAllowed] internal static Stream CreateRequestAndGetResponseStream(Uri uri) { WebRequest request = CreateRequest(uri); return GetResponseStream(request); } [FriendAccessAllowed] internal static Stream CreateRequestAndGetResponseStream(Uri uri, out ContentType contentType) { WebRequest request = CreateRequest(uri); return GetResponseStream(request, out contentType); } [FriendAccessAllowed] internal static WebResponse CreateRequestAndGetResponse(Uri uri) { WebRequest request = CreateRequest(uri); return GetResponse(request); } /// <SecurityNote> /// Critical: Calls the critical HandleWebResponse(), which expects unaltered, authentic HttpWebResponses. /// Safe: The response is obtained right here and is passed directly to HandleWebResponse(). /// Even if the given request object is bogus, it cannot produce an HttpWebResponse, because the class /// has no public or protected constructor. However, a bogus request could attach to itself an /// HttpWebResponse from a real request and alter it. This possibility is prevented by a type check. /// A critical assumption is that HttpWebRequest cannot be derived from and therefore its behavior /// cannot be altered (beyond what its public APIs allow, but the security-sensitive ones demand /// appropriate permission). /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] [FriendAccessAllowed] internal static WebResponse GetResponse(WebRequest request) { WebResponse response = request.GetResponse(); // 'is' is used here instead of exact type checks to allow for the (remote) possibility that an internal // implementation type derived from HttpWebRequest/Response may be used by System.Net. if (response is HttpWebResponse && !(request is HttpWebRequest)) throw new ArgumentException(); // It is not clear whether WebRequest.GetRespone() can ever return null, but some of the v1 code had // this check, so it is added here just in case. if (response == null) { Uri requestUri = BaseUriHelper.PackAppBaseUri.MakeRelativeUri(request.RequestUri); throw new IOException(SR.Get(SRID.GetResponseFailed, requestUri.ToString())); } HandleWebResponse(response); return response; } /// <SecurityNote> /// [See GetResponse()] /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] [FriendAccessAllowed] internal static WebResponse EndGetResponse(WebRequest request, IAsyncResult ar) { WebResponse response = request.EndGetResponse(ar); if (response is HttpWebResponse && !(request is HttpWebRequest)) throw new ArgumentException(); // It is not clear whether WebRequest.GetRespone() can ever return null, but some of the v1 code had // this check, so it is added here just in case. if (response == null) { Uri requestUri = BaseUriHelper.PackAppBaseUri.MakeRelativeUri(request.RequestUri); throw new IOException(SR.Get(SRID.GetResponseFailed, requestUri.ToString())); } HandleWebResponse(response); return response; } [FriendAccessAllowed] internal static Stream GetResponseStream(WebRequest request) { WebResponse response = GetResponse(request); return response.GetResponseStream(); } /// <summary> /// Gets the response from the given request and determines the content type using the special rules /// implemented in GetContentType(). /// </summary> [FriendAccessAllowed] internal static Stream GetResponseStream(WebRequest request, out ContentType contentType) { WebResponse response = GetResponse(request); contentType = GetContentType(response); return response.GetResponseStream(); } // [Apr'07. Code moved here from BaseUriHelper.GetContentType().] /// <summary> /// Tries hard to obtain the content type of the given WebResponse. Special cases: /// - The ContentType property may throw if not implemented. /// - Unconfigured web servers don't return the right type for WPF content. This method does lookup based on /// file extension. /// </summary> [FriendAccessAllowed] internal static ContentType GetContentType(WebResponse response) { ContentType contentType = ContentType.Empty; // FileWebResponse returns a generic mime type for all files regardless of extension. // We have requested fix but it's postponed to orcas. This is a work around for that. // if (!(response is FileWebResponse)) { // For all other cases use the WebResponse's ContentType if it is available try { contentType = new ContentType(response.ContentType); // If our content type is octet-stream or text/plain, we might be dealing with an unconfigured server. // If the extension is .xaml or .xbap we ignore the server's content type and determine // the content type based on the URI's extension. if (MimeTypeMapper.OctetMime.AreTypeAndSubTypeEqual(contentType, true) || MimeTypeMapper.TextPlainMime.AreTypeAndSubTypeEqual(contentType, true)) { string extension = MimeTypeMapper.GetFileExtension(response.ResponseUri); if ((String.Compare(extension, MimeTypeMapper.XamlExtension, StringComparison.OrdinalIgnoreCase) == 0) || (String.Compare(extension, MimeTypeMapper.XbapExtension, StringComparison.OrdinalIgnoreCase) == 0)) { contentType = ContentType.Empty; // Will cause GetMimeTypeFromUri to be called below } } } #pragma warning disable 6502 catch (NotImplementedException) { // this is a valid result and indicates that the subclass chose not to implement this property } catch (NotSupportedException) { // this is a valid result and indicates that the subclass chose not to implement this property } #pragma warning restore 6502 } // DevDiv2 29007 - IE9 - pack://siteoforigin:,,,/ Uris fail for standalone applications // Something about the contentType object we get when IE9 is installed breaks file-system pack://siteoforigin:,,, Uris // when we get here with a blank ContentType object. // Workaround: Since we're only checking that content type hasn't been determined yet, checking the public properties versus // ContentType.Empty's copy of the same gets the same result, and also works for all versions of IE. if (contentType.TypeComponent == ContentType.Empty.TypeComponent && contentType.OriginalString == ContentType.Empty.OriginalString && contentType.SubTypeComponent == ContentType.Empty.SubTypeComponent) { contentType = MimeTypeMapper.GetMimeTypeFromUri(response.ResponseUri); } return contentType; } }; }
// 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.Diagnostics.Tracing; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Serialization.Formatters.Binary; using System.Security; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Runtime.Serialization.Formatters.Tests { public class BinaryFormatterTests : RemoteExecutorTestBase { public static IEnumerable<object> SerializableObjects() { // Primitive types yield return byte.MinValue; yield return byte.MaxValue; yield return sbyte.MinValue; yield return sbyte.MaxValue; yield return short.MinValue; yield return short.MaxValue; yield return int.MinValue; yield return int.MaxValue; yield return uint.MinValue; yield return uint.MaxValue; yield return long.MinValue; yield return long.MaxValue; yield return ulong.MinValue; yield return ulong.MaxValue; yield return char.MinValue; yield return char.MaxValue; yield return float.MinValue; yield return float.MaxValue; yield return double.MinValue; yield return double.MaxValue; yield return decimal.MinValue; yield return decimal.MaxValue; yield return decimal.MinusOne; yield return true; yield return false; yield return ""; yield return "c"; yield return "\u4F60\u597D"; yield return "some\0data\0with\0null\0chars"; yield return "<>&\"\'"; yield return " < "; yield return "minchar" + char.MinValue + "minchar"; // Enum values yield return DayOfWeek.Monday; yield return DateTimeKind.Local; // Nullables yield return (int?)1; yield return (StructWithIntField?)new StructWithIntField() { X = 42 }; // Other core serializable types yield return IntPtr.Zero; yield return UIntPtr.Zero; yield return DateTime.Now; yield return DateTimeOffset.Now; yield return DateTimeKind.Local; yield return TimeSpan.FromDays(7); yield return new Version(1, 2, 3, 4); yield return new Guid("0CACAA4D-C6BD-420A-B660-2F557337CA89"); yield return new AttributeUsageAttribute(AttributeTargets.Class); yield return new List<int>(); yield return new List<int>() { 1, 2, 3, 4, 5 }; yield return new Dictionary<int, string>() { { 1, "test" }, { 2, "another test" } }; yield return Tuple.Create(1); yield return Tuple.Create(1, "2"); yield return Tuple.Create(1, "2", 3u); yield return Tuple.Create(1, "2", 3u, 4L); yield return Tuple.Create(1, "2", 3u, 4L, 5.6); yield return Tuple.Create(1, "2", 3u, 4L, 5.6, 7.8f); yield return Tuple.Create(1, "2", 3u, 4L, 5.6, 7.8f, 9m); yield return Tuple.Create(1, "2", 3u, 4L, 5.6, 7.8f, 9m, Tuple.Create(10)); yield return new KeyValuePair<int, byte>(42, 84); // Arrays of primitive types yield return Enumerable.Range(0, 256).Select(i => (byte)i).ToArray(); yield return new int[] { }; yield return new int[] { 1 }; yield return new int[] { 1, 2, 3, 4, 5 }; yield return new char[] { 'a', 'b', 'c', 'd', 'e' }; yield return new string[] { }; yield return new string[] { "hello", "world" }; yield return new short[] { short.MaxValue }; yield return new long[] { long.MaxValue }; yield return new ushort[] { ushort.MaxValue }; yield return new uint[] { uint.MaxValue }; yield return new ulong[] { ulong.MaxValue }; yield return new bool[] { true, false }; yield return new double[] { 1.2 }; yield return new float[] { 1.2f, 3.4f }; // Arrays of other types yield return new object[] { }; yield return new Guid[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() }; yield return new DayOfWeek[] { DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday }; yield return new Point[] { new Point(1, 2), new Point(3, 4) }; yield return new ObjectWithArrays { IntArray = new int[0], StringArray = new string[] { "hello", "world" }, ByteArray = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }, JaggedArray = new int[][] { new int[] { 1, 2, 3 }, new int[] { 4, 5, 6, 7 } }, MultiDimensionalArray = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } }, TreeArray = new Tree<int>[] { new Tree<int>(1, new Tree<int>(2, null, null), new Tree<int>(3, null, null)) } }; yield return new object[] { new int[,] { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 11, 12, 13, 14, 15 } } }; yield return new object[] { new int[,,] { { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 11, 12, 13, 14, 15 } } } }; yield return new object[] { new int[,,,,] { { { { { 1 } } } } } }; yield return new ArraySegment<int>(new int[] { 1, 2, 3, 4, 5 }, 1, 2); yield return Enumerable.Range(0, 10000).Select(i => (object)i).ToArray(); yield return new object[200]; // fewer than 256 nulls yield return new object[300]; // more than 256 nulls // Non-vector arrays yield return Array.CreateInstance(typeof(uint), new[] { 5 }, new[] { 1 }); yield return Array.CreateInstance(typeof(int), new[] { 0, 0, 0 }, new[] { 0, 0, 0 }); var arr = Array.CreateInstance(typeof(string), new[] { 1, 2 }, new[] { 3, 4 }); arr.SetValue("hello", new[] { 3, 5 }); yield return arr; // Various globalization types yield return CultureInfo.CurrentCulture; yield return CultureInfo.InvariantCulture; // Internal specialized equality comparers yield return EqualityComparer<byte>.Default; yield return EqualityComparer<int>.Default; yield return EqualityComparer<string>.Default; yield return EqualityComparer<int?>.Default; yield return EqualityComparer<double?>.Default; yield return EqualityComparer<object>.Default; yield return EqualityComparer<Int32Enum>.Default; // Custom object var sealedObjectWithIntStringFields = new SealedObjectWithIntStringFields(); yield return sealedObjectWithIntStringFields; yield return new SealedObjectWithIntStringFields() { Member1 = 42, Member2 = null, Member3 = "84" }; // Custom object with fields pointing to the same object yield return new ObjectWithIntStringUShortUIntULongAndCustomObjectFields { Member1 = 10, Member2 = "hello", _member3 = "hello", Member4 = sealedObjectWithIntStringFields, Member4shared = sealedObjectWithIntStringFields, Member5 = new SealedObjectWithIntStringFields(), Member6 = "Hello World", str1 = "hello < world", str2 = "<", str3 = "< world", str4 = "hello < world", u16 = ushort.MaxValue, u32 = uint.MaxValue, u64 = ulong.MaxValue, }; // Simple type without a default ctor var point = new Point(1, 2); yield return point; // Graph without cycles yield return new Tree<int>(42, null, null); yield return new Tree<int>(1, new Tree<int>(2, new Tree<int>(3, null, null), null), null); yield return new Tree<Colors>(Colors.Red, null, new Tree<Colors>(Colors.Blue, null, new Tree<Colors>(Colors.Green, null, null))); yield return new Tree<int>(1, new Tree<int>(2, new Tree<int>(3, null, null), new Tree<int>(4, null, null)), new Tree<int>(5, null, null)); // Graph with cycles Graph<int> a = new Graph<int> { Value = 1 }; yield return a; Graph<int> b = new Graph<int> { Value = 2, Links = new[] { a } }; yield return b; Graph<int> c = new Graph<int> { Value = 3, Links = new[] { a, b } }; yield return c; Graph<int> d = new Graph<int> { Value = 3, Links = new[] { a, b, c } }; yield return d; a.Links = new[] { b, c, d }; // complete the cycle yield return a; // Structs yield return new EmptyStruct(); yield return new StructWithIntField { X = 42 }; yield return new StructWithStringFields { String1 = "hello", String2 = "world" }; yield return new StructContainingOtherStructs { Nested1 = new StructWithStringFields { String1 = "a", String2 = "b" }, Nested2 = new StructWithStringFields { String1 = "3", String2 = "4" } }; yield return new StructContainingArraysOfOtherStructs(); yield return new StructContainingArraysOfOtherStructs { Nested = new StructContainingOtherStructs[0] }; var s = new StructContainingArraysOfOtherStructs { Nested = new[] { new StructContainingOtherStructs { Nested1 = new StructWithStringFields { String1 = "a", String2 = "b" }, Nested2 = new StructWithStringFields { String1 = "3", String2 = "4" } }, new StructContainingOtherStructs { Nested1 = new StructWithStringFields { String1 = "e", String2 = "f" }, Nested2 = new StructWithStringFields { String1 = "7", String2 = "8" } }, } }; yield return s; yield return new object[] { s, new StructContainingArraysOfOtherStructs?(s) }; // ISerializable yield return new BasicISerializableObject(1, "2"); yield return new DerivedISerializableWithNonPublicDeserializationCtor(1, "2"); // Various other special cases yield return new TypeWithoutNamespace(); } public static IEnumerable<object> NonSerializableObjects() { yield return new NonSerializableStruct(); yield return new NonSerializableClass(); yield return new SerializableClassWithBadField(); yield return new object[] { 1, 2, 3, new NonSerializableClass() }; } public static IEnumerable<object[]> ValidateBasicObjectsRoundtrip_MemberData() { foreach (object obj in SerializableObjects()) { foreach (FormatterAssemblyStyle assemblyFormat in new[] { FormatterAssemblyStyle.Full, FormatterAssemblyStyle.Simple }) { foreach (TypeFilterLevel filterLevel in new[] { TypeFilterLevel.Full, TypeFilterLevel.Low }) { foreach (FormatterTypeStyle typeFormat in new[] { FormatterTypeStyle.TypesAlways, FormatterTypeStyle.TypesWhenNeeded, FormatterTypeStyle.XsdString }) { yield return new object[] { obj, assemblyFormat, filterLevel, typeFormat}; } } } } } [Theory] [MemberData(nameof(ValidateBasicObjectsRoundtrip_MemberData))] public void ValidateBasicObjectsRoundtrip(object obj, FormatterAssemblyStyle assemblyFormat, TypeFilterLevel filterLevel, FormatterTypeStyle typeFormat) { object result = FormatterClone(obj, null, assemblyFormat, filterLevel, typeFormat); if (!ReferenceEquals(obj, string.Empty)) // "" is interned and will roundtrip as the same object { Assert.NotSame(obj, result); } Assert.Equal(obj, result); } [Fact] public void RoundtripManyObjectsInOneStream() { object[] objects = SerializableObjects().ToArray(); var s = new MemoryStream(); var f = new BinaryFormatter(); foreach (object obj in objects) { f.Serialize(s, obj); } s.Position = 0; foreach (object obj in objects) { object result = f.Deserialize(s); Assert.Equal(obj, result); } } [Fact] public void SameObjectRepeatedInArray() { object o = new object(); object[] arr = new[] { o, o, o, o, o }; object[] result = FormatterClone(arr); Assert.Equal(arr.Length, result.Length); Assert.NotSame(arr, result); Assert.NotSame(arr[0], result[0]); for (int i = 1; i < result.Length; i++) { Assert.Same(result[0], result[i]); } } public static IEnumerable<object[]> SerializableExceptions() { yield return new object[] { new AbandonedMutexException() }; yield return new object[] { new AggregateException(new FieldAccessException(), new MemberAccessException()) }; yield return new object[] { new AmbiguousMatchException() }; yield return new object[] { new ArgumentException("message", "paramName") }; yield return new object[] { new ArgumentNullException("paramName") }; yield return new object[] { new ArgumentOutOfRangeException("paramName", 42, "message") }; yield return new object[] { new ArithmeticException() }; yield return new object[] { new ArrayTypeMismatchException("message") }; yield return new object[] { new BadImageFormatException("message", "filename") }; yield return new object[] { new COMException() }; yield return new object[] { new CultureNotFoundException() }; yield return new object[] { new DataMisalignedException("message") }; yield return new object[] { new DecoderFallbackException() }; yield return new object[] { new DirectoryNotFoundException() }; yield return new object[] { new DivideByZeroException() }; yield return new object[] { new DllNotFoundException() }; yield return new object[] { new EncoderFallbackException() }; yield return new object[] { new EndOfStreamException() }; yield return new object[] { new EventSourceException() }; yield return new object[] { new Exception("message") }; yield return new object[] { new FieldAccessException("message", new FieldAccessException()) }; yield return new object[] { new FileLoadException() }; yield return new object[] { new FileNotFoundException() }; yield return new object[] { new FormatException("message") }; yield return new object[] { new IndexOutOfRangeException() }; yield return new object[] { new InsufficientExecutionStackException() }; yield return new object[] { new InvalidCastException() }; yield return new object[] { new InvalidComObjectException() }; yield return new object[] { new InvalidOleVariantTypeException() }; yield return new object[] { new InvalidOperationException() }; yield return new object[] { new InvalidProgramException() }; yield return new object[] { new InvalidTimeZoneException() }; yield return new object[] { new IOException() }; yield return new object[] { new KeyNotFoundException() }; yield return new object[] { new LockRecursionException() }; yield return new object[] { new MarshalDirectiveException() }; yield return new object[] { new MemberAccessException() }; yield return new object[] { new MethodAccessException() }; yield return new object[] { new MissingFieldException() }; yield return new object[] { new MissingMemberException() }; yield return new object[] { new NotImplementedException() }; yield return new object[] { new NotSupportedException() }; yield return new object[] { new NullReferenceException() }; yield return new object[] { new ObjectDisposedException("objectName") }; yield return new object[] { new OperationCanceledException(new CancellationTokenSource().Token) }; yield return new object[] { new OutOfMemoryException() }; yield return new object[] { new OverflowException() }; yield return new object[] { new PathTooLongException() }; yield return new object[] { new PlatformNotSupportedException() }; yield return new object[] { new RankException() }; yield return new object[] { new SafeArrayRankMismatchException() }; yield return new object[] { new SafeArrayTypeMismatchException() }; yield return new object[] { new SecurityException() }; yield return new object[] { new SEHException() }; yield return new object[] { new SemaphoreFullException() }; yield return new object[] { new SerializationException() }; yield return new object[] { new SynchronizationLockException() }; yield return new object[] { new TargetInvocationException("message", new Exception()) }; yield return new object[] { new TargetParameterCountException() }; yield return new object[] { new TaskCanceledException(Task.CompletedTask) }; yield return new object[] { new TaskSchedulerException() }; yield return new object[] { new TimeoutException() }; yield return new object[] { new TypeAccessException() }; yield return new object[] { new TypeInitializationException(typeof(string).FullName, new Exception()) }; yield return new object[] { new TypeLoadException() }; yield return new object[] { new UnauthorizedAccessException("message", new ArgumentNullException()) }; yield return new object[] { new VerificationException() }; yield return new object[] { new WaitHandleCannotBeOpenedException() }; } [Theory] [MemberData(nameof(SerializableExceptions))] public void Roundtrip_Exceptions(Exception expected) { BinaryFormatterHelpers.AssertRoundtrips(expected); } private static int Identity(int i) => i; [Fact] public void Roundtrip_Delegates_NoTarget() { Func<int, int> expected = Identity; Assert.Null(expected.Target); Func<int, int> actual = FormatterClone(expected); Assert.NotSame(expected, actual); Assert.Same(expected.GetMethodInfo(), actual.GetMethodInfo()); Assert.Equal(expected(42), actual(42)); } [Fact] public void Roundtrip_Delegates_Target() { var owsam = new ObjectWithStateAndMethod { State = 42 }; Func<int> expected = owsam.GetState; Assert.Same(owsam, expected.Target); Func<int> actual = FormatterClone(expected); Assert.NotSame(expected, actual); Assert.NotSame(expected.Target, actual.Target); Assert.Equal(expected(), actual()); } public static IEnumerable<object[]> SerializableObjectsWithFuncOfObjectToCompare() { object target = 42; yield return new object[] { new Random(), new Func<object, object>(o => ((Random)o).Next()) }; } [Theory] [MemberData(nameof(SerializableObjectsWithFuncOfObjectToCompare))] public void Roundtrip_ObjectsWithComparers(object obj, Func<object, object> getResult) { object actual = FormatterClone(obj); Assert.Equal(getResult(obj), getResult(actual)); } public static IEnumerable<object[]> ValidateNonSerializableTypes_MemberData() { foreach (object obj in NonSerializableObjects()) { foreach (FormatterAssemblyStyle assemblyFormat in new[] { FormatterAssemblyStyle.Full, FormatterAssemblyStyle.Simple }) { foreach (TypeFilterLevel filterLevel in new[] { TypeFilterLevel.Full, TypeFilterLevel.Low }) { foreach (FormatterTypeStyle typeFormat in new[] { FormatterTypeStyle.TypesAlways, FormatterTypeStyle.TypesWhenNeeded, FormatterTypeStyle.XsdString }) { yield return new object[] { obj, assemblyFormat, filterLevel, typeFormat }; } } } } } [Theory] [MemberData(nameof(ValidateNonSerializableTypes_MemberData))] public void ValidateNonSerializableTypes(object obj, FormatterAssemblyStyle assemblyFormat, TypeFilterLevel filterLevel, FormatterTypeStyle typeFormat) { var f = new BinaryFormatter() { AssemblyFormat = assemblyFormat, FilterLevel = filterLevel, TypeFormat = typeFormat }; using (var s = new MemoryStream()) { Assert.Throws<SerializationException>(() => f.Serialize(s, obj)); } } [Fact] public void SerializeNonSerializableTypeWithSurrogate() { var p = new NonSerializablePair<int, string>() { Value1 = 1, Value2 = "2" }; Assert.False(p.GetType().IsSerializable); Assert.Throws<SerializationException>(() => FormatterClone(p)); NonSerializablePair<int, string> result = FormatterClone(p, new NonSerializablePairSurrogate()); Assert.NotSame(p, result); Assert.Equal(p.Value1, result.Value1); Assert.Equal(p.Value2, result.Value2); } [Fact] public void SerializationEvents_FireAsExpected() { var f = new BinaryFormatter(); var obj = new IncrementCountsDuringRoundtrip(null); Assert.Equal(0, obj.IncrementedDuringOnSerializingMethod); Assert.Equal(0, obj.IncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod); using (var s = new MemoryStream()) { f.Serialize(s, obj); s.Position = 0; Assert.Equal(1, obj.IncrementedDuringOnSerializingMethod); Assert.Equal(1, obj.IncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod); var result = (IncrementCountsDuringRoundtrip)f.Deserialize(s); Assert.Equal(1, obj.IncrementedDuringOnSerializingMethod); Assert.Equal(1, obj.IncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod); Assert.Equal(1, result.IncrementedDuringOnSerializingMethod); Assert.Equal(0, result.IncrementedDuringOnSerializedMethod); Assert.Equal(1, result.IncrementedDuringOnDeserializingMethod); Assert.Equal(1, result.IncrementedDuringOnDeserializedMethod); } } [Fact] public void SerializationEvents_DerivedTypeWithEvents_FireAsExpected() { var f = new BinaryFormatter(); var obj = new DerivedIncrementCountsDuringRoundtrip(null); Assert.Equal(0, obj.IncrementedDuringOnSerializingMethod); Assert.Equal(0, obj.IncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod); Assert.Equal(0, obj.DerivedIncrementedDuringOnSerializingMethod); Assert.Equal(0, obj.DerivedIncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializedMethod); using (var s = new MemoryStream()) { f.Serialize(s, obj); s.Position = 0; Assert.Equal(1, obj.IncrementedDuringOnSerializingMethod); Assert.Equal(1, obj.IncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod); Assert.Equal(1, obj.DerivedIncrementedDuringOnSerializingMethod); Assert.Equal(1, obj.DerivedIncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializedMethod); var result = (DerivedIncrementCountsDuringRoundtrip)f.Deserialize(s); Assert.Equal(1, obj.IncrementedDuringOnSerializingMethod); Assert.Equal(1, obj.IncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod); Assert.Equal(1, obj.DerivedIncrementedDuringOnSerializingMethod); Assert.Equal(1, obj.DerivedIncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializedMethod); Assert.Equal(1, result.IncrementedDuringOnSerializingMethod); Assert.Equal(0, result.IncrementedDuringOnSerializedMethod); Assert.Equal(1, result.IncrementedDuringOnDeserializingMethod); Assert.Equal(1, result.IncrementedDuringOnDeserializedMethod); Assert.Equal(1, result.DerivedIncrementedDuringOnSerializingMethod); Assert.Equal(0, result.DerivedIncrementedDuringOnSerializedMethod); Assert.Equal(1, result.DerivedIncrementedDuringOnDeserializingMethod); Assert.Equal(1, result.DerivedIncrementedDuringOnDeserializedMethod); } } [Fact] public void Properties_Roundtrip() { var f = new BinaryFormatter(); Assert.Null(f.Binder); var binder = new DelegateBinder(); f.Binder = binder; Assert.Same(binder, f.Binder); Assert.NotNull(f.Context); Assert.Null(f.Context.Context); Assert.Equal(StreamingContextStates.All, f.Context.State); var context = new StreamingContext(StreamingContextStates.Clone); f.Context = context; Assert.Equal(StreamingContextStates.Clone, f.Context.State); Assert.Null(f.SurrogateSelector); var selector = new SurrogateSelector(); f.SurrogateSelector = selector; Assert.Same(selector, f.SurrogateSelector); Assert.Equal(FormatterAssemblyStyle.Simple, f.AssemblyFormat); f.AssemblyFormat = FormatterAssemblyStyle.Full; Assert.Equal(FormatterAssemblyStyle.Full, f.AssemblyFormat); Assert.Equal(TypeFilterLevel.Full, f.FilterLevel); f.FilterLevel = TypeFilterLevel.Low; Assert.Equal(TypeFilterLevel.Low, f.FilterLevel); Assert.Equal(FormatterTypeStyle.TypesAlways, f.TypeFormat); f.TypeFormat = FormatterTypeStyle.XsdString; Assert.Equal(FormatterTypeStyle.XsdString, f.TypeFormat); } [Fact] public void SerializeDeserialize_InvalidArguments_ThrowsException() { var f = new BinaryFormatter(); Assert.Throws<ArgumentNullException>("serializationStream", () => f.Serialize(null, new object())); Assert.Throws<ArgumentNullException>("serializationStream", () => f.Deserialize(null)); Assert.Throws<SerializationException>(() => f.Deserialize(new MemoryStream())); // seekable, 0-length } [Theory] [InlineData(FormatterAssemblyStyle.Simple, false)] [InlineData(FormatterAssemblyStyle.Full, true)] public void MissingField_FailsWithAppropriateStyle(FormatterAssemblyStyle style, bool exceptionExpected) { var f = new BinaryFormatter(); var s = new MemoryStream(); f.Serialize(s, new Version1ClassWithoutField()); s.Position = 0; f = new BinaryFormatter() { AssemblyFormat = style }; f.Binder = new DelegateBinder { BindToTypeDelegate = (_, __) => typeof(Version2ClassWithoutOptionalField) }; if (exceptionExpected) { Assert.Throws<SerializationException>(() => f.Deserialize(s)); } else { var result = (Version2ClassWithoutOptionalField)f.Deserialize(s); Assert.NotNull(result); Assert.Equal(null, result.Value); } } [Theory] [InlineData(FormatterAssemblyStyle.Simple)] [InlineData(FormatterAssemblyStyle.Full)] public void OptionalField_Missing_Success(FormatterAssemblyStyle style) { var f = new BinaryFormatter(); var s = new MemoryStream(); f.Serialize(s, new Version1ClassWithoutField()); s.Position = 0; f = new BinaryFormatter() { AssemblyFormat = style }; f.Binder = new DelegateBinder { BindToTypeDelegate = (_, __) => typeof(Version2ClassWithOptionalField) }; var result = (Version2ClassWithOptionalField)f.Deserialize(s); Assert.NotNull(result); Assert.Equal(null, result.Value); } [Fact] public void ObjectReference_RealObjectSerialized() { var obj = new ObjRefReturnsObj { Real = 42 }; object real = FormatterClone<object>(obj); Assert.Equal(42, real); } public static IEnumerable<object[]> Deserialize_FuzzInput_MemberData() { var rand = new Random(42); foreach (object obj in SerializableObjects()) { const int FuzzingsPerObject = 3; for (int i = 0; i < FuzzingsPerObject; i++) { yield return new object[] { obj, rand, i }; } } } [OuterLoop] [Theory] [MemberData(nameof(Deserialize_FuzzInput_MemberData))] public void Deserialize_FuzzInput(object obj, Random rand, int fuzzTrial) { // Get the serialized data for the object var f = new BinaryFormatter(); var s = new MemoryStream(); f.Serialize(s, obj); // Make some "random" changes to it byte[] data = s.ToArray(); for (int i = 1; i < rand.Next(1, 100); i++) { data[rand.Next(data.Length)] = (byte)rand.Next(256); } // Try to deserialize that. try { f.Deserialize(new MemoryStream(data)); // Since there's no checksum, it's possible we changed data that didn't corrupt the instance } catch (ArgumentOutOfRangeException) { } catch (ArrayTypeMismatchException) { } catch (DecoderFallbackException) { } catch (FormatException) { } catch (IndexOutOfRangeException) { } catch (InvalidCastException) { } catch (OutOfMemoryException) { } catch (OverflowException) { } catch (NullReferenceException) { } catch (SerializationException) { } catch (TargetInvocationException) { } } [Fact] public void Deserialize_EndOfStream_ThrowsException() { var f = new BinaryFormatter(); var s = new MemoryStream(); f.Serialize(s, 1024); for (long i = s.Length - 1; i >= 0; i--) { s.Position = 0; var data = new byte[i]; Assert.Equal(data.Length, s.Read(data, 0, data.Length)); Assert.Throws<SerializationException>(() => f.Deserialize(new MemoryStream(data))); } } public static IEnumerable<object[]> Roundtrip_CrossProcess_MemberData() { // Just a few objects to verify we can roundtrip out of process memory yield return new object[] { "test" }; yield return new object[] { new List<int> { 1, 2, 3, 4, 5 } }; yield return new object[] { new Tree<int>(1, new Tree<int>(2, new Tree<int>(3, null, null), new Tree<int>(4, null, null)), new Tree<int>(5, null, null)) }; } [Theory] [MemberData(nameof(Roundtrip_CrossProcess_MemberData))] public void Roundtrip_CrossProcess(object obj) { string outputPath = GetTestFilePath(); string inputPath = GetTestFilePath(); // Serialize out to a file using (FileStream fs = File.OpenWrite(outputPath)) { new BinaryFormatter().Serialize(fs, obj); } // In another process, deserialize from that file and serialize to another RemoteInvoke((remoteInput, remoteOutput) => { Assert.False(File.Exists(remoteOutput)); using (FileStream input = File.OpenRead(remoteInput)) using (FileStream output = File.OpenWrite(remoteOutput)) { var b = new BinaryFormatter(); b.Serialize(output, b.Deserialize(input)); return SuccessExitCode; } }, $"\"{outputPath}\"", $"\"{inputPath}\"").Dispose(); // Deserialize what the other process serialized and compare it to the original using (FileStream fs = File.OpenRead(inputPath)) { object deserialized = new BinaryFormatter().Deserialize(fs); Assert.Equal(obj, deserialized); } } [ActiveIssue(16753)] //Fails on desktop and core: 'Unable to cast object of type 'System.UInt32[][*]' to type 'System.Object[]' [Fact] public void Roundtrip_ArrayContainingArrayAtNonZeroLowerBound() { FormatterClone(Array.CreateInstance(typeof(uint[]), new[] { 5 }, new[] { 1 })); } private class DelegateBinder : SerializationBinder { public Func<string, string, Type> BindToTypeDelegate = null; public override Type BindToType(string assemblyName, string typeName) => BindToTypeDelegate?.Invoke(assemblyName, typeName); } private static T FormatterClone<T>( T obj, ISerializationSurrogate surrogate = null, FormatterAssemblyStyle assemblyFormat = FormatterAssemblyStyle.Full, TypeFilterLevel filterLevel = TypeFilterLevel.Full, FormatterTypeStyle typeFormat = FormatterTypeStyle.TypesAlways) { BinaryFormatter f; if (surrogate == null) { f = new BinaryFormatter(); } else { var c = new StreamingContext(); var s = new SurrogateSelector(); s.AddSurrogate(obj.GetType(), c, surrogate); f = new BinaryFormatter(s, c); } f.AssemblyFormat = assemblyFormat; f.FilterLevel = filterLevel; f.TypeFormat = typeFormat; using (var s = new MemoryStream()) { f.Serialize(s, obj); Assert.NotEqual(0, s.Position); s.Position = 0; return (T)(f.Deserialize(s)); } } } }
/* * Copyright (C) 2009 JavaRosa ,Copyright (C) 2014 Simbacode * * 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 org.javarosa.core.util.externalizable; using System; using System.Collections; using System.IO; using System.Text; namespace org.javarosa.xpath.expr { public class XPathStep : Externalizable { public const int AXIS_CHILD = 0; public const int AXIS_DESCENDANT = 1; public const int AXIS_PARENT = 2; public const int AXIS_ANCESTOR = 3; public const int AXIS_FOLLOWING_SIBLING = 4; public const int AXIS_PRECEDING_SIBLING = 5; public const int AXIS_FOLLOWING = 6; public const int AXIS_PRECEDING = 7; public const int AXIS_ATTRIBUTE = 8; public const int AXIS_NAMESPACE = 9; public const int AXIS_SELF = 10; public const int AXIS_DESCENDANT_OR_SELF = 11; public const int AXIS_ANCESTOR_OR_SELF = 12; public const int TEST_NAME = 0; public const int TEST_NAME_WILDCARD = 1; public const int TEST_NAMESPACE_WILDCARD = 2; public const int TEST_TYPE_NODE = 3; public const int TEST_TYPE_TEXT = 4; public const int TEST_TYPE_COMMENT = 5; public const int TEST_TYPE_PROCESSING_INSTRUCTION = 6; public static XPathStep ABBR_SELF() { return new XPathStep(AXIS_SELF, TEST_TYPE_NODE); } public static XPathStep ABBR_PARENT() { return new XPathStep(AXIS_PARENT, TEST_TYPE_NODE); } public static XPathStep ABBR_DESCENDANTS() { return new XPathStep(AXIS_DESCENDANT_OR_SELF, TEST_TYPE_NODE); } public int axis; public int test; public XPathExpression[] predicates; //test-dependent variables public XPathQName name; //TEST_NAME only public String namespace_; //TEST_NAMESPACE_WILDCARD only public String literal; //TEST_TYPE_PROCESSING_INSTRUCTION only public XPathStep() { } //for deserialization public XPathStep(int axis, int test) { this.axis = axis; this.test = test; this.predicates = new XPathExpression[0]; } public XPathStep(int axis, XPathQName name) : this(axis, TEST_NAME) { this.name = name; } public XPathStep(int axis, String namespace_) : this(axis, TEST_NAMESPACE_WILDCARD) { this.namespace_ = namespace_; } public String ToString() { StringBuilder sb = new StringBuilder(); sb.Append("{step:"); sb.Append(axisStr(axis)); sb.Append(","); sb.Append(testStr()); if (predicates.Length > 0) { sb.Append(",{"); for (int i = 0; i < predicates.Length; i++) { sb.Append(predicates[i].ToString()); if (i < predicates.Length - 1) sb.Append(","); } sb.Append("}"); } sb.Append("}"); return sb.ToString(); } public static String axisStr(int axis) { switch (axis) { case AXIS_CHILD: return "child"; case AXIS_DESCENDANT: return "descendant"; case AXIS_PARENT: return "parent"; case AXIS_ANCESTOR: return "ancestor"; case AXIS_FOLLOWING_SIBLING: return "following-sibling"; case AXIS_PRECEDING_SIBLING: return "preceding-sibling"; case AXIS_FOLLOWING: return "following"; case AXIS_PRECEDING: return "preceding"; case AXIS_ATTRIBUTE: return "attribute"; case AXIS_NAMESPACE: return "namespace"; case AXIS_SELF: return "self"; case AXIS_DESCENDANT_OR_SELF: return "descendant-or-self"; case AXIS_ANCESTOR_OR_SELF: return "ancestor-or-self"; default: return null; } } public String testStr() { switch (test) { case TEST_NAME: return name.ToString(); case TEST_NAME_WILDCARD: return "*"; case TEST_NAMESPACE_WILDCARD: return namespace_ + ":*"; case TEST_TYPE_NODE: return "node()"; case TEST_TYPE_TEXT: return "text()"; case TEST_TYPE_COMMENT: return "comment()"; case TEST_TYPE_PROCESSING_INSTRUCTION: return "proc-instr(" + (literal == null ? "" : "\'" + literal + "\'") + ")"; default: return null; } } public Boolean Equals(Object o) { if (o is XPathStep) { XPathStep x = (XPathStep)o; //shortcuts for faster evaluation if (axis != x.axis && test != x.test || predicates.Length != x.predicates.Length) { return false; } switch (test) { case TEST_NAME: if (!name.equals(x.name)) { return false; } break; case TEST_NAMESPACE_WILDCARD: if (!namespace_.Equals(x.namespace_)) { return false; } break; case TEST_TYPE_PROCESSING_INSTRUCTION: if (!ExtUtil.Equals(literal, x.literal)) { return false; } break; default: break; } return ExtUtil.arrayEquals(predicates, x.predicates); } else { return false; } } public void readExternal(BinaryReader in_, PrototypeFactory pf) { axis = ExtUtil.readInt(in_); test = ExtUtil.readInt(in_); switch (test) { case TEST_NAME: name = (XPathQName)ExtUtil.read(in_, typeof(XPathQName)); break; case TEST_NAMESPACE_WILDCARD: namespace_ = ExtUtil.readString(in_); break; case TEST_TYPE_PROCESSING_INSTRUCTION: literal = (String)ExtUtil.read(in_, new ExtWrapNullable(typeof(String))); break; } ArrayList v = (ArrayList)ExtUtil.read(in_, new ExtWrapListPoly(), pf); predicates = new XPathExpression[v.Count]; for (int i = 0; i < predicates.Length; i++) predicates[i] = (XPathExpression)v[i]; } public void writeExternal(BinaryWriter out_) { ExtUtil.writeNumeric(out_, axis); ExtUtil.writeNumeric(out_, test); switch (test) { case TEST_NAME: ExtUtil.write(out_, name); break; case TEST_NAMESPACE_WILDCARD: ExtUtil.writeString(out_, namespace_); break; case TEST_TYPE_PROCESSING_INSTRUCTION: ExtUtil.write(out_, new ExtWrapNullable(literal)); break; } ArrayList v = new ArrayList(); for (int i = 0; i < predicates.Length; i++) v.Add(predicates[i]); ExtUtil.write(out_, new ExtWrapListPoly(v)); } } }