context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using System.Text; using System.Xml; namespace ResxCheck { static class ResxCheck { /// <summary> /// Produces a list of unused resources in Messages and FriendlyNames. /// </summary> /// <param name="removeUnused">If true, will actually purge unused messages from the Messages.resx file</param> public static void FindUnusedMessages(string rootDir, bool removeUnused) { Assembly assembly = Assembly.LoadFrom(Path.Combine(rootDir, @"XenModel\bin\Debug\XenModel.dll")); int totalMessages = 0, totalFriendlyErrorNames = 0; var resources = new List<string>(); Type messagesType = assembly.GetType("XenAdmin.Messages"); Type friendlyNamesType = assembly.GetType("XenAdmin.FriendlyNames"); foreach (PropertyInfo property in messagesType.GetProperties(BindingFlags.Static | BindingFlags.NonPublic)) { resources.Add("Messages." + property.Name.Trim()); totalMessages++; } foreach (PropertyInfo property in friendlyNamesType.GetProperties(BindingFlags.Static | BindingFlags.NonPublic)) { resources.Add("FriendlyNames." + property.Name.Trim()); totalFriendlyErrorNames++; } // Build file list for project List<FileInfo> files = new List<FileInfo>(); RecursiveGetCsFiles(new DirectoryInfo(rootDir), files); files.RemoveAll(f => f.Name.StartsWith("Messages.") || f.Name.StartsWith("FriendlyNames.")); Console.WriteLine(string.Format("Looking in {0} files", files.Count)); // Now remove resources from the list if they appear in source files foreach (FileInfo fileinfo in files) { string[] lines = File.ReadAllLines(fileinfo.FullName); foreach (string line in lines) { string curLine = line; resources.RemoveAll(resource => curLine.Contains(resource)); } } int messages = 0, friendlyErrorNames = 0; foreach (string unused in resources) { if (unused.StartsWith("Messages.")) { messages++; } else if (unused.StartsWith("FriendlyNames.")) { friendlyErrorNames++; } Console.WriteLine(unused); } Console.WriteLine(string.Format("Messages.resx: {0}/{1} are unused", messages, totalMessages)); Console.WriteLine(string.Format("FriendlyNames.resx: {0}/{1} are unused", friendlyErrorNames, totalFriendlyErrorNames)); // Remove unused messages from Messages.rex. Note that this method is extremely // crude and depends on the exact format of the XML. if (removeUnused) { Console.WriteLine("Removing unused messages from Messages.resx"); List<string> unusedFromMessages = new List<string>(); foreach (string line in resources) { if (line.StartsWith("Messages.")) { unusedFromMessages.Add(line.Substring(9)); } } string path = Path.Combine(rootDir, "Messages.resx"); XmlDocument doc = new XmlDocument(); doc.LoadXml(File.ReadAllText(path)); List<XmlNode> nodesToRemove = new List<XmlNode>(); foreach (XmlNode node in doc.GetElementsByTagName("data")) { if (unusedFromMessages.Contains(node.Attributes["name"].Value)) { nodesToRemove.Add(node); } } foreach (XmlNode node in nodesToRemove) { doc.ChildNodes[1].RemoveChild(node); } doc.Save(path); } } private static void RecursiveGetCsFiles(DirectoryInfo dir, List<FileInfo> files) { files.AddRange(dir.GetFiles("*.cs")); foreach (DirectoryInfo subdir in dir.GetDirectories()) { RecursiveGetCsFiles(subdir, files); } } private static void RecursiveGetResxFiles(DirectoryInfo dir, List<FileInfo> files) { files.AddRange(dir.GetFiles("*.resx")); foreach (DirectoryInfo subdir in dir.GetDirectories()) { if (subdir.Name == "i18n") continue; RecursiveGetResxFiles(subdir, files); } } private static void FindNodesInJaButNotEn(string rootDir) { // Find all english resxs List<FileInfo> enResxFiles = new List<FileInfo>(); RecursiveGetResxFiles(new DirectoryInfo(rootDir), enResxFiles); foreach (FileInfo enResxFile in enResxFiles) { string enResxPath = enResxFile.FullName; XmlDocument enXml = new XmlDocument(); enXml.LoadXml(File.ReadAllText(enResxPath)); string jaFilename = enResxPath.Substring(rootDir.Length); jaFilename = jaFilename.Insert(jaFilename.Length - 5, ".ja"); string jaResxPath = rootDir + "\\i18n\\ja" + jaFilename; XmlDocument jaXml = new XmlDocument(); if (!File.Exists(jaResxPath)) { continue; } jaXml.LoadXml(File.ReadAllText(jaResxPath)); XmlNodeList enDataNodes = enXml.GetElementsByTagName("data"); XmlNodeList jaDataNodes = jaXml.GetElementsByTagName("data"); List<XmlNode> jaDataNodeList = new List<XmlNode>(); foreach (XmlNode jaNode in jaDataNodes) { jaDataNodeList.Add(jaNode); } List<XmlNode> inJaButNotEn = jaDataNodeList.FindAll((Predicate<XmlNode>)delegate(XmlNode jaNode) { string jaDataName = jaNode.Attributes["name"].Value; foreach (XmlNode enNode in enDataNodes) { if (enNode.Attributes["name"].Value == jaDataName) { return enNode.InnerXml != jaNode.InnerXml; } } return true; }); foreach (XmlNode node in inJaButNotEn) { System.Console.WriteLine(string.Format("'{0}' is in '{1}' but not in '{2}'", node.Attributes["name"].Value, jaResxPath, enResxFile.Name)); } } } private static readonly string[] i18nYes = new string[] { "Text", "ToolTipText", "HeaderText", "AccessibleDescription", "ToolTip", "Filter" }; private static readonly string[] i18nNo = new string[] { "ZOrder", "Size", "Location", "Anchor", "Type", "MinimumSize", "ClientSize", "Font", "TabIndex", "Parent", "LayoutSettings", "Margin", "Padding", "ColumnCount", "Dock", "AutoSize", "Name", "ImeMode", "IntegralHeight", "Visible", "InitialImage", "AutoScaleDimensions", "FlowDirection", "RowCount", "ImageAlign", "WrapContents", "Enabled", "TextAlign", "StartPosition", "SizeMode", "Multiline", "ScrollBars", "ItemHeight", "CellBorderStyle", "AutoSizeMode", "Image", "AutoCompleteCustomSource", "AutoCompleteCustomSource1", "AutoCompleteCustomSource2", "BulletIndent", "Width", "MinimumWidth", "AutoScroll", "ImageSize", "MaxLength", "BackgroundImageLayout", "ImageTransparentColor", "ImageIndex", "SplitterDistance", "MaximumSize", "ThousandsSeparator", "RightToLeft", "TextImageRelation", "ContentAlignment", "SelectedImageIndex", "HorizontalScrollbar", "CheckAlign", "RightToLeftLayout", "ShowShortcutKeys", "ShortcutKeys", "ShortcutKeyDisplayString", "Localizable", "Icon", "Menu", "AutoScrollMinSize", "Items", "ScrollAlwaysVisible", "Items1", "Items2", "Items3", "MaxDropDownItems" }; private static bool IsI18nableProperty(string filename, string name) { foreach (string property in i18nYes) { if (name.EndsWith("." + property)) { // Keep these tags return true; } } foreach (string property in i18nNo) { if (name.EndsWith("." + property)) { // Reject these tags return false; } } // We haven't seen these tags before - keep them but issue a notification Console.WriteLine(filename + ": " + name); return true; } private static bool ExcludeResx(string filePath) { return filePath.EndsWith(@"\Properties\Resources.resx") || filePath.EndsWith(@"\Help\HelpManager.resx") || filePath.EndsWith(@"\DotNetVnc\KeyMap.resx"); } /// <summary> /// Try from the immediate window e.g. /// XenAdmin.ResxCheck.TrimJaResxs(@"C:\Documents and Settings\hwarrington\xenadmin-unstable.hg\XenAdmin") /// </summary> /// <param name="rootDir"></param> private static void TrimJaResxs(string rootDir) { // Find all english resxs List<FileInfo> enResxFiles = new List<FileInfo>(); RecursiveGetResxFiles(new DirectoryInfo(rootDir), enResxFiles); List<string> names = new List<string>(); foreach (FileInfo enResxFile in enResxFiles) { if (ExcludeResx(enResxFile.FullName)) { continue; } // Load the en resx string enResxPath = enResxFile.FullName; XmlDocument enXml = new XmlDocument(); enXml.LoadXml(File.ReadAllText(enResxPath)); XmlNodeList enDataNodes = enXml.GetElementsByTagName("data"); // Find the ja resx string jaFilename = enResxPath.Substring(rootDir.Length); jaFilename = jaFilename.Insert(jaFilename.Length - 5, ".ja"); string jaResxPath = rootDir + "\\i18n\\ja" + jaFilename; if (!File.Exists(jaResxPath)) { // There is no ja resx file corresponding to the en resx. We need to check there are no i18nable tags // in the en resx. bool i18nRequired = false; foreach (XmlNode enNode in enDataNodes) { if (IsI18nableProperty(enResxFile.Name, enNode.Attributes["name"].Value)) { Console.WriteLine(string.Format("{0} is missing. Tag {1} needs i18n. Copying en resx across.", jaFilename, enNode.Attributes["name"].Value)); Directory.CreateDirectory(Path.GetDirectoryName(jaResxPath)); File.Copy(enResxPath, jaResxPath); i18nRequired = true; break; } } if (!i18nRequired) { continue; } } // Load the ja resx XmlDocument jaXml = new XmlDocument(); jaXml.LoadXml(File.ReadAllText(jaResxPath)); XmlNodeList jaDataNodes = jaXml.GetElementsByTagName("data"); // Take a copy of the jaDataNodes List<XmlNode> jaDataNodeList = new List<XmlNode>(); foreach (XmlNode node in jaDataNodes) { jaDataNodeList.Add(node); } // Go through all the ja nodes, keeping only the ones where their values differ from the en original // Don't bother to do this for the messages files. if (enResxFile.Name != "Messages.resx" && enResxFile.Name != "FriendlyNames.resx" && enResxFile.Name != "FriendlyNames.resx") { foreach (XmlNode jaNode in jaDataNodeList) { string jaDataName = jaNode.Attributes["name"].Value; if (!IsI18nableProperty(jaFilename, jaDataName)) { // Delete node jaXml.GetElementsByTagName("root")[0].RemoveChild(jaNode); continue; } foreach (XmlNode enNode in enDataNodes) { if (enNode.Attributes["name"].Value == jaDataName) { if (enNode.InnerXml == jaNode.InnerXml) { // If node unchanged, delete it jaXml.GetElementsByTagName("root")[0].RemoveChild(jaNode); break; } } } } } // Now add any nodes that are in en but not ja (as long as they are of the i18nable types). foreach (XmlNode enNode in enDataNodes) { bool needToAdd = true; foreach (XmlNode jaNode in jaDataNodes) { if (enNode.Attributes["name"].Value == jaNode.Attributes["name"].Value) { needToAdd = false; break; } } if (needToAdd && IsI18nableProperty(enResxFile.Name, enNode.Attributes["name"].Value)) { XmlNode n = jaXml.GetElementsByTagName("root")[0].AppendChild(jaXml.ImportNode(enNode, true)); foreach (XmlNode child in n.ChildNodes) { if (child is XmlWhitespace) continue; if (child is XmlSignificantWhitespace) continue; else child.InnerText += " (ja)"; } } } XmlWriterSettings settings = new XmlWriterSettings(); settings.CloseOutput = true; settings.Indent = true; XmlWriter writer = XmlWriter.Create(jaResxPath, settings); jaXml.WriteContentTo(writer); writer.Flush(); writer.Close(); } Console.WriteLine("Done"); } /// <summary> /// Checks I haven't screwed stuff up while changing the autogen resx stuff. /// </summary> public static void CheckNotBorked() { XmlDocument origXml = new XmlDocument(); origXml.LoadXml(File.ReadAllText(@"C:\Documents and Settings\hwarrington\xenadmin-unstable.hg\XenAdmin\XenAPI\FriendlyNames.resx")); XmlDocument newXml = new XmlDocument(); newXml.LoadXml(File.ReadAllText(@"Q:\local\scratch-2\hwarrington\build.hg\myrepos\api.hg\ocaml\idl\csharp_backend\autogen-gui\FriendlyNames.resx")); CheckAIncludesB(origXml, newXml); CheckAIncludesB(newXml, origXml); } private static XmlNode FindByName(XmlDocument doc, string name) { foreach (XmlNode node in doc.GetElementsByTagName("data")) { if (name == node.Attributes["name"].Value) return node; } return null; } private static void CheckAIncludesB(XmlDocument origXml, XmlDocument newXml) { XmlNodeList origDataNodes = origXml.GetElementsByTagName("data"); foreach (XmlNode oldNode in origDataNodes) { string name = oldNode.Attributes["name"].Value; string oldValue = oldNode.InnerXml; XmlNode newNode = FindByName(newXml, name); if (newNode == null) { throw new Exception(String.Format("Node with name {0} exists in old but not new!", name)); } string newValue = newNode.InnerXml; if (newValue != oldValue) { throw new Exception(String.Format("Node with name {0} has value {1} in old but {2} in new!", name, oldValue, newValue)); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Linq.Expressions; using Elasticsearch.Net; using Nest.Resolvers; ///This file contains all the typed request parameters that are generated of the client spec. ///This file is automatically generated from https://github.com/elasticsearch/elasticsearch-rest-api-spec ///Generated of commit namespace Nest { public static class RequestPameterExtensions { ///<summary>A comma-separated list of fields to return in the output</summary> internal static CatFielddataRequestParameters _Fields<T>( this CatFielddataRequestParameters qs, IEnumerable<Expression<Func<T, object>>> fields) where T : class { var _fields = fields.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("fields", _fields); return qs; } ///<summary>A comma-separated list of fields to return in the response</summary> internal static ExplainRequestParameters _Fields<T>( this ExplainRequestParameters qs, IEnumerable<Expression<Func<T, object>>> fields) where T : class { var _fields = fields.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("fields", _fields); return qs; } ///<summary>A list of fields to exclude from the returned _source field</summary> internal static ExplainRequestParameters _SourceExclude<T>( this ExplainRequestParameters qs, IEnumerable<Expression<Func<T, object>>> source_exclude) where T : class { var _source_exclude = source_exclude.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("_source_exclude", _source_exclude); return qs; } ///<summary>A list of fields to extract and return from the _source field</summary> internal static ExplainRequestParameters _SourceInclude<T>( this ExplainRequestParameters qs, IEnumerable<Expression<Func<T, object>>> source_include) where T : class { var _source_include = source_include.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("_source_include", _source_include); return qs; } ///<summary>A comma-separated list of fields to return in the response</summary> internal static GetRequestParameters _Fields<T>( this GetRequestParameters qs, IEnumerable<Expression<Func<T, object>>> fields) where T : class { var _fields = fields.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("fields", _fields); return qs; } ///<summary>A list of fields to exclude from the returned _source field</summary> internal static GetRequestParameters _SourceExclude<T>( this GetRequestParameters qs, IEnumerable<Expression<Func<T, object>>> source_exclude) where T : class { var _source_exclude = source_exclude.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("_source_exclude", _source_exclude); return qs; } ///<summary>A list of fields to extract and return from the _source field</summary> internal static GetRequestParameters _SourceInclude<T>( this GetRequestParameters qs, IEnumerable<Expression<Func<T, object>>> source_include) where T : class { var _source_include = source_include.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("_source_include", _source_include); return qs; } ///<summary>A list of fields to exclude from the returned _source field</summary> internal static SourceRequestParameters _SourceExclude<T>( this SourceRequestParameters qs, IEnumerable<Expression<Func<T, object>>> source_exclude) where T : class { var _source_exclude = source_exclude.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("_source_exclude", _source_exclude); return qs; } ///<summary>A list of fields to extract and return from the _source field</summary> internal static SourceRequestParameters _SourceInclude<T>( this SourceRequestParameters qs, IEnumerable<Expression<Func<T, object>>> source_include) where T : class { var _source_include = source_include.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("_source_include", _source_include); return qs; } ///<summary>Use the analyzer configured for this field (instead of passing the analyzer name)</summary> internal static AnalyzeRequestParameters _Field<T>( this AnalyzeRequestParameters qs, Expression<Func<T, object>> field) where T : class { var p = (PropertyPathMarker)field; var _field = p; qs.AddQueryString("field", _field); return qs; } ///<summary>A comma-separated list of fields to clear when using the `field_data` parameter (default: all)</summary> internal static ClearCacheRequestParameters _Fields<T>( this ClearCacheRequestParameters qs, IEnumerable<Expression<Func<T, object>>> fields) where T : class { var _fields = fields.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("fields", _fields); return qs; } ///<summary>A comma-separated list of fields for `fielddata` and `suggest` index metric (supports wildcards)</summary> internal static IndicesStatsRequestParameters _CompletionFields<T>( this IndicesStatsRequestParameters qs, IEnumerable<Expression<Func<T, object>>> completion_fields) where T : class { var _completion_fields = completion_fields.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("completion_fields", _completion_fields); return qs; } ///<summary>A comma-separated list of fields for `fielddata` index metric (supports wildcards)</summary> internal static IndicesStatsRequestParameters _FielddataFields<T>( this IndicesStatsRequestParameters qs, IEnumerable<Expression<Func<T, object>>> fielddata_fields) where T : class { var _fielddata_fields = fielddata_fields.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("fielddata_fields", _fielddata_fields); return qs; } ///<summary>A comma-separated list of fields for `fielddata` and `completion` index metric (supports wildcards)</summary> internal static IndicesStatsRequestParameters _Fields<T>( this IndicesStatsRequestParameters qs, IEnumerable<Expression<Func<T, object>>> fields) where T : class { var _fields = fields.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("fields", _fields); return qs; } ///<summary>A comma-separated list of fields to return in the response</summary> internal static MultiGetRequestParameters _Fields<T>( this MultiGetRequestParameters qs, IEnumerable<Expression<Func<T, object>>> fields) where T : class { var _fields = fields.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("fields", _fields); return qs; } ///<summary>A list of fields to exclude from the returned _source field</summary> internal static MultiGetRequestParameters _SourceExclude<T>( this MultiGetRequestParameters qs, IEnumerable<Expression<Func<T, object>>> source_exclude) where T : class { var _source_exclude = source_exclude.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("_source_exclude", _source_exclude); return qs; } ///<summary>A list of fields to extract and return from the _source field</summary> internal static MultiGetRequestParameters _SourceInclude<T>( this MultiGetRequestParameters qs, IEnumerable<Expression<Func<T, object>>> source_include) where T : class { var _source_include = source_include.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("_source_include", _source_include); return qs; } ///<summary>Specific fields to perform the query against</summary> internal static MoreLikeThisRequestParameters _MltFields<T>( this MoreLikeThisRequestParameters qs, IEnumerable<Expression<Func<T, object>>> mlt_fields) where T : class { var _mlt_fields = mlt_fields.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("mlt_fields", _mlt_fields); return qs; } ///<summary>A comma-separated list of fields to return. Applies to all returned documents unless otherwise specified in body &quot;params&quot; or &quot;docs&quot;.</summary> internal static MultiTermVectorsRequestParameters _Fields<T>( this MultiTermVectorsRequestParameters qs, IEnumerable<Expression<Func<T, object>>> fields) where T : class { var _fields = fields.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("fields", _fields); return qs; } ///<summary>A comma-separated list of fields for `fielddata` and `suggest` index metric (supports wildcards)</summary> internal static NodesStatsRequestParameters _CompletionFields<T>( this NodesStatsRequestParameters qs, IEnumerable<Expression<Func<T, object>>> completion_fields) where T : class { var _completion_fields = completion_fields.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("completion_fields", _completion_fields); return qs; } ///<summary>A comma-separated list of fields for `fielddata` index metric (supports wildcards)</summary> internal static NodesStatsRequestParameters _FielddataFields<T>( this NodesStatsRequestParameters qs, IEnumerable<Expression<Func<T, object>>> fielddata_fields) where T : class { var _fielddata_fields = fielddata_fields.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("fielddata_fields", _fielddata_fields); return qs; } ///<summary>A comma-separated list of fields for `fielddata` and `completion` index metric (supports wildcards)</summary> internal static NodesStatsRequestParameters _Fields<T>( this NodesStatsRequestParameters qs, IEnumerable<Expression<Func<T, object>>> fields) where T : class { var _fields = fields.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("fields", _fields); return qs; } ///<summary>Specify which field to use for suggestions</summary> internal static SearchRequestParameters _SuggestField<T>( this SearchRequestParameters qs, Expression<Func<T, object>> suggest_field) where T : class { var p = (PropertyPathMarker)suggest_field; var _suggest_field = p; qs.AddQueryString("suggest_field", _suggest_field); return qs; } ///<summary>A comma-separated list of fields to return.</summary> internal static TermvectorRequestParameters _Fields<T>( this TermvectorRequestParameters qs, IEnumerable<Expression<Func<T, object>>> fields) where T : class { var _fields = fields.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("fields", _fields); return qs; } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // ElementAtQueryOperator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Threading; namespace System.Linq.Parallel { /// <summary> /// ElementAt just retrieves an element at a specific index. There is some cross-partition /// coordination to force partitions to stop looking once a partition has found the /// sought-after element. /// </summary> /// <typeparam name="TSource"></typeparam> internal sealed class ElementAtQueryOperator<TSource> : UnaryQueryOperator<TSource, TSource> { private readonly int _index; // The index that we're looking for. private readonly bool _prematureMerge = false; // Whether to prematurely merge the input of this operator. private readonly bool _limitsParallelism = false; // Whether this operator limits parallelism //--------------------------------------------------------------------------------------- // Constructs a new instance of the contains search operator. // // Arguments: // child - the child tree to enumerate. // index - index we are searching for. // internal ElementAtQueryOperator(IEnumerable<TSource> child, int index) : base(child) { Debug.Assert(child != null, "child data source cannot be null"); Debug.Assert(index >= 0, "index can't be less than 0"); _index = index; OrdinalIndexState childIndexState = Child.OrdinalIndexState; if (ExchangeUtilities.IsWorseThan(childIndexState, OrdinalIndexState.Correct)) { _prematureMerge = true; _limitsParallelism = childIndexState != OrdinalIndexState.Shuffled; } } //--------------------------------------------------------------------------------------- // Just opens the current operator, including opening the child and wrapping it with // partitions as needed. // internal override QueryResults<TSource> Open( QuerySettings settings, bool preferStriping) { // We just open the child operator. QueryResults<TSource> childQueryResults = Child.Open(settings, false); return new UnaryQueryOperatorResults(childQueryResults, this, settings, preferStriping); } internal override void WrapPartitionedStream<TKey>( PartitionedStream<TSource, TKey> inputStream, IPartitionedStreamRecipient<TSource> recipient, bool preferStriping, QuerySettings settings) { // If the child OOP index is not correct, reindex. int partitionCount = inputStream.PartitionCount; PartitionedStream<TSource, int> intKeyStream; if (_prematureMerge) { intKeyStream = ExecuteAndCollectResults(inputStream, partitionCount, Child.OutputOrdered, preferStriping, settings).GetPartitionedStream(); Debug.Assert(intKeyStream.OrdinalIndexState == OrdinalIndexState.Indexable); } else { intKeyStream = (PartitionedStream<TSource, int>)(object)inputStream; } // Create a shared cancellation variable and then return a possibly wrapped new enumerator. Shared<bool> resultFoundFlag = new Shared<bool>(false); PartitionedStream<TSource, int> outputStream = new PartitionedStream<TSource, int>( partitionCount, Util.GetDefaultComparer<int>(), OrdinalIndexState.Correct); for (int i = 0; i < partitionCount; i++) { outputStream[i] = new ElementAtQueryOperatorEnumerator(intKeyStream[i], _index, resultFoundFlag, settings.CancellationState.MergedCancellationToken); } recipient.Receive(outputStream); } //--------------------------------------------------------------------------------------- // Returns an enumerable that represents the query executing sequentially. // internal override IEnumerable<TSource> AsSequentialQuery(CancellationToken token) { Debug.Fail("This method should never be called as fallback to sequential is handled in Aggregate()."); throw new NotSupportedException(); } //--------------------------------------------------------------------------------------- // Whether this operator performs a premature merge that would not be performed in // a similar sequential operation (i.e., in LINQ to Objects). // internal override bool LimitsParallelism { get { return _limitsParallelism; } } /// <summary> /// Executes the query, either sequentially or in parallel, depending on the query execution mode and /// whether a premature merge was inserted by this ElementAt operator. /// </summary> /// <param name="result">result</param> /// <param name="withDefaultValue">withDefaultValue</param> /// <returns>whether an element with this index exists</returns> internal bool Aggregate(out TSource result, bool withDefaultValue) { // If we were to insert a premature merge before this ElementAt, and we are executing in conservative mode, run the whole query // sequentially. if (LimitsParallelism && SpecifiedQuerySettings.WithDefaults().ExecutionMode.Value != ParallelExecutionMode.ForceParallelism) { CancellationState cancelState = SpecifiedQuerySettings.CancellationState; if (withDefaultValue) { IEnumerable<TSource> childAsSequential = Child.AsSequentialQuery(cancelState.ExternalCancellationToken); IEnumerable<TSource> childWithCancelChecks = CancellableEnumerable.Wrap(childAsSequential, cancelState.ExternalCancellationToken); result = ExceptionAggregator.WrapEnumerable(childWithCancelChecks, cancelState).ElementAtOrDefault(_index); } else { IEnumerable<TSource> childAsSequential = Child.AsSequentialQuery(cancelState.ExternalCancellationToken); IEnumerable<TSource> childWithCancelChecks = CancellableEnumerable.Wrap(childAsSequential, cancelState.ExternalCancellationToken); result = ExceptionAggregator.WrapEnumerable(childWithCancelChecks, cancelState).ElementAt(_index); } return true; } using (IEnumerator<TSource> e = GetEnumerator(ParallelMergeOptions.FullyBuffered)) { if (e.MoveNext()) { TSource current = e.Current; Debug.Assert(!e.MoveNext(), "expected enumerator to be empty"); result = current; return true; } } result = default(TSource); return false; } //--------------------------------------------------------------------------------------- // This enumerator performs the search for the element at the specified index. // class ElementAtQueryOperatorEnumerator : QueryOperatorEnumerator<TSource, int> { private QueryOperatorEnumerator<TSource, int> _source; // The source data. private int _index; // The index of the element to seek. private Shared<bool> _resultFoundFlag; // Whether to cancel the operation. private CancellationToken _cancellationToken; //--------------------------------------------------------------------------------------- // Instantiates a new any/all search operator. // internal ElementAtQueryOperatorEnumerator(QueryOperatorEnumerator<TSource, int> source, int index, Shared<bool> resultFoundFlag, CancellationToken cancellationToken) { Debug.Assert(source != null); Debug.Assert(index >= 0); Debug.Assert(resultFoundFlag != null); _source = source; _index = index; _resultFoundFlag = resultFoundFlag; _cancellationToken = cancellationToken; } //--------------------------------------------------------------------------------------- // Enumerates the entire input until the element with the specified is found or another // partition has signaled that it found the element. // internal override bool MoveNext(ref TSource currentElement, ref int currentKey) { // Just walk the enumerator until we've found the element. int i = 0; while (_source.MoveNext(ref currentElement, ref currentKey)) { if ((i++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); if (_resultFoundFlag.Value) { // Another partition found the element. break; } if (currentKey == _index) { // We have found the element. Cancel other searches and return true. _resultFoundFlag.Value = true; return true; } } return false; } protected override void Dispose(bool disposing) { Debug.Assert(_source != null); _source.Dispose(); } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using OpenMetaverse; using OpenSim.Region.Framework.Scenes; using OpenSim.Tests.Common; namespace OpenSim.Region.Framework.Scenes.Tests { [TestFixture] public class BorderTests { [Test] public void TestCross() { TestHelper.InMethod(); List<Border> testborders = new List<Border>(); Border NorthBorder = new Border(); NorthBorder.BorderLine = new Vector3(0, 256, 256); //<--- NorthBorder.CrossDirection = Cardinals.N; testborders.Add(NorthBorder); Border SouthBorder = new Border(); SouthBorder.BorderLine = new Vector3(0, 256, 0); //---> SouthBorder.CrossDirection = Cardinals.S; testborders.Add(SouthBorder); Border EastBorder = new Border(); EastBorder.BorderLine = new Vector3(0, 256, 256); //<--- EastBorder.CrossDirection = Cardinals.E; testborders.Add(EastBorder); Border WestBorder = new Border(); WestBorder.BorderLine = new Vector3(0, 256, 0); //---> WestBorder.CrossDirection = Cardinals.W; testborders.Add(WestBorder); Vector3 position = new Vector3(200,200,21); foreach (Border b in testborders) { Assert.That(!b.TestCross(position)); } position = new Vector3(200,280,21); Assert.That(NorthBorder.TestCross(position)); // Test automatic border crossing // by setting the border crossing aabb to be the whole region position = new Vector3(25,25,21); // safely within one 256m region // The Z value of the BorderLine is reversed, making all positions within the region // trigger bordercross SouthBorder.BorderLine = new Vector3(0,256,256); // automatic border cross in the region Assert.That(SouthBorder.TestCross(position)); NorthBorder.BorderLine = new Vector3(0, 256, 0); // automatic border cross in the region Assert.That(NorthBorder.TestCross(position)); EastBorder.BorderLine = new Vector3(0, 256, 0); // automatic border cross in the region Assert.That(EastBorder.TestCross(position)); WestBorder.BorderLine = new Vector3(0, 256, 255); // automatic border cross in the region Assert.That(WestBorder.TestCross(position)); } [Test] public void TestCrossSquare512() { TestHelper.InMethod(); List<Border> testborders = new List<Border>(); Border NorthBorder = new Border(); NorthBorder.BorderLine = new Vector3(0, 512, 512); NorthBorder.CrossDirection = Cardinals.N; testborders.Add(NorthBorder); Border SouthBorder = new Border(); SouthBorder.BorderLine = new Vector3(0, 512, 0); SouthBorder.CrossDirection = Cardinals.S; testborders.Add(SouthBorder); Border EastBorder = new Border(); EastBorder.BorderLine = new Vector3(0, 512, 512); EastBorder.CrossDirection = Cardinals.E; testborders.Add(EastBorder); Border WestBorder = new Border(); WestBorder.BorderLine = new Vector3(0, 512, 0); WestBorder.CrossDirection = Cardinals.W; testborders.Add(WestBorder); Vector3 position = new Vector3(450,220,21); foreach (Border b in testborders) { Assert.That(!b.TestCross(position)); } //Trigger east border position = new Vector3(513,220,21); foreach (Border b in testborders) { if (b.CrossDirection == Cardinals.E) Assert.That(b.TestCross(position)); else Assert.That(!b.TestCross(position)); } //Trigger west border position = new Vector3(-1, 220, 21); foreach (Border b in testborders) { if (b.CrossDirection == Cardinals.W) Assert.That(b.TestCross(position)); else Assert.That(!b.TestCross(position)); } //Trigger north border position = new Vector3(220, 513, 21); foreach (Border b in testborders) { if (b.CrossDirection == Cardinals.N) Assert.That(b.TestCross(position)); else Assert.That(!b.TestCross(position)); } //Trigger south border position = new Vector3(220, -1, 21); foreach (Border b in testborders) { if (b.CrossDirection == Cardinals.S) Assert.That(b.TestCross(position)); else Assert.That(!b.TestCross(position)); } } [Test] public void TestCrossRectangle512x256() { TestHelper.InMethod(); List<Border> testborders = new List<Border>(); Border NorthBorder = new Border(); NorthBorder.BorderLine = new Vector3(0, 512, 256); NorthBorder.CrossDirection = Cardinals.N; testborders.Add(NorthBorder); Border SouthBorder = new Border(); SouthBorder.BorderLine = new Vector3(0, 512, 0); SouthBorder.CrossDirection = Cardinals.S; testborders.Add(SouthBorder); Border EastBorder = new Border(); EastBorder.BorderLine = new Vector3(0, 256, 512); EastBorder.CrossDirection = Cardinals.E; testborders.Add(EastBorder); Border WestBorder = new Border(); WestBorder.BorderLine = new Vector3(0, 256, 0); WestBorder.CrossDirection = Cardinals.W; testborders.Add(WestBorder); Vector3 position = new Vector3(450, 220, 21); foreach (Border b in testborders) { Assert.That(!b.TestCross(position)); } //Trigger east border position = new Vector3(513, 220, 21); foreach (Border b in testborders) { if (b.CrossDirection == Cardinals.E) Assert.That(b.TestCross(position)); else Assert.That(!b.TestCross(position)); } //Trigger west border position = new Vector3(-1, 220, 21); foreach (Border b in testborders) { if (b.CrossDirection == Cardinals.W) Assert.That(b.TestCross(position)); else Assert.That(!b.TestCross(position)); } //Trigger north border position = new Vector3(220, 257, 21); foreach (Border b in testborders) { if (b.CrossDirection == Cardinals.N) Assert.That(b.TestCross(position)); else Assert.That(!b.TestCross(position)); } //Trigger south border position = new Vector3(220, -1, 21); foreach (Border b in testborders) { if (b.CrossDirection == Cardinals.S) Assert.That(b.TestCross(position)); else Assert.That(!b.TestCross(position)); } } [Test] public void TestCrossOdd512x512w256hole() { TestHelper.InMethod(); List<Border> testborders = new List<Border>(); // 512____ // | | // 256__| |___ // | | // |______| // 0 | 512 // 256 // Compound North border since the hole is at the top Border NorthBorder1 = new Border(); NorthBorder1.BorderLine = new Vector3(0, 256, 512); NorthBorder1.CrossDirection = Cardinals.N; testborders.Add(NorthBorder1); Border NorthBorder2 = new Border(); NorthBorder2.BorderLine = new Vector3(256, 512, 256); NorthBorder2.CrossDirection = Cardinals.N; testborders.Add(NorthBorder2); Border SouthBorder = new Border(); SouthBorder.BorderLine = new Vector3(0, 512, 0); SouthBorder.CrossDirection = Cardinals.S; testborders.Add(SouthBorder); //Compound East border Border EastBorder1 = new Border(); EastBorder1.BorderLine = new Vector3(0, 256, 512); EastBorder1.CrossDirection = Cardinals.E; testborders.Add(EastBorder1); Border EastBorder2 = new Border(); EastBorder2.BorderLine = new Vector3(257, 512, 256); EastBorder2.CrossDirection = Cardinals.E; testborders.Add(EastBorder2); Border WestBorder = new Border(); WestBorder.BorderLine = new Vector3(0, 512, 0); WestBorder.CrossDirection = Cardinals.W; testborders.Add(WestBorder); Vector3 position = new Vector3(450, 220, 21); foreach (Border b in testborders) { Assert.That(!b.TestCross(position)); } position = new Vector3(220, 450, 21); foreach (Border b in testborders) { Assert.That(!b.TestCross(position)); } bool result = false; int bordersTriggered = 0; position = new Vector3(450, 450, 21); foreach (Border b in testborders) { if (b.TestCross(position)) { bordersTriggered++; result = true; } } Assert.That(result); Assert.That(bordersTriggered == 2); } } }
// 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; ///<summary> ///System.AttributeUsageAttribute.AttributeUsageAttribute(AttributeTargets validOn) ///</summary> public class AttributeUsageAttributeCtor { public static int Main() { AttributeUsageAttributeCtor testObj = new AttributeUsageAttributeCtor(); TestLibrary.TestFramework.BeginTestCase("for Constructor of System.AttributeUsageAttribute"); 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; retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; retVal = PosTest7() && retVal; retVal = PosTest8() && retVal; retVal = PosTest9() && retVal; retVal = PosTest10() && retVal; retVal = PosTest11() && retVal; retVal = PosTest12() && retVal; retVal = PosTest13() && retVal; retVal = PosTest14() && retVal; retVal = PosTest15() && retVal; retVal = PosTest16() && retVal; retVal = PosTest17() && retVal; return retVal; } #region Test Logic public bool PosTest1() { bool retVal = true; AttributeTargets validOn = AttributeTargets.All; TestLibrary.TestFramework.BeginScenario("PosTest1:set ValidOn as AttributeTargets.All and create a instance of class AttributeUsageAttribute."); try { AttributeUsageAttribute aUT = new AttributeUsageAttribute(validOn); if (aUT == null) { TestLibrary.TestFramework.LogError("001", "ExpectedObject(Not null) !=Actual(null)"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; AttributeTargets validOn = AttributeTargets.Assembly; TestLibrary.TestFramework.BeginScenario("PosTest2:set ValidOn as AttributeTargets.Assembly and create a instance of class AttributeUsageAttribute."); try { AttributeUsageAttribute aUT = new AttributeUsageAttribute(validOn); if (aUT == null) { TestLibrary.TestFramework.LogError("003", "ExpectedObject(Not null) !=Actual(null)"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; AttributeTargets validOn = AttributeTargets.Module; TestLibrary.TestFramework.BeginScenario("PosTest3:set ValidOn as AttributeTargets.Module and create a instance of class AttributeUsageAttribute."); try { AttributeUsageAttribute aUT = new AttributeUsageAttribute(validOn); if (aUT == null) { TestLibrary.TestFramework.LogError("005", "ExpectedObject(Not null) !=Actual(null)"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; AttributeTargets validOn = AttributeTargets.Class; TestLibrary.TestFramework.BeginScenario("PosTest4:set ValidOn as AttributeTargets.Class and create a instance of class AttributeUsageAttribute."); try { AttributeUsageAttribute aUT = new AttributeUsageAttribute(validOn); if (aUT == null) { TestLibrary.TestFramework.LogError("007", "ExpectedObject(Not null) !=Actual(null)"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; AttributeTargets validOn = AttributeTargets.Struct; TestLibrary.TestFramework.BeginScenario("PosTest5:set ValidOn as AttributeTargets.Struct and create a instance of class AttributeUsageAttribute."); try { AttributeUsageAttribute aUT = new AttributeUsageAttribute(validOn); if (aUT == null) { TestLibrary.TestFramework.LogError("009", "ExpectedObject(Not null) !=Actual(null)"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; AttributeTargets validOn = AttributeTargets.All; TestLibrary.TestFramework.BeginScenario("PosTest6:set ValidOn as AttributeTargets.Enum and create a instance of class AttributeUsageAttribute."); try { AttributeUsageAttribute aUT = new AttributeUsageAttribute(validOn); if (aUT == null) { TestLibrary.TestFramework.LogError("011", "ExpectedObject(Not null) !=Actual(null)"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest7() { bool retVal = true; AttributeTargets validOn = AttributeTargets.Constructor; TestLibrary.TestFramework.BeginScenario("PosTest7:set ValidOn as AttributeTargets.Constructor and create a instance of class AttributeUsageAttribute."); try { AttributeUsageAttribute aUT = new AttributeUsageAttribute(validOn); if (aUT == null) { TestLibrary.TestFramework.LogError("013", "ExpectedObject(Not null) !=Actual(null)"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("014", "Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest8() { bool retVal = true; AttributeTargets validOn = AttributeTargets.Method; TestLibrary.TestFramework.BeginScenario("PosTest8:set ValidOn as AttributeTargets.Method and create a instance of class AttributeUsageAttribute."); try { AttributeUsageAttribute aUT = new AttributeUsageAttribute(validOn); if (aUT == null) { TestLibrary.TestFramework.LogError("015", "ExpectedObject(Not null) !=Actual(null)"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("016", "Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest9() { bool retVal = true; AttributeTargets validOn = AttributeTargets.Property; TestLibrary.TestFramework.BeginScenario("PosTest9:set ValidOn as AttributeTargets.Property and create a instance of class AttributeUsageAttribute."); try { AttributeUsageAttribute aUT = new AttributeUsageAttribute(validOn); if (aUT == null) { TestLibrary.TestFramework.LogError("017", "ExpectedObject(Not null) !=Actual(null)"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("018", "Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest10() { bool retVal = true; AttributeTargets validOn = AttributeTargets.Field; TestLibrary.TestFramework.BeginScenario("PosTest10:set ValidOn as AttributeTargets.Field and create a instance of class AttributeUsageAttribute."); try { AttributeUsageAttribute aUT = new AttributeUsageAttribute(validOn); if (aUT == null) { TestLibrary.TestFramework.LogError("019", "ExpectedObject(Not null) !=Actual(null)"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("020", "Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest11() { bool retVal = true; AttributeTargets validOn = AttributeTargets.Event; TestLibrary.TestFramework.BeginScenario("PosTest11:set ValidOn as AttributeTargets.Event and create a instance of class AttributeUsageAttribute."); try { AttributeUsageAttribute aUT = new AttributeUsageAttribute(validOn); if (aUT == null) { TestLibrary.TestFramework.LogError("021", "ExpectedObject(Not null) !=Actual(null)"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("022", "Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest12() { bool retVal = true; AttributeTargets validOn = AttributeTargets.Interface; TestLibrary.TestFramework.BeginScenario("PosTest12:set ValidOn as AttributeTargets.Interface and create a instance of class AttributeUsageAttribute."); try { AttributeUsageAttribute aUT = new AttributeUsageAttribute(validOn); if (aUT == null) { TestLibrary.TestFramework.LogError("023", "ExpectedObject(Not null) !=Actual(null)"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("024", "Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest13() { bool retVal = true; AttributeTargets validOn = AttributeTargets.Parameter; TestLibrary.TestFramework.BeginScenario("PosTest13:set ValidOn as AttributeTargets.Parameter and create a instance of class AttributeUsageAttribute."); try { AttributeUsageAttribute aUT = new AttributeUsageAttribute(validOn); if (aUT == null) { TestLibrary.TestFramework.LogError("025", "ExpectedObject(Not null) !=Actual(null)"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("026", "Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest14() { bool retVal = true; AttributeTargets validOn = AttributeTargets.Delegate; TestLibrary.TestFramework.BeginScenario("PosTest14:set ValidOn as AttributeTargets.Delegate and create a instance of class AttributeUsageAttribute."); try { AttributeUsageAttribute aUT = new AttributeUsageAttribute(validOn); if (aUT == null) { TestLibrary.TestFramework.LogError("027", "ExpectedObject(Not null) !=Actual(null)"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("028", "Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest15() { bool retVal = true; AttributeTargets validOn = AttributeTargets.ReturnValue; TestLibrary.TestFramework.BeginScenario("PosTest15:set ValidOn as AttributeTargets.ReturnValue and create a instance of class AttributeUsageAttribute."); try { AttributeUsageAttribute aUT = new AttributeUsageAttribute(validOn); if (aUT == null) { TestLibrary.TestFramework.LogError("029", "ExpectedObject(Not null) !=Actual(null)"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("030", "Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest16() { bool retVal = true; AttributeTargets validOn = AttributeTargets.GenericParameter; TestLibrary.TestFramework.BeginScenario("PosTest16:set ValidOn as AttributeTargets.GenericParameter and create a instance of class AttributeUsageAttribute."); try { AttributeUsageAttribute aUT = new AttributeUsageAttribute(validOn); if (aUT == null) { TestLibrary.TestFramework.LogError("031", "ExpectedObject(Not null) !=Actual(null)"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("032", "Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest17() { bool retVal = true; AttributeTargets expectedValue = (AttributeTargets)(TestLibrary.Generator.GetInt32(-55) % (UInt16.MaxValue + 1)); TestLibrary.TestFramework.BeginScenario("PosTest17:set ValidOn as Random int16 and try to get it."); try { AttributeUsageAttribute aUT = new AttributeUsageAttribute(expectedValue); if (aUT == null) { TestLibrary.TestFramework.LogError("033", "ExpectedObject(Not null) !=Actual(null)"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("034", "Unexpected exception:" + e); retVal = false; } return retVal; } #endregion }
#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.IO; #if HAVE_ASYNC using System.Threading; using System.Threading.Tasks; #endif using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Diagnostics.CodeAnalysis; #if !HAVE_LINQ using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Newtonsoft.Json.Utilities { internal static class BufferUtils { public static char[] RentBuffer(IArrayPool<char>? bufferPool, int minSize) { if (bufferPool == null) { return new char[minSize]; } char[] buffer = bufferPool.Rent(minSize); return buffer; } public static void ReturnBuffer(IArrayPool<char>? bufferPool, char[]? buffer) { bufferPool?.Return(buffer); } public static char[] EnsureBufferSize(IArrayPool<char>? bufferPool, int size, char[]? buffer) { if (bufferPool == null) { return new char[size]; } if (buffer != null) { bufferPool.Return(buffer); } return bufferPool.Rent(size); } } internal static class JavaScriptUtils { internal static readonly bool[] SingleQuoteCharEscapeFlags = new bool[128]; internal static readonly bool[] DoubleQuoteCharEscapeFlags = new bool[128]; internal static readonly bool[] HtmlCharEscapeFlags = new bool[128]; private const int UnicodeTextLength = 6; static JavaScriptUtils() { IList<char> escapeChars = new List<char> { '\n', '\r', '\t', '\\', '\f', '\b', }; for (int i = 0; i < ' '; i++) { escapeChars.Add((char)i); } foreach (char escapeChar in escapeChars.Union(new[] { '\'' })) { SingleQuoteCharEscapeFlags[escapeChar] = true; } foreach (char escapeChar in escapeChars.Union(new[] { '"' })) { DoubleQuoteCharEscapeFlags[escapeChar] = true; } foreach (char escapeChar in escapeChars.Union(new[] { '"', '\'', '<', '>', '&' })) { HtmlCharEscapeFlags[escapeChar] = true; } } private const string EscapedUnicodeText = "!"; public static bool[] GetCharEscapeFlags(StringEscapeHandling stringEscapeHandling, char quoteChar) { if (stringEscapeHandling == StringEscapeHandling.EscapeHtml) { return HtmlCharEscapeFlags; } if (quoteChar == '"') { return DoubleQuoteCharEscapeFlags; } return SingleQuoteCharEscapeFlags; } public static bool ShouldEscapeJavaScriptString(string? s, bool[] charEscapeFlags) { if (s == null) { return false; } for (int i = 0; i < s.Length; i++) { char c = s[i]; if (c >= charEscapeFlags.Length || charEscapeFlags[c]) { return true; } } return false; } public static void WriteEscapedJavaScriptString(TextWriter writer, string? s, char delimiter, bool appendDelimiters, bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, IArrayPool<char>? bufferPool, ref char[]? writeBuffer) { // leading delimiter if (appendDelimiters) { writer.Write(delimiter); } if (!StringUtils.IsNullOrEmpty(s)) { int lastWritePosition = FirstCharToEscape(s, charEscapeFlags, stringEscapeHandling); if (lastWritePosition == -1) { writer.Write(s); } else { if (lastWritePosition != 0) { if (writeBuffer == null || writeBuffer.Length < lastWritePosition) { writeBuffer = BufferUtils.EnsureBufferSize(bufferPool, lastWritePosition, writeBuffer); } // write unchanged chars at start of text. s.CopyTo(0, writeBuffer, 0, lastWritePosition); writer.Write(writeBuffer, 0, lastWritePosition); } int length; for (int i = lastWritePosition; i < s.Length; i++) { char c = s[i]; if (c < charEscapeFlags.Length && !charEscapeFlags[c]) { continue; } string? escapedValue; switch (c) { case '\t': escapedValue = @"\t"; break; case '\n': escapedValue = @"\n"; break; case '\r': escapedValue = @"\r"; break; case '\f': escapedValue = @"\f"; break; case '\b': escapedValue = @"\b"; break; case '\\': escapedValue = @"\\"; break; case '\u0085': // Next Line escapedValue = @"\u0085"; break; case '\u2028': // Line Separator escapedValue = @"\u2028"; break; case '\u2029': // Paragraph Separator escapedValue = @"\u2029"; break; default: if (c < charEscapeFlags.Length || stringEscapeHandling == StringEscapeHandling.EscapeNonAscii) { if (c == '\'' && stringEscapeHandling != StringEscapeHandling.EscapeHtml) { escapedValue = @"\'"; } else if (c == '"' && stringEscapeHandling != StringEscapeHandling.EscapeHtml) { escapedValue = @"\"""; } else { if (writeBuffer == null || writeBuffer.Length < UnicodeTextLength) { writeBuffer = BufferUtils.EnsureBufferSize(bufferPool, UnicodeTextLength, writeBuffer); } StringUtils.ToCharAsUnicode(c, writeBuffer!); // slightly hacky but it saves multiple conditions in if test escapedValue = EscapedUnicodeText; } } else { escapedValue = null; } break; } if (escapedValue == null) { continue; } bool isEscapedUnicodeText = string.Equals(escapedValue, EscapedUnicodeText, StringComparison.Ordinal); if (i > lastWritePosition) { length = i - lastWritePosition + ((isEscapedUnicodeText) ? UnicodeTextLength : 0); int start = (isEscapedUnicodeText) ? UnicodeTextLength : 0; if (writeBuffer == null || writeBuffer.Length < length) { char[] newBuffer = BufferUtils.RentBuffer(bufferPool, length); // the unicode text is already in the buffer // copy it over when creating new buffer if (isEscapedUnicodeText) { MiscellaneousUtils.Assert(writeBuffer != null, "Write buffer should never be null because it is set when the escaped unicode text is encountered."); Array.Copy(writeBuffer, newBuffer, UnicodeTextLength); } BufferUtils.ReturnBuffer(bufferPool, writeBuffer); writeBuffer = newBuffer; } s.CopyTo(lastWritePosition, writeBuffer, start, length - start); // write unchanged chars before writing escaped text writer.Write(writeBuffer, start, length - start); } lastWritePosition = i + 1; if (!isEscapedUnicodeText) { writer.Write(escapedValue); } else { writer.Write(writeBuffer, 0, UnicodeTextLength); } } MiscellaneousUtils.Assert(lastWritePosition != 0); length = s.Length - lastWritePosition; if (length > 0) { if (writeBuffer == null || writeBuffer.Length < length) { writeBuffer = BufferUtils.EnsureBufferSize(bufferPool, length, writeBuffer); } s.CopyTo(lastWritePosition, writeBuffer, 0, length); // write remaining text writer.Write(writeBuffer, 0, length); } } } // trailing delimiter if (appendDelimiters) { writer.Write(delimiter); } } public static string ToEscapedJavaScriptString(string? value, char delimiter, bool appendDelimiters, StringEscapeHandling stringEscapeHandling) { bool[] charEscapeFlags = GetCharEscapeFlags(stringEscapeHandling, delimiter); using (StringWriter w = StringUtils.CreateStringWriter(value?.Length ?? 16)) { char[]? buffer = null; WriteEscapedJavaScriptString(w, value, delimiter, appendDelimiters, charEscapeFlags, stringEscapeHandling, null, ref buffer); return w.ToString(); } } private static int FirstCharToEscape(string s, bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling) { for (int i = 0; i != s.Length; i++) { char c = s[i]; if (c < charEscapeFlags.Length) { if (charEscapeFlags[c]) { return i; } } else if (stringEscapeHandling == StringEscapeHandling.EscapeNonAscii) { return i; } else { switch (c) { case '\u0085': case '\u2028': case '\u2029': return i; } } } return -1; } #if HAVE_ASYNC public static Task WriteEscapedJavaScriptStringAsync(TextWriter writer, string s, char delimiter, bool appendDelimiters, bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, JsonTextWriter client, char[] writeBuffer, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { return cancellationToken.FromCanceled(); } if (appendDelimiters) { return WriteEscapedJavaScriptStringWithDelimitersAsync(writer, s, delimiter, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken); } if (StringUtils.IsNullOrEmpty(s)) { return cancellationToken.CancelIfRequestedAsync() ?? AsyncUtils.CompletedTask; } return WriteEscapedJavaScriptStringWithoutDelimitersAsync(writer, s, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken); } private static Task WriteEscapedJavaScriptStringWithDelimitersAsync(TextWriter writer, string s, char delimiter, bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, JsonTextWriter client, char[] writeBuffer, CancellationToken cancellationToken) { Task task = writer.WriteAsync(delimiter, cancellationToken); if (!task.IsCompletedSucessfully()) { return WriteEscapedJavaScriptStringWithDelimitersAsync(task, writer, s, delimiter, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken); } if (!StringUtils.IsNullOrEmpty(s)) { task = WriteEscapedJavaScriptStringWithoutDelimitersAsync(writer, s, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken); if (task.IsCompletedSucessfully()) { return writer.WriteAsync(delimiter, cancellationToken); } } return WriteCharAsync(task, writer, delimiter, cancellationToken); } private static async Task WriteEscapedJavaScriptStringWithDelimitersAsync(Task task, TextWriter writer, string s, char delimiter, bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, JsonTextWriter client, char[] writeBuffer, CancellationToken cancellationToken) { await task.ConfigureAwait(false); if (!StringUtils.IsNullOrEmpty(s)) { await WriteEscapedJavaScriptStringWithoutDelimitersAsync(writer, s, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken).ConfigureAwait(false); } await writer.WriteAsync(delimiter).ConfigureAwait(false); } public static async Task WriteCharAsync(Task task, TextWriter writer, char c, CancellationToken cancellationToken) { await task.ConfigureAwait(false); await writer.WriteAsync(c, cancellationToken).ConfigureAwait(false); } private static Task WriteEscapedJavaScriptStringWithoutDelimitersAsync( TextWriter writer, string s, bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, JsonTextWriter client, char[] writeBuffer, CancellationToken cancellationToken) { int i = FirstCharToEscape(s, charEscapeFlags, stringEscapeHandling); return i == -1 ? writer.WriteAsync(s, cancellationToken) : WriteDefinitelyEscapedJavaScriptStringWithoutDelimitersAsync(writer, s, i, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken); } private static async Task WriteDefinitelyEscapedJavaScriptStringWithoutDelimitersAsync( TextWriter writer, string s, int lastWritePosition, bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, JsonTextWriter client, char[] writeBuffer, CancellationToken cancellationToken) { if (writeBuffer == null || writeBuffer.Length < lastWritePosition) { writeBuffer = client.EnsureWriteBuffer(lastWritePosition, UnicodeTextLength); } if (lastWritePosition != 0) { s.CopyTo(0, writeBuffer, 0, lastWritePosition); // write unchanged chars at start of text. await writer.WriteAsync(writeBuffer, 0, lastWritePosition, cancellationToken).ConfigureAwait(false); } int length; bool isEscapedUnicodeText = false; string? escapedValue = null; for (int i = lastWritePosition; i < s.Length; i++) { char c = s[i]; if (c < charEscapeFlags.Length && !charEscapeFlags[c]) { continue; } switch (c) { case '\t': escapedValue = @"\t"; break; case '\n': escapedValue = @"\n"; break; case '\r': escapedValue = @"\r"; break; case '\f': escapedValue = @"\f"; break; case '\b': escapedValue = @"\b"; break; case '\\': escapedValue = @"\\"; break; case '\u0085': // Next Line escapedValue = @"\u0085"; break; case '\u2028': // Line Separator escapedValue = @"\u2028"; break; case '\u2029': // Paragraph Separator escapedValue = @"\u2029"; break; default: if (c < charEscapeFlags.Length || stringEscapeHandling == StringEscapeHandling.EscapeNonAscii) { if (c == '\'' && stringEscapeHandling != StringEscapeHandling.EscapeHtml) { escapedValue = @"\'"; } else if (c == '"' && stringEscapeHandling != StringEscapeHandling.EscapeHtml) { escapedValue = @"\"""; } else { if (writeBuffer.Length < UnicodeTextLength) { writeBuffer = client.EnsureWriteBuffer(UnicodeTextLength, 0); } StringUtils.ToCharAsUnicode(c, writeBuffer); isEscapedUnicodeText = true; } } else { continue; } break; } if (i > lastWritePosition) { length = i - lastWritePosition + (isEscapedUnicodeText ? UnicodeTextLength : 0); int start = isEscapedUnicodeText ? UnicodeTextLength : 0; if (writeBuffer.Length < length) { writeBuffer = client.EnsureWriteBuffer(length, UnicodeTextLength); } s.CopyTo(lastWritePosition, writeBuffer, start, length - start); // write unchanged chars before writing escaped text await writer.WriteAsync(writeBuffer, start, length - start, cancellationToken).ConfigureAwait(false); } lastWritePosition = i + 1; if (!isEscapedUnicodeText) { await writer.WriteAsync(escapedValue!, cancellationToken).ConfigureAwait(false); } else { await writer.WriteAsync(writeBuffer, 0, UnicodeTextLength, cancellationToken).ConfigureAwait(false); isEscapedUnicodeText = false; } } length = s.Length - lastWritePosition; if (length != 0) { if (writeBuffer.Length < length) { writeBuffer = client.EnsureWriteBuffer(length, 0); } s.CopyTo(lastWritePosition, writeBuffer, 0, length); // write remaining text await writer.WriteAsync(writeBuffer, 0, length, cancellationToken).ConfigureAwait(false); } } #endif public static bool TryGetDateFromConstructorJson(JsonReader reader, out DateTime dateTime, [NotNullWhen(false)]out string? errorMessage) { dateTime = default; errorMessage = null; if (!TryGetDateConstructorValue(reader, out long? t1, out errorMessage) || t1 == null) { errorMessage = errorMessage ?? "Date constructor has no arguments."; return false; } if (!TryGetDateConstructorValue(reader, out long? t2, out errorMessage)) { return false; } else if (t2 != null) { // Only create a list when there is more than one argument List<long> dateArgs = new List<long> { t1.Value, t2.Value }; while (true) { if (!TryGetDateConstructorValue(reader, out long? integer, out errorMessage)) { return false; } else if (integer != null) { dateArgs.Add(integer.Value); } else { break; } } if (dateArgs.Count > 7) { errorMessage = "Unexpected number of arguments when reading date constructor."; return false; } // Pad args out to the number used by the ctor while (dateArgs.Count < 7) { dateArgs.Add(0); } dateTime = new DateTime((int)dateArgs[0], (int)dateArgs[1] + 1, dateArgs[2] == 0 ? 1 : (int)dateArgs[2], (int)dateArgs[3], (int)dateArgs[4], (int)dateArgs[5], (int)dateArgs[6]); } else { dateTime = DateTimeUtils.ConvertJavaScriptTicksToDateTime(t1.Value); } return true; } private static bool TryGetDateConstructorValue(JsonReader reader, out long? integer, out string? errorMessage) { integer = null; errorMessage = null; if (!reader.Read()) { errorMessage = "Unexpected end when reading date constructor."; return false; } if (reader.TokenType == JsonToken.EndConstructor) { return true; } if (reader.TokenType != JsonToken.Integer) { errorMessage = "Unexpected token when reading date constructor. Expected Integer, got " + reader.TokenType; return false; } integer = (long)reader.Value!; return true; } } }
// 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.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Transforms; using osu.Framework.MathUtils; using osu.Framework.Testing; using osu.Framework.Timing; using osuTK; using osuTK.Graphics; namespace osu.Framework.Tests.Visual.TestCaseDrawable { public class TestCaseTransformRewinding : TestCase { private const double interval = 250; private const int interval_count = 4; private static double intervalAt(int sequence) => interval * sequence; private ManualClock manualClock; private FramedClock manualFramedClock; [SetUp] public void SetUp() => Schedule(() => { Clear(); manualClock = new ManualClock(); manualFramedClock = new FramedClock(manualClock); }); [Test] public void BasicScale() { boxTest(box => { box.Scale = Vector2.One; box.ScaleTo(0, interval * 4); }); checkAtTime(250, box => Precision.AlmostEquals(box.Scale.X, 0.75f)); checkAtTime(500, box => Precision.AlmostEquals(box.Scale.X, 0.5f)); checkAtTime(750, box => Precision.AlmostEquals(box.Scale.X, 0.25f)); checkAtTime(1000, box => Precision.AlmostEquals(box.Scale.X, 0f)); checkAtTime(500, box => Precision.AlmostEquals(box.Scale.X, 0.5f)); checkAtTime(250, box => Precision.AlmostEquals(box.Scale.X, 0.75f)); AddAssert("check transform count", () => box.Transforms.Count == 1); } [Test] public void ScaleSequence() { boxTest(box => { box.Scale = Vector2.One; box.ScaleTo(0.75f, interval).Then() .ScaleTo(0.5f, interval).Then() .ScaleTo(0.25f, interval).Then() .ScaleTo(0, interval); }); int i = 0; checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 0.75f)); checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 0.5f)); checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 0.25f)); checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 0f)); checkAtTime(interval * (i -= 2), box => Precision.AlmostEquals(box.Scale.X, 0.5f)); checkAtTime(interval * --i, box => Precision.AlmostEquals(box.Scale.X, 0.75f)); AddAssert("check transform count", () => box.Transforms.Count == 4); } [Test] public void BasicMovement() { boxTest(box => { box.Scale = new Vector2(0.25f); box.Anchor = Anchor.TopLeft; box.Origin = Anchor.TopLeft; box.MoveTo(new Vector2(0.75f, 0), interval).Then() .MoveTo(new Vector2(0.75f, 0.75f), interval).Then() .MoveTo(new Vector2(0, 0.75f), interval).Then() .MoveTo(new Vector2(0), interval); }); int i = 0; checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.X, 0.75f)); checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Y, 0.75f)); checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.X, 0f)); checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Y, 0f)); checkAtTime(interval * (i -= 2), box => Precision.AlmostEquals(box.Y, 0.75f)); checkAtTime(interval * --i, box => Precision.AlmostEquals(box.X, 0.75f)); AddAssert("check transform count", () => box.Transforms.Count == 4); } [Test] public void MoveSequence() { boxTest(box => { box.Scale = new Vector2(0.25f); box.Anchor = Anchor.TopLeft; box.Origin = Anchor.TopLeft; box.ScaleTo(0.5f, interval).MoveTo(new Vector2(0.5f), interval).Then() .ScaleTo(0.1f, interval).MoveTo(new Vector2(0, 0.75f), interval).Then() .ScaleTo(1f, interval).MoveTo(new Vector2(0, 0), interval).Then() .FadeTo(0, interval); }); int i = 0; checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.X, 0.5f) && Precision.AlmostEquals(box.Scale.X, 0.5f)); checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Y, 0.75f) && Precision.AlmostEquals(box.Scale.X, 0.1f)); checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.X, 0f)); checkAtTime(interval * (i += 2), box => Precision.AlmostEquals(box.Alpha, 0f)); checkAtTime(interval * (i - 2), box => Precision.AlmostEquals(box.Alpha, 1f)); AddAssert("check transform count", () => box.Transforms.Count == 7); } [Test] public void MoveCancelSequence() { boxTest(box => { box.Scale = new Vector2(0.25f); box.Anchor = Anchor.TopLeft; box.Origin = Anchor.TopLeft; box.ScaleTo(0.5f, interval).Then().ScaleTo(1, interval); Scheduler.AddDelayed(() => { box.ScaleTo(new Vector2(0.1f), interval); }, interval / 2); }); int i = 0; checkAtTime(interval * i, box => Precision.AlmostEquals(box.Scale.X, 0.25f)); checkAtTime(interval * ++i, box => !Precision.AlmostEquals(box.Scale.X, 0.5f)); checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 0.1f)); AddAssert("check transform count", () => box.Transforms.Count == 2); } [Test] public void SameTypeInType() { boxTest(box => { box.ScaleTo(0.5f, interval * 4); box.Delay(interval * 2).ScaleTo(1, interval); }); int i = 0; checkAtTime(interval * i, box => Precision.AlmostEquals(box.Scale.X, 0.25f)); checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 0.3125f)); checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 0.375f)); checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 1)); checkAtTime(interval * --i, box => Precision.AlmostEquals(box.Scale.X, 0.375f)); checkAtTime(interval * --i, box => Precision.AlmostEquals(box.Scale.X, 0.3125f)); checkAtTime(interval * --i, box => Precision.AlmostEquals(box.Scale.X, 0.25f)); AddAssert("check transform count", () => box.Transforms.Count == 2); } [Test] public void SameTypeInPartialOverlap() { boxTest(box => { box.ScaleTo(0.5f, interval * 2); box.Delay(interval).ScaleTo(1, interval * 2); }); int i = 0; checkAtTime(interval * i, box => Precision.AlmostEquals(box.Scale.X, 0.25f)); checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 0.375f)); checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 0.6875f)); checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 1)); checkAtTime(interval * ++i, box => Precision.AlmostEquals(box.Scale.X, 1)); checkAtTime(interval * --i, box => Precision.AlmostEquals(box.Scale.X, 1)); checkAtTime(interval * --i, box => Precision.AlmostEquals(box.Scale.X, 0.6875f)); checkAtTime(interval * --i, box => Precision.AlmostEquals(box.Scale.X, 0.375f)); AddAssert("check transform count", () => box.Transforms.Count == 2); } [Test] public void StartInMiddleOfSequence() { boxTest(box => { box.Alpha = 0; box.Delay(interval * 2).FadeInFromZero(interval); box.ScaleTo(0.9f, interval * 4); }, 750); checkAtTime(interval * 3, box => Precision.AlmostEquals(box.Alpha, 1)); checkAtTime(interval * 4, box => Precision.AlmostEquals(box.Alpha, 1) && Precision.AlmostEquals(box.Scale.X, 0.9f)); checkAtTime(interval * 2, box => Precision.AlmostEquals(box.Alpha, 0) && Precision.AlmostEquals(box.Scale.X, 0.575f)); AddAssert("check transform count", () => box.Transforms.Count == 3); } [Test] public void LoopSequence() { boxTest(box => { box.RotateTo(0).RotateTo(90, interval).Loop(); }); const int count = 4; for (int i = 0; i <= count; i++) { if (i > 0) checkAtTime(interval * i - 1, box => Precision.AlmostEquals(box.Rotation, 90f, 1)); checkAtTime(interval * i, box => Precision.AlmostEquals(box.Rotation, 0)); } AddAssert("check transform count", () => box.Transforms.Count == 10); for (int i = count; i >= 0; i--) { if (i > 0) checkAtTime(interval * i - 1, box => Precision.AlmostEquals(box.Rotation, 90f, 1)); checkAtTime(interval * i, box => Precision.AlmostEquals(box.Rotation, 0)); } } [Test] public void StartInMiddleOfLoopSequence() { boxTest(box => { box.RotateTo(0).RotateTo(90, interval).Loop(); }, 750); checkAtTime(750, box => Precision.AlmostEquals(box.Rotation, 0f)); AddAssert("check transform count", () => box.Transforms.Count == 8); const int count = 4; for (int i = 0; i <= count; i++) { if (i > 0) checkAtTime(interval * i - 1, box => Precision.AlmostEquals(box.Rotation, 90f, 1)); checkAtTime(interval * i, box => Precision.AlmostEquals(box.Rotation, 0)); } AddAssert("check transform count", () => box.Transforms.Count == 10); for (int i = count; i >= 0; i--) { if (i > 0) checkAtTime(interval * i - 1, box => Precision.AlmostEquals(box.Rotation, 90f, 1)); checkAtTime(interval * i, box => Precision.AlmostEquals(box.Rotation, 0)); } } private Box box; private void checkAtTime(double time, Func<Box, bool> assert) { AddAssert($"check at time {time}", () => { manualClock.CurrentTime = time; box.Clock = manualFramedClock; box.UpdateSubTree(); return assert(box); }); } private void boxTest(Action<Box> action, int startTime = 0) { AddStep("add box", () => { Add(new AnimationContainer(startTime) { Child = box = new Box { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.Both, RelativePositionAxes = Axes.Both, Scale = new Vector2(0.25f), }, ExaminableDrawable = box, }); action(box); }); } private class AnimationContainer : Container { public override bool RemoveCompletedTransforms => false; protected override Container<Drawable> Content => content; private readonly Container content; private readonly SpriteText minTimeText; private readonly SpriteText currentTimeText; private readonly SpriteText maxTimeText; private readonly Tick seekingTick; private readonly WrappingTimeContainer wrapping; public Box ExaminableDrawable; private readonly FlowContainer<DrawableTransform> transforms; public AnimationContainer(int startTime = 0) { Anchor = Anchor.Centre; Origin = Anchor.Centre; RelativeSizeAxes = Axes.Both; InternalChild = wrapping = new WrappingTimeContainer(startTime) { RelativeSizeAxes = Axes.Both, Children = new Drawable[] { new Container { FillMode = FillMode.Fit, RelativeSizeAxes = Axes.Both, Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(0.6f), Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.DarkGray, }, content = new Container { RelativeSizeAxes = Axes.Both, Masking = true, }, } }, transforms = new FillFlowContainer<DrawableTransform> { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Spacing = Vector2.One, RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Width = 0.2f, }, new Container { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, RelativeSizeAxes = Axes.Both, Size = new Vector2(0.8f, 0.1f), Children = new Drawable[] { minTimeText = new SpriteText { Anchor = Anchor.BottomLeft, Origin = Anchor.TopLeft, }, currentTimeText = new SpriteText { RelativePositionAxes = Axes.X, Anchor = Anchor.BottomLeft, Origin = Anchor.BottomCentre, Y = -10, }, maxTimeText = new SpriteText { Anchor = Anchor.BottomRight, Origin = Anchor.TopRight, }, seekingTick = new Tick(0, false), new Tick(0), new Tick(1), new Tick(2), new Tick(3), new Tick(4), } } } }; } private List<Transform> displayedTransforms; protected override void Update() { base.Update(); double time = wrapping.Time.Current; minTimeText.Text = wrapping.MinTime.ToString("n0"); currentTimeText.Text = time.ToString("n0"); seekingTick.X = currentTimeText.X = (float)(time / (wrapping.MaxTime - wrapping.MinTime)); maxTimeText.Text = wrapping.MaxTime.ToString("n0"); maxTimeText.Colour = time > wrapping.MaxTime ? Color4.Gray : wrapping.Time.Elapsed > 0 ? Color4.Blue : Color4.Red; minTimeText.Colour = time < wrapping.MinTime ? Color4.Gray : content.Time.Elapsed > 0 ? Color4.Blue : Color4.Red; if (displayedTransforms == null || !ExaminableDrawable.Transforms.SequenceEqual(displayedTransforms)) { transforms.Clear(); foreach (var t in ExaminableDrawable.Transforms) transforms.Add(new DrawableTransform(t)); displayedTransforms = new List<Transform>(ExaminableDrawable.Transforms); } } private class DrawableTransform : CompositeDrawable { private readonly Transform transform; private readonly Box applied; private readonly Box appliedToEnd; private readonly SpriteText text; private const float height = 15; public DrawableTransform(Transform transform) { this.transform = transform; RelativeSizeAxes = Axes.X; Height = height; InternalChildren = new Drawable[] { applied = new Box { Size = new Vector2(height) }, appliedToEnd = new Box { X = height + 2, Size = new Vector2(height) }, text = new SpriteText { X = (height + 2) * 2, Font = new FontUsage(size: height) }, }; } protected override void Update() { base.Update(); applied.Colour = transform.Applied ? Color4.Green : Color4.Red; appliedToEnd.Colour = transform.AppliedToEnd ? Color4.Green : Color4.Red; text.Text = transform.ToString(); } } private class Tick : Box { private readonly int tick; private readonly bool colouring; public Tick(int tick, bool colouring = true) { this.tick = tick; this.colouring = colouring; Anchor = Anchor.BottomLeft; Origin = Anchor.BottomCentre; Size = new Vector2(1, 10); Colour = Color4.White; RelativePositionAxes = Axes.X; X = (float)tick / interval_count; } protected override void Update() { base.Update(); if (colouring) Colour = Time.Current > tick * interval ? Color4.Yellow : Color4.White; } } } private class WrappingTimeContainer : Container { // Padding, in milliseconds, at each end of maxima of the clock time private const double time_padding = 50; public double MinTime => clock.MinTime + time_padding; public double MaxTime => clock.MaxTime - time_padding; private readonly ReversibleClock clock; public WrappingTimeContainer(double startTime) { clock = new ReversibleClock(startTime); } [BackgroundDependencyLoader] private void load() { // Replace the game clock, but keep it as a reference clock.SetSource(Clock); Clock = clock; } protected override void LoadComplete() { base.LoadComplete(); clock.MinTime = -time_padding; clock.MaxTime = intervalAt(interval_count) + time_padding; } private class ReversibleClock : IFrameBasedClock { private readonly double startTime; public double MinTime; public double MaxTime = 1000; private IFrameBasedClock trackingClock; private bool reversed; public ReversibleClock(double startTime) { this.startTime = startTime; } public void SetSource(IFrameBasedClock trackingClock) { this.trackingClock = new FramedOffsetClock(trackingClock) { Offset = -trackingClock.CurrentTime + startTime }; } public double CurrentTime { get; private set; } public double Rate => trackingClock.Rate; public bool IsRunning => trackingClock.IsRunning; public double ElapsedFrameTime => (reversed ? -1 : 1) * trackingClock.ElapsedFrameTime; public double FramesPerSecond => trackingClock.FramesPerSecond; public FrameTimeInfo TimeInfo => new FrameTimeInfo { Current = CurrentTime, Elapsed = ElapsedFrameTime }; public void ProcessFrame() { trackingClock.ProcessFrame(); // There are two iterations, when iteration % 2 == 0 : not reversed int iteration = (int)(trackingClock.CurrentTime / (MaxTime - MinTime)); reversed = iteration % 2 == 1; double iterationTime = trackingClock.CurrentTime % (MaxTime - MinTime); if (reversed) CurrentTime = MaxTime - iterationTime; else CurrentTime = MinTime + iterationTime; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================================= ** ** ** ** Purpose: Synchronizes access to a shared resource or region of code in a multi-threaded ** program. ** ** =============================================================================*/ using System; using System.Diagnostics; using System.Runtime.CompilerServices; namespace System.Threading { public static class Monitor { #region Object->Lock/Condition mapping #if !FEATURE_SYNCTABLE private static ConditionalWeakTable<object, Lock> s_lockTable = new ConditionalWeakTable<object, Lock>(); private static ConditionalWeakTable<object, Lock>.CreateValueCallback s_createLock = (o) => new Lock(); #endif private static ConditionalWeakTable<object, Condition> s_conditionTable = new ConditionalWeakTable<object, Condition>(); private static ConditionalWeakTable<object, Condition>.CreateValueCallback s_createCondition = (o) => new Condition(GetLock(o)); internal static Lock GetLock(Object obj) { if (obj == null) throw new ArgumentNullException(nameof(obj)); Debug.Assert(!(obj is Lock), "Do not use Monitor.Enter or TryEnter on a Lock instance; use Lock methods directly instead."); #if FEATURE_SYNCTABLE return ObjectHeader.GetLockObject(obj); #else return s_lockTable.GetValue(obj, s_createLock); #endif } private static Condition GetCondition(Object obj) { Debug.Assert( !(obj is Condition || obj is Lock), "Do not use Monitor.Pulse or Wait on a Lock or Condition instance; use the methods on Condition instead."); return s_conditionTable.GetValue(obj, s_createCondition); } #endregion #region Public Enter/Exit methods public static void Enter(Object obj) { Lock lck = GetLock(obj); if (lck.TryAcquire(0)) return; TryAcquireContended(lck, obj, Timeout.Infinite); } public static void Enter(Object obj, ref bool lockTaken) { if (lockTaken) throw new ArgumentException(SR.Argument_MustBeFalse, nameof(lockTaken)); Lock lck = GetLock(obj); if (lck.TryAcquire(0)) { lockTaken = true; return; } TryAcquireContended(lck, obj, Timeout.Infinite); lockTaken = true; } public static bool TryEnter(Object obj) { return GetLock(obj).TryAcquire(0); } public static void TryEnter(Object obj, ref bool lockTaken) { if (lockTaken) throw new ArgumentException(SR.Argument_MustBeFalse, nameof(lockTaken)); lockTaken = GetLock(obj).TryAcquire(0); } public static bool TryEnter(Object obj, int millisecondsTimeout) { if (millisecondsTimeout < -1) throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); Lock lck = GetLock(obj); if (lck.TryAcquire(0)) return true; return TryAcquireContended(lck, obj, millisecondsTimeout); } public static void TryEnter(Object obj, int millisecondsTimeout, ref bool lockTaken) { if (lockTaken) throw new ArgumentException(SR.Argument_MustBeFalse, nameof(lockTaken)); if (millisecondsTimeout < -1) throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); Lock lck = GetLock(obj); if (lck.TryAcquire(0)) { lockTaken = true; return; } lockTaken = TryAcquireContended(lck, obj, millisecondsTimeout); } public static bool TryEnter(Object obj, TimeSpan timeout) => TryEnter(obj, WaitHandle.ToTimeoutMilliseconds(timeout)); public static void TryEnter(Object obj, TimeSpan timeout, ref bool lockTaken) => TryEnter(obj, WaitHandle.ToTimeoutMilliseconds(timeout), ref lockTaken); public static void Exit(Object obj) { GetLock(obj).Release(); } public static bool IsEntered(Object obj) { return GetLock(obj).IsAcquired; } #endregion #region Public Wait/Pulse methods // Remoting is not supported, ignore exitContext public static bool Wait(Object obj, int millisecondsTimeout, bool exitContext) => Wait(obj, millisecondsTimeout); // Remoting is not supported, ignore exitContext public static bool Wait(Object obj, TimeSpan timeout, bool exitContext) => Wait(obj, WaitHandle.ToTimeoutMilliseconds(timeout)); public static bool Wait(Object obj, int millisecondsTimeout) { Condition condition = GetCondition(obj); DebugBlockingItem blockingItem; using (new DebugBlockingScope(obj, DebugBlockingItemType.MonitorEvent, millisecondsTimeout, out blockingItem)) { return condition.Wait(millisecondsTimeout); } } public static bool Wait(Object obj, TimeSpan timeout) => Wait(obj, WaitHandle.ToTimeoutMilliseconds(timeout)); public static bool Wait(Object obj) => Wait(obj, Timeout.Infinite); public static void Pulse(object obj) { GetCondition(obj).SignalOne(); } public static void PulseAll(object obj) { GetCondition(obj).SignalAll(); } #endregion #region Slow path for Entry/TryEnter methods. internal static bool TryAcquireContended(Lock lck, Object obj, int millisecondsTimeout) { DebugBlockingItem blockingItem; using (new DebugBlockingScope(obj, DebugBlockingItemType.MonitorCriticalSection, millisecondsTimeout, out blockingItem)) { return lck.TryAcquire(millisecondsTimeout); } } #endregion #region Debugger support // The debugger binds to the fields below by name. Do not change any names or types without // updating the debugger! // The head of the list of DebugBlockingItem stack objects used by the debugger to implement // ICorDebugThread4::GetBlockingObjects. Usually the list either is empty or contains a single // item. However, a wait on an STA thread may reenter via the message pump and cause the thread // to be blocked on a second object. [ThreadStatic] private static IntPtr t_firstBlockingItem; // Different ways a thread can be blocked that the debugger will expose. // Do not change or add members without updating the debugger code. private enum DebugBlockingItemType { MonitorCriticalSection = 0, MonitorEvent = 1 } // Represents an item a thread is blocked on. This structure is allocated on the stack and accessed by the debugger. // Fields are volatile to avoid potential compiler optimizations. private struct DebugBlockingItem { // The object the thread is waiting on public volatile object _object; // Indicates how the thread is blocked on the item public volatile DebugBlockingItemType _blockingType; // Blocking timeout in milliseconds or Timeout.Infinite for no timeout public volatile int _timeout; // Next pointer in the linked list of DebugBlockingItem records public volatile IntPtr _next; } private unsafe struct DebugBlockingScope : IDisposable { public DebugBlockingScope(object obj, DebugBlockingItemType blockingType, int timeout, out DebugBlockingItem blockingItem) { blockingItem._object = obj; blockingItem._blockingType = blockingType; blockingItem._timeout = timeout; blockingItem._next = t_firstBlockingItem; t_firstBlockingItem = (IntPtr)Unsafe.AsPointer(ref blockingItem); } public void Dispose() { t_firstBlockingItem = Unsafe.Read<DebugBlockingItem>((void*)t_firstBlockingItem)._next; } } #endregion } }
// Copyright (C) 2014 dot42 // // Original filename: Java.Security.Interfaces.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. #pragma warning disable 1717 namespace Java.Security.Interfaces { /// <summary> /// <para>The interface for an PKCS#1 RSA private key. </para> /// </summary> /// <java-name> /// java/security/interfaces/RSAPrivateKey /// </java-name> [Dot42.DexImport("java/security/interfaces/RSAPrivateKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IRSAPrivateKeyConstants /* scope: __dot42__ */ { /// <summary> /// <para>The serial version identifier. </para> /// </summary> /// <java-name> /// serialVersionUID /// </java-name> [Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)] public const long SerialVersionUID = 5187144804936595022; } /// <summary> /// <para>The interface for an PKCS#1 RSA private key. </para> /// </summary> /// <java-name> /// java/security/interfaces/RSAPrivateKey /// </java-name> [Dot42.DexImport("java/security/interfaces/RSAPrivateKey", AccessFlags = 1537)] public partial interface IRSAPrivateKey : global::Java.Security.IPrivateKey, global::Java.Security.Interfaces.IRSAKey /* scope: __dot42__ */ { /// <summary> /// <para>Returns the private exponent <c> d </c> .</para><para></para> /// </summary> /// <returns> /// <para>the private exponent <c> d </c> . </para> /// </returns> /// <java-name> /// getPrivateExponent /// </java-name> [Dot42.DexImport("getPrivateExponent", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetPrivateExponent() /* MethodBuilder.Create */ ; } /// <summary> /// <para>The interface for an Elliptic Curve (EC) public key. </para> /// </summary> /// <java-name> /// java/security/interfaces/ECPublicKey /// </java-name> [Dot42.DexImport("java/security/interfaces/ECPublicKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IECPublicKeyConstants /* scope: __dot42__ */ { /// <summary> /// <para>The serial version identifier. </para> /// </summary> /// <java-name> /// serialVersionUID /// </java-name> [Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)] public const long SerialVersionUID = -3314988629879632826; } /// <summary> /// <para>The interface for an Elliptic Curve (EC) public key. </para> /// </summary> /// <java-name> /// java/security/interfaces/ECPublicKey /// </java-name> [Dot42.DexImport("java/security/interfaces/ECPublicKey", AccessFlags = 1537)] public partial interface IECPublicKey : global::Java.Security.IPublicKey, global::Java.Security.Interfaces.IECKey /* scope: __dot42__ */ { /// <summary> /// <para>Returns the public point <c> W </c> on an elliptic curve (EC).</para><para></para> /// </summary> /// <returns> /// <para>the public point <c> W </c> on an elliptic curve (EC). </para> /// </returns> /// <java-name> /// getW /// </java-name> [Dot42.DexImport("getW", "()Ljava/security/spec/ECPoint;", AccessFlags = 1025)] global::Java.Security.Spec.ECPoint GetW() /* MethodBuilder.Create */ ; } /// <summary> /// <para>The interface for a Digital Signature Algorithm (DSA) private key. </para> /// </summary> /// <java-name> /// java/security/interfaces/DSAPrivateKey /// </java-name> [Dot42.DexImport("java/security/interfaces/DSAPrivateKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IDSAPrivateKeyConstants /* scope: __dot42__ */ { /// <summary> /// <para>The serial version identifier. </para> /// </summary> /// <java-name> /// serialVersionUID /// </java-name> [Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)] public const long SerialVersionUID = 7776497482533790279; } /// <summary> /// <para>The interface for a Digital Signature Algorithm (DSA) private key. </para> /// </summary> /// <java-name> /// java/security/interfaces/DSAPrivateKey /// </java-name> [Dot42.DexImport("java/security/interfaces/DSAPrivateKey", AccessFlags = 1537)] public partial interface IDSAPrivateKey : global::Java.Security.Interfaces.IDSAKey, global::Java.Security.IPrivateKey /* scope: __dot42__ */ { /// <summary> /// <para>Returns the private key value <c> x </c> .</para><para></para> /// </summary> /// <returns> /// <para>the private key value <c> x </c> . </para> /// </returns> /// <java-name> /// getX /// </java-name> [Dot42.DexImport("getX", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetX() /* MethodBuilder.Create */ ; } /// <summary> /// <para>The interface for a PKCS#1 RSA public key. </para> /// </summary> /// <java-name> /// java/security/interfaces/RSAPublicKey /// </java-name> [Dot42.DexImport("java/security/interfaces/RSAPublicKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IRSAPublicKeyConstants /* scope: __dot42__ */ { /// <summary> /// <para>The serial version identifier. </para> /// </summary> /// <java-name> /// serialVersionUID /// </java-name> [Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)] public const long SerialVersionUID = -8727434096241101194; } /// <summary> /// <para>The interface for a PKCS#1 RSA public key. </para> /// </summary> /// <java-name> /// java/security/interfaces/RSAPublicKey /// </java-name> [Dot42.DexImport("java/security/interfaces/RSAPublicKey", AccessFlags = 1537)] public partial interface IRSAPublicKey : global::Java.Security.IPublicKey, global::Java.Security.Interfaces.IRSAKey /* scope: __dot42__ */ { /// <summary> /// <para>Returns the public exponent <c> e </c> .</para><para></para> /// </summary> /// <returns> /// <para>the public exponent <c> e </c> . </para> /// </returns> /// <java-name> /// getPublicExponent /// </java-name> [Dot42.DexImport("getPublicExponent", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetPublicExponent() /* MethodBuilder.Create */ ; } /// <summary> /// <para>The base interface for PKCS#1 RSA public and private keys. </para> /// </summary> /// <java-name> /// java/security/interfaces/RSAKey /// </java-name> [Dot42.DexImport("java/security/interfaces/RSAKey", AccessFlags = 1537)] public partial interface IRSAKey /* scope: __dot42__ */ { /// <summary> /// <para>Returns the modulus.</para><para></para> /// </summary> /// <returns> /// <para>the modulus. </para> /// </returns> /// <java-name> /// getModulus /// </java-name> [Dot42.DexImport("getModulus", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetModulus() /* MethodBuilder.Create */ ; } /// <summary> /// <para>The base interface for Digital Signature Algorithm (DSA) public or private keys. </para> /// </summary> /// <java-name> /// java/security/interfaces/DSAKey /// </java-name> [Dot42.DexImport("java/security/interfaces/DSAKey", AccessFlags = 1537)] public partial interface IDSAKey /* scope: __dot42__ */ { /// <summary> /// <para>Returns the DSA key parameters.</para><para></para> /// </summary> /// <returns> /// <para>the DSA key parameters. </para> /// </returns> /// <java-name> /// getParams /// </java-name> [Dot42.DexImport("getParams", "()Ljava/security/interfaces/DSAParams;", AccessFlags = 1025)] global::Java.Security.Interfaces.IDSAParams GetParams() /* MethodBuilder.Create */ ; } /// <summary> /// <para>The interface for key generators that can generate DSA key pairs. </para> /// </summary> /// <java-name> /// java/security/interfaces/DSAKeyPairGenerator /// </java-name> [Dot42.DexImport("java/security/interfaces/DSAKeyPairGenerator", AccessFlags = 1537)] public partial interface IDSAKeyPairGenerator /* scope: __dot42__ */ { /// <summary> /// <para>Initializes this generator with the prime (<c> p </c> ), subprime (<c> q </c> ), and base (<c> g </c> ) values from the specified parameters.</para><para></para> /// </summary> /// <java-name> /// initialize /// </java-name> [Dot42.DexImport("initialize", "(Ljava/security/interfaces/DSAParams;Ljava/security/SecureRandom;)V", AccessFlags = 1025)] void Initialize(global::Java.Security.Interfaces.IDSAParams @params, global::Java.Security.SecureRandom random) /* MethodBuilder.Create */ ; /// <summary> /// <para>Initializes this generator for the specified modulus length. Valid values for the modulus length are the multiples of 8 between 512 and 1024. </para><para>The parameter <c> genParams </c> specifies whether this method should generate new prime (<c> p </c> ), subprime (<c> q </c> ), and base (<c> g </c> ) values or whether it will use the pre-calculated values for the specified modulus length. Default parameters are available for modulus lengths of 512 and 1024 bits.</para><para></para> /// </summary> /// <java-name> /// initialize /// </java-name> [Dot42.DexImport("initialize", "(IZLjava/security/SecureRandom;)V", AccessFlags = 1025)] void Initialize(int modlen, bool genParams, global::Java.Security.SecureRandom random) /* MethodBuilder.Create */ ; } /// <summary> /// <para>The interface for a Digital Signature Algorithm (DSA) public key. </para> /// </summary> /// <java-name> /// java/security/interfaces/DSAPublicKey /// </java-name> [Dot42.DexImport("java/security/interfaces/DSAPublicKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IDSAPublicKeyConstants /* scope: __dot42__ */ { /// <summary> /// <para>The serial version identifier. </para> /// </summary> /// <java-name> /// serialVersionUID /// </java-name> [Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)] public const long SerialVersionUID = 1234526332779022332; } /// <summary> /// <para>The interface for a Digital Signature Algorithm (DSA) public key. </para> /// </summary> /// <java-name> /// java/security/interfaces/DSAPublicKey /// </java-name> [Dot42.DexImport("java/security/interfaces/DSAPublicKey", AccessFlags = 1537)] public partial interface IDSAPublicKey : global::Java.Security.Interfaces.IDSAKey, global::Java.Security.IPublicKey /* scope: __dot42__ */ { /// <summary> /// <para>Returns the public key value <c> y </c> .</para><para></para> /// </summary> /// <returns> /// <para>the public key value <c> y </c> . </para> /// </returns> /// <java-name> /// getY /// </java-name> [Dot42.DexImport("getY", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetY() /* MethodBuilder.Create */ ; } /// <summary> /// <para>The interface for a PKCS#1 RSA private key using CRT information values. </para> /// </summary> /// <java-name> /// java/security/interfaces/RSAPrivateCrtKey /// </java-name> [Dot42.DexImport("java/security/interfaces/RSAPrivateCrtKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IRSAPrivateCrtKeyConstants /* scope: __dot42__ */ { /// <summary> /// <para>The serial version identifier. </para> /// </summary> /// <java-name> /// serialVersionUID /// </java-name> [Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)] public const long SerialVersionUID = -5682214253527700368; } /// <summary> /// <para>The interface for a PKCS#1 RSA private key using CRT information values. </para> /// </summary> /// <java-name> /// java/security/interfaces/RSAPrivateCrtKey /// </java-name> [Dot42.DexImport("java/security/interfaces/RSAPrivateCrtKey", AccessFlags = 1537)] public partial interface IRSAPrivateCrtKey : global::Java.Security.Interfaces.IRSAPrivateKey /* scope: __dot42__ */ { /// <summary> /// <para>Returns the CRT coefficient, <c> q^-1 mod p </c> .</para><para></para> /// </summary> /// <returns> /// <para>the CRT coefficient. </para> /// </returns> /// <java-name> /// getCrtCoefficient /// </java-name> [Dot42.DexImport("getCrtCoefficient", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetCrtCoefficient() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the prime factor <c> p </c> of <c> n </c> .</para><para></para> /// </summary> /// <returns> /// <para>the prime factor <c> p </c> of <c> n </c> . </para> /// </returns> /// <java-name> /// getPrimeP /// </java-name> [Dot42.DexImport("getPrimeP", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetPrimeP() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the prime factor <c> q </c> of <c> n </c> .</para><para></para> /// </summary> /// <returns> /// <para>the prime factor <c> q </c> of <c> n </c> . </para> /// </returns> /// <java-name> /// getPrimeQ /// </java-name> [Dot42.DexImport("getPrimeQ", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetPrimeQ() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the CRT exponent of the primet <c> p </c> .</para><para></para> /// </summary> /// <returns> /// <para>the CRT exponent of the prime <c> p </c> . </para> /// </returns> /// <java-name> /// getPrimeExponentP /// </java-name> [Dot42.DexImport("getPrimeExponentP", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetPrimeExponentP() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the CRT exponent of the prime <c> q </c> .</para><para></para> /// </summary> /// <returns> /// <para>the CRT exponent of the prime <c> q </c> . </para> /// </returns> /// <java-name> /// getPrimeExponentQ /// </java-name> [Dot42.DexImport("getPrimeExponentQ", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetPrimeExponentQ() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the public exponent <c> e </c> .</para><para></para> /// </summary> /// <returns> /// <para>the public exponent <c> e </c> . </para> /// </returns> /// <java-name> /// getPublicExponent /// </java-name> [Dot42.DexImport("getPublicExponent", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetPublicExponent() /* MethodBuilder.Create */ ; } /// <summary> /// <para>The interface for Digital Signature Algorithm (DSA) specific parameters. </para> /// </summary> /// <java-name> /// java/security/interfaces/DSAParams /// </java-name> [Dot42.DexImport("java/security/interfaces/DSAParams", AccessFlags = 1537)] public partial interface IDSAParams /* scope: __dot42__ */ { /// <summary> /// <para>Returns the base (<c> g </c> ) value.</para><para></para> /// </summary> /// <returns> /// <para>the base (<c> g </c> ) value. </para> /// </returns> /// <java-name> /// getG /// </java-name> [Dot42.DexImport("getG", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetG() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the prime (<c> p </c> ) value.</para><para></para> /// </summary> /// <returns> /// <para>the prime (<c> p </c> ) value. </para> /// </returns> /// <java-name> /// getP /// </java-name> [Dot42.DexImport("getP", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetP() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the subprime (<c> q </c> value.</para><para></para> /// </summary> /// <returns> /// <para>the subprime (<c> q </c> value. </para> /// </returns> /// <java-name> /// getQ /// </java-name> [Dot42.DexImport("getQ", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetQ() /* MethodBuilder.Create */ ; } /// <summary> /// <para>The interface for an Elliptic Curve (EC) private key. </para> /// </summary> /// <java-name> /// java/security/interfaces/ECPrivateKey /// </java-name> [Dot42.DexImport("java/security/interfaces/ECPrivateKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IECPrivateKeyConstants /* scope: __dot42__ */ { /// <summary> /// <para>The serial version identifier. </para> /// </summary> /// <java-name> /// serialVersionUID /// </java-name> [Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)] public const long SerialVersionUID = -7896394956925609184; } /// <summary> /// <para>The interface for an Elliptic Curve (EC) private key. </para> /// </summary> /// <java-name> /// java/security/interfaces/ECPrivateKey /// </java-name> [Dot42.DexImport("java/security/interfaces/ECPrivateKey", AccessFlags = 1537)] public partial interface IECPrivateKey : global::Java.Security.IPrivateKey, global::Java.Security.Interfaces.IECKey /* scope: __dot42__ */ { /// <summary> /// <para>Returns the private value <c> S </c> .</para><para></para> /// </summary> /// <returns> /// <para>the private value <c> S </c> . </para> /// </returns> /// <java-name> /// getS /// </java-name> [Dot42.DexImport("getS", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetS() /* MethodBuilder.Create */ ; } /// <summary> /// <para>The base interface for Elliptic Curve (EC) public or private keys. </para> /// </summary> /// <java-name> /// java/security/interfaces/ECKey /// </java-name> [Dot42.DexImport("java/security/interfaces/ECKey", AccessFlags = 1537)] public partial interface IECKey /* scope: __dot42__ */ { /// <summary> /// <para>Returns the EC key parameters.</para><para></para> /// </summary> /// <returns> /// <para>the EC key parameters. </para> /// </returns> /// <java-name> /// getParams /// </java-name> [Dot42.DexImport("getParams", "()Ljava/security/spec/ECParameterSpec;", AccessFlags = 1025)] global::Java.Security.Spec.ECParameterSpec GetParams() /* MethodBuilder.Create */ ; } /// <summary> /// <para>The interface for a Multi-Prime RSA private key. Specified by . </para> /// </summary> /// <java-name> /// java/security/interfaces/RSAMultiPrimePrivateCrtKey /// </java-name> [Dot42.DexImport("java/security/interfaces/RSAMultiPrimePrivateCrtKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IRSAMultiPrimePrivateCrtKeyConstants /* scope: __dot42__ */ { /// <summary> /// <para>the serial version identifier. </para> /// </summary> /// <java-name> /// serialVersionUID /// </java-name> [Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)] public const long SerialVersionUID = 618058533534628008; } /// <summary> /// <para>The interface for a Multi-Prime RSA private key. Specified by . </para> /// </summary> /// <java-name> /// java/security/interfaces/RSAMultiPrimePrivateCrtKey /// </java-name> [Dot42.DexImport("java/security/interfaces/RSAMultiPrimePrivateCrtKey", AccessFlags = 1537)] public partial interface IRSAMultiPrimePrivateCrtKey : global::Java.Security.Interfaces.IRSAPrivateKey /* scope: __dot42__ */ { /// <summary> /// <para>Returns the CRT coefficient, <c> q^-1 mod p </c> .</para><para></para> /// </summary> /// <returns> /// <para>the CRT coefficient. </para> /// </returns> /// <java-name> /// getCrtCoefficient /// </java-name> [Dot42.DexImport("getCrtCoefficient", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetCrtCoefficient() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the information for the additional primes.</para><para></para> /// </summary> /// <returns> /// <para>the information for the additional primes, or <c> null </c> if there are only the two primes (<c> p, q </c> ), </para> /// </returns> /// <java-name> /// getOtherPrimeInfo /// </java-name> [Dot42.DexImport("getOtherPrimeInfo", "()[Ljava/security/spec/RSAOtherPrimeInfo;", AccessFlags = 1025)] global::Java.Security.Spec.RSAOtherPrimeInfo[] GetOtherPrimeInfo() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the prime factor <c> p </c> of <c> n </c> .</para><para></para> /// </summary> /// <returns> /// <para>the prime factor <c> p </c> of <c> n </c> . </para> /// </returns> /// <java-name> /// getPrimeP /// </java-name> [Dot42.DexImport("getPrimeP", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetPrimeP() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the prime factor <c> q </c> of <c> n </c> .</para><para></para> /// </summary> /// <returns> /// <para>the prime factor <c> q </c> of <c> n </c> . </para> /// </returns> /// <java-name> /// getPrimeQ /// </java-name> [Dot42.DexImport("getPrimeQ", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetPrimeQ() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the CRT exponent of the prime <c> p </c> .</para><para></para> /// </summary> /// <returns> /// <para>the CRT exponent of the prime <c> p </c> . </para> /// </returns> /// <java-name> /// getPrimeExponentP /// </java-name> [Dot42.DexImport("getPrimeExponentP", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetPrimeExponentP() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the CRT exponent of the prime <c> q </c> .</para><para></para> /// </summary> /// <returns> /// <para>the CRT exponent of the prime <c> q </c> . </para> /// </returns> /// <java-name> /// getPrimeExponentQ /// </java-name> [Dot42.DexImport("getPrimeExponentQ", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetPrimeExponentQ() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the public exponent <c> e </c> .</para><para></para> /// </summary> /// <returns> /// <para>the public exponent <c> e </c> . </para> /// </returns> /// <java-name> /// getPublicExponent /// </java-name> [Dot42.DexImport("getPublicExponent", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetPublicExponent() /* MethodBuilder.Create */ ; } }
using System; using System.IO; using System.Threading; using Console = Lucene.Net.Util.SystemConsole; namespace Lucene.Net.Store { /* * 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. */ /// <summary> /// Used by <see cref="MockDirectoryWrapper"/> to create an output stream that /// will throw an <see cref="IOException"/> on fake disk full, track max /// disk space actually used, and maybe throw random /// <see cref="IOException"/>s. /// </summary> public class MockIndexOutputWrapper : IndexOutput { private MockDirectoryWrapper dir; private readonly IndexOutput @delegate; private bool first = true; internal readonly string name; internal byte[] singleByte = new byte[1]; /// <summary> /// Construct an empty output buffer. </summary> public MockIndexOutputWrapper(MockDirectoryWrapper dir, IndexOutput @delegate, string name) { this.dir = dir; this.name = name; this.@delegate = @delegate; } private void CheckCrashed() { // If MockRAMDir crashed since we were opened, then don't write anything if (dir.crashed) { throw new IOException("MockDirectoryWrapper was crashed; cannot write to " + name); } } private void CheckDiskFull(byte[] b, int offset, DataInput @in, long len) { long freeSpace = dir.maxSize == 0 ? 0 : dir.maxSize - dir.GetSizeInBytes(); long realUsage = 0; // Enforce disk full: if (dir.maxSize != 0 && freeSpace <= len) { // Compute the real disk free. this will greatly slow // down our test but makes it more accurate: realUsage = dir.GetRecomputedActualSizeInBytes(); freeSpace = dir.maxSize - realUsage; } if (dir.maxSize != 0 && freeSpace <= len) { if (freeSpace > 0) { realUsage += freeSpace; if (b != null) { @delegate.WriteBytes(b, offset, (int)freeSpace); } else { @delegate.CopyBytes(@in, len); } } if (realUsage > dir.maxUsedSize) { dir.maxUsedSize = realUsage; } string message = "fake disk full at " + dir.GetRecomputedActualSizeInBytes() + " bytes when writing " + name + " (file length=" + @delegate.Length; if (freeSpace > 0) { message += "; wrote " + freeSpace + " of " + len + " bytes"; } message += ")"; // LUCENENET TODO: Finish implementation /*if (LuceneTestCase.VERBOSE) { Console.WriteLine(Thread.CurrentThread.Name + ": MDW: now throw fake disk full"); (new Exception()).printStackTrace(System.out); }*/ throw new IOException(message); } } protected override void Dispose(bool disposing) { if (disposing) { try { dir.MaybeThrowDeterministicException(); } finally { @delegate.Dispose(); if (dir.trackDiskUsage) { // Now compute actual disk usage & track the maxUsedSize // in the MockDirectoryWrapper: long size = dir.GetRecomputedActualSizeInBytes(); if (size > dir.maxUsedSize) { dir.maxUsedSize = size; } } dir.RemoveIndexOutput(this, name); } } } public override void Flush() { dir.MaybeThrowDeterministicException(); @delegate.Flush(); } public override void WriteByte(byte b) { singleByte[0] = b; WriteBytes(singleByte, 0, 1); } public override void WriteBytes(byte[] b, int offset, int len) { CheckCrashed(); CheckDiskFull(b, offset, null, len); if (dir.randomState.Next(200) == 0) { int half = len / 2; @delegate.WriteBytes(b, offset, half); Thread.Sleep(0); @delegate.WriteBytes(b, offset + half, len - half); } else { @delegate.WriteBytes(b, offset, len); } dir.MaybeThrowDeterministicException(); if (first) { // Maybe throw random exception; only do this on first // write to a new file: first = false; dir.MaybeThrowIOException(name); } } public override long GetFilePointer() { return @delegate.GetFilePointer(); } [Obsolete("(4.1) this method will be removed in Lucene 5.0")] public override void Seek(long pos) { @delegate.Seek(pos); } public override long Length { get => @delegate.Length; set => @delegate.Length = value; } public override void CopyBytes(DataInput input, long numBytes) { CheckCrashed(); CheckDiskFull(null, 0, input, numBytes); @delegate.CopyBytes(input, numBytes); dir.MaybeThrowDeterministicException(); } public override long Checksum => @delegate.Checksum; public override string ToString() { return "MockIndexOutputWrapper(" + @delegate + ")"; } } }
// 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.Diagnostics; using System.Runtime.InteropServices; using System.Text; namespace System.Security.Cryptography.Asn1 { internal partial class AsnReader { /// <summary> /// Reads the next value as character string with a UNIVERSAL tag appropriate to the specified /// encoding type, returning the contents as an unprocessed <see cref="ReadOnlyMemory{T}"/> /// over the original data. /// </summary> /// <param name="encodingType"> /// A <see cref="UniversalTagNumber"/> corresponding to the value type to process. /// </param> /// <param name="contents"> /// On success, receives a <see cref="ReadOnlyMemory{T}"/> over the original data /// corresponding to the contents of the character string. /// </param> /// <returns> /// <c>true</c> and advances the reader if the value had a primitive encoding, /// <c>false</c> and does not advance the reader if it had a constructed encoding. /// </returns> /// <remarks> /// This method does not determine if the string used only characters defined by the encoding. /// </remarks> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="encodingType"/> is not a known character string type. /// </exception> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules /// </exception> /// <seealso cref="TryCopyCharacterStringBytes(UniversalTagNumber,Span{byte},out int)"/> public bool TryReadPrimitiveCharacterStringBytes( UniversalTagNumber encodingType, out ReadOnlyMemory<byte> contents) { return TryReadPrimitiveCharacterStringBytes( new Asn1Tag(encodingType), encodingType, out contents); } /// <summary> /// Reads the next value as a character with a specified tag, returning the contents /// as an unprocessed <see cref="ReadOnlyMemory{T}"/> over the original data. /// </summary> /// <param name="expectedTag">The tag to check for before reading.</param> /// <param name="encodingType"> /// A <see cref="UniversalTagNumber"/> corresponding to the value type to process. /// </param> /// <param name="contents"> /// On success, receives a <see cref="ReadOnlyMemory{T}"/> over the original data /// corresponding to the value of the OCTET STRING. /// </param> /// <returns> /// <c>true</c> and advances the reader if the OCTET STRING value had a primitive encoding, /// <c>false</c> and does not advance the reader if it had a constructed encoding. /// </returns> /// <remarks> /// This method does not determine if the string used only characters defined by the encoding. /// </remarks> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagClass"/> is /// <see cref="TagClass.Universal"/>, but /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagValue"/> is not the same as /// <paramref name="encodingType"/>. /// </exception> /// <seealso cref="TryCopyCharacterStringBytes(Asn1Tag,UniversalTagNumber,Span{byte},out int)"/> public bool TryReadPrimitiveCharacterStringBytes( Asn1Tag expectedTag, UniversalTagNumber encodingType, out ReadOnlyMemory<byte> contents) { CheckCharacterStringEncodingType(encodingType); // T-REC-X.690-201508 sec 8.23.3, all character strings are encoded as octet strings. return TryReadPrimitiveOctetStringBytes(expectedTag, encodingType, out contents); } /// <summary> /// Reads the next value as character string with a UNIVERSAL tag appropriate to the specified /// encoding type, copying the value into a provided destination buffer. /// </summary> /// <param name="encodingType"> /// A <see cref="UniversalTagNumber"/> corresponding to the value type to process. /// </param> /// <param name="destination">The buffer in which to write.</param> /// <param name="bytesWritten"> /// On success, receives the number of bytes written to <paramref name="destination"/>. /// </param> /// <returns> /// <c>true</c> and advances the reader if <paramref name="destination"/> had sufficient /// length to receive the value, otherwise /// <c>false</c> and the reader does not advance. /// </returns> /// <remarks> /// This method does not determine if the string used only characters defined by the encoding. /// </remarks> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="encodingType"/> is not a known character string type. /// </exception> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules /// </exception> /// <seealso cref="TryReadPrimitiveCharacterStringBytes(UniversalTagNumber,out ReadOnlyMemory{byte})"/> /// <seealso cref="ReadCharacterString(UniversalTagNumber)"/> /// <seealso cref="TryCopyCharacterString(UniversalTagNumber,Span{char},out int)"/> public bool TryCopyCharacterStringBytes( UniversalTagNumber encodingType, Span<byte> destination, out int bytesWritten) { return TryCopyCharacterStringBytes( new Asn1Tag(encodingType), encodingType, destination, out bytesWritten); } /// <summary> /// Reads the next value as character string with the specified tag and /// encoding type, copying the value into a provided destination buffer. /// </summary> /// <param name="expectedTag">The tag to check for before reading.</param> /// <param name="encodingType"> /// A <see cref="UniversalTagNumber"/> corresponding to the value type to process. /// </param> /// <param name="destination">The buffer in which to write.</param> /// <param name="bytesWritten"> /// On success, receives the number of bytes written to <paramref name="destination"/>. /// </param> /// <returns> /// <c>true</c> and advances the reader if <paramref name="destination"/> had sufficient /// length to receive the value, otherwise /// <c>false</c> and the reader does not advance. /// </returns> /// <remarks> /// This method does not determine if the string used only characters defined by the encoding. /// </remarks> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="encodingType"/> is not a known character string type. /// </exception> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagClass"/> is /// <see cref="TagClass.Universal"/>, but /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagValue"/> is not the same as /// <paramref name="encodingType"/>. /// </exception> /// <seealso cref="TryReadPrimitiveCharacterStringBytes(Asn1Tag,UniversalTagNumber,out ReadOnlyMemory{byte})"/> /// <seealso cref="ReadCharacterString(Asn1Tag,UniversalTagNumber)"/> /// <seealso cref="TryCopyCharacterString(Asn1Tag,UniversalTagNumber,Span{char},out int)"/> public bool TryCopyCharacterStringBytes( Asn1Tag expectedTag, UniversalTagNumber encodingType, Span<byte> destination, out int bytesWritten) { CheckCharacterStringEncodingType(encodingType); bool copied = TryCopyCharacterStringBytes( expectedTag, encodingType, destination, out int bytesRead, out bytesWritten); if (copied) { _data = _data.Slice(bytesRead); } return copied; } /// <summary> /// Reads the next value as character string with a UNIVERSAL tag appropriate to the specified /// encoding type, copying the value into a provided destination buffer. /// </summary> /// <param name="encodingType"> /// A <see cref="UniversalTagNumber"/> corresponding to the value type to process. /// </param> /// <param name="destination">The buffer in which to write.</param> /// <param name="bytesWritten"> /// On success, receives the number of bytes written to <paramref name="destination"/>. /// </param> /// <returns> /// <c>true</c> and advances the reader if <paramref name="destination"/> had sufficient /// length to receive the value, otherwise /// <c>false</c> and the reader does not advance. /// </returns> /// <remarks> /// This method does not determine if the string used only characters defined by the encoding. /// </remarks> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="encodingType"/> is not a known character string type. /// </exception> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules /// </exception> /// <seealso cref="TryReadPrimitiveCharacterStringBytes(UniversalTagNumber,out ReadOnlyMemory{byte})"/> /// <seealso cref="ReadCharacterString(UniversalTagNumber)"/> /// <seealso cref="TryCopyCharacterString(UniversalTagNumber,Span{char},out int)"/> public bool TryCopyCharacterStringBytes( UniversalTagNumber encodingType, ArraySegment<byte> destination, out int bytesWritten) { return TryCopyCharacterStringBytes( new Asn1Tag(encodingType), encodingType, destination.AsSpan(), out bytesWritten); } /// <summary> /// Reads the next value as character string with the specified tag and /// encoding type, copying the value into a provided destination buffer. /// </summary> /// <param name="expectedTag">The tag to check for before reading.</param> /// <param name="encodingType"> /// A <see cref="UniversalTagNumber"/> corresponding to the value type to process. /// </param> /// <param name="destination">The buffer in which to write.</param> /// <param name="bytesWritten"> /// On success, receives the number of bytes written to <paramref name="destination"/>. /// </param> /// <returns> /// <c>true</c> and advances the reader if <paramref name="destination"/> had sufficient /// length to receive the value, otherwise /// <c>false</c> and the reader does not advance. /// </returns> /// <remarks> /// This method does not determine if the string used only characters defined by the encoding. /// </remarks> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="encodingType"/> is not a known character string type. /// </exception> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagClass"/> is /// <see cref="TagClass.Universal"/>, but /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagValue"/> is not the same as /// <paramref name="encodingType"/>. /// </exception> /// <seealso cref="TryReadPrimitiveCharacterStringBytes(Asn1Tag,UniversalTagNumber,out ReadOnlyMemory{byte})"/> /// <seealso cref="ReadCharacterString(Asn1Tag,UniversalTagNumber)"/> /// <seealso cref="TryCopyCharacterString(Asn1Tag,UniversalTagNumber,Span{char},out int)"/> public bool TryCopyCharacterStringBytes( Asn1Tag expectedTag, UniversalTagNumber encodingType, ArraySegment<byte> destination, out int bytesWritten) { return TryCopyCharacterStringBytes( expectedTag, encodingType, destination.AsSpan(), out bytesWritten); } /// <summary> /// Reads the next value as character string with a UNIVERSAL tag appropriate to the specified /// encoding type, copying the decoded value into a provided destination buffer. /// </summary> /// <param name="encodingType"> /// A <see cref="UniversalTagNumber"/> corresponding to the value type to process. /// </param> /// <param name="destination">The buffer in which to write.</param> /// <param name="charsWritten"> /// On success, receives the number of chars written to <paramref name="destination"/>. /// </param> /// <returns> /// <c>true</c> and advances the reader if <paramref name="destination"/> had sufficient /// length to receive the value, otherwise /// <c>false</c> and the reader does not advance. /// </returns> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="encodingType"/> is not a known character string type. /// </exception> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules --OR-- /// the string did not successfully decode /// </exception> /// <seealso cref="TryReadPrimitiveCharacterStringBytes(UniversalTagNumber,out ReadOnlyMemory{byte})"/> /// <seealso cref="ReadCharacterString(UniversalTagNumber)"/> /// <seealso cref="TryCopyCharacterStringBytes(UniversalTagNumber,Span{byte},out int)"/> public bool TryCopyCharacterString( UniversalTagNumber encodingType, Span<char> destination, out int charsWritten) { return TryCopyCharacterString( new Asn1Tag(encodingType), encodingType, destination, out charsWritten); } /// <summary> /// Reads the next value as character string with the specified tag and /// encoding type, copying the decoded value into a provided destination buffer. /// </summary> /// <param name="expectedTag">The tag to check for before reading.</param> /// <param name="encodingType"> /// A <see cref="UniversalTagNumber"/> corresponding to the value type to process. /// </param> /// <param name="destination">The buffer in which to write.</param> /// <param name="charsWritten"> /// On success, receives the number of chars written to <paramref name="destination"/>. /// </param> /// <returns> /// <c>true</c> and advances the reader if <paramref name="destination"/> had sufficient /// length to receive the value, otherwise /// <c>false</c> and the reader does not advance. /// </returns> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="encodingType"/> is not a known character string type. /// </exception> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules --OR-- /// the string did not successfully decode /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagClass"/> is /// <see cref="TagClass.Universal"/>, but /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagValue"/> is not the same as /// <paramref name="encodingType"/>. /// </exception> /// <seealso cref="TryReadPrimitiveCharacterStringBytes(Asn1Tag,UniversalTagNumber,out ReadOnlyMemory{byte})"/> /// <seealso cref="TryCopyCharacterStringBytes(Asn1Tag,UniversalTagNumber,Span{byte},out int)"/> /// <seealso cref="ReadCharacterString(Asn1Tag,UniversalTagNumber)"/> public bool TryCopyCharacterString( Asn1Tag expectedTag, UniversalTagNumber encodingType, Span<char> destination, out int charsWritten) { Text.Encoding encoding = AsnCharacterStringEncodings.GetEncoding(encodingType); return TryCopyCharacterString(expectedTag, encodingType, encoding, destination, out charsWritten); } /// <summary> /// Reads the next value as character string with a UNIVERSAL tag appropriate to the specified /// encoding type, copying the decoded value into a provided destination buffer. /// </summary> /// <param name="encodingType"> /// A <see cref="UniversalTagNumber"/> corresponding to the value type to process. /// </param> /// <param name="destination">The buffer in which to write.</param> /// <param name="charsWritten"> /// On success, receives the number of chars written to <paramref name="destination"/>. /// </param> /// <returns> /// <c>true</c> and advances the reader if <paramref name="destination"/> had sufficient /// length to receive the value, otherwise /// <c>false</c> and the reader does not advance. /// </returns> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="encodingType"/> is not a known character string type. /// </exception> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules --OR-- /// the string did not successfully decode /// </exception> /// <seealso cref="TryReadPrimitiveCharacterStringBytes(UniversalTagNumber,out ReadOnlyMemory{byte})"/> /// <seealso cref="ReadCharacterString(UniversalTagNumber)"/> /// <seealso cref="TryCopyCharacterStringBytes(UniversalTagNumber,ArraySegment{byte},out int)"/> /// <seealso cref="TryCopyCharacterString(Asn1Tag,UniversalTagNumber,ArraySegment{char},out int)"/> public bool TryCopyCharacterString( UniversalTagNumber encodingType, ArraySegment<char> destination, out int charsWritten) { return TryCopyCharacterString( new Asn1Tag(encodingType), encodingType, destination.AsSpan(), out charsWritten); } /// <summary> /// Reads the next value as character string with the specified tag and /// encoding type, copying the decoded value into a provided destination buffer. /// </summary> /// <param name="expectedTag">The tag to check for before reading.</param> /// <param name="encodingType"> /// A <see cref="UniversalTagNumber"/> corresponding to the value type to process. /// </param> /// <param name="destination">The buffer in which to write.</param> /// <param name="charsWritten"> /// On success, receives the number of chars written to <paramref name="destination"/>. /// </param> /// <returns> /// <c>true</c> and advances the reader if <paramref name="destination"/> had sufficient /// length to receive the value, otherwise /// <c>false</c> and the reader does not advance. /// </returns> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="encodingType"/> is not a known character string type. /// </exception> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules --OR-- /// the string did not successfully decode /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagClass"/> is /// <see cref="TagClass.Universal"/>, but /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagValue"/> is not the same as /// <paramref name="encodingType"/>. /// </exception> /// <seealso cref="TryReadPrimitiveCharacterStringBytes(Asn1Tag,UniversalTagNumber,out ReadOnlyMemory{byte})"/> /// <seealso cref="TryCopyCharacterStringBytes(Asn1Tag,UniversalTagNumber,ArraySegment{byte},out int)"/> /// <seealso cref="ReadCharacterString(Asn1Tag,UniversalTagNumber)"/> public bool TryCopyCharacterString( Asn1Tag expectedTag, UniversalTagNumber encodingType, ArraySegment<char> destination, out int charsWritten) { return TryCopyCharacterString( expectedTag, encodingType, destination.AsSpan(), out charsWritten); } /// <summary> /// Reads the next value as character string with a UNIVERSAL tag appropriate to the specified /// encoding type, returning the decoded value as a <see cref="string"/>. /// </summary> /// <param name="encodingType"> /// A <see cref="UniversalTagNumber"/> corresponding to the value type to process. /// </param> /// <returns> /// the decoded value as a <see cref="string"/>. /// </returns> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="encodingType"/> is not a known character string type. /// </exception> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules --OR-- /// the string did not successfully decode /// </exception> /// <seealso cref="TryReadPrimitiveCharacterStringBytes(UniversalTagNumber,out ReadOnlyMemory{byte})"/> /// <seealso cref="TryCopyCharacterStringBytes(UniversalTagNumber,Span{byte},out int)"/> /// <seealso cref="TryCopyCharacterString(UniversalTagNumber,Span{char},out int)"/> /// <seealso cref="ReadCharacterString(Asn1Tag,UniversalTagNumber)"/> public string ReadCharacterString(UniversalTagNumber encodingType) => ReadCharacterString(new Asn1Tag(encodingType), encodingType); /// <summary> /// Reads the next value as character string with the specified tag and /// encoding type, returning the decoded value as a <see cref="string"/>. /// </summary> /// <param name="expectedTag">The tag to check for before reading.</param> /// <param name="encodingType"> /// A <see cref="UniversalTagNumber"/> corresponding to the value type to process. /// </param> /// <returns> /// the decoded value as a <see cref="string"/>. /// </returns> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="encodingType"/> is not a known character string type. /// </exception> /// <exception cref="CryptographicException"> /// the next value does not have the correct tag --OR-- /// the length encoding is not valid under the current encoding rules --OR-- /// the contents are not valid under the current encoding rules --OR-- /// the string did not successfully decode /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagClass"/> is /// <see cref="TagClass.Universal"/>, but /// <paramref name="expectedTag"/>.<see cref="Asn1Tag.TagValue"/> is not the same as /// <paramref name="encodingType"/>. /// </exception> /// <seealso cref="TryReadPrimitiveCharacterStringBytes(Asn1Tag,UniversalTagNumber,out ReadOnlyMemory{byte})"/> /// <seealso cref="TryCopyCharacterStringBytes(Asn1Tag,UniversalTagNumber,Span{byte},out int)"/> /// <seealso cref="TryCopyCharacterString(Asn1Tag,UniversalTagNumber,Span{char},out int)"/> public string ReadCharacterString(Asn1Tag expectedTag, UniversalTagNumber encodingType) { Text.Encoding encoding = AsnCharacterStringEncodings.GetEncoding(encodingType); return ReadCharacterString(expectedTag, encodingType, encoding); } // T-REC-X.690-201508 sec 8.23 private bool TryCopyCharacterStringBytes( Asn1Tag expectedTag, UniversalTagNumber universalTagNumber, Span<byte> destination, out int bytesRead, out int bytesWritten) { // T-REC-X.690-201508 sec 8.23.3, all character strings are encoded as octet strings. if (TryReadPrimitiveOctetStringBytes( expectedTag, out Asn1Tag actualTag, out int? contentLength, out int headerLength, out ReadOnlyMemory<byte> contents, universalTagNumber)) { bytesWritten = contents.Length; if (destination.Length < bytesWritten) { bytesWritten = 0; bytesRead = 0; return false; } contents.Span.CopyTo(destination); bytesRead = headerLength + bytesWritten; return true; } Debug.Assert(actualTag.IsConstructed); bool copied = TryCopyConstructedOctetStringContents( Slice(_data, headerLength, contentLength), destination, contentLength == null, out int contentBytesRead, out bytesWritten); if (copied) { bytesRead = headerLength + contentBytesRead; } else { bytesRead = 0; } return copied; } private static unsafe bool TryCopyCharacterString( ReadOnlySpan<byte> source, Span<char> destination, Text.Encoding encoding, out int charsWritten) { if (source.Length == 0) { charsWritten = 0; return true; } fixed (byte* bytePtr = &MemoryMarshal.GetReference(source)) fixed (char* charPtr = &MemoryMarshal.GetReference(destination)) { try { int charCount = encoding.GetCharCount(bytePtr, source.Length); if (charCount > destination.Length) { charsWritten = 0; return false; } charsWritten = encoding.GetChars(bytePtr, source.Length, charPtr, destination.Length); Debug.Assert(charCount == charsWritten); } catch (DecoderFallbackException e) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e); } return true; } } private string ReadCharacterString( Asn1Tag expectedTag, UniversalTagNumber universalTagNumber, Text.Encoding encoding) { byte[] rented = null; // T-REC-X.690-201508 sec 8.23.3, all character strings are encoded as octet strings. ReadOnlySpan<byte> contents = GetOctetStringContents( expectedTag, universalTagNumber, out int bytesRead, ref rented); try { string str; if (contents.Length == 0) { str = string.Empty; } else { unsafe { fixed (byte* bytePtr = &MemoryMarshal.GetReference(contents)) { try { str = encoding.GetString(bytePtr, contents.Length); } catch (DecoderFallbackException e) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e); } } } } _data = _data.Slice(bytesRead); return str; } finally { if (rented != null) { Array.Clear(rented, 0, contents.Length); ArrayPool<byte>.Shared.Return(rented); } } } private bool TryCopyCharacterString( Asn1Tag expectedTag, UniversalTagNumber universalTagNumber, Text.Encoding encoding, Span<char> destination, out int charsWritten) { byte[] rented = null; // T-REC-X.690-201508 sec 8.23.3, all character strings are encoded as octet strings. ReadOnlySpan<byte> contents = GetOctetStringContents( expectedTag, universalTagNumber, out int bytesRead, ref rented); try { bool copied = TryCopyCharacterString( contents, destination, encoding, out charsWritten); if (copied) { _data = _data.Slice(bytesRead); } return copied; } finally { if (rented != null) { Array.Clear(rented, 0, contents.Length); ArrayPool<byte>.Shared.Return(rented); } } } private static void CheckCharacterStringEncodingType(UniversalTagNumber encodingType) { // T-REC-X.680-201508 sec 41 switch (encodingType) { case UniversalTagNumber.BMPString: case UniversalTagNumber.GeneralString: case UniversalTagNumber.GraphicString: case UniversalTagNumber.IA5String: case UniversalTagNumber.ISO646String: case UniversalTagNumber.NumericString: case UniversalTagNumber.PrintableString: case UniversalTagNumber.TeletexString: // T61String is an alias for TeletexString (already listed) case UniversalTagNumber.UniversalString: case UniversalTagNumber.UTF8String: case UniversalTagNumber.VideotexString: // VisibleString is an alias for ISO646String (already listed) return; } throw new ArgumentOutOfRangeException(nameof(encodingType)); } } }
// Client.cs // // Authors: // Andrzej Wytyczak-Partyka <iapart@gmail.com> // James Willcox <snorp@snorp.net> // // Copyright (C) 2008 Andrzej Wytyczak-Partyka // Copyright (C) 2005 James Willcox <snorp@snorp.net> // // 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 // // using System; using System.Runtime.InteropServices; using System.Threading; using System.IO; using System.Web; using System.Net; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; namespace DPAP { public class Client { private const int UpdateSleepInterval = 2 * 60 * 1000; // 2 minutes private IPAddress address; private UInt16 port; private ContentCodeBag bag; private ServerInfo server_info; private List<Database> databases = new List<Database> (); private ContentFetcher fetcher; private int revision; private bool update_running; private string service_name; public event EventHandler Updated; internal int Revision { get { return revision; } } public string Name { get { return service_name; } } public IPAddress Address { get { return address; } } public ushort Port { get { return port; } } public AuthenticationMethod AuthenticationMethod { get { return server_info.AuthenticationMethod; } } public IList<Database> Databases { get { return new ReadOnlyCollection<Database> (databases); } } internal ContentCodeBag Bag { get { return bag; } } internal ContentFetcher Fetcher { get { return fetcher; } } public Client (Service service) : this (service.Address, service.Port, service.Name) { } public Client (string host, UInt16 port) : this (Dns.GetHostEntry (host).AddressList [0], port, "") { } public Client (IPAddress address, UInt16 port, String name) { this.address = address; this.port = port; this.service_name = name; fetcher = new ContentFetcher (address, port); Login (null,null); } ~Client () { Dispose (); } public void Dispose () { update_running = false; if (fetcher != null) { fetcher.Dispose (); fetcher = null; } } private void ParseSessionId (ContentNode node) { fetcher.SessionId = (int) node.GetChild ("dmap.sessionid").Value; } public void Login () { Login (null, null); } public void Login (string password) { Login (null, password); } public void Login (string username, string password) { fetcher.Username = username; fetcher.Password = password; try { bag = ContentCodeBag.ParseCodes (fetcher.Fetch ("/content-codes")); ContentNode node = ContentParser.Parse (bag, fetcher.Fetch ("/login")); ParseSessionId (node); FetchDatabases (); Refresh (); // FIXME - the update handling mechanism is currently disabled /* if (server_info.SupportsUpdate) { update_running = true; Thread thread = new Thread (UpdateLoop); thread.IsBackground = true; thread.Start (); }*/ } catch (WebException e) { if (e.Response != null && (e.Response as HttpWebResponse).StatusCode == HttpStatusCode.Unauthorized) throw new AuthenticationException ("Username or password incorrect"); else throw new LoginException ("Failed to login", e); } catch (Exception e) { throw new LoginException ("Failed to login", e); } } public void Logout () { try { update_running = false; fetcher.KillAll (); fetcher.Fetch ("/logout"); } catch (WebException) { // some servers don't implement this, etc. } fetcher.SessionId = 0; } private void FetchDatabases () { ContentNode dbnode = ContentParser.Parse (bag, fetcher.Fetch ("/databases")); // DEBUG //dbnode.Dump (); foreach (ContentNode child in (ContentNode []) dbnode.Value) { if (child.Name != "dmap.listing") continue; foreach (ContentNode item in (ContentNode []) child.Value) { // DEBUG //item.Dump (); Database db = new Database (this, item); Console.WriteLine ("Adding database {0} with id={1} and album count={2}." , db.Name,db.Id,db.Albums.Count); //Console.WriteLine ("Photo " + db.Photos [0].FileName); databases.Add (db); } } } private int GetCurrentRevision () { ContentNode rev_node = ContentParser.Parse (bag, fetcher.Fetch ("/update"), "dmap.serverrevision"); return (int) rev_node.Value; } private int WaitForRevision (int currentRevision) { ContentNode rev_node = ContentParser.Parse (bag, fetcher.Fetch ("/update", "revision-number=" + currentRevision)); return (int) rev_node.GetChild ("dmap.serverrevision").Value; } private void Refresh () { int newrev = 0; /* if (server_info.SupportsUpdate) { if (revision == 0) newrev = GetCurrentRevision (); else newrev = WaitForRevision (revision); if (newrev == revision) return; } */ // Console.WriteLine ("Got new revision: " + newrev); foreach (Database db in databases) { db.Refresh (newrev); } revision = newrev; if (Updated != null) Updated (this, new EventArgs ()); } private void UpdateLoop () { while (true) { try { if (!update_running) break; Refresh (); } catch (WebException) { if (!update_running) break; // chill out for a while, maybe the server went down // temporarily or something. Thread.Sleep (UpdateSleepInterval); } catch (Exception e) { if (!update_running) break; Console.Error.WriteLine ("Exception in update loop: " + e); Thread.Sleep (UpdateSleepInterval); } } } } }
/* ** $Id: llex.c,v 2.20.1.1 2007/12/27 13:02:25 roberto Exp $ ** Lexical Analyzer ** See Copyright Notice in lua.h */ using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using System.Diagnostics; namespace SharpLua { using TValue = Lua.lua_TValue; using lua_Number = System.Double; using ZIO = Lua.Zio; public partial class Lua { public const int FIRST_RESERVED = 257; /* maximum length of a reserved word */ public const int TOKEN_LEN = 9; // "function" /* * WARNING: if you change the order of this enumeration, * grep "ORDER RESERVED" */ public enum RESERVED { /* terminal symbols denoted by reserved words */ TK_AND = FIRST_RESERVED, TK_BREAK, TK_CONTINUE, TK_DO, TK_ELSE, TK_ELSEIF, TK_END, TK_FALSE, TK_FOR, TK_FUNCTION, TK_IF, TK_IN, TK_LOCAL, TK_NIL, TK_NOT, TK_OR, TK_REPEAT, TK_RETURN, TK_THEN, TK_TRUE, TK_UNTIL, TK_WHILE, /* other terminal symbols */ TK_CONCAT, TK_DOTS, TK_EQ, TK_GE, TK_LE, TK_NE, TK_NUMBER, TK_NAME, TK_STRING, TK_EOS, }; /* number of reserved words */ public const int NUM_RESERVED = (int)RESERVED.TK_WHILE - FIRST_RESERVED + 1; public class SemInfo { public SemInfo() { } public SemInfo(SemInfo copy) { this.r = copy.r; this.ts = copy.ts; } public lua_Number r; public TString ts; } ; /* semantics information */ public class Token { public Token() { } public Token(Token copy) { this.token = copy.token; this.seminfo = new SemInfo(copy.seminfo); } public int token; public SemInfo seminfo = new SemInfo(); }; public class LexState { public int current; /* current character (charint) */ public int linenumber; /* input line counter */ public int lastline; /* line of last token `consumed' */ public Token t = new Token(); /* current token */ public Token lookahead = new Token(); /* look ahead token */ public FuncState fs; /* `FuncState' is private to the parser */ public LuaState L; public ZIO z; /* input stream */ public Mbuffer buff; /* buffer for tokens */ public TString source; /* current source name */ public char decpoint; /* locale decimal point */ }; public static void next(LexState ls) { ls.current = zgetc(ls.z); } public static bool currIsNewline(LexState ls) { return (ls.current == '\n' || ls.current == '\r'); } /* ORDER RESERVED */ public static readonly string[] luaX_tokens = { "and", "break", "continue", "do", "else", "elseif", "end", "false", "for", "function", "if", "in", "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while", "..", "...", "==", ">=", "<=", "~=", "<number>", "<name>", "<string>", "<eof>", }; public static void save_and_next(LexState ls) { save(ls, ls.current); next(ls); } private static void save(LexState ls, int c) { Mbuffer b = ls.buff; if (b.n + 1 > b.buffsize) { uint newsize; if (b.buffsize >= MAX_SIZET / 2) luaX_lexerror(ls, "lexical element too long", 0); newsize = b.buffsize * 2; luaZ_resizebuffer(ls.L, b, (int)newsize); } b.buffer[b.n++] = (char)c; } public static void luaX_init(LuaState L) { int i; for (i = 0; i < NUM_RESERVED; i++) { TString ts = luaS_new(L, luaX_tokens[i]); luaS_fix(ts); /* reserved words are never collected */ lua_assert(luaX_tokens[i].Length + 1 <= TOKEN_LEN); ts.tsv.reserved = cast_byte(i + 1); /* reserved word */ } } public const int MAXSRC = 80; public static CharPtr luaX_token2str(LexState ls, int token) { if (token < FIRST_RESERVED) { lua_assert(token == (byte)token); return (iscntrl(token)) ? luaO_pushfstring(ls.L, "char(%d)", token) : luaO_pushfstring(ls.L, "%c", token); } else return luaX_tokens[(int)token - FIRST_RESERVED]; } public static CharPtr txtToken(LexState ls, int token) { switch (token) { case (int)RESERVED.TK_NAME: case (int)RESERVED.TK_STRING: case (int)RESERVED.TK_NUMBER: save(ls, '\0'); return luaZ_buffer(ls.buff); default: return luaX_token2str(ls, token); } } public static void luaX_lexerror(LexState ls, CharPtr msg, int token) { CharPtr buff = new char[MAXSRC]; luaO_chunkid(buff, getstr(ls.source), MAXSRC); msg = luaO_pushfstring(ls.L, "%s:%d: %s", buff, ls.linenumber, msg); if (token != 0) luaO_pushfstring(ls.L, "%s near " + LUA_QS, msg, txtToken(ls, token)); luaD_throw(ls.L, LUA_ERRSYNTAX); } public static void luaX_syntaxerror(LexState ls, CharPtr msg) { luaX_lexerror(ls, msg, ls.t.token); } public static TString luaX_newstring(LexState ls, CharPtr str, uint l) { LuaState L = ls.L; TString ts = luaS_newlstr(L, str, l); TValue o = luaH_setstr(L, ls.fs.h, ts); /* entry for `str' */ if (ttisnil(o)) { setbvalue(o, 1); /* make sure `str' will not be collected */ luaC_checkGC(L); } return ts; } private static void inclinenumber(LexState ls) { int old = ls.current; lua_assert(currIsNewline(ls)); next(ls); /* skip `\n' or `\r' */ if (currIsNewline(ls) && ls.current != old) next(ls); /* skip `\n\r' or `\r\n' */ if (++ls.linenumber >= MAX_INT) luaX_syntaxerror(ls, "chunk has too many lines"); } public static void luaX_setinput(LuaState L, LexState ls, ZIO z, TString source) { ls.decpoint = '.'; ls.L = L; ls.lookahead.token = (int)RESERVED.TK_EOS; /* no look-ahead token */ ls.z = z; ls.fs = null; ls.linenumber = 1; ls.lastline = 1; ls.source = source; luaZ_resizebuffer(ls.L, ls.buff, LUA_MINBUFFER); /* initialize buffer */ next(ls); /* read first char */ } /* ** ======================================================= ** LEXICAL ANALYZER ** ======================================================= */ private static int check_next(LexState ls, CharPtr set) { if (strchr(set, (char)ls.current) == null) return 0; save_and_next(ls); return 1; } private static void buffreplace(LexState ls, char from, char to) { uint n = luaZ_bufflen(ls.buff); CharPtr p = luaZ_buffer(ls.buff); while ((n--) != 0) if (p[n] == from) p[n] = to; } private static void trydecpoint(LexState ls, SemInfo seminfo) { /* format error: try to update decimal point separator */ // todo: add proper support for localeconv - mjf //lconv cv = localeconv(); char old = ls.decpoint; ls.decpoint = '.'; // (cv ? cv.decimal_point[0] : '.'); buffreplace(ls, old, ls.decpoint); /* try updated decimal separator */ if (luaO_str2d(luaZ_buffer(ls.buff), out seminfo.r) == 0) { /* format error with correct decimal point: no more options */ buffreplace(ls, ls.decpoint, '.'); /* undo change (for error message) */ luaX_lexerror(ls, "malformed number", (int)RESERVED.TK_NUMBER); } } /* LUA_NUMBER */ private static void read_numeral(LexState ls, SemInfo seminfo) { lua_assert(isdigit(ls.current)); do { save_and_next(ls); } while (isdigit(ls.current) || ls.current == '.'); if (check_next(ls, "EePp") != 0) /* 'E' or 'P'? */ check_next(ls, "+-"); /* optional exponent sign */ while (isalnum(ls.current) || ls.current == '_') save_and_next(ls); save(ls, '\0'); buffreplace(ls, '.', ls.decpoint); /* follow locale for decimal point */ if (luaO_str2d(luaZ_buffer(ls.buff), out seminfo.r) == 0) /* format error? */ trydecpoint(ls, seminfo); /* try to update decimal point separator */ } private static int skip_sep(LexState ls) { int count = 0; int s = ls.current; lua_assert(s == '[' || s == ']'); save_and_next(ls); while (ls.current == '=') { save_and_next(ls); count++; } return (ls.current == s) ? count : (-count) - 1; } private static void read_long_string(LexState ls, SemInfo seminfo, int sep) { //int cont = 0; //(void)(cont); /* avoid warnings when `cont' is not used */ save_and_next(ls); /* skip 2nd `[' */ if (currIsNewline(ls)) /* string starts with a newline? */ inclinenumber(ls); /* skip it */ for (; ; ) { switch (ls.current) { case EOZ: luaX_lexerror(ls, (seminfo != null) ? "unfinished long string" : "unfinished long comment", (int)RESERVED.TK_EOS); break; /* to avoid warnings */ #if LUA_COMPAT_LSTR case '[': { if (skip_sep(ls) == sep) { save_and_next(ls); /* skip 2nd `[' */ cont++; #if LUA_COMPAT_LSTR if (sep == 0) luaX_lexerror(ls, "nesting of [[...]] is deprecated", '['); #endif } break; } #endif case ']': if (skip_sep(ls) == sep) { save_and_next(ls); /* skip 2nd `]' */ //#if defined(LUA_COMPAT_LSTR) && LUA_COMPAT_LSTR == 2 // cont--; // if (sep == 0 && cont >= 0) break; //#endif goto endloop; } break; case '\n': case '\r': save(ls, '\n'); inclinenumber(ls); if (seminfo == null) luaZ_resetbuffer(ls.buff); /* avoid wasting space */ break; default: { if (seminfo != null) save_and_next(ls); else next(ls); } break; } } endloop: if (seminfo != null) { seminfo.ts = luaX_newstring(ls, luaZ_buffer(ls.buff) + (2 + sep), (uint)(luaZ_bufflen(ls.buff) - 2 * (2 + sep))); } } static void read_string(LexState ls, int del, SemInfo seminfo) { save_and_next(ls); while (ls.current != del) { switch (ls.current) { case EOZ: luaX_lexerror(ls, "unfinished string", (int)RESERVED.TK_EOS); continue; /* to avoid warnings */ case '\n': case '\r': luaX_lexerror(ls, "unfinished string", (int)RESERVED.TK_STRING); continue; /* to avoid warnings */ case '\\': { int c; next(ls); /* do not save the `\' */ switch (ls.current) { case 'a': c = '\a'; break; case 'b': c = '\b'; break; case 'f': c = '\f'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; case 'v': c = '\v'; break; case '\n': /* go through */ case '\r': save(ls, '\n'); inclinenumber(ls); continue; case EOZ: continue; /* will raise an error next loop */ default: { if (!isdigit(ls.current)) save_and_next(ls); /* handles \\, \", \', and \? */ else { /* \xxx */ int i = 0; c = 0; do { c = 10 * c + (ls.current - '0'); next(ls); } while (++i < 3 && isdigit(ls.current)); //if (c > System.Byte.MaxValue) // luaX_lexerror(ls, "escape sequence too large", (int)RESERVED.TK_STRING); save(ls, c); } continue; } } save(ls, c); next(ls); continue; } default: save_and_next(ls); break; } } save_and_next(ls); /* skip delimiter */ seminfo.ts = luaX_newstring(ls, luaZ_buffer(ls.buff) + 1, luaZ_bufflen(ls.buff) - 2); } private static int llex(LexState ls, SemInfo seminfo) { luaZ_resetbuffer(ls.buff); for (; ; ) { switch (ls.current) { case '\n': case '\r': { inclinenumber(ls); continue; } case '-': { next(ls); if (ls.current != '-') return '-'; /* else is a comment */ next(ls); if (ls.current == '[') { int sep = skip_sep(ls); luaZ_resetbuffer(ls.buff); /* `skip_sep' may dirty the buffer */ if (sep >= 0) { read_long_string(ls, null, sep); /* long comment */ luaZ_resetbuffer(ls.buff); continue; } } /* else short comment */ while (!currIsNewline(ls) && ls.current != EOZ) next(ls); continue; } case '[': { int sep = skip_sep(ls); if (sep >= 0) { read_long_string(ls, seminfo, sep); return (int)RESERVED.TK_STRING; } else if (sep == -1) return '['; else luaX_lexerror(ls, "invalid long string delimiter", (int)RESERVED.TK_STRING); } break; case '=': { next(ls); if (ls.current != '=') return '='; else { next(ls); return (int)RESERVED.TK_EQ; } } case '<': { // either <, <=, or << next(ls); if (ls.current == '=') { next(ls); return (int)RESERVED.TK_LE; } else { return '<'; } } case '>': { // either >, >=, or >> next(ls); if (ls.current == '=') { next(ls); return (int)RESERVED.TK_GE; } else return '>'; } case '~': { next(ls); if (ls.current != '=') return '~'; else { next(ls); return (int)RESERVED.TK_NE; } } case '"': case '\'': { read_string(ls, ls.current, seminfo); return (int)RESERVED.TK_STRING; } case '.': { save_and_next(ls); if (check_next(ls, ".") != 0) { if (check_next(ls, ".") != 0) return (int)RESERVED.TK_DOTS; /* ... */ else return (int)RESERVED.TK_CONCAT; /* .. */ } else if (!isdigit(ls.current)) return '.'; else { read_numeral(ls, seminfo); return (int)RESERVED.TK_NUMBER; } } case EOZ: { return (int)RESERVED.TK_EOS; } default: { if (isspace(ls.current)) { lua_assert(!currIsNewline(ls)); next(ls); continue; } else if (isdigit(ls.current)) { read_numeral(ls, seminfo); return (int)RESERVED.TK_NUMBER; } else if (isalpha(ls.current) || ls.current == '_') { /* identifier or reserved word */ TString ts; do { save_and_next(ls); } while (isalnum(ls.current) || ls.current == '_'); ts = luaX_newstring(ls, luaZ_buffer(ls.buff), luaZ_bufflen(ls.buff)); if (ts.tsv.reserved > 0) /* reserved word? */ { return ts.tsv.reserved - 1 + FIRST_RESERVED; } else { seminfo.ts = ts; return (int)RESERVED.TK_NAME; } } else { int c = ls.current; next(ls); return c; /* single-char tokens (+ - / ...) */ } } } } } public static void luaX_next(LexState ls) { ls.lastline = ls.linenumber; if (ls.lookahead.token != (int)RESERVED.TK_EOS) { /* is there a look-ahead token? */ ls.t = new Token(ls.lookahead); /* use this one */ ls.lookahead.token = (int)RESERVED.TK_EOS; /* and discharge it */ } else ls.t.token = llex(ls, ls.t.seminfo); /* read next token */ } public static void luaX_lookahead(LexState ls) { lua_assert(ls.lookahead.token == (int)RESERVED.TK_EOS); ls.lookahead.token = llex(ls, ls.lookahead.seminfo); } } }
// <copyright file="RemoteWebDriver.cs" company="WebDriver Committers"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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. // </copyright> using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Text.RegularExpressions; using OpenQA.Selenium.Html5; using OpenQA.Selenium.Interactions; using OpenQA.Selenium.Internal; namespace OpenQA.Selenium.Remote { /// <summary> /// Provides a way to use the driver through /// </summary> /// /// <example> /// <code> /// [TestFixture] /// public class Testing /// { /// private IWebDriver driver; /// <para></para> /// [SetUp] /// public void SetUp() /// { /// driver = new RemoteWebDriver(new Uri("http://127.0.0.1:4444/wd/hub"),DesiredCapabilities.InternetExplorer()); /// } /// <para></para> /// [Test] /// public void TestGoogle() /// { /// driver.Navigate().GoToUrl("http://www.google.co.uk"); /// /* /// * Rest of the test /// */ /// } /// <para></para> /// [TearDown] /// public void TearDown() /// { /// driver.Quit(); /// } /// } /// </code> /// </example> public class RemoteWebDriver : IWebDriver, ISearchContext, IJavaScriptExecutor, IFindsById, IFindsByClassName, IFindsByLinkText, IFindsByName, IFindsByTagName, IFindsByXPath, IFindsByPartialLinkText, IFindsByCssSelector, ITakesScreenshot, IHasCapabilities, IHasWebStorage, IHasLocationContext, IHasApplicationCache, IAllowsFileDetection, IHasSessionId, IActionExecutor { /// <summary> /// The default command timeout for HTTP requests in a RemoteWebDriver instance. /// </summary> protected static readonly TimeSpan DefaultCommandTimeout = TimeSpan.FromSeconds(60); private const string DefaultRemoteServerUrl = "http://127.0.0.1:4444/wd/hub"; private ICommandExecutor executor; private ICapabilities capabilities; private SessionId sessionId; private IWebStorage storage; private IApplicationCache appCache; private ILocationContext locationContext; private IFileDetector fileDetector = new DefaultFileDetector(); private RemoteWebElementFactory elementFactory; /// <summary> /// Initializes a new instance of the <see cref="RemoteWebDriver"/> class. This constructor defaults proxy to http://127.0.0.1:4444/wd/hub /// </summary> /// <param name="options">An <see cref="DriverOptions"/> object containing the desired capabilities of the browser.</param> public RemoteWebDriver(DriverOptions options) : this(ConvertOptionsToCapabilities(options)) { } /// <summary> /// Initializes a new instance of the <see cref="RemoteWebDriver"/> class. This constructor defaults proxy to http://127.0.0.1:4444/wd/hub /// </summary> /// <param name="desiredCapabilities">An <see cref="ICapabilities"/> object containing the desired capabilities of the browser.</param> public RemoteWebDriver(ICapabilities desiredCapabilities) : this(new Uri(DefaultRemoteServerUrl), desiredCapabilities) { } /// <summary> /// Initializes a new instance of the <see cref="RemoteWebDriver"/> class. This constructor defaults proxy to http://127.0.0.1:4444/wd/hub /// </summary> /// <param name="remoteAddress">URI containing the address of the WebDriver remote server (e.g. http://127.0.0.1:4444/wd/hub).</param> /// <param name="options">An <see cref="DriverOptions"/> object containing the desired capabilities of the browser.</param> public RemoteWebDriver(Uri remoteAddress, DriverOptions options) : this(remoteAddress, ConvertOptionsToCapabilities(options)) { } /// <summary> /// Initializes a new instance of the <see cref="RemoteWebDriver"/> class /// </summary> /// <param name="remoteAddress">URI containing the address of the WebDriver remote server (e.g. http://127.0.0.1:4444/wd/hub).</param> /// <param name="desiredCapabilities">An <see cref="ICapabilities"/> object containing the desired capabilities of the browser.</param> public RemoteWebDriver(Uri remoteAddress, ICapabilities desiredCapabilities) : this(remoteAddress, desiredCapabilities, RemoteWebDriver.DefaultCommandTimeout) { } /// <summary> /// Initializes a new instance of the <see cref="RemoteWebDriver"/> class using the specified remote address, desired capabilities, and command timeout. /// </summary> /// <param name="remoteAddress">URI containing the address of the WebDriver remote server (e.g. http://127.0.0.1:4444/wd/hub).</param> /// <param name="desiredCapabilities">An <see cref="ICapabilities"/> object containing the desired capabilities of the browser.</param> /// <param name="commandTimeout">The maximum amount of time to wait for each command.</param> public RemoteWebDriver(Uri remoteAddress, ICapabilities desiredCapabilities, TimeSpan commandTimeout) : this(new HttpCommandExecutor(remoteAddress, commandTimeout), desiredCapabilities) { } /// <summary> /// Initializes a new instance of the <see cref="RemoteWebDriver"/> class /// </summary> /// <param name="commandExecutor">An <see cref="ICommandExecutor"/> object which executes commands for the driver.</param> /// <param name="desiredCapabilities">An <see cref="ICapabilities"/> object containing the desired capabilities of the browser.</param> public RemoteWebDriver(ICommandExecutor commandExecutor, ICapabilities desiredCapabilities) { this.executor = commandExecutor; this.StartClient(); this.StartSession(desiredCapabilities); this.elementFactory = new RemoteWebElementFactory(this); if (this.capabilities.HasCapability(CapabilityType.SupportsApplicationCache)) { object appCacheCapability = this.capabilities.GetCapability(CapabilityType.SupportsApplicationCache); if (appCacheCapability is bool && (bool)appCacheCapability) { this.appCache = new RemoteApplicationCache(this); } } if (this.capabilities.HasCapability(CapabilityType.SupportsLocationContext)) { object locationContextCapability = this.capabilities.GetCapability(CapabilityType.SupportsLocationContext); if (locationContextCapability is bool && (bool)locationContextCapability) { this.locationContext = new RemoteLocationContext(this); } } if (this.capabilities.HasCapability(CapabilityType.SupportsWebStorage)) { object webContextCapability = this.capabilities.GetCapability(CapabilityType.SupportsWebStorage); if (webContextCapability is bool && (bool)webContextCapability) { this.storage = new RemoteWebStorage(this); } } if ((this as ISupportsLogs) != null) { // Only add the legacy log commands if the driver supports // retrieving the logs via the extension end points. this.CommandExecutor.CommandInfoRepository.TryAddCommand(DriverCommand.GetAvailableLogTypes, new CommandInfo(CommandInfo.GetCommand, "/session/{sessionId}/se/log/types")); this.CommandExecutor.CommandInfoRepository.TryAddCommand(DriverCommand.GetLog, new CommandInfo(CommandInfo.GetCommand, "/session/{sessionId}/se/logs")); } } /// <summary> /// Gets or sets the URL the browser is currently displaying. /// </summary> /// <seealso cref="IWebDriver.Url"/> /// <seealso cref="INavigation.GoToUrl(string)"/> /// <seealso cref="INavigation.GoToUrl(System.Uri)"/> public string Url { get { Response commandResponse = this.Execute(DriverCommand.GetCurrentUrl, null); return commandResponse.Value.ToString(); } set { if (value == null) { throw new ArgumentNullException("value", "Argument 'url' cannot be null."); } Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("url", value); this.Execute(DriverCommand.Get, parameters); } } /// <summary> /// Gets the title of the current browser window. /// </summary> public string Title { get { Response commandResponse = this.Execute(DriverCommand.GetTitle, null); object returnedTitle = commandResponse != null ? commandResponse.Value : string.Empty; return returnedTitle.ToString(); } } /// <summary> /// Gets the source of the page last loaded by the browser. /// </summary> public string PageSource { get { string pageSource = string.Empty; Response commandResponse = this.Execute(DriverCommand.GetPageSource, null); pageSource = commandResponse.Value.ToString(); return pageSource; } } /// <summary> /// Gets the current window handle, which is an opaque handle to this /// window that uniquely identifies it within this driver instance. /// </summary> public string CurrentWindowHandle { get { Response commandResponse = this.Execute(DriverCommand.GetCurrentWindowHandle, null); return commandResponse.Value.ToString(); } } /// <summary> /// Gets the window handles of open browser windows. /// </summary> public ReadOnlyCollection<string> WindowHandles { get { Response commandResponse = this.Execute(DriverCommand.GetWindowHandles, null); object[] handles = (object[])commandResponse.Value; List<string> handleList = new List<string>(); foreach (object handle in handles) { handleList.Add(handle.ToString()); } return handleList.AsReadOnly(); } } /// <summary> /// Gets a value indicating whether web storage is supported for this driver. /// </summary> public bool HasWebStorage { get { return this.storage != null; } } /// <summary> /// Gets an <see cref="IWebStorage"/> object for managing web storage. /// </summary> public IWebStorage WebStorage { get { if (this.storage == null) { throw new InvalidOperationException("Driver does not support manipulating HTML5 web storage. Use the HasWebStorage property to test for the driver capability"); } return this.storage; } } /// <summary> /// Gets a value indicating whether manipulating the application cache is supported for this driver. /// </summary> public bool HasApplicationCache { get { return this.appCache != null; } } /// <summary> /// Gets an <see cref="IApplicationCache"/> object for managing application cache. /// </summary> public IApplicationCache ApplicationCache { get { if (this.appCache == null) { throw new InvalidOperationException("Driver does not support manipulating the HTML5 application cache. Use the HasApplicationCache property to test for the driver capability"); } return this.appCache; } } /// <summary> /// Gets a value indicating whether manipulating geolocation is supported for this driver. /// </summary> public bool HasLocationContext { get { return this.locationContext != null; } } /// <summary> /// Gets an <see cref="ILocationContext"/> object for managing browser location. /// </summary> public ILocationContext LocationContext { get { if (this.locationContext == null) { throw new InvalidOperationException("Driver does not support setting HTML5 geolocation information. Use the HasLocationContext property to test for the driver capability"); } return this.locationContext; } } /// <summary> /// Gets the capabilities that the RemoteWebDriver instance is currently using /// </summary> public ICapabilities Capabilities { get { return this.capabilities; } } /// <summary> /// Gets or sets the <see cref="IFileDetector"/> responsible for detecting /// sequences of keystrokes representing file paths and names. /// </summary> public virtual IFileDetector FileDetector { get { return this.fileDetector; } set { if (value == null) { throw new ArgumentNullException("value", "FileDetector cannot be null"); } this.fileDetector = value; } } /// <summary> /// Gets the <see cref="SessionId"/> for the current session of this driver. /// </summary> public SessionId SessionId { get { return this.sessionId; } } /// <summary> /// Gets a value indicating whether this object is a valid action executor. /// </summary> public bool IsActionExecutor { get { return true; } } /// <summary> /// Gets the <see cref="ICommandExecutor"/> which executes commands for this driver. /// </summary> protected ICommandExecutor CommandExecutor { get { return this.executor; } } /// <summary> /// Gets or sets the factory object used to create instances of <see cref="RemoteWebElement"/> /// or its subclasses. /// </summary> protected RemoteWebElementFactory ElementFactory { get { return this.elementFactory; } set { this.elementFactory = value; } } /// <summary> /// Finds the first element in the page that matches the <see cref="By"/> object /// </summary> /// <param name="by">By mechanism to find the object</param> /// <returns>IWebElement object so that you can interact with that object</returns> /// <example> /// <code> /// IWebDriver driver = new InternetExplorerDriver(); /// IWebElement elem = driver.FindElement(By.Name("q")); /// </code> /// </example> public IWebElement FindElement(By by) { if (by == null) { throw new ArgumentNullException("by", "by cannot be null"); } return by.FindElement(this); } /// <summary> /// Finds the elements on the page by using the <see cref="By"/> object and returns a ReadOnlyCollection of the Elements on the page /// </summary> /// <param name="by">By mechanism to find the element</param> /// <returns>ReadOnlyCollection of IWebElement</returns> /// <example> /// <code> /// IWebDriver driver = new InternetExplorerDriver(); /// ReadOnlyCollection<![CDATA[<IWebElement>]]> classList = driver.FindElements(By.ClassName("class")); /// </code> /// </example> public ReadOnlyCollection<IWebElement> FindElements(By by) { if (by == null) { throw new ArgumentNullException("by", "by cannot be null"); } return by.FindElements(this); } /// <summary> /// Closes the Browser /// </summary> public void Close() { this.Execute(DriverCommand.Close, null); } /// <summary> /// Close the Browser and Dispose of WebDriver /// </summary> public void Quit() { this.Dispose(); } /// <summary> /// Method For getting an object to set the Speed /// </summary> /// <returns>Returns an IOptions object that allows the driver to set the speed and cookies and getting cookies</returns> /// <seealso cref="IOptions"/> /// <example> /// <code> /// IWebDriver driver = new InternetExplorerDriver(); /// driver.Manage().GetCookies(); /// </code> /// </example> public IOptions Manage() { return new RemoteOptions(this); } /// <summary> /// Method to allow you to Navigate with WebDriver /// </summary> /// <returns>Returns an INavigation Object that allows the driver to navigate in the browser</returns> /// <example> /// <code> /// IWebDriver driver = new InternetExplorerDriver(); /// driver.Navigate().GoToUrl("http://www.google.co.uk"); /// </code> /// </example> public INavigation Navigate() { return new RemoteNavigator(this); } /// <summary> /// Method to give you access to switch frames and windows /// </summary> /// <returns>Returns an Object that allows you to Switch Frames and Windows</returns> /// <example> /// <code> /// IWebDriver driver = new InternetExplorerDriver(); /// driver.SwitchTo().Frame("FrameName"); /// </code> /// </example> public ITargetLocator SwitchTo() { return new RemoteTargetLocator(this); } /// <summary> /// Executes JavaScript in the context of the currently selected frame or window /// </summary> /// <param name="script">The JavaScript code to execute.</param> /// <param name="args">The arguments to the script.</param> /// <returns>The value returned by the script.</returns> public object ExecuteScript(string script, params object[] args) { return this.ExecuteScriptCommand(script, DriverCommand.ExecuteScript, args); } /// <summary> /// Executes JavaScript asynchronously in the context of the currently selected frame or window. /// </summary> /// <param name="script">The JavaScript code to execute.</param> /// <param name="args">The arguments to the script.</param> /// <returns>The value returned by the script.</returns> public object ExecuteAsyncScript(string script, params object[] args) { return this.ExecuteScriptCommand(script, DriverCommand.ExecuteAsyncScript, args); } /// <summary> /// Finds the first element in the page that matches the ID supplied /// </summary> /// <param name="id">ID of the element</param> /// <returns>IWebElement object so that you can interact with that object</returns> /// <example> /// <code> /// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox()); /// IWebElement elem = driver.FindElementById("id") /// </code> /// </example> public IWebElement FindElementById(string id) { return this.FindElement("css selector", "#" + EscapeCssSelector(id)); } /// <summary> /// Finds the first element in the page that matches the ID supplied /// </summary> /// <param name="id">ID of the Element</param> /// <returns>ReadOnlyCollection of Elements that match the object so that you can interact that object</returns> /// <example> /// <code> /// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox()); /// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsById("id") /// </code> /// </example> public ReadOnlyCollection<IWebElement> FindElementsById(string id) { string selector = EscapeCssSelector(id); if (string.IsNullOrEmpty(selector)) { // Finding multiple elements with an empty ID will return // an empty list. However, finding by a CSS selector of '#' // throws an exception, even in the multiple elements case, // which means we need to short-circuit that behavior. return new List<IWebElement>().AsReadOnly(); } return this.FindElements("css selector", "#" + selector); } /// <summary> /// Finds the first element in the page that matches the CSS Class supplied /// </summary> /// <param name="className">className of the</param> /// <returns>IWebElement object so that you can interact that object</returns> /// <example> /// <code> /// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox()); /// IWebElement elem = driver.FindElementByClassName("classname") /// </code> /// </example> public IWebElement FindElementByClassName(string className) { string selector = EscapeCssSelector(className); if (selector.Contains(" ")) { // Finding elements by class name with whitespace is not allowed. // However, converting the single class name to a valid CSS selector // by prepending a '.' may result in a still-valid, but incorrect // selector. Thus, we short-ciruit that behavior here. throw new InvalidSelectorException("Compound class names not allowed. Cannot have whitespace in class name. Use CSS selectors instead."); } return this.FindElement("css selector", "." + selector); } /// <summary> /// Finds a list of elements that match the class name supplied /// </summary> /// <param name="className">CSS class Name on the element</param> /// <returns>ReadOnlyCollection of IWebElement object so that you can interact with those objects</returns> /// <example> /// <code> /// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox()); /// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByClassName("classname") /// </code> /// </example> public ReadOnlyCollection<IWebElement> FindElementsByClassName(string className) { string selector = EscapeCssSelector(className); if (selector.Contains(" ")) { // Finding elements by class name with whitespace is not allowed. // However, converting the single class name to a valid CSS selector // by prepending a '.' may result in a still-valid, but incorrect // selector. Thus, we short-ciruit that behavior here. throw new InvalidSelectorException("Compound class names not allowed. Cannot have whitespace in class name. Use CSS selectors instead."); } return this.FindElements("css selector", "." + selector); } /// <summary> /// Finds the first of elements that match the link text supplied /// </summary> /// <param name="linkText">Link text of element </param> /// <returns>IWebElement object so that you can interact that object</returns> /// <example> /// <code> /// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox()); /// IWebElement elem = driver.FindElementsByLinkText("linktext") /// </code> /// </example> public IWebElement FindElementByLinkText(string linkText) { return this.FindElement("link text", linkText); } /// <summary> /// Finds a list of elements that match the link text supplied /// </summary> /// <param name="linkText">Link text of element</param> /// <returns>ReadOnlyCollection<![CDATA[<IWebElement>]]> object so that you can interact with those objects</returns> /// <example> /// <code> /// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox()); /// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByClassName("classname") /// </code> /// </example> public ReadOnlyCollection<IWebElement> FindElementsByLinkText(string linkText) { return this.FindElements("link text", linkText); } /// <summary> /// Finds the first of elements that match the part of the link text supplied /// </summary> /// <param name="partialLinkText">part of the link text</param> /// <returns>IWebElement object so that you can interact that object</returns> /// <example> /// <code> /// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox()); /// IWebElement elem = driver.FindElementsByPartialLinkText("partOfLink") /// </code> /// </example> public IWebElement FindElementByPartialLinkText(string partialLinkText) { return this.FindElement("partial link text", partialLinkText); } /// <summary> /// Finds a list of elements that match the class name supplied /// </summary> /// <param name="partialLinkText">part of the link text</param> /// <returns>ReadOnlyCollection<![CDATA[<IWebElement>]]> objects so that you can interact that object</returns> /// <example> /// <code> /// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox()); /// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByPartialLinkText("partOfTheLink") /// </code> /// </example> public ReadOnlyCollection<IWebElement> FindElementsByPartialLinkText(string partialLinkText) { return this.FindElements("partial link text", partialLinkText); } /// <summary> /// Finds the first of elements that match the name supplied /// </summary> /// <param name="name">Name of the element on the page</param> /// <returns>IWebElement object so that you can interact that object</returns> /// <example> /// <code> /// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox()); /// elem = driver.FindElementsByName("name") /// </code> /// </example> public IWebElement FindElementByName(string name) { return this.FindElement("css selector", "*[name=\"" + name + "\"]"); } /// <summary> /// Finds a list of elements that match the name supplied /// </summary> /// <param name="name">Name of element</param> /// <returns>ReadOnlyCollect of IWebElement objects so that you can interact that object</returns> /// <example> /// <code> /// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox()); /// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByName("name") /// </code> /// </example> public ReadOnlyCollection<IWebElement> FindElementsByName(string name) { return this.FindElements("css selector", "*[name=\"" + name + "\"]"); } /// <summary> /// Finds the first of elements that match the DOM Tag supplied /// </summary> /// <param name="tagName">DOM tag Name of the element being searched</param> /// <returns>IWebElement object so that you can interact that object</returns> /// <example> /// <code> /// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox()); /// IWebElement elem = driver.FindElementsByTagName("tag") /// </code> /// </example> public IWebElement FindElementByTagName(string tagName) { return this.FindElement("css selector", tagName); } /// <summary> /// Finds a list of elements that match the DOM Tag supplied /// </summary> /// <param name="tagName">DOM tag Name of element being searched</param> /// <returns>IWebElement object so that you can interact that object</returns> /// <example> /// <code> /// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox()); /// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByTagName("tag") /// </code> /// </example> public ReadOnlyCollection<IWebElement> FindElementsByTagName(string tagName) { return this.FindElements("css selector", tagName); } /// <summary> /// Finds the first of elements that match the XPath supplied /// </summary> /// <param name="xpath">xpath to the element</param> /// <returns>IWebElement object so that you can interact that object</returns> /// <example> /// <code> /// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox()); /// IWebElement elem = driver.FindElementsByXPath("//table/tbody/tr/td/a"); /// </code> /// </example> public IWebElement FindElementByXPath(string xpath) { return this.FindElement("xpath", xpath); } /// <summary> /// Finds a list of elements that match the XPath supplied /// </summary> /// <param name="xpath">xpath to the element</param> /// <returns>ReadOnlyCollection of IWebElement objects so that you can interact that object</returns> /// <example> /// <code> /// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox()); /// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByXpath("//tr/td/a") /// </code> /// </example> public ReadOnlyCollection<IWebElement> FindElementsByXPath(string xpath) { return this.FindElements("xpath", xpath); } /// <summary> /// Finds the first element matching the specified CSS selector. /// </summary> /// <param name="cssSelector">The CSS selector to match.</param> /// <returns>The first <see cref="IWebElement"/> matching the criteria.</returns> public IWebElement FindElementByCssSelector(string cssSelector) { return this.FindElement("css selector", cssSelector); } /// <summary> /// Finds all elements matching the specified CSS selector. /// </summary> /// <param name="cssSelector">The CSS selector to match.</param> /// <returns>A <see cref="ReadOnlyCollection{T}"/> containing all /// <see cref="IWebElement">IWebElements</see> matching the criteria.</returns> public ReadOnlyCollection<IWebElement> FindElementsByCssSelector(string cssSelector) { return this.FindElements("css selector", cssSelector); } /// <summary> /// Gets a <see cref="Screenshot"/> object representing the image of the page on the screen. /// </summary> /// <returns>A <see cref="Screenshot"/> object containing the image.</returns> public Screenshot GetScreenshot() { // Get the screenshot as base64. Response screenshotResponse = this.Execute(DriverCommand.Screenshot, null); string base64 = screenshotResponse.Value.ToString(); // ... and convert it. return new Screenshot(base64); } /// <summary> /// Dispose the RemoteWebDriver Instance /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Performs the specified list of actions with this action executor. /// </summary> /// <param name="actionSequenceList">The list of action sequences to perform.</param> public void PerformActions(IList<ActionSequence> actionSequenceList) { if (actionSequenceList == null) { throw new ArgumentNullException("actionSequenceList", "List of action sequences must not be null"); } List<object> objectList = new List<object>(); foreach (ActionSequence sequence in actionSequenceList) { objectList.Add(sequence.ToDictionary()); } Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters["actions"] = objectList; this.Execute(DriverCommand.Actions, parameters); } /// <summary> /// Resets the input state of the action executor. /// </summary> public void ResetInputState() { this.Execute(DriverCommand.CancelActions, null); } /// <summary> /// Escapes invalid characters in a CSS selector. /// </summary> /// <param name="selector">The selector to escape.</param> /// <returns>The selector with invalid characters escaped.</returns> internal static string EscapeCssSelector(string selector) { string escaped = Regex.Replace(selector, @"([ '""\\#.:;,!?+<>=~*^$|%&@`{}\-/\[\]\(\)])", @"\$1"); if (selector.Length > 0 && char.IsDigit(selector[0])) { escaped = @"\" + (30 + int.Parse(selector.Substring(0, 1), CultureInfo.InvariantCulture)).ToString(CultureInfo.InvariantCulture) + " " + selector.Substring(1); } return escaped; } /// <summary> /// Executes commands with the driver /// </summary> /// <param name="driverCommandToExecute">Command that needs executing</param> /// <param name="parameters">Parameters needed for the command</param> /// <returns>WebDriver Response</returns> internal Response InternalExecute(string driverCommandToExecute, Dictionary<string, object> parameters) { return this.Execute(driverCommandToExecute, parameters); } /// <summary> /// Find the element in the response /// </summary> /// <param name="response">Response from the browser</param> /// <returns>Element from the page</returns> internal IWebElement GetElementFromResponse(Response response) { if (response == null) { throw new NoSuchElementException(); } RemoteWebElement element = null; Dictionary<string, object> elementDictionary = response.Value as Dictionary<string, object>; if (elementDictionary != null) { element = this.elementFactory.CreateElement(elementDictionary); } return element; } /// <summary> /// Finds the elements that are in the response /// </summary> /// <param name="response">Response from the browser</param> /// <returns>Collection of elements</returns> internal ReadOnlyCollection<IWebElement> GetElementsFromResponse(Response response) { List<IWebElement> toReturn = new List<IWebElement>(); object[] elements = response.Value as object[]; if (elements != null) { foreach (object elementObject in elements) { Dictionary<string, object> elementDictionary = elementObject as Dictionary<string, object>; if (elementDictionary != null) { RemoteWebElement element = this.elementFactory.CreateElement(elementDictionary); toReturn.Add(element); } } } return toReturn.AsReadOnly(); } /// <summary> /// Stops the client from running /// </summary> /// <param name="disposing">if its in the process of disposing</param> protected virtual void Dispose(bool disposing) { try { this.Execute(DriverCommand.Quit, null); } catch (NotImplementedException) { } catch (InvalidOperationException) { } catch (WebDriverException) { } finally { this.StopClient(); this.sessionId = null; } } /// <summary> /// Starts a session with the driver /// </summary> /// <param name="desiredCapabilities">Capabilities of the browser</param> protected void StartSession(ICapabilities desiredCapabilities) { Dictionary<string, object> parameters = new Dictionary<string, object>(); // If the object passed into the RemoteWebDriver constructor is a // RemoteSessionSettings object, it is expected that all intermediate // and end nodes are compliant with the W3C WebDriver Specification, // and therefore will already contain all of the appropriate values // for establishing a session. RemoteSessionSettings remoteSettings = desiredCapabilities as RemoteSessionSettings; if (remoteSettings == null) { Dictionary<string, object> matchCapabilities = this.GetCapabilitiesDictionary(desiredCapabilities); List<object> firstMatchCapabilitiesList = new List<object>(); firstMatchCapabilitiesList.Add(matchCapabilities); Dictionary<string, object> specCompliantCapabilitiesDictionary = new Dictionary<string, object>(); specCompliantCapabilitiesDictionary["firstMatch"] = firstMatchCapabilitiesList; parameters.Add("capabilities", specCompliantCapabilitiesDictionary); } else { parameters.Add("capabilities", remoteSettings.ToDictionary()); } Response response = this.Execute(DriverCommand.NewSession, parameters); Dictionary<string, object> rawCapabilities = (Dictionary<string, object>)response.Value; ReturnedCapabilities returnedCapabilities = new ReturnedCapabilities(rawCapabilities); this.capabilities = returnedCapabilities; this.sessionId = new SessionId(response.SessionId); } /// <summary> /// Gets the capabilities as a dictionary. /// </summary> /// <param name="capabilitiesToConvert">The dictionary to return.</param> /// <returns>A Dictionary consisting of the capabilities requested.</returns> /// <remarks>This method is only transitional. Do not rely on it. It will be removed /// once browser driver capability formats stabilize.</remarks> protected virtual Dictionary<string, object> GetCapabilitiesDictionary(ICapabilities capabilitiesToConvert) { Dictionary<string, object> capabilitiesDictionary = new Dictionary<string, object>(); IHasCapabilitiesDictionary capabilitiesObject = capabilitiesToConvert as IHasCapabilitiesDictionary; foreach (KeyValuePair<string, object> entry in capabilitiesObject.CapabilitiesDictionary) { if (CapabilityType.IsSpecCompliantCapabilityName(entry.Key)) { capabilitiesDictionary.Add(entry.Key, entry.Value); } } return capabilitiesDictionary; } /// <summary> /// Executes a command with this driver . /// </summary> /// <param name="driverCommandToExecute">A <see cref="DriverCommand"/> value representing the command to execute.</param> /// <param name="parameters">A <see cref="Dictionary{K, V}"/> containing the names and values of the parameters of the command.</param> /// <returns>A <see cref="Response"/> containing information about the success or failure of the command and any data returned by the command.</returns> protected virtual Response Execute(string driverCommandToExecute, Dictionary<string, object> parameters) { Command commandToExecute = new Command(this.sessionId, driverCommandToExecute, parameters); Response commandResponse = new Response(); try { commandResponse = this.executor.Execute(commandToExecute); } catch (System.Net.WebException e) { commandResponse.Status = WebDriverResult.UnhandledError; commandResponse.Value = e; } if (commandResponse.Status != WebDriverResult.Success) { UnpackAndThrowOnError(commandResponse); } return commandResponse; } /// <summary> /// Starts the command executor, enabling communication with the browser. /// </summary> protected virtual void StartClient() { } /// <summary> /// Stops the command executor, ending further communication with the browser. /// </summary> protected virtual void StopClient() { } /// <summary> /// Finds an element matching the given mechanism and value. /// </summary> /// <param name="mechanism">The mechanism by which to find the element.</param> /// <param name="value">The value to use to search for the element.</param> /// <returns>The first <see cref="IWebElement"/> matching the given criteria.</returns> protected IWebElement FindElement(string mechanism, string value) { Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("using", mechanism); parameters.Add("value", value); Response commandResponse = this.Execute(DriverCommand.FindElement, parameters); return this.GetElementFromResponse(commandResponse); } /// <summary> /// Finds all elements matching the given mechanism and value. /// </summary> /// <param name="mechanism">The mechanism by which to find the elements.</param> /// <param name="value">The value to use to search for the elements.</param> /// <returns>A collection of all of the <see cref="IWebElement">IWebElements</see> matching the given criteria.</returns> protected ReadOnlyCollection<IWebElement> FindElements(string mechanism, string value) { Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("using", mechanism); parameters.Add("value", value); Response commandResponse = this.Execute(DriverCommand.FindElements, parameters); return this.GetElementsFromResponse(commandResponse); } /// <summary> /// Executes JavaScript in the context of the currently selected frame or window using a specific command. /// </summary> /// <param name="script">The JavaScript code to execute.</param> /// <param name="commandName">The name of the command to execute.</param> /// <param name="args">The arguments to the script.</param> /// <returns>The value returned by the script.</returns> protected object ExecuteScriptCommand(string script, string commandName, params object[] args) { object[] convertedArgs = ConvertArgumentsToJavaScriptObjects(args); Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("script", script); if (convertedArgs != null && convertedArgs.Length > 0) { parameters.Add("args", convertedArgs); } else { parameters.Add("args", new object[] { }); } Response commandResponse = this.Execute(commandName, parameters); return this.ParseJavaScriptReturnValue(commandResponse.Value); } private static object ConvertObjectToJavaScriptObject(object arg) { IWrapsElement argAsWrapsElement = arg as IWrapsElement; IWebElementReference argAsElementReference = arg as IWebElementReference; IEnumerable argAsEnumerable = arg as IEnumerable; IDictionary argAsDictionary = arg as IDictionary; if (argAsElementReference == null && argAsWrapsElement != null) { argAsElementReference = argAsWrapsElement.WrappedElement as IWebElementReference; } object converted = null; if (arg is string || arg is float || arg is double || arg is int || arg is long || arg is bool || arg == null) { converted = arg; } else if (argAsElementReference != null) { // TODO: Remove "ELEMENT" addition when all remote ends are spec-compliant. Dictionary<string, object> elementDictionary = argAsElementReference.ToDictionary(); elementDictionary.Add(RemoteWebElement.LegacyElementReferencePropertyName, argAsElementReference.ElementReferenceId); converted = elementDictionary; } else if (argAsDictionary != null) { // Note that we must check for the argument being a dictionary before // checking for IEnumerable, since dictionaries also implement IEnumerable. // Additionally, JavaScript objects have property names as strings, so all // keys will be converted to strings. Dictionary<string, object> dictionary = new Dictionary<string, object>(); foreach (var key in argAsDictionary.Keys) { dictionary.Add(key.ToString(), ConvertObjectToJavaScriptObject(argAsDictionary[key])); } converted = dictionary; } else if (argAsEnumerable != null) { List<object> objectList = new List<object>(); foreach (object item in argAsEnumerable) { objectList.Add(ConvertObjectToJavaScriptObject(item)); } converted = objectList.ToArray(); } else { throw new ArgumentException("Argument is of an illegal type" + arg.ToString(), "arg"); } return converted; } /// <summary> /// Converts the arguments to JavaScript objects. /// </summary> /// <param name="args">The arguments.</param> /// <returns>The list of the arguments converted to JavaScript objects.</returns> private static object[] ConvertArgumentsToJavaScriptObjects(object[] args) { if (args == null) { return new object[] { null }; } for (int i = 0; i < args.Length; i++) { args[i] = ConvertObjectToJavaScriptObject(args[i]); } return args; } private static void UnpackAndThrowOnError(Response errorResponse) { // Check the status code of the error, and only handle if not success. if (errorResponse.Status != WebDriverResult.Success) { Dictionary<string, object> errorAsDictionary = errorResponse.Value as Dictionary<string, object>; if (errorAsDictionary != null) { ErrorResponse errorResponseObject = new ErrorResponse(errorAsDictionary); string errorMessage = errorResponseObject.Message; switch (errorResponse.Status) { case WebDriverResult.NoSuchElement: throw new NoSuchElementException(errorMessage); case WebDriverResult.NoSuchFrame: throw new NoSuchFrameException(errorMessage); case WebDriverResult.UnknownCommand: throw new NotImplementedException(errorMessage); case WebDriverResult.ObsoleteElement: throw new StaleElementReferenceException(errorMessage); case WebDriverResult.ElementClickIntercepted: throw new ElementClickInterceptedException(errorMessage); case WebDriverResult.ElementNotInteractable: throw new ElementNotInteractableException(errorMessage); case WebDriverResult.ElementNotDisplayed: throw new ElementNotVisibleException(errorMessage); case WebDriverResult.InvalidElementState: case WebDriverResult.ElementNotSelectable: throw new InvalidElementStateException(errorMessage); case WebDriverResult.UnhandledError: throw new WebDriverException(errorMessage); case WebDriverResult.NoSuchDocument: throw new NoSuchElementException(errorMessage); case WebDriverResult.Timeout: throw new WebDriverTimeoutException(errorMessage); case WebDriverResult.NoSuchWindow: throw new NoSuchWindowException(errorMessage); case WebDriverResult.InvalidCookieDomain: throw new InvalidCookieDomainException(errorMessage); case WebDriverResult.UnableToSetCookie: throw new UnableToSetCookieException(errorMessage); case WebDriverResult.AsyncScriptTimeout: throw new WebDriverTimeoutException(errorMessage); case WebDriverResult.UnexpectedAlertOpen: // TODO(JimEvans): Handle the case where the unexpected alert setting // has been set to "ignore", so there is still a valid alert to be // handled. string alertText = string.Empty; if (errorAsDictionary.ContainsKey("alert")) { Dictionary<string, object> alertDescription = errorAsDictionary["alert"] as Dictionary<string, object>; if (alertDescription != null && alertDescription.ContainsKey("text")) { alertText = alertDescription["text"].ToString(); } } else if (errorAsDictionary.ContainsKey("data")) { Dictionary<string, object> alertData = errorAsDictionary["data"] as Dictionary<string, object>; if (alertData != null && alertData.ContainsKey("text")) { alertText = alertData["text"].ToString(); } } throw new UnhandledAlertException(errorMessage, alertText); case WebDriverResult.NoAlertPresent: throw new NoAlertPresentException(errorMessage); case WebDriverResult.InvalidSelector: throw new InvalidSelectorException(errorMessage); case WebDriverResult.NoSuchDriver: throw new WebDriverException(errorMessage); case WebDriverResult.InvalidArgument: throw new WebDriverArgumentException(errorMessage); case WebDriverResult.UnexpectedJavaScriptError: throw new JavaScriptException(errorMessage); case WebDriverResult.MoveTargetOutOfBounds: throw new MoveTargetOutOfBoundsException(errorMessage); default: throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "{0} ({1})", errorMessage, errorResponse.Status)); } } else { throw new WebDriverException("Unexpected error. " + errorResponse.Value.ToString()); } } } private static ICapabilities ConvertOptionsToCapabilities(DriverOptions options) { if (options == null) { throw new ArgumentNullException("options", "Driver options must not be null"); } return options.ToCapabilities(); } private object ParseJavaScriptReturnValue(object responseValue) { object returnValue = null; Dictionary<string, object> resultAsDictionary = responseValue as Dictionary<string, object>; object[] resultAsArray = responseValue as object[]; if (resultAsDictionary != null) { if (this.elementFactory.ContainsElementReference(resultAsDictionary)) { returnValue = this.elementFactory.CreateElement(resultAsDictionary); } else { // Recurse through the dictionary, re-parsing each value. string[] keyCopy = new string[resultAsDictionary.Keys.Count]; resultAsDictionary.Keys.CopyTo(keyCopy, 0); foreach (string key in keyCopy) { resultAsDictionary[key] = this.ParseJavaScriptReturnValue(resultAsDictionary[key]); } returnValue = resultAsDictionary; } } else if (resultAsArray != null) { bool allElementsAreWebElements = true; List<object> toReturn = new List<object>(); foreach (object item in resultAsArray) { object parsedItem = this.ParseJavaScriptReturnValue(item); IWebElement parsedItemAsElement = parsedItem as IWebElement; if (parsedItemAsElement == null) { allElementsAreWebElements = false; } toReturn.Add(parsedItem); } if (toReturn.Count > 0 && allElementsAreWebElements) { List<IWebElement> elementList = new List<IWebElement>(); foreach (object listItem in toReturn) { IWebElement itemAsElement = listItem as IWebElement; elementList.Add(itemAsElement); } returnValue = elementList.AsReadOnly(); } else { returnValue = toReturn.AsReadOnly(); } } else { returnValue = responseValue; } return returnValue; } } }
/*This script has been, partially or completely, generated by the Fungus.GenerateVariableWindow*/ using UnityEngine; namespace Fungus { // <summary> /// Get or Set a property of a Rigidbody component /// </summary> [CommandInfo("Property", "Rigidbody", "Get or Set a property of a Rigidbody component")] [AddComponentMenu("")] public class RigidbodyProperty : BaseVariableProperty { //generated property public enum Property { Velocity, AngularVelocity, Drag, AngularDrag, Mass, UseGravity, MaxDepenetrationVelocity, IsKinematic, FreezeRotation, CenterOfMass, WorldCenterOfMass, InertiaTensorRotation, InertiaTensor, DetectCollisions, Position, Rotation, SolverIterations, SolverVelocityIterations, SleepThreshold, MaxAngularVelocity, } [SerializeField] protected Property property; [SerializeField] protected RigidbodyData rigidbodyData; [SerializeField] [VariableProperty(typeof(Vector3Variable), typeof(FloatVariable), typeof(BooleanVariable), typeof(QuaternionVariable), typeof(IntegerVariable))] protected Variable inOutVar; public override void OnEnter() { var iov = inOutVar as Vector3Variable; var iof = inOutVar as FloatVariable; var iob = inOutVar as BooleanVariable; var ioq = inOutVar as QuaternionVariable; var ioi = inOutVar as IntegerVariable; var target = rigidbodyData.Value; switch (getOrSet) { case GetSet.Get: switch (property) { case Property.Velocity: iov.Value = target.velocity; break; case Property.AngularVelocity: iov.Value = target.angularVelocity; break; case Property.Drag: iof.Value = target.drag; break; case Property.AngularDrag: iof.Value = target.angularDrag; break; case Property.Mass: iof.Value = target.mass; break; case Property.UseGravity: iob.Value = target.useGravity; break; case Property.MaxDepenetrationVelocity: iof.Value = target.maxDepenetrationVelocity; break; case Property.IsKinematic: iob.Value = target.isKinematic; break; case Property.FreezeRotation: iob.Value = target.freezeRotation; break; case Property.CenterOfMass: iov.Value = target.centerOfMass; break; case Property.WorldCenterOfMass: iov.Value = target.worldCenterOfMass; break; case Property.InertiaTensorRotation: ioq.Value = target.inertiaTensorRotation; break; case Property.InertiaTensor: iov.Value = target.inertiaTensor; break; case Property.DetectCollisions: iob.Value = target.detectCollisions; break; case Property.Position: iov.Value = target.position; break; case Property.Rotation: ioq.Value = target.rotation; break; case Property.SolverIterations: ioi.Value = target.solverIterations; break; case Property.SleepThreshold: iof.Value = target.sleepThreshold; break; case Property.MaxAngularVelocity: iof.Value = target.maxAngularVelocity; break; case Property.SolverVelocityIterations: ioi.Value = target.solverVelocityIterations; break; default: Debug.Log("Unsupported get or set attempted"); break; } break; case GetSet.Set: switch (property) { case Property.Velocity: target.velocity = iov.Value; break; case Property.AngularVelocity: target.angularVelocity = iov.Value; break; case Property.Drag: target.drag = iof.Value; break; case Property.AngularDrag: target.angularDrag = iof.Value; break; case Property.Mass: target.mass = iof.Value; break; case Property.UseGravity: target.useGravity = iob.Value; break; case Property.MaxDepenetrationVelocity: target.maxDepenetrationVelocity = iof.Value; break; case Property.IsKinematic: target.isKinematic = iob.Value; break; case Property.FreezeRotation: target.freezeRotation = iob.Value; break; case Property.CenterOfMass: target.centerOfMass = iov.Value; break; case Property.InertiaTensorRotation: target.inertiaTensorRotation = ioq.Value; break; case Property.InertiaTensor: target.inertiaTensor = iov.Value; break; case Property.DetectCollisions: target.detectCollisions = iob.Value; break; case Property.Position: target.position = iov.Value; break; case Property.Rotation: target.rotation = ioq.Value; break; case Property.SolverIterations: target.solverIterations = ioi.Value; break; case Property.SleepThreshold: target.sleepThreshold = iof.Value; break; case Property.MaxAngularVelocity: target.maxAngularVelocity = iof.Value; break; case Property.SolverVelocityIterations: target.solverVelocityIterations = ioi.Value; break; default: Debug.Log("Unsupported get or set attempted"); break; } break; default: break; } Continue(); } public override string GetSummary() { if (rigidbodyData.Value == null) { return "Error: no rigidbody set"; } if (inOutVar == null) { return "Error: no variable set to push or pull data to or from"; } return getOrSet.ToString() + " " + property.ToString(); } public override Color GetButtonColor() { return new Color32(235, 191, 217, 255); } public override bool HasReference(Variable variable) { if (rigidbodyData.rigidbodyRef == variable || inOutVar == variable) return true; return false; } } }
using System; using System.Collections.Generic; using System.Linq; using Pomelo.EntityFrameworkCore.MySql.Scaffolding.Internal; using Pomelo.EntityFrameworkCore.MySql.FunctionalTests.TestUtilities; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Scaffolding.Metadata; using Microsoft.EntityFrameworkCore.TestUtilities; using Microsoft.Extensions.Logging; using Xunit; using Microsoft.EntityFrameworkCore.Internal; using System.Diagnostics; using Microsoft.EntityFrameworkCore.Diagnostics.Internal; using Microsoft.EntityFrameworkCore.Metadata; using Pomelo.EntityFrameworkCore.MySql.Diagnostics.Internal; using Microsoft.EntityFrameworkCore.Scaffolding; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.Extensions.DependencyInjection; using Pomelo.EntityFrameworkCore.MySql.Infrastructure; using Pomelo.EntityFrameworkCore.MySql.Infrastructure.Internal; using Pomelo.EntityFrameworkCore.MySql.Metadata.Internal; using Pomelo.EntityFrameworkCore.MySql.Tests; using Pomelo.EntityFrameworkCore.MySql.Tests.TestUtilities.Attributes; // ReSharper disable InconsistentNaming namespace Pomelo.EntityFrameworkCore.MySql.FunctionalTests.Scaffolding { public class MySqlDatabaseModelFactoryTest : IClassFixture<MySqlDatabaseModelFactoryTest.MySqlDatabaseModelFixture> { protected MySqlDatabaseModelFixture Fixture { get; } public MySqlDatabaseModelFactoryTest(MySqlDatabaseModelFixture fixture) { Fixture = fixture; Fixture.ListLoggerFactory.Clear(); } protected readonly List<(LogLevel Level, EventId Id, string Message)> Log = new List<(LogLevel Level, EventId Id, string Message)>(); private void Test(string createSql, IEnumerable<string> tables, IEnumerable<string> schemas, Action<DatabaseModel> asserter, string cleanupSql) { try { Fixture.TestStore.ExecuteNonQuery(createSql); var databaseModelFactory = new MySqlDatabaseModelFactory( new DiagnosticsLogger<DbLoggerCategory.Scaffolding>( Fixture.ListLoggerFactory, new LoggingOptions(), new DiagnosticListener("Fake"), new MySqlLoggingDefinitions(), new NullDbContextLogger()), Fixture.ServiceProvider.GetService<IRelationalTypeMappingSource>(), Fixture.ServiceProvider.GetService<IMySqlOptions>()); var databaseModel = databaseModelFactory.Create(Fixture.TestStore.ConnectionString, new DatabaseModelFactoryOptions(tables, schemas)); Assert.NotNull(databaseModel); asserter(databaseModel); } finally { if (!string.IsNullOrEmpty(cleanupSql)) { Fixture.TestStore.ExecuteNonQuery(cleanupSql); } } } #region FilteringSchemaTable [Fact(Skip = "Issue #582")] public void Filter_tables() { Test( @" CREATE TABLE Everest ( id int ); CREATE TABLE Denali ( id int );", new[] { "Everest" }, Enumerable.Empty<string>(), dbModel => { var table = Assert.Single(dbModel.Tables); // ReSharper disable once PossibleNullReferenceException Assert.Equal("Everest", table.Name); }, @" DROP TABLE IF EXISTS Everest; DROP TABLE IF EXISTS Denali;"); } [Fact(Skip = "Issue #582")] public void Filter_tables_is_case_insensitive() { Test( @" CREATE TABLE Everest ( id int ); CREATE TABLE Denali ( id int );", new[] { "eVeReSt" }, Enumerable.Empty<string>(), dbModel => { var table = Assert.Single(dbModel.Tables); // ReSharper disable once PossibleNullReferenceException Assert.Equal("Everest", table.Name); }, @" DROP TABLE IF EXISTS Everest; DROP TABLE IF EXISTS Denali;"); } #endregion #region Table [Fact(Skip = "Issue #582")] public void Create_tables() { Test( @" CREATE TABLE Everest ( id int ); CREATE TABLE Denali ( id int );", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { Assert.Collection( dbModel.Tables.OrderBy(t => t.Name), d => Assert.Equal("Denali", d.Name), e => Assert.Equal("Everest", e.Name)); }, @" DROP TABLE IF EXISTS Everest; DROP TABLE IF EXISTS Denali;"); } [Fact] public void Create_table_with_collation() { Test( @" CREATE TABLE `Mountains` ( `Name` varchar(255) NOT NULL COLLATE latin1_general_cs, `Text1` longtext NOT NULL COLLATE latin1_general_ci, `Text2` longtext NOT NULL ) COLLATE latin1_general_ci;", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var table = Assert.Single(dbModel.Tables); Assert.Equal("latin1_general_ci", table[RelationalAnnotationNames.Collation]); Assert.Collection( table.Columns.OrderBy(c => c.Name), c => Assert.Equal("latin1_general_cs", c.Collation), c => Assert.Null(c.Collation), c => Assert.Null(c.Collation)); }, @" DROP TABLE IF EXISTS `Mountains`;"); } [Fact(Skip = "Issue #582")] public void Create_columns() { Test( @" CREATE TABLE MountainsColumns ( Id integer primary key, Name text NOT NULL );", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var table = dbModel.Tables.Single(); Assert.Equal(2, table.Columns.Count); Assert.All( table.Columns, c => { Assert.Equal("MountainsColumns", c.Table.Name); }); Assert.Single(table.Columns.Where(c => c.Name == "Id")); Assert.Single(table.Columns.Where(c => c.Name == "Name")); }, @"DROP TABLE IF EXISTS MountainsColumns;"); } [Fact(Skip = "Issue #582")] public void Create_primary_key() { Test( @"CREATE TABLE Place ( Id int PRIMARY KEY );", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var pk = dbModel.Tables.Single().PrimaryKey; Assert.Equal("Place", pk.Table.Name); Assert.Equal(new List<string> { "Id" }, pk.Columns.Select(ic => ic.Name).ToList()); }, @"DROP TABLE IF EXISTS Place;"); } [Fact(Skip = "Issue #582")] public void Create_unique_constraints() { Test( @" CREATE TABLE Place ( Id int PRIMARY KEY, Name int UNIQUE, Location int ); CREATE INDEX IX_Location_Name ON Place (Location, Name);", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var uniqueConstraint = Assert.Single(dbModel.Tables.Single().UniqueConstraints); // ReSharper disable once PossibleNullReferenceException Assert.Equal("Place", uniqueConstraint.Table.Name); Assert.Equal(new List<string> { "Name" }, uniqueConstraint.Columns.Select(ic => ic.Name).ToList()); }, @"DROP TABLE IF EXISTS Place;"); } [Fact(Skip = "Issue #582")] public void Create_indexes() { Test( @" CREATE TABLE IndexTable ( Id int, Name int, IndexProperty int ); CREATE INDEX IX_NAME on IndexTable ( Name ); CREATE INDEX IX_INDEX on IndexTable ( IndexProperty );", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var table = dbModel.Tables.Single(); Assert.Equal(2, table.Indexes.Count); Assert.All( table.Indexes, c => { Assert.Equal("IndexTable", c.Table.Name); }); Assert.Single(table.Indexes.Where(c => c.Name == "IX_NAME")); Assert.Single(table.Indexes.Where(c => c.Name == "IX_INDEX")); }, @"DROP TABLE IF EXISTS IndexTable;"); } [Fact(Skip = "Issue #582")] public void Create_foreign_keys() { Test( @" CREATE TABLE PrincipalTable ( Id int PRIMARY KEY ); CREATE TABLE FirstDependent ( Id int PRIMARY KEY, ForeignKeyId int, FOREIGN KEY (ForeignKeyId) REFERENCES PrincipalTable(Id) ON DELETE CASCADE ); CREATE TABLE SecondDependent ( Id int PRIMARY KEY, FOREIGN KEY (Id) REFERENCES PrincipalTable(Id) ON DELETE NO ACTION );", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var firstFk = Assert.Single(dbModel.Tables.Single(t => t.Name == "FirstDependent").ForeignKeys); // ReSharper disable once PossibleNullReferenceException Assert.Equal("FirstDependent", firstFk.Table.Name); Assert.Equal("PrincipalTable", firstFk.PrincipalTable.Name); Assert.Equal(new List<string> { "ForeignKeyId" }, firstFk.Columns.Select(ic => ic.Name).ToList()); Assert.Equal(new List<string> { "Id" }, firstFk.PrincipalColumns.Select(ic => ic.Name).ToList()); Assert.Equal(ReferentialAction.Cascade, firstFk.OnDelete); var secondFk = Assert.Single(dbModel.Tables.Single(t => t.Name == "SecondDependent").ForeignKeys); // ReSharper disable once PossibleNullReferenceException Assert.Equal("SecondDependent", secondFk.Table.Name); Assert.Equal("PrincipalTable", secondFk.PrincipalTable.Name); Assert.Equal(new List<string> { "Id" }, secondFk.Columns.Select(ic => ic.Name).ToList()); Assert.Equal(new List<string> { "Id" }, secondFk.PrincipalColumns.Select(ic => ic.Name).ToList()); Assert.Equal(ReferentialAction.NoAction, secondFk.OnDelete); }, @" DROP TABLE IF EXISTS SecondDependent; DROP TABLE IF EXISTS FirstDependent; DROP TABLE IF EXISTS PrincipalTable;"); } [Fact] public void Create_dependent_table_with_missing_principal_table_creates_model_without_it() { Test( @" CREATE TABLE PrincipalTable ( Id int PRIMARY KEY ); CREATE TABLE DependentTable ( Id int PRIMARY KEY, ForeignKeyId int, FOREIGN KEY (ForeignKeyId) REFERENCES PrincipalTable(Id) );", new[] { "DependentTable" }, Enumerable.Empty<string>(), dbModel => { var table = Assert.Single(dbModel.Tables); Assert.Equal("DependentTable", table.Name); }, @" DROP TABLE IF EXISTS DependentTable; DROP TABLE IF EXISTS PrincipalTable;"); } [ConditionalFact] [SupportedServerVersionCondition(nameof(ServerVersionSupport.IdentifyJsonColumsByCheckConstraints))] public void Create_json_column() { Test( @" CREATE TABLE `PlaceDetails` ( `JsonCharacteristics` json, `TextDescription` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin, `TextDependingOnValidJsonCharacteristics` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci CHECK (json_valid(`JsonCharacteristics`)), `TextCharacteristics` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci CHECK (json_valid(`TextCharacteristics`)), `OtherJsonCharacteristics` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin CHECK (json_valid(`OtherJsonCharacteristics`)) ) CHARACTER SET latin1 COLLATE latin1_general_ci;", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var table = Assert.Single(dbModel.Tables.Where(t => t.Name == "PlaceDetails")); var jsonCharacteristicsColumn = Assert.Single(table.Columns.Where(c => c.Name == "JsonCharacteristics")); var textDescriptionColumn = Assert.Single(table.Columns.Where(c => c.Name == "TextDescription")); var textDependingOnValidJsonCharacteristicsColumn = Assert.Single(table.Columns.Where(c => c.Name == "TextDependingOnValidJsonCharacteristics")); var textCharacteristicsColumn = Assert.Single(table.Columns.Where(c => c.Name == "TextCharacteristics")); var otherJsonCharacteristicsColumn = Assert.Single(table.Columns.Where(c => c.Name == "OtherJsonCharacteristics")); Assert.Equal("json", jsonCharacteristicsColumn.StoreType); Assert.Null(jsonCharacteristicsColumn[MySqlAnnotationNames.CharSet]); Assert.Null(jsonCharacteristicsColumn.Collation); Assert.Equal("longtext", textDescriptionColumn.StoreType); Assert.Equal("utf8mb4", textDescriptionColumn[MySqlAnnotationNames.CharSet]); Assert.Equal("utf8mb4_bin", textDescriptionColumn.Collation); Assert.Equal("longtext", textDependingOnValidJsonCharacteristicsColumn.StoreType); Assert.Equal("utf8mb4", textDependingOnValidJsonCharacteristicsColumn[MySqlAnnotationNames.CharSet]); Assert.Equal("utf8mb4_general_ci", textDependingOnValidJsonCharacteristicsColumn.Collation); Assert.Equal("longtext", textCharacteristicsColumn.StoreType); Assert.Equal("utf8mb4", textCharacteristicsColumn[MySqlAnnotationNames.CharSet]); Assert.Equal("utf8mb4_general_ci", textCharacteristicsColumn.Collation); Assert.Equal("json", otherJsonCharacteristicsColumn.StoreType); Assert.Null(otherJsonCharacteristicsColumn[MySqlAnnotationNames.CharSet]); Assert.Null(otherJsonCharacteristicsColumn.Collation); }, @" DROP TABLE IF EXISTS `PlaceDetails`;"); } [ConditionalFact] [SupportedServerVersionCondition(nameof(ServerVersionSupport.DefaultExpression), nameof(ServerVersionSupport.AlternativeDefaultExpression))] public void Create_guid_columns() { Test( @" CREATE TABLE `GuidTable` ( `GuidTableId` char(36) NOT NULL DEFAULT (UUID()) PRIMARY KEY, `DefaultUuid` char(36) NOT NULL DEFAULT (UUID()) );", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var table = Assert.Single(dbModel.Tables.Where(t => t.Name == "GuidTable")); var guidTableIdColumn = Assert.Single(table.Columns.Where(c => c.Name == "GuidTableId")); var defaultUuidColumn = Assert.Single(table.Columns.Where(c => c.Name == "DefaultUuid")); Assert.Equal(ValueGenerated.OnAdd, guidTableIdColumn.ValueGenerated); Assert.Null(guidTableIdColumn.DefaultValueSql); Assert.Null(defaultUuidColumn.ValueGenerated); Assert.Equal("uuid()", defaultUuidColumn.DefaultValueSql); }, @" DROP TABLE IF EXISTS `GuidTable`;"); } [ConditionalFact] public void Create_default_value_column() { Test( $@" CREATE TABLE `DefaultValueTable` ( `DefaultValueInt` int not null default '42', `DefaultValueString` varchar(255) not null default 'Answer to everything', `DefaultValueFunction` datetime not null default CURRENT_TIMESTAMP() );", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var table = Assert.Single(dbModel.Tables.Where(t => t.Name == "DefaultValueTable")); var defaultValueIntColumn = Assert.Single(table.Columns.Where(c => c.Name == "DefaultValueInt")); var defaultValueStringColumn = Assert.Single(table.Columns.Where(c => c.Name == "DefaultValueString")); var defaultValueFunctionColumn = Assert.Single(table.Columns.Where(c => c.Name == "DefaultValueFunction")); Assert.Equal("'42'", defaultValueIntColumn.DefaultValueSql); Assert.Equal("'Answer to everything'", defaultValueStringColumn.DefaultValueSql); Assert.Contains("current_timestamp", defaultValueFunctionColumn.DefaultValueSql, StringComparison.OrdinalIgnoreCase); }, @" DROP TABLE IF EXISTS `DefaultValueTable`;"); } [ConditionalFact] [SupportedServerVersionCondition(nameof(ServerVersionSupport.AlternativeDefaultExpression))] public void Create_default_value_column_simple_function_expression() { Test( $@" CREATE TABLE `DefaultValueSimpleExpressionTable` ( `DefaultValueSimpleFunctionExpression` double not null default rand() );", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var table = Assert.Single(dbModel.Tables.Where(t => t.Name == "DefaultValueSimpleExpressionTable")); var defaultValueSimpleFunctionExpressionColumn = table.Columns.SingleOrDefault(c => c.Name == "DefaultValueSimpleFunctionExpression"); Assert.Equal("rand()", defaultValueSimpleFunctionExpressionColumn.DefaultValueSql); }, @" DROP TABLE IF EXISTS `DefaultValueSimpleExpressionTable`;"); } [ConditionalFact] [SupportedServerVersionCondition(nameof(ServerVersionSupport.DefaultExpression), nameof(ServerVersionSupport.AlternativeDefaultExpression))] public void Create_default_value_expression_column() { Test( $@" CREATE TABLE `DefaultValueExpressionTable` ( `DefaultValueExpression` varchar(255) not null default (CONCAT(CAST(42 as char), ' is the answer to everything')), `DefaultValueExpressionInt` int not null default (42) );", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var table = Assert.Single(dbModel.Tables.Where(t => t.Name == "DefaultValueExpressionTable")); var defaultValueExpressionColumn = Assert.Single(table.Columns.Where(c => c.Name == "DefaultValueExpression")); var defaultValueExpressionIntColumn = Assert.Single(table.Columns.Where(c => c.Name == "DefaultValueExpressionInt")); Assert.Contains("CONCAT(CAST(42 as char", defaultValueExpressionColumn.DefaultValueSql, StringComparison.OrdinalIgnoreCase); Assert.Contains(" is the answer to everything", defaultValueExpressionColumn.DefaultValueSql, StringComparison.OrdinalIgnoreCase); Assert.Equal("'42'", defaultValueExpressionIntColumn.DefaultValueSql); }, @" DROP TABLE IF EXISTS `DefaultValueExpressionTable`;"); } [ConditionalFact] [SupportedServerVersionCondition("10.4.0-mariadb")] public void Create_view_with_column_type_containing_comment_after_cast() { // Any cast (necessary or not) will result in MariaDB adding a comment to the column type // when queried through `INFORMATION_SCHEMA`.`COLUMNS`. Test( @" CREATE TABLE `item_data` ( `id` INT(11) NOT NULL, `text_datetime` TEXT NOT NULL, `real_datetime_1` DATETIME NOT NULL, `real_datetime_2` DATETIME NOT NULL, PRIMARY KEY (`id`) ); CREATE VIEW `item_data_view` AS SELECT `item`.`id`, CAST(`item`.`text_datetime` AS DATETIME) AS `text_datetime_converted`, CAST(`item`.`real_datetime_1` AS DATETIME) AS `real_datetime_1_converted`, `item`.`real_datetime_2` AS `real_datetime_2_original` FROM `item_data` `item`;", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var table = Assert.Single(dbModel.Tables.Where(t => t.Name == "item_data_view")); var textDateTimeConvertedColumn = Assert.Single(table.Columns.Where(c => c.Name == "text_datetime_converted")); var realDateTime1ConvertedColumn = Assert.Single(table.Columns.Where(c => c.Name == "real_datetime_1_converted")); var realDateTime2OriginalColumn = Assert.Single(table.Columns.Where(c => c.Name == "real_datetime_2_original")); Assert.Equal("datetime", textDateTimeConvertedColumn.StoreType); Assert.Equal("datetime", realDateTime1ConvertedColumn.StoreType); Assert.Equal("datetime", realDateTime2OriginalColumn.StoreType); }, @" DROP VIEW IF EXISTS `item_data_view`; DROP TABLE IF EXISTS `item_data`;"); } #endregion #region ColumnFacets [Fact] public void Column_storetype_is_set() { Test( @" CREATE TABLE StoreType ( /* IntegerProperty int, RealProperty real, TextProperty text, BlobProperty blob,*/ GeometryProperty geometry, PointProperty point/*, RandomProperty randomType*/ );", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var columns = dbModel.Tables.Single().Columns; //Assert.Equal("integer", columns.Single(c => c.Name == "IntegerProperty").StoreType); //Assert.Equal("real", columns.Single(c => c.Name == "RealProperty").StoreType); //Assert.Equal("text", columns.Single(c => c.Name == "TextProperty").StoreType); //Assert.Equal("blob", columns.Single(c => c.Name == "BlobProperty").StoreType); Assert.Equal("geometry", columns.Single(c => c.Name == "GeometryProperty").StoreType); Assert.Equal("point", columns.Single(c => c.Name == "PointProperty").StoreType); //Assert.Equal("randomType", columns.Single(c => c.Name == "RandomProperty").StoreType); }, @"DROP TABLE IF EXISTS StoreType;"); } [Fact(Skip = "Issue #582")] public void Column_nullability_is_set() { Test( @" CREATE TABLE Nullable ( Id int, NullableInt int NULL, NonNullString text NOT NULL );", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var columns = dbModel.Tables.Single().Columns; Assert.True(columns.Single(c => c.Name == "NullableInt").IsNullable); Assert.False(columns.Single(c => c.Name == "NonNullString").IsNullable); }, @"DROP TABLE IF EXISTS Nullable;"); } [Fact(Skip = "Issue #582")] public void Column_default_value_is_set() { Test( @" CREATE TABLE DefaultValue ( Id int, SomeText text DEFAULT 'Something', RealColumn real DEFAULT 3.14, Created datetime DEFAULT 'October 20, 2015 11am' );", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var columns = dbModel.Tables.Single().Columns; Assert.Equal("'Something'", columns.Single(c => c.Name == "SomeText").DefaultValueSql); Assert.Equal("3.14", columns.Single(c => c.Name == "RealColumn").DefaultValueSql); Assert.Equal("'October 20, 2015 11am'", columns.Single(c => c.Name == "Created").DefaultValueSql); }, @"DROP TABLE IF EXISTS DefaultValue;"); } [Theory(Skip = "Issue #582")] [InlineData("DOUBLE NOT NULL DEFAULT 0")] [InlineData("FLOAT NOT NULL DEFAULT 0")] [InlineData("INT NOT NULL DEFAULT 0")] [InlineData("INTEGER NOT NULL DEFAULT 0")] [InlineData("REAL NOT NULL DEFAULT 0")] [InlineData("NULL DEFAULT NULL")] [InlineData("NOT NULL DEFAULT NULL")] public void Column_default_value_is_ignored_when_clr_default(string columnSql) { Test( $"CREATE TABLE DefaultValueClr (IgnoredDefault {columnSql})", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var column = Assert.Single(Assert.Single(dbModel.Tables).Columns); Assert.Null(column.DefaultValueSql); }, "DROP TABLE IF EXISTS DefaultValueClr"); } [ConditionalFact] [SupportedServerVersionCondition(nameof(ServerVersionSupport.GeneratedColumns))] public void Computed_value_virtual() => Test(@" CREATE TABLE `ComputedValues` ( `Id` int, `A` int NOT NULL, `B` int NOT NULL, `SumOfAAndB` int GENERATED ALWAYS AS (`A` + `B`) VIRTUAL );", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var columns = dbModel.Tables.Single().Columns; var column = columns.Single(c => c.Name == "SumOfAAndB"); Assert.Null(column.DefaultValueSql); Assert.Equal(@"`A` + `B`", column.ComputedColumnSql); Assert.False(column.IsStored); }, @"DROP TABLE IF EXISTS `ComputedValues`"); [ConditionalFact] [SupportedServerVersionCondition(nameof(ServerVersionSupport.GeneratedColumns))] public void Computed_value_stored() => Test(@" CREATE TABLE `ComputedValues` ( `Id` int, `A` int NOT NULL, `B` int NOT NULL, `SumOfAAndB` int GENERATED ALWAYS AS (`A` + `B`) STORED );", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var columns = dbModel.Tables.Single().Columns; var column = columns.Single(c => c.Name == "SumOfAAndB"); Assert.Null(column.DefaultValueSql); Assert.Equal(@"`A` + `B`", column.ComputedColumnSql); Assert.True(column.IsStored); }, @"DROP TABLE IF EXISTS `ComputedValues`"); [ConditionalFact] [SupportedServerVersionCondition(nameof(ServerVersionSupport.GeneratedColumns))] public void Computed_value_virtual_using_constant_string() => Test(@" CREATE TABLE `Users` ( `id` int NOT NULL AUTO_INCREMENT, `FirstName` varchar(150) NOT NULL, `LastName` varchar(150) NOT NULL, `FullName` varchar(301) GENERATED ALWAYS AS (concat(`FirstName`, _utf8mb4' ', `LastName`)) VIRTUAL, PRIMARY KEY (`id`) );", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var columns = dbModel.Tables.Single().Columns; var column = columns.Single(c => c.Name == "FullName"); Assert.Equal(@"concat(`FirstName`,_utf8mb4' ',`LastName`)", column.ComputedColumnSql); Assert.False(column.IsStored); }, @"DROP TABLE IF EXISTS `Users`"); [ConditionalFact] [SupportedServerVersionCondition(nameof(ServerVersionSupport.AlternativeDefaultExpression))] public void Default_value_curdate_mariadb() { // MariaDB allows to use `curdate()` as a default value, while MySQL doesn't. Test( @" CREATE TABLE `IceCreams` ( `IceCreamId` int, `Name` varchar(255) NOT NULL, `BestServedBefore` datetime DEFAULT curdate() );", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var columns = dbModel.Tables.Single() .Columns; var column = columns.Single(c => c.Name == "BestServedBefore"); Assert.Equal(@"curdate()", column.DefaultValueSql); }, @"DROP TABLE IF EXISTS `IceCreams`"); } #endregion #region PrimaryKeyFacets [Fact(Skip = "Issue #582")] public void Create_composite_primary_key() { Test( @" CREATE TABLE CompositePrimaryKey ( Id1 int, Id2 text, PRIMARY KEY ( Id2, Id1 ) );", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var pk = dbModel.Tables.Single().PrimaryKey; Assert.Equal("CompositePrimaryKey", pk.Table.Name); Assert.Equal(new List<string> { "Id2", "Id1" }, pk.Columns.Select(ic => ic.Name).ToList()); }, @"DROP TABLE IF EXISTS CompositePrimaryKey;"); } [Fact(Skip = "Issue #582")] public void Create_primary_key_when_integer_primary_key_alised_to_rowid() { Test( @" CREATE TABLE RowidPrimaryKey ( Id integer PRIMARY KEY );", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var pk = dbModel.Tables.Single().PrimaryKey; Assert.Equal("RowidPrimaryKey", pk.Table.Name); Assert.Equal(new List<string> { "Id" }, pk.Columns.Select(ic => ic.Name).ToList()); }, @"DROP TABLE IF EXISTS RowidPrimaryKey;"); } [Fact(Skip = "Issue #582")] public void Set_name_for_primary_key() { Test( @" CREATE TABLE PrimaryKeyName ( Id int, CONSTRAINT PK PRIMARY KEY (Id) );", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var pk = dbModel.Tables.Single().PrimaryKey; Assert.Equal("PrimaryKeyName", pk.Table.Name); Assert.Equal("PK", pk.Name); Assert.Equal(new List<string> { "Id" }, pk.Columns.Select(ic => ic.Name).ToList()); }, @"DROP TABLE IF EXISTS PrimaryKeyName;"); } [Fact] public void Prefix_lengths_for_primary_key() { Test( @" CREATE TABLE `IceCreams` ( `Brand` longtext NOT NULL, `Name` varchar(128) NOT NULL, PRIMARY KEY (`Name`, `Brand`(20)) );", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var pk = dbModel.Tables.Single().PrimaryKey; Assert.Equal("IceCreams", pk.Table.Name, StringComparer.OrdinalIgnoreCase); Assert.Equal(2, pk.Columns.Count); Assert.Equal("Name", pk.Columns[0].Name, StringComparer.OrdinalIgnoreCase); Assert.Equal("Brand", pk.Columns[1].Name, StringComparer.OrdinalIgnoreCase); Assert.Equal(new [] { 0, 20 }, pk.FindAnnotation(MySqlAnnotationNames.IndexPrefixLength)?.Value); }, @"DROP TABLE IF EXISTS `IceCreams`;"); } [Fact] public void Column_srid_value_is_set() { Test( @" CREATE TABLE `IceCreamShop` ( `IceCreamShopId` int NOT NULL, `Location` geometry NOT NULL /*!80003 SRID 0 */, PRIMARY KEY (`IceCreamShopId`) );", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var columns = dbModel.Tables.Single().Columns; if (AppConfig.ServerVersion.Supports.SpatialReferenceSystemRestrictedColumns) { Assert.Equal( 0, columns.Single(c => c.Name == "Location") .FindAnnotation(MySqlAnnotationNames.SpatialReferenceSystemId) ?.Value); } else { Assert.Null( columns.Single(c => c.Name == "Location") .FindAnnotation(MySqlAnnotationNames.SpatialReferenceSystemId) ?.Value); } }, @"DROP TABLE IF EXISTS `IceCreamShop`;"); } #endregion #region UniqueConstraintFacets [Fact(Skip = "Issue #582")] public void Create_composite_unique_constraint() { Test( @" CREATE TABLE CompositeUniqueConstraint ( Id1 int, Id2 text, UNIQUE ( Id2, Id1 ) );", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var constraint = Assert.Single(dbModel.Tables.Single().UniqueConstraints); // ReSharper disable once PossibleNullReferenceException Assert.Equal("CompositeUniqueConstraint", constraint.Table.Name); Assert.Equal(new List<string> { "Id2", "Id1" }, constraint.Columns.Select(ic => ic.Name).ToList()); }, @"DROP TABLE IF EXISTS CompositeUniqueConstraint;"); } [Fact(Skip = "Issue #582")] public void Set_name_for_unique_constraint() { Test( @" CREATE TABLE UniqueConstraintName ( Id int, CONSTRAINT UK UNIQUE (Id) );", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var constraint = Assert.Single(dbModel.Tables.Single().UniqueConstraints); // ReSharper disable once PossibleNullReferenceException Assert.Equal("UniqueConstraintName", constraint.Table.Name); Assert.Equal("UK", constraint.Name); Assert.Equal(new List<string> { "Id" }, constraint.Columns.Select(ic => ic.Name).ToList()); }, @"DROP TABLE IF EXISTS UniqueConstraintName;"); } #endregion #region IndexFacets [Fact(Skip = "Issue #582")] public void Create_composite_index() { Test( @" CREATE TABLE CompositeIndex ( Id1 int, Id2 text ); CREATE INDEX IX_COMPOSITE on CompositeIndex (Id2, Id1);", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var index = Assert.Single(dbModel.Tables.Single().Indexes); // ReSharper disable once PossibleNullReferenceException Assert.Equal("CompositeIndex", index.Table.Name); Assert.Equal("IX_COMPOSITE", index.Name); Assert.Equal(new List<string> { "Id2", "Id1" }, index.Columns.Select(ic => ic.Name).ToList()); }, @"DROP TABLE IF EXISTS CompositeIndex;"); } [Fact(Skip = "Issue #582")] public void Set_unique_for_unique_index() { Test( @" CREATE TABLE UniqueIndex ( Id1 int, Id2 text ); CREATE UNIQUE INDEX IX_UNIQUE on UniqueIndex (Id2);", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var index = Assert.Single(dbModel.Tables.Single().Indexes); // ReSharper disable once PossibleNullReferenceException Assert.Equal("UniqueIndex", index.Table.Name); Assert.Equal("IX_UNIQUE", index.Name); Assert.True(index.IsUnique); Assert.Equal(new List<string> { "Id2" }, index.Columns.Select(ic => ic.Name).ToList()); }, @"DROP TABLE IF EXISTS UniqueIndex;"); } [Fact] public void Prefix_lengths_for_index() { Test( @" CREATE TABLE `IceCreams` ( `IceCreamId` int NOT NULL, `Brand` longtext NOT NULL, `Name` varchar(128) NOT NULL, PRIMARY KEY (`IceCreamId`) ); CREATE INDEX `IX_IceCreams_Brand_Name` ON `IceCreams` (`Name`, `Brand`(20)); ", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var index = Assert.Single(dbModel.Tables.Single().Indexes); Assert.Equal("IceCreams", index.Table.Name, StringComparer.OrdinalIgnoreCase); Assert.Equal("IX_IceCreams_Brand_Name", index.Name, StringComparer.OrdinalIgnoreCase); Assert.Equal(2, index.Columns.Count); Assert.Equal("Name", index.Columns[0].Name, StringComparer.OrdinalIgnoreCase); Assert.Equal("Brand", index.Columns[1].Name, StringComparer.OrdinalIgnoreCase); Assert.Equal(new [] { 0, 20 }, index.FindAnnotation(MySqlAnnotationNames.IndexPrefixLength)?.Value); }, @"DROP TABLE IF EXISTS `IceCreams`;"); } [Fact] public void Prefix_lengths_for_multiple_indexes_same_colums() { Test( @" CREATE TABLE `IceCreams` ( `IceCreamId` int NOT NULL, `Brand` varchar(128) NOT NULL, `Name` varchar(128) NOT NULL, PRIMARY KEY (`IceCreamId`) ); CREATE INDEX `IX_IceCreams_Brand_Name_1` ON `IceCreams` (`Name`, `Brand`(20)); CREATE UNIQUE INDEX `IX_IceCreams_Brand_Name_2` ON `IceCreams` (`Brand`(40), `Name`(120)); ", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var index = Assert.Single(dbModel.Tables.Single().Indexes); Assert.Equal("IceCreams", index.Table.Name, StringComparer.OrdinalIgnoreCase); Assert.Equal("IX_IceCreams_Brand_Name_1", index.Name, StringComparer.OrdinalIgnoreCase); Assert.True(index.IsUnique); Assert.Equal(2, index.Columns.Count); Assert.Equal("Name", index.Columns[0].Name, StringComparer.OrdinalIgnoreCase); Assert.Equal("Brand", index.Columns[1].Name, StringComparer.OrdinalIgnoreCase); Assert.Equal(new [] { 0, 40 }, index[MySqlAnnotationNames.IndexPrefixLength]); }, @"DROP TABLE IF EXISTS `IceCreams`;"); } [Fact] public void Prefix_lengths_for_multiple_indexes_same_columns_without_prefix_lengths() { Test( @" CREATE TABLE `IceCreams` ( `IceCreamId` int NOT NULL, `Brand` varchar(128) NOT NULL, `Name` varchar(128) NOT NULL, PRIMARY KEY (`IceCreamId`) ); CREATE INDEX `IX_IceCreams_Brand_Name_1` ON `IceCreams` (`Name`(120), `Brand`(20)); CREATE UNIQUE INDEX `IX_IceCreams_Brand_Name_2` ON `IceCreams` (`Brand`, `Name`); ", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var index = Assert.Single(dbModel.Tables.Single().Indexes); Assert.Equal("IceCreams", index.Table.Name, StringComparer.OrdinalIgnoreCase); Assert.Equal("IX_IceCreams_Brand_Name_1", index.Name, StringComparer.OrdinalIgnoreCase); Assert.True(index.IsUnique); Assert.Equal(2, index.Columns.Count); Assert.Equal("Name", index.Columns[0].Name, StringComparer.OrdinalIgnoreCase); Assert.Equal("Brand", index.Columns[1].Name, StringComparer.OrdinalIgnoreCase); Assert.Null(index[MySqlAnnotationNames.IndexPrefixLength]); }, @"DROP TABLE IF EXISTS `IceCreams`;"); } [Fact] public void Set_fulltext_for_fulltext_index() { Test( @" CREATE TABLE `IceCreams` ( `IceCreamId` int NOT NULL, `Name` varchar(255) NOT NULL, PRIMARY KEY (`IceCreamId`) ); CREATE FULLTEXT INDEX `IX_IceCreams_Name` ON `IceCreams` (`Name`);", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var index = Assert.Single(dbModel.Tables.Single().Indexes); Assert.Equal("IceCreams", index.Table.Name, StringComparer.OrdinalIgnoreCase); Assert.Equal(1, index.Columns.Count); Assert.Equal("Name", index.Columns[0].Name, StringComparer.OrdinalIgnoreCase); Assert.Equal(true, index.FindAnnotation(MySqlAnnotationNames.FullTextIndex)?.Value); }, @"DROP TABLE IF EXISTS `IceCreams`;"); } [ConditionalFact] [SupportedServerVersionCondition(nameof(ServerVersionSupport.FullTextParser))] public void Set_fulltextparser_for_fulltext_index_with_parser() { Test( @" CREATE TABLE `IceCreams` ( `IceCreamId` int NOT NULL, `Name` varchar(255) NOT NULL, PRIMARY KEY (`IceCreamId`) ); CREATE FULLTEXT INDEX `IX_IceCreams_Name` ON `IceCreams` (`Name`) /*!50703 WITH PARSER `ngram` */;", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var index = Assert.Single(dbModel.Tables.Single().Indexes); Assert.Equal("IceCreams", index.Table.Name, StringComparer.OrdinalIgnoreCase); Assert.Equal(1, index.Columns.Count); Assert.Equal("Name", index.Columns[0].Name, StringComparer.OrdinalIgnoreCase); Assert.Equal(true, index.FindAnnotation(MySqlAnnotationNames.FullTextIndex)?.Value); Assert.Equal("ngram", index.FindAnnotation(MySqlAnnotationNames.FullTextParser)?.Value); }, @"DROP TABLE IF EXISTS `IceCreams`;"); } [ConditionalFact] [SupportedServerVersionCondition(nameof(ServerVersionSupport.SpatialIndexes))] public void Set_spatial_for_spatial_index() { Test( @" CREATE TABLE `IceCreamShop` ( `IceCreamShopId` int NOT NULL, `Location` geometry NOT NULL, PRIMARY KEY (`IceCreamShopId`) ); CREATE SPATIAL INDEX `IX_IceCreams_Location` ON `IceCreamShop` (`Location`);", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var index = Assert.Single(dbModel.Tables.Single().Indexes); Assert.Equal("IceCreamShop", index.Table.Name, StringComparer.OrdinalIgnoreCase); Assert.Equal(1, index.Columns.Count); Assert.Equal("Location", index.Columns[0].Name, StringComparer.OrdinalIgnoreCase); Assert.Equal(true, index.FindAnnotation(MySqlAnnotationNames.SpatialIndex)?.Value); }, @"DROP TABLE IF EXISTS `IceCreamShop`;"); } #endregion #region ForeignKeyFacets [Fact(Skip = "Issue #582")] public void Create_composite_foreign_key() { Test( @" CREATE TABLE PrincipalTable ( Id1 int, Id2 int, PRIMARY KEY (Id1, Id2) ); CREATE TABLE DependentTable ( Id int PRIMARY KEY, ForeignKeyId1 int, ForeignKeyId2 int, FOREIGN KEY (ForeignKeyId1, ForeignKeyId2) REFERENCES PrincipalTable(Id1, Id2) ON DELETE CASCADE );", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var fk = Assert.Single(dbModel.Tables.Single(t => t.Name == "DependentTable").ForeignKeys); // ReSharper disable once PossibleNullReferenceException Assert.Equal("DependentTable", fk.Table.Name); Assert.Equal("PrincipalTable", fk.PrincipalTable.Name); Assert.Equal(new List<string> { "ForeignKeyId1", "ForeignKeyId2" }, fk.Columns.Select(ic => ic.Name).ToList()); Assert.Equal(new List<string> { "Id1", "Id2" }, fk.PrincipalColumns.Select(ic => ic.Name).ToList()); Assert.Equal(ReferentialAction.Cascade, fk.OnDelete); }, @" DROP TABLE IF EXISTS DependentTable; DROP TABLE IF EXISTS PrincipalTable;"); } [Fact(Skip = "Issue #582")] public void Create_multiple_foreign_key_in_same_table() { Test( @" CREATE TABLE PrincipalTable ( Id int PRIMARY KEY ); CREATE TABLE AnotherPrincipalTable ( Id int PRIMARY KEY ); CREATE TABLE DependentTable ( Id int PRIMARY KEY, ForeignKeyId1 int, ForeignKeyId2 int, FOREIGN KEY (ForeignKeyId1) REFERENCES PrincipalTable(Id) ON DELETE CASCADE, FOREIGN KEY (ForeignKeyId2) REFERENCES AnotherPrincipalTable(Id) ON DELETE CASCADE );", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var foreignKeys = dbModel.Tables.Single(t => t.Name == "DependentTable").ForeignKeys; Assert.Equal(2, foreignKeys.Count); var principalFk = Assert.Single(foreignKeys.Where(f => f.PrincipalTable.Name == "PrincipalTable")); // ReSharper disable once PossibleNullReferenceException Assert.Equal("DependentTable", principalFk.Table.Name); Assert.Equal("PrincipalTable", principalFk.PrincipalTable.Name); Assert.Equal(new List<string> { "ForeignKeyId1" }, principalFk.Columns.Select(ic => ic.Name).ToList()); Assert.Equal(new List<string> { "Id" }, principalFk.PrincipalColumns.Select(ic => ic.Name).ToList()); Assert.Equal(ReferentialAction.Cascade, principalFk.OnDelete); var anotherPrincipalFk = Assert.Single(foreignKeys.Where(f => f.PrincipalTable.Name == "AnotherPrincipalTable")); // ReSharper disable once PossibleNullReferenceException Assert.Equal("DependentTable", anotherPrincipalFk.Table.Name); Assert.Equal("AnotherPrincipalTable", anotherPrincipalFk.PrincipalTable.Name); Assert.Equal(new List<string> { "ForeignKeyId2" }, anotherPrincipalFk.Columns.Select(ic => ic.Name).ToList()); Assert.Equal(new List<string> { "Id" }, anotherPrincipalFk.PrincipalColumns.Select(ic => ic.Name).ToList()); Assert.Equal(ReferentialAction.Cascade, anotherPrincipalFk.OnDelete); }, @" DROP TABLE IF EXISTS DependentTable; DROP TABLE IF EXISTS AnotherPrincipalTable; DROP TABLE IF EXISTS PrincipalTable;"); } [Fact(Skip = "Issue #582")] public void Create_foreign_key_referencing_unique_constraint() { Test( @" CREATE TABLE PrincipalTable ( Id1 int, Id2 int UNIQUE ); CREATE TABLE DependentTable ( Id int PRIMARY KEY, ForeignKeyId int, FOREIGN KEY (ForeignKeyId) REFERENCES PrincipalTable(Id2) ON DELETE CASCADE );", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var fk = Assert.Single(dbModel.Tables.Single(t => t.Name == "DependentTable").ForeignKeys); // ReSharper disable once PossibleNullReferenceException Assert.Equal("DependentTable", fk.Table.Name); Assert.Equal("PrincipalTable", fk.PrincipalTable.Name); Assert.Equal(new List<string> { "ForeignKeyId" }, fk.Columns.Select(ic => ic.Name).ToList()); Assert.Equal(new List<string> { "Id2" }, fk.PrincipalColumns.Select(ic => ic.Name).ToList()); Assert.Equal(ReferentialAction.Cascade, fk.OnDelete); }, @" DROP TABLE IF EXISTS DependentTable; DROP TABLE IF EXISTS PrincipalTable;"); } [Fact(Skip = "Issue #582")] public void Set_name_for_foreign_key() { Test( @" CREATE TABLE PrincipalTable ( Id int PRIMARY KEY ); CREATE TABLE DependentTable ( Id int PRIMARY KEY, ForeignKeyId int, CONSTRAINT MYFK FOREIGN KEY (ForeignKeyId) REFERENCES PrincipalTable(Id) ON DELETE CASCADE );", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var fk = Assert.Single(dbModel.Tables.Single(t => t.Name == "DependentTable").ForeignKeys); // ReSharper disable once PossibleNullReferenceException Assert.Equal("DependentTable", fk.Table.Name); Assert.Equal("PrincipalTable", fk.PrincipalTable.Name); Assert.Equal(new List<string> { "ForeignKeyId" }, fk.Columns.Select(ic => ic.Name).ToList()); Assert.Equal(new List<string> { "Id" }, fk.PrincipalColumns.Select(ic => ic.Name).ToList()); Assert.Equal(ReferentialAction.Cascade, fk.OnDelete); Assert.Equal("MYFK", fk.Name); }, @" DROP TABLE IF EXISTS DependentTable; DROP TABLE IF EXISTS PrincipalTable;"); } [Fact(Skip = "Issue #582")] public void Set_referential_action_for_foreign_key() { Test( @" CREATE TABLE PrincipalTable ( Id int PRIMARY KEY ); CREATE TABLE DependentTable ( Id int PRIMARY KEY, ForeignKeyId int, FOREIGN KEY (ForeignKeyId) REFERENCES PrincipalTable(Id) ON DELETE SET NULL );", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var fk = Assert.Single(dbModel.Tables.Single(t => t.Name == "DependentTable").ForeignKeys); // ReSharper disable once PossibleNullReferenceException Assert.Equal("DependentTable", fk.Table.Name); Assert.Equal("PrincipalTable", fk.PrincipalTable.Name); Assert.Equal(new List<string> { "ForeignKeyId" }, fk.Columns.Select(ic => ic.Name).ToList()); Assert.Equal(new List<string> { "Id" }, fk.PrincipalColumns.Select(ic => ic.Name).ToList()); Assert.Equal(ReferentialAction.SetNull, fk.OnDelete); }, @" DROP TABLE IF EXISTS DependentTable; DROP TABLE IF EXISTS PrincipalTable;"); } [Fact] public void Ensure_constraints_scaffold_with_case_mismatch() { // The lower case table reference to a mixed cased table will only be accepted under certain conditions // (lower_case_table_names <> 0). Test( @" CREATE TABLE `PrincipalTable` ( `Id` INT NOT NULL, PRIMARY KEY (`Id`)); set @sql = concat(' CREATE TABLE `DependentTable` ( `Id` INT NOT NULL, `ForeignKeyId` INT NOT NULL, PRIMARY KEY (`Id`), CONSTRAINT `ForeignKey_Id` FOREIGN KEY (`ForeignKeyId`) REFERENCES `', IF(@@lower_case_table_names <> 0, LOWER('PrincipalTable'), 'PrincipalTable'), '` (`Id`) )'); PREPARE dynamic_statement FROM @sql; EXECUTE dynamic_statement; DEALLOCATE PREPARE dynamic_statement;", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var principal = dbModel.Tables.FirstOrDefault(t => string.Equals(t.Name, "PrincipalTable", StringComparison.OrdinalIgnoreCase)); var dependent = dbModel.Tables.FirstOrDefault(t => string.Equals(t.Name, "DependentTable", StringComparison.OrdinalIgnoreCase)); Assert.NotNull(principal); Assert.NotNull(dependent); Assert.Contains(dependent.ForeignKeys, t => t.PrincipalTable.Name == principal.Name); }, @" DROP TABLE IF EXISTS DependentTable; DROP TABLE IF EXISTS PrincipalTable;" ); } #endregion #region Warnings [Fact(Skip = "Issue #582")] public void Warn_for_schema_filtering() { Test( @"CREATE TABLE Everest ( id int );", Enumerable.Empty<string>(), new[] { "dbo" }, dbModel => { var (Level, Id, Message) = Assert.Single(Log.Where(t => t.Level == LogLevel.Warning)); }, @"DROP TABLE IF EXISTS Everest;"); } [Fact(Skip = "Issue #582")] public void Warn_missing_table() { Test( @"CREATE TABLE Blank ( Id int );", new[] { "MyTable" }, Enumerable.Empty<string>(), dbModel => { Assert.Empty(dbModel.Tables); var (Level, Id, Message) = Assert.Single(Log.Where(t => t.Level == LogLevel.Warning)); }, @"DROP TABLE IF EXISTS Blank;"); } [Fact(Skip = "Issue #582")] public void Warn_missing_principal_table_for_foreign_key() { Test( @" CREATE TABLE PrincipalTable ( Id int PRIMARY KEY ); CREATE TABLE DependentTable ( Id int PRIMARY KEY, ForeignKeyId int, CONSTRAINT MYFK FOREIGN KEY (ForeignKeyId) REFERENCES PrincipalTable(Id) ON DELETE CASCADE );", new[] { "DependentTable" }, Enumerable.Empty<string>(), dbModel => { var (Level, Id, Message) = Assert.Single(Log.Where(t => t.Level == LogLevel.Warning)); }, @" DROP TABLE IF EXISTS DependentTable; DROP TABLE IF EXISTS PrincipalTable;"); } [Fact(Skip = "Issue #582")] public void Warn_missing_principal_column_for_foreign_key() { Test( @" CREATE TABLE PrincipalTable ( Id int PRIMARY KEY ); CREATE TABLE DependentTable ( Id int PRIMARY KEY, ForeignKeyId int, CONSTRAINT MYFK FOREIGN KEY (ForeignKeyId) REFERENCES PrincipalTable(ImaginaryId) ON DELETE CASCADE );", Enumerable.Empty<string>(), Enumerable.Empty<string>(), dbModel => { var (Level, Id, Message) = Assert.Single(Log.Where(t => t.Level == LogLevel.Warning)); }, @" DROP TABLE IF EXISTS DependentTable; DROP TABLE IF EXISTS PrincipalTable;"); } #endregion public class MySqlDatabaseModelFixture : SharedStoreFixtureBase<PoolableDbContext> { protected override string StoreName { get; } = nameof(MySqlDatabaseModelFactoryTest); protected override ITestStoreFactory TestStoreFactory => MySqlTestStoreFactory.Instance; public new MySqlTestStore TestStore => (MySqlTestStore)base.TestStore; protected override bool ShouldLogCategory(string logCategory) => logCategory == DbLoggerCategory.Scaffolding.Name; } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Pathoschild.Stardew.Common; using Pathoschild.Stardew.Common.UI; using Pathoschild.Stardew.DataLayers.Framework.Components; using StardewModdingAPI; using StardewModdingAPI.Events; using StardewValley; using StardewValley.Menus; namespace Pathoschild.Stardew.DataLayers.Framework { /// <summary>Renders a data layer over the world.</summary> internal class DataLayerOverlay : BaseOverlay { /********* ** Fields *********/ /***** ** Constants and config *****/ /// <summary>The pixel margin above the displayed legend.</summary> private readonly int TopMargin = 30; /// <summary>The pixel margin left of the displayed legend.</summary> private readonly int LeftMargin = 15; /// <summary>The number of pixels between the arrows and label.</summary> private readonly int ArrowPadding = 10; /// <summary>Get whether the overlay should be drawn.</summary> private readonly Func<bool> DrawOverlay; /***** ** Layer state *****/ /// <summary>The available data layers.</summary> private readonly ILayer[] Layers; /// <summary>The legend entries to show.</summary> private LegendEntry[] LegendEntries; /***** ** Grid state *****/ /// <summary>When two groups of the same color overlap, draw one border around their edges instead of their individual borders.</summary> private readonly bool CombineOverlappingBorders; /// <summary>An empty set of tiles.</summary> private readonly Vector2[] EmptyTiles = Array.Empty<Vector2>(); /// <summary>An empty set of tile groups.</summary> private readonly TileGroup[] EmptyTileGroups = Array.Empty<TileGroup>(); /// <summary>The visible tiles.</summary> private Vector2[] VisibleTiles; /// <summary>The tile layer data to render.</summary> private TileGroup[] TileGroups; /// <summary>The tick countdown until the next layer update.</summary> private int UpdateCountdown; /// <summary>Whether to show a tile grid by default.</summary> private readonly bool ShowGrid; /// <summary>The width of grid lines between tiles, if enabled.</summary> private readonly int GridBorderSize = 1; /// <summary>The color of grid lines between tiles, if enabled.</summary> private readonly Color GridColor = Color.Black; /***** ** UI state *****/ /// <summary>The last visible area.</summary> private Rectangle LastVisibleArea; /// <summary>Whether the game was paused last time the menu was updated.</summary> private bool WasPaused; /***** ** Components *****/ /// <summary>The UI component for the layer title and legend.</summary> private LegendComponent Legend; /// <summary>The clickable 'previous layer' icon.</summary> private ClickableTextureComponent PrevButton; /// <summary>The clickable 'next layer' icon.</summary> private ClickableTextureComponent NextButton; /********* ** Accessors *********/ /// <summary>The current layer being rendered.</summary> public ILayer CurrentLayer { get; private set; } /********* ** Public methods *********/ /// <summary>Construct an instance.</summary> /// <param name="events">The SMAPI events available for mods.</param> /// <param name="inputHelper">An API for checking and changing input state.</param> /// <param name="reflection">Simplifies access to private code.</param> /// <param name="layers">The data layers to render.</param> /// <param name="drawOverlay">Get whether the overlay should be drawn.</param> /// <param name="combineOverlappingBorders">When two groups of the same color overlap, draw one border around their edges instead of their individual borders.</param> /// <param name="showGrid">Whether to show a tile grid when a layer is open.</param> public DataLayerOverlay(IModEvents events, IInputHelper inputHelper, IReflectionHelper reflection, ILayer[] layers, Func<bool> drawOverlay, bool combineOverlappingBorders, bool showGrid) : base(events, inputHelper, reflection, assumeUiMode: true) { if (!layers.Any()) throw new InvalidOperationException("Can't initialize the data layers overlay with no data layers."); this.Layers = layers.OrderBy(p => p.Name).ToArray(); this.DrawOverlay = drawOverlay; this.CombineOverlappingBorders = combineOverlappingBorders; this.ShowGrid = showGrid; this.SetLayer(this.Layers.First()); } /// <summary>Switch to the next data layer.</summary> public void NextLayer() { int index = Array.IndexOf(this.Layers, this.CurrentLayer) + 1; if (index >= this.Layers.Length) index = 0; this.SetLayer(this.Layers[index]); } /// <summary>Switch to the previous data layer.</summary> public void PrevLayer() { int index = Array.IndexOf(this.Layers, this.CurrentLayer) - 1; if (index < 0) index = this.Layers.Length - 1; this.SetLayer(this.Layers[index]); } /// <summary>Switch to the data layer with the given ID, if any.</summary> /// <param name="id">The layer ID.</param> public void TrySetLayer(string id) { if (id == null) return; ILayer layer = this.Layers.FirstOrDefault(p => p.Id == id); if (layer != null) this.SetLayer(layer); } /// <summary>Switch to the given data layer.</summary> /// <param name="layer">The data layer to select.</param> public void SetLayer(ILayer layer) { this.CurrentLayer = layer; this.LegendEntries = this.CurrentLayer.Legend.ToArray(); this.TileGroups = this.EmptyTileGroups; this.UpdateCountdown = 0; this.ReinitializeComponents(); } /// <summary>Update the overlay.</summary> public void Update() { // move UI if it overlaps pause message if (this.WasPaused != Game1.HostPaused) { this.WasPaused = Game1.HostPaused; this.ReinitializeComponents(); } // get updated tiles if (Game1.currentLocation == null || this.CurrentLayer == null) { this.VisibleTiles = this.EmptyTiles; this.TileGroups = this.EmptyTileGroups; } else { Rectangle visibleArea = TileHelper.GetVisibleArea(expand: 1); if (--this.UpdateCountdown <= 0 || (this.CurrentLayer.UpdateWhenVisibleTilesChange && visibleArea != this.LastVisibleArea)) { GameLocation location = Game1.currentLocation; Vector2 cursorTile = TileHelper.GetTileFromCursor(); this.VisibleTiles = visibleArea.GetTiles().ToArray(); this.TileGroups = this.CurrentLayer.Update(location, visibleArea, this.VisibleTiles, cursorTile).ToArray(); this.LastVisibleArea = visibleArea; this.UpdateCountdown = this.CurrentLayer.UpdateTickRate; } } } /********* ** Protected methods *********/ /// <inheritdoc /> protected override bool ReceiveCursorHover(int x, int y) { this.PrevButton.tryHover(x, y); this.NextButton.tryHover(x, y); return this.PrevButton.containsPoint(x, y) || this.NextButton.containsPoint(x, y); } /// <inheritdoc /> protected override bool ReceiveLeftClick(int x, int y) { if (this.PrevButton.containsPoint(x, y)) { this.PrevLayer(); return true; } if (this.NextButton.containsPoint(x, y)) { this.NextLayer(); return true; } return base.ReceiveLeftClick(x, y); } /// <inheritdoc /> protected override void DrawWorld(SpriteBatch spriteBatch) { if (!this.DrawOverlay()) return; int tileSize = Game1.tileSize; const int borderSize = 4; IDictionary<Vector2, TileDrawData> tiles = this.AggregateTileData(this.TileGroups, this.CombineOverlappingBorders); foreach (Vector2 tilePos in this.VisibleTiles) { Vector2 pixelPosition = tilePos * tileSize - new Vector2(Game1.viewport.X, Game1.viewport.Y); // draw tile data bool hasLeftBorder = false, hasRightBorder = false, hasTopBorder = false, hasBottomBorder = false; int gridSize = this.ShowGrid || this.CurrentLayer.AlwaysShowGrid ? this.GridBorderSize : 0; if (tiles.TryGetValue(tilePos, out TileDrawData tile)) { // draw overlay foreach (Color color in tile.Colors) spriteBatch.Draw(CommonHelper.Pixel, new Rectangle((int)pixelPosition.X, (int)pixelPosition.Y, tileSize, tileSize), color * .3f); // draw group borders foreach (Color color in tile.BorderColors.Keys) { TileEdge edges = tile.BorderColors[color]; int leftBorderSize = edges.HasFlag(TileEdge.Left) ? borderSize : gridSize; int rightBorderSize = edges.HasFlag(TileEdge.Right) ? borderSize : gridSize; int topBorderSize = edges.HasFlag(TileEdge.Top) ? borderSize : gridSize; int bottomBorderSize = edges.HasFlag(TileEdge.Bottom) ? borderSize : gridSize; hasLeftBorder = this.DrawBorder(spriteBatch, pixelPosition, TileEdge.Left, color, leftBorderSize); hasRightBorder = this.DrawBorder(spriteBatch, pixelPosition, TileEdge.Right, color, rightBorderSize); hasTopBorder = this.DrawBorder(spriteBatch, pixelPosition, TileEdge.Top, color, topBorderSize); hasBottomBorder = this.DrawBorder(spriteBatch, pixelPosition, TileEdge.Bottom, color, bottomBorderSize); } } // draw grid if (gridSize > 0) { Color color = (tile?.Colors.First() ?? this.GridColor) * 0.5f; int width = this.GridBorderSize; if (!hasLeftBorder) this.DrawBorder(spriteBatch, pixelPosition, TileEdge.Left, color, width); if (!hasRightBorder) this.DrawBorder(spriteBatch, pixelPosition, TileEdge.Right, color, width); if (!hasTopBorder) this.DrawBorder(spriteBatch, pixelPosition, TileEdge.Top, color, width); if (!hasBottomBorder) this.DrawBorder(spriteBatch, pixelPosition, TileEdge.Bottom, color, width); } } } /// <inheritdoc /> protected override void DrawUi(SpriteBatch batch) { // draw top-left UI if (this.DrawOverlay() && Game1.displayHUD) { this.Legend.Draw(batch); this.PrevButton.draw(batch); this.NextButton.draw(batch); } } /// <summary>Reinitialize the UI components.</summary> private void ReinitializeComponents() { // move UI to avoid covering 'paused' message (which has a hardcoded size) int topMargin = this.TopMargin; if (Game1.HostPaused) topMargin += 96; // init UI var leftArrow = CommonSprites.Icons.LeftArrow; var rightArrow = CommonSprites.Icons.RightArrow; this.PrevButton = new ClickableTextureComponent(new Rectangle(this.LeftMargin, this.TopMargin + 10, leftArrow.Width, leftArrow.Height), CommonSprites.Icons.Sheet, leftArrow, 1); this.Legend = new LegendComponent(this.PrevButton.bounds.Right + this.ArrowPadding, topMargin, this.Layers, this.CurrentLayer.Name, this.LegendEntries); this.NextButton = new ClickableTextureComponent(new Rectangle(this.Legend.bounds.Right + this.ArrowPadding, this.TopMargin + 10, rightArrow.Width, rightArrow.Height), CommonSprites.Icons.Sheet, rightArrow, 1); } /// <summary>Draw a tile border.</summary> /// <param name="spriteBatch">The sprite batch to which to draw.</param> /// <param name="origin">The top-left pixel position of the tile relative to the screen.</param> /// <param name="edge">The tile edge to draw.</param> /// <param name="color">The border color.</param> /// <param name="width">The border width.</param> /// <returns>Returns whether a border was drawn. This may return false if the width is zero, or the edge is invalid.</returns> private bool DrawBorder(SpriteBatch spriteBatch, Vector2 origin, TileEdge edge, Color color, int width) { if (width <= 0) return false; switch (edge) { case TileEdge.Left: spriteBatch.Draw(CommonHelper.Pixel, new Rectangle((int)origin.X, (int)origin.Y, width, Game1.tileSize), color); return true; case TileEdge.Right: spriteBatch.Draw(CommonHelper.Pixel, new Rectangle((int)(origin.X + Game1.tileSize - width), (int)origin.Y, width, Game1.tileSize), color); return true; case TileEdge.Top: spriteBatch.Draw(CommonHelper.Pixel, new Rectangle((int)origin.X, (int)origin.Y, Game1.tileSize, width), color); return true; case TileEdge.Bottom: spriteBatch.Draw(CommonHelper.Pixel, new Rectangle((int)origin.X, (int)(origin.Y + Game1.tileSize - width), Game1.tileSize, width), color); return true; } return false; } /// <summary>Aggregate tile data to draw.</summary> /// <param name="groups">The tile groups to draw.</param> /// <param name="combineOverlappingBorders">When two groups of the same color overlap, draw one border around their edges instead of their individual borders.</param> private IDictionary<Vector2, TileDrawData> AggregateTileData(IEnumerable<TileGroup> groups, bool combineOverlappingBorders) { // collect tile details IDictionary<Vector2, TileDrawData> tiles = new Dictionary<Vector2, TileDrawData>(); foreach (TileGroup group in groups) { Lazy<HashSet<Vector2>> inGroupLazy = new Lazy<HashSet<Vector2>>(() => new HashSet<Vector2>(group.Tiles.Select(p => p.TilePosition))); foreach (TileData groupTile in group.Tiles) { // get tile data Vector2 position = groupTile.TilePosition; if (!tiles.TryGetValue(position, out TileDrawData data)) data = tiles[position] = new TileDrawData(position); // update data data.Colors.Add(groupTile.Color); if (group.OuterBorderColor.HasValue && !data.BorderColors.ContainsKey(group.OuterBorderColor.Value)) data.BorderColors[group.OuterBorderColor.Value] = TileEdge.None; // we'll detect combined borders next // detect borders (if not combined) if (!combineOverlappingBorders && group.OuterBorderColor.HasValue) { Color borderColor = group.OuterBorderColor.Value; int x = (int)groupTile.TilePosition.X; int y = (int)groupTile.TilePosition.Y; HashSet<Vector2> inGroup = inGroupLazy.Value; TileEdge edge = data.BorderColors[borderColor]; if (!inGroup.Contains(new Vector2(x - 1, y))) edge |= TileEdge.Left; if (!inGroup.Contains(new Vector2(x + 1, y))) edge |= TileEdge.Right; if (!inGroup.Contains(new Vector2(x, y - 1))) edge |= TileEdge.Top; if (!inGroup.Contains(new Vector2(x, y + 1))) edge |= TileEdge.Bottom; data.BorderColors[borderColor] = edge; } } } // detect color borders if (combineOverlappingBorders) { foreach (Vector2 position in tiles.Keys) { // get tile int x = (int)position.X; int y = (int)position.Y; TileDrawData data = tiles[position]; if (!data.BorderColors.Any()) continue; // get neighbors tiles.TryGetValue(new Vector2(x - 1, y), out TileDrawData left); tiles.TryGetValue(new Vector2(x + 1, y), out TileDrawData right); tiles.TryGetValue(new Vector2(x, y - 1), out TileDrawData top); tiles.TryGetValue(new Vector2(x, y + 1), out TileDrawData bottom); // detect edges foreach (Color color in data.BorderColors.Keys.ToArray()) { if (left == null || !left.BorderColors.ContainsKey(color)) data.BorderColors[color] |= TileEdge.Left; if (right == null || !right.BorderColors.ContainsKey(color)) data.BorderColors[color] |= TileEdge.Right; if (top == null || !top.BorderColors.ContainsKey(color)) data.BorderColors[color] |= TileEdge.Top; if (bottom == null || !bottom.BorderColors.ContainsKey(color)) data.BorderColors[color] |= TileEdge.Bottom; } } } return tiles; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using App.Metrics; using App.Metrics.Counter; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Newtonsoft.Json; using Tweek.Publishing.Service.Model.Hooks; using Tweek.Publishing.Service.Model.Rules; namespace Tweek.Publishing.Helpers { using KeyPathsDictionary = Dictionary<Hook, HashSet<string>>; public class HooksHelper { private readonly IMetrics _metrics; private readonly ILogger _logger; private readonly Func<string, Task<string>> _git; private readonly TriggerHooksHelper _triggerHelper; private readonly Regex _keysRegex; private readonly CounterOptions _hooksMetric = new CounterOptions {Context = "publishing", Name = "hooks"}; private readonly MetricTags _metricsFailure = new MetricTags("Status", "Failure"); private readonly string[] _postCommitHookTypes = {"notification_webhook"}; public HooksHelper(Func<string, Task<string>> gitExecutor, TriggerHooksHelper triggerHelper, IMetrics metrics, ILogger logger = null) { _logger = logger ?? NullLogger.Instance; _git = gitExecutor; _metrics = metrics; _triggerHelper = triggerHelper; _keysRegex = new Regex(@"(?:implementations/jpad/|manifests/)(.*)\..*", RegexOptions.Compiled); } public async Task TriggerPostCommitHooks(string commitId) { try { var keyPaths = await GetKeyPathsFromCommit(commitId); var author = await GetCommitAuthor(commitId); var allHooks = await GetAllHooks(commitId); var keyPathsByHook = LinkKeyPathsByHook(keyPaths, allHooks); keyPathsByHook = FilterNonPostCommitHooks(keyPathsByHook); var usedKeyPaths = GetUsedKeyPaths(keyPathsByHook); var keyPathsDiffs = await GetKeyPathsDiffs(usedKeyPaths, commitId); var hooksWithData = GetHooksWithData(keyPathsByHook, keyPathsDiffs, author); await _triggerHelper.TriggerHooks(hooksWithData, commitId); } catch (Exception ex) { _logger.LogError(ex, $"Failed triggering post commit hook for commit {commitId}"); _metrics.Measure.Counter.Increment(_hooksMetric, _metricsFailure); } } private static Dictionary<Hook, HookData> GetHooksWithData( KeyPathsDictionary keyPathsByHook, IReadOnlyDictionary<string, KeyPathDiff> keyPathsDiffs, Author author ) => keyPathsByHook.Select(kvp => ( key: kvp.Key, value: kvp.Value .Select(keyPath => keyPathsDiffs[keyPath]) .Where(diff => HasRelevantTags(diff, kvp.Key.Tags))) ) .Where(kvp => kvp.value.Any()) .ToDictionary( kvp => kvp.key, kvp => new HookData(author, kvp.value)); private static bool HasRelevantTags(KeyPathDiff diff, string[] tags) { if (tags == null || !tags.Any()) { return true; } var oldValueTags = diff.oldValue.GetValueOrDefault().manifest?.Meta?.Tags ?? new string[]{}; var newValueTags = diff.newValue.GetValueOrDefault().manifest?.Meta?.Tags ?? new string[]{}; return oldValueTags.Union(newValueTags).Any(tags.Contains); } private async Task<Dictionary<string, KeyPathDiff>> GetKeyPathsDiffs(IEnumerable<string> keyPaths, string commitId) { var keyPathDiffs = await Task.WhenAll(keyPaths.Map(async keyPath => { var newValue = await GetKeyPathData(keyPath, commitId); var oldValue = await GetOldKeyPathData(keyPath, commitId); return (key: keyPath, value: new KeyPathDiff(oldValue, newValue)); })); return keyPathDiffs.ToDictionary(tuple => tuple.key, tuple => tuple.value); } private async Task<KeyPathData?> GetOldKeyPathData(string keyPath, string commitId, int commitOffset = 1) => await GetKeyPathData(keyPath, $"{commitId}~{commitOffset}"); private async Task<KeyPathData?> GetKeyPathData(string keyPath, string revision) { string manifestJson; var manifestPath = $"manifests/{keyPath}.json"; try { manifestJson = await _git($"show {revision}:{manifestPath}"); } catch (Exception ex) { var missingFileMessage = $"fatal: Path '{manifestPath}' does not exist in '{revision}'\n"; if (ex.InnerException?.Message == missingFileMessage) return null; throw ex; } var manifest = JsonConvert.DeserializeObject<Manifest>(manifestJson); var implementation = await GetImplementation(manifest, revision); return new KeyPathData(keyPath, implementation, manifest); } private async Task<string> GetImplementation(Manifest manifest, string revision) { if (manifest.Implementation.Type != "file") return null; var implementationFilePath = manifest.GetFileImplementationPath(); return await _git($"show {revision}:{implementationFilePath}"); } private static IEnumerable<string> GetUsedKeyPaths(KeyPathsDictionary keyPathsByHook) => keyPathsByHook.Values.Aggregate(new HashSet<string>(), (keyPathsAcc, currentKeyPaths) => { keyPathsAcc.UnionWith(currentKeyPaths); return keyPathsAcc; }); private KeyPathsDictionary FilterNonPostCommitHooks(KeyPathsDictionary hooksDictionary) { return hooksDictionary .Where(kvp => _postCommitHookTypes.Contains(kvp.Key.Type)) .ToDictionary(kvp => kvp.Key, kvp => kvp.Value); } private static KeyPathsDictionary LinkKeyPathsByHook(IEnumerable<string> allKeyPaths, IEnumerable<Hook> allHooks) => allHooks .Select(hook => (hook, keyPaths: hook.GetMatchingKeyPaths(allKeyPaths))) .Where(hookTuple => hookTuple.keyPaths.Any()) .ToDictionary( hookGrouping => hookGrouping.hook, hookGrouping => hookGrouping.keyPaths.ToHashSet() ); private async Task<Hook[]> GetAllHooks(string commitId) { var hooksFile = await _git($"show {commitId}:hooks.json"); return JsonConvert.DeserializeObject<Hook[]>(hooksFile); } private async Task<Author> GetCommitAuthor(string commitId) { var authorJson = await _git($@"show {commitId} --no-patch --format=""{{\""name\"":\""%an\"",\""email\"":\""%ae\""}}"""); return JsonConvert.DeserializeObject<Author>(authorJson); } private async Task<IEnumerable<string>> GetKeyPathsFromCommit(string commitId) { var files = await _git($"diff-tree --no-commit-id --name-only -r {commitId}"); return files .Split('\n', StringSplitOptions.RemoveEmptyEntries) .Select(file => _keysRegex.Match(file).Groups.Values.Last().Value) .Distinct() .Where(keyPath => keyPath != ""); } } public struct KeyPathData { public string keyPath; public string implementation; public Manifest manifest; public KeyPathData(string keyPath, string implementation, Manifest manifest) { this.keyPath = keyPath; this.implementation = implementation; this.manifest = manifest; } } public struct Author { public string name; public string email; public Author(string name, string email) { this.name = name; this.email = email; } } public struct KeyPathDiff { public KeyPathData? oldValue; public KeyPathData? newValue; public KeyPathDiff(KeyPathData? oldValue, KeyPathData? newValue) { this.oldValue = oldValue; this.newValue = newValue; } } public struct HookData { public Author author; public IEnumerable<KeyPathDiff> updates; public HookData(Author author, IEnumerable<KeyPathDiff> updates) { this.author = author; this.updates = updates; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Threading; using Xunit; namespace System.Linq.Parallel.Tests { public class SumTests { public static IEnumerable<object[]> SumData(int[] counts) { foreach (object[] results in UnorderedSources.Ranges(counts.Cast<int>(), x => Functions.SumRange(0L, x))) yield return results; } // // Sum // [Theory] [MemberData("SumData", (object)(new int[] { 0, 1, 2, 16 }))] public static void Sum_Int(Labeled<ParallelQuery<int>> labeled, int count, int sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(sum, query.Sum()); Assert.Equal(sum, query.Select(x => (int?)x).Sum()); Assert.Equal(default(int), query.Select(x => (int?)null).Sum()); Assert.Equal(-sum, query.Sum(x => -x)); Assert.Equal(-sum, query.Sum(x => -(int?)x)); Assert.Equal(default(int), query.Sum(x => (int?)null)); } [Theory] [MemberData("SumData", (object)(new int[] { 1, 2, 16 }))] public static void Sum_Int_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, int sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(Functions.SumRange(0, count / 2), query.Select(x => x < count / 2 ? (int?)x : null).Sum()); Assert.Equal(-Functions.SumRange(0, count / 2), query.Sum(x => x < count / 2 ? -(int?)x : null)); } [Theory] [MemberData("SumData", (object)(new int[] { 1, 2, 16 }))] public static void Sum_Int_AllNull(Labeled<ParallelQuery<int>> labeled, int count, int sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(0, query.Select(x => (int?)null).Sum()); Assert.Equal(0, query.Sum(x => (int?)null)); } [Theory] [OuterLoop] [MemberData("SumData", (object)(new int[] { 1024 * 4, 1024 * 64 }))] public static void Sum_Int_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int sum) { Sum_Int(labeled, count, sum); } [Theory] [MemberData("Ranges", (object)(new int[] { 2 }), MemberType = typeof(UnorderedSources))] public static void Sum_Int_Overflow(Labeled<ParallelQuery<int>> labeled, int count) { Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? int.MaxValue : x).Sum()); Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? int.MaxValue : (int?)x).Sum()); Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? int.MinValue : -x)); Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? int.MinValue : -(int?)x)); } [Theory] [MemberData("SumData", (object)(new int[] { 0, 1, 2, 16 }))] public static void Sum_Long(Labeled<ParallelQuery<int>> labeled, int count, long sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(sum, query.Select(x => (long)x).Sum()); Assert.Equal(sum, query.Select(x => (long?)x).Sum()); Assert.Equal(default(long), query.Select(x => (long?)null).Sum()); Assert.Equal(-sum, query.Sum(x => -(long)x)); Assert.Equal(-sum, query.Sum(x => -(long?)x)); Assert.Equal(default(long), query.Sum(x => (long?)null)); } [Theory] [OuterLoop] [MemberData("SumData", (object)(new int[] { 1024 * 4, 1024 * 1024 }))] public static void Sum_Long_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, long sum) { Sum_Long(labeled, count, sum); } [Theory] [MemberData("SumData", (object)(new int[] { 1, 2, 16 }))] public static void Sum_Long_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, long sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(Functions.SumRange(0L, count / 2), query.Select(x => x < count / 2 ? (long?)x : null).Sum()); Assert.Equal(-Functions.SumRange(0L, count / 2), query.Sum(x => x < count / 2 ? -(long?)x : null)); } [Theory] [MemberData("SumData", (object)(new int[] { 1, 2, 16 }))] public static void Sum_Long_AllNull(Labeled<ParallelQuery<int>> labeled, int count, long sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(0, query.Select(x => (long?)null).Sum()); Assert.Equal(0, query.Sum(x => (long?)null)); } [Theory] [MemberData("Ranges", (object)(new int[] { 2 }), MemberType = typeof(UnorderedSources))] public static void Sum_Long_Overflow(Labeled<ParallelQuery<int>> labeled, int count) { Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? long.MaxValue : x).Sum()); Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? long.MaxValue : (long?)x).Sum()); Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? long.MinValue : -x)); Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? long.MinValue : -(long?)x)); } [Theory] [MemberData("SumData", (object)(new int[] { 0, 1, 2, 16 }))] public static void Sum_Float(Labeled<ParallelQuery<int>> labeled, int count, float sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(sum, query.Select(x => (float)x).Sum()); Assert.Equal(sum, query.Select(x => (float?)x).Sum()); Assert.Equal(default(float), query.Select(x => (float?)null).Sum()); Assert.Equal(-sum, query.Sum(x => -(float)x)); Assert.Equal(-sum, query.Sum(x => -(float?)x)); Assert.Equal(default(float), query.Sum(x => (float?)null)); } [Theory] [OuterLoop] [MemberData("SumData", (object)(new int[] { 1024 * 4, 1024 * 1024 }))] public static void Sum_Float_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, float sum) { Sum_Float(labeled, count, sum); } [Theory] [MemberData("Ranges", (object)(new int[] { 2 }), MemberType = typeof(UnorderedSources))] public static void Sum_Float_Overflow(Labeled<ParallelQuery<int>> labeled, int count) { Assert.Equal(float.PositiveInfinity, labeled.Item.Select(x => float.MaxValue).Sum()); Assert.Equal(float.PositiveInfinity, labeled.Item.Select(x => (float?)float.MaxValue).Sum().Value); Assert.Equal(float.PositiveInfinity, labeled.Item.Sum(x => float.MaxValue)); Assert.Equal(float.PositiveInfinity, labeled.Item.Sum(x => (float?)float.MaxValue).Value); Assert.Equal(float.PositiveInfinity, labeled.Item.Select(x => float.PositiveInfinity).Sum()); Assert.Equal(float.PositiveInfinity, labeled.Item.Select(x => (float?)float.PositiveInfinity).Sum().Value); Assert.Equal(float.PositiveInfinity, labeled.Item.Sum(x => float.PositiveInfinity)); Assert.Equal(float.PositiveInfinity, labeled.Item.Sum(x => (float?)float.PositiveInfinity).Value); Assert.Equal(float.NegativeInfinity, labeled.Item.Select(x => float.MinValue).Sum()); Assert.Equal(float.NegativeInfinity, labeled.Item.Select(x => (float?)float.MinValue).Sum().Value); Assert.Equal(float.NegativeInfinity, labeled.Item.Sum(x => float.MinValue)); Assert.Equal(float.NegativeInfinity, labeled.Item.Sum(x => (float?)float.MinValue).Value); Assert.Equal(float.NegativeInfinity, labeled.Item.Select(x => float.NegativeInfinity).Sum()); Assert.Equal(float.NegativeInfinity, labeled.Item.Select(x => (float?)float.NegativeInfinity).Sum().Value); Assert.Equal(float.NegativeInfinity, labeled.Item.Sum(x => float.NegativeInfinity)); Assert.Equal(float.NegativeInfinity, labeled.Item.Sum(x => (float?)float.NegativeInfinity).Value); } [Theory] [MemberData("Ranges", (object)(new int[] { 2 }), MemberType = typeof(UnorderedSources))] public static void Sum_Float_NaN(Labeled<ParallelQuery<int>> labeled, int count) { Assert.Equal(float.NaN, labeled.Item.Select(x => x == 0 ? float.NaN : x).Sum()); Assert.Equal(float.NaN, labeled.Item.Select(x => (float?)(x == 0 ? float.NaN : x)).Sum().Value); Assert.Equal(float.NaN, labeled.Item.Sum(x => x == 0 ? float.NaN : x)); Assert.Equal(float.NaN, labeled.Item.Sum(x => (float?)(x == 0 ? float.NaN : x)).Value); Assert.Equal(float.NaN, labeled.Item.Select(x => x == 0 ? float.NaN : x).Sum()); Assert.Equal(float.NaN, labeled.Item.Select(x => (float?)(x == 0 ? float.NaN : x)).Sum().Value); Assert.Equal(float.NaN, labeled.Item.Sum(x => x == 0 ? float.NaN : x)); Assert.Equal(float.NaN, labeled.Item.Sum(x => (float?)(x == 0 ? float.NaN : x)).Value); Assert.Equal(float.NaN, labeled.Item.Select(x => x == 0 ? float.NaN : -x).Sum()); Assert.Equal(float.NaN, labeled.Item.Select(x => (float?)(x == 0 ? float.NaN : x)).Sum().Value); Assert.Equal(float.NaN, labeled.Item.Sum(x => x == 0 ? float.NaN : -x)); Assert.Equal(float.NaN, labeled.Item.Sum(x => (float?)(x == 0 ? float.NaN : -x)).Value); Assert.Equal(float.NaN, labeled.Item.Select(x => x == 0 ? float.NaN : x).Sum()); Assert.Equal(float.NaN, labeled.Item.Select(x => (float?)(x == 0 ? float.NaN : x)).Sum().Value); Assert.Equal(float.NaN, labeled.Item.Sum(x => x == 0 ? float.NaN : x)); Assert.Equal(float.NaN, labeled.Item.Sum(x => (float?)(x == 0 ? float.NaN : x)).Value); } [Theory] [MemberData("SumData", (object)(new int[] { 1, 2, 16 }))] public static void Sum_Float_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, float sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(Functions.SumRange(0, count / 2), query.Select(x => x < count / 2 ? (float?)x : null).Sum()); Assert.Equal(-Functions.SumRange(0, count / 2), query.Sum(x => x < count / 2 ? -(float?)x : null)); } [Theory] [MemberData("SumData", (object)(new int[] { 1, 2, 16 }))] public static void Sum_Float_AllNull(Labeled<ParallelQuery<int>> labeled, int count, float sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(0, query.Select(x => (float?)null).Sum()); Assert.Equal(0, query.Sum(x => (float?)null)); } [Theory] [MemberData("SumData", (object)(new int[] { 0, 1, 2, 16 }))] public static void Sum_Double(Labeled<ParallelQuery<int>> labeled, int count, double sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(sum, query.Select(x => (double)x).Sum()); Assert.Equal(sum, query.Select(x => (double?)x).Sum()); Assert.Equal(default(double), query.Select(x => (double?)null).Sum()); Assert.Equal(-sum, query.Sum(x => -(double)x)); Assert.Equal(-sum, query.Sum(x => -(double?)x)); Assert.Equal(default(double), query.Sum(x => (double?)null)); } [Theory] [OuterLoop] [MemberData("SumData", (object)(new int[] { 1024 * 4, 1024 * 1024 }))] public static void Sum_Double_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, double sum) { Sum_Double(labeled, count, sum); } [Theory] [MemberData("Ranges", (object)(new int[] { 2 }), MemberType = typeof(UnorderedSources))] public static void Sum_Double_Overflow(Labeled<ParallelQuery<int>> labeled, int count) { Assert.Equal(double.PositiveInfinity, labeled.Item.Select(x => double.MaxValue).Sum()); Assert.Equal(double.PositiveInfinity, labeled.Item.Select(x => (double?)double.MaxValue).Sum().Value); Assert.Equal(double.PositiveInfinity, labeled.Item.Sum(x => double.MaxValue)); Assert.Equal(double.PositiveInfinity, labeled.Item.Sum(x => (double?)double.MaxValue).Value); Assert.Equal(double.PositiveInfinity, labeled.Item.Select(x => double.PositiveInfinity).Sum()); Assert.Equal(double.PositiveInfinity, labeled.Item.Select(x => (double?)double.PositiveInfinity).Sum().Value); Assert.Equal(double.PositiveInfinity, labeled.Item.Sum(x => double.PositiveInfinity)); Assert.Equal(double.PositiveInfinity, labeled.Item.Sum(x => (double?)double.PositiveInfinity).Value); Assert.Equal(double.NegativeInfinity, labeled.Item.Select(x => double.MinValue).Sum()); Assert.Equal(double.NegativeInfinity, labeled.Item.Select(x => (double?)double.MinValue).Sum().Value); Assert.Equal(double.NegativeInfinity, labeled.Item.Sum(x => double.MinValue)); Assert.Equal(double.NegativeInfinity, labeled.Item.Sum(x => (double?)double.MinValue).Value); Assert.Equal(double.NegativeInfinity, labeled.Item.Select(x => double.NegativeInfinity).Sum()); Assert.Equal(double.NegativeInfinity, labeled.Item.Select(x => (double?)double.NegativeInfinity).Sum().Value); Assert.Equal(double.NegativeInfinity, labeled.Item.Sum(x => double.NegativeInfinity)); Assert.Equal(double.NegativeInfinity, labeled.Item.Sum(x => (double?)double.NegativeInfinity).Value); } [Theory] [MemberData("Ranges", (object)(new int[] { 2 }), MemberType = typeof(UnorderedSources))] public static void Sum_Double_NaN(Labeled<ParallelQuery<int>> labeled, int count) { Assert.Equal(double.NaN, labeled.Item.Select(x => x == 0 ? double.NaN : x).Sum()); Assert.Equal(double.NaN, labeled.Item.Select(x => (double?)(x == 0 ? double.NaN : x)).Sum().Value); Assert.Equal(double.NaN, labeled.Item.Sum(x => x == 0 ? double.NaN : x)); Assert.Equal(double.NaN, labeled.Item.Sum(x => (double?)(x == 0 ? double.NaN : x)).Value); Assert.Equal(double.NaN, labeled.Item.Select(x => x == 0 ? double.NaN : x).Sum()); Assert.Equal(double.NaN, labeled.Item.Select(x => (double?)(x == 0 ? double.NaN : x)).Sum().Value); Assert.Equal(double.NaN, labeled.Item.Sum(x => x == 0 ? double.NaN : x)); Assert.Equal(double.NaN, labeled.Item.Sum(x => (double?)(x == 0 ? double.NaN : x)).Value); Assert.Equal(double.NaN, labeled.Item.Select(x => x == 0 ? double.NaN : -x).Sum()); Assert.Equal(double.NaN, labeled.Item.Select(x => (double?)(x == 0 ? double.NaN : x)).Sum().Value); Assert.Equal(double.NaN, labeled.Item.Sum(x => x == 0 ? double.NaN : -x)); Assert.Equal(double.NaN, labeled.Item.Sum(x => (double?)(x == 0 ? double.NaN : -x)).Value); Assert.Equal(double.NaN, labeled.Item.Select(x => x == 0 ? double.NaN : x).Sum()); Assert.Equal(double.NaN, labeled.Item.Select(x => (double?)(x == 0 ? double.NaN : x)).Sum().Value); Assert.Equal(double.NaN, labeled.Item.Sum(x => x == 0 ? double.NaN : x)); Assert.Equal(double.NaN, labeled.Item.Sum(x => (double?)(x == 0 ? double.NaN : x)).Value); } [Theory] [MemberData("SumData", (object)(new int[] { 1, 2, 16 }))] public static void Sum_Double_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, double sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(Functions.SumRange(0, count / 2), query.Select(x => x < count / 2 ? (double?)x : null).Sum()); Assert.Equal(-Functions.SumRange(0, count / 2), query.Sum(x => x < count / 2 ? -(double?)x : null)); } [Theory] [MemberData("SumData", (object)(new int[] { 1, 2, 16 }))] public static void Sum_Double_AllNull(Labeled<ParallelQuery<int>> labeled, int count, double sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(0, query.Select(x => (double?)null).Sum()); Assert.Equal(0, query.Sum(x => (double?)null)); } [Theory] [MemberData("SumData", (object)(new int[] { 0, 1, 2, 16 }))] public static void Sum_Decimal(Labeled<ParallelQuery<int>> labeled, int count, decimal sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(sum, query.Select(x => (decimal)x).Sum()); Assert.Equal(sum, query.Select(x => (decimal?)x).Sum()); Assert.Equal(default(decimal), query.Select(x => (decimal?)null).Sum()); Assert.Equal(-sum, query.Sum(x => -(decimal)x)); Assert.Equal(default(decimal), query.Sum(x => (decimal?)null)); } [Theory] [OuterLoop] [MemberData("SumData", (object)(new int[] { 1024 * 4, 1024 * 1024 }))] public static void Sum_Decimal_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, decimal sum) { Sum_Decimal(labeled, count, sum); } [Theory] [MemberData("Ranges", (object)(new int[] { 2 }), MemberType = typeof(UnorderedSources))] public static void Sum_Decimal_Overflow(Labeled<ParallelQuery<int>> labeled, int count) { Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? decimal.MaxValue : x).Sum()); Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? decimal.MaxValue : (decimal?)x).Sum()); Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? decimal.MinValue : -x)); Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Sum(x => x == 0 ? decimal.MinValue : -(decimal?)x)); } [Theory] [MemberData("SumData", (object)(new int[] { 1, 2, 16 }))] public static void Sum_Decimal_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, decimal sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(Functions.SumRange(0, count / 2), query.Select(x => x < count / 2 ? (decimal?)x : null).Sum()); Assert.Equal(-Functions.SumRange(0, count / 2), query.Sum(x => x < count / 2 ? -(decimal?)x : null)); } [Theory] [MemberData("SumData", (object)(new int[] { 1, 2, 16 }))] public static void Sum_Decimal_AllNull(Labeled<ParallelQuery<int>> labeled, int count, decimal sum) { ParallelQuery<int> query = labeled.Item; Assert.Equal(0, query.Select(x => (decimal?)null).Sum()); Assert.Equal(0, query.Sum(x => (decimal?)null)); } [Theory] [MemberData("Ranges", (object)(new int[] { 2 }), MemberType = typeof(UnorderedSources))] public static void Sum_OperationCanceledException_PreCanceled(Labeled<ParallelQuery<int>> labeled, int count) { CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (int?)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (long)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (long?)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (float)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (float?)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (double)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (double?)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (decimal)x)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Sum(x => (decimal?)x)); } [Theory] [MemberData("Ranges", (object)(new int[] { 2 }), MemberType = typeof(UnorderedSources))] public static void Sum_AggregateException(Labeled<ParallelQuery<int>> labeled, int count) { Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, int>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, int?>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, long>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, long?>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, float>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, float?>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, double>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, double?>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, decimal>)(x => { throw new DeliberateTestException(); }))); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Sum((Func<int, decimal?>)(x => { throw new DeliberateTestException(); }))); } [Fact] public static void Sum_ArgumentNullException() { Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Sum()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat(0, 1).Sum((Func<int, int>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int?>)null).Sum()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((int?)0, 1).Sum((Func<int?, int?>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<long>)null).Sum()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((long)0, 1).Sum((Func<long, long>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<long?>)null).Sum()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((long?)0, 1).Sum((Func<long?, long?>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<float>)null).Sum()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((float)0, 1).Sum((Func<float, float>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<float?>)null).Sum()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((float?)0, 1).Sum((Func<float?, float>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<double>)null).Sum()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((double)0, 1).Sum((Func<double, double>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<double?>)null).Sum()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((double?)0, 1).Sum((Func<double?, double>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<decimal>)null).Sum()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((decimal)0, 1).Sum((Func<decimal, decimal>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<decimal?>)null).Sum()); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((decimal?)0, 1).Sum((Func<decimal?, decimal>)null)); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace GitHubHookApi.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); } } } }
using NUnit.Framework; using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; namespace Exodrifter.Rumor.Engine.Tests { public static class ExpressionSerialization { #region Comparison [Test] public static void SerializeIsExpression() { var v = new NumberLiteral(2); var a = new IsExpression(v, v); var b = SerializationUtil.Reserialize(a); Assert.AreEqual(a, b); } [Test] public static void SerializeIsNotExpression() { var v = new NumberLiteral(2); var a = new IsNotExpression(v, v); var b = SerializationUtil.Reserialize(a); Assert.AreEqual(a, b); } [Test] public static void SerializeLessThanExpression() { var v = new NumberLiteral(2); var a = new LessThanExpression(v, v); var b = SerializationUtil.Reserialize(a); Assert.AreEqual(a, b); } [Test] public static void SerializeLessThanOrEqualExpression() { var v = new NumberLiteral(2); var a = new LessThanOrEqualExpression(v, v); var b = SerializationUtil.Reserialize(a); Assert.AreEqual(a, b); } [Test] public static void SerializeGreaterThanExpression() { var v = new NumberLiteral(2); var a = new GreaterThanExpression(v, v); var b = SerializationUtil.Reserialize(a); Assert.AreEqual(a, b); } [Test] public static void SerializeGreaterThanOrEqualExpression() { var v = new NumberLiteral(2); var a = new GreaterThanOrEqualExpression(v, v); var b = SerializationUtil.Reserialize(a); Assert.AreEqual(a, b); } #endregion #region Literal [Test] public static void SerializeBooleanLiteral() { var a = new BooleanLiteral(true); var b = SerializationUtil.Reserialize(a); Assert.AreEqual(a, b); } [Test] public static void SerializeNumberLiteral() { var a = new NumberLiteral(2); var b = SerializationUtil.Reserialize(a); Assert.AreEqual(a, b); } [Test] public static void SerializeStringLiteral() { var a = new StringLiteral("Hello world!"); var b = SerializationUtil.Reserialize(a); Assert.AreEqual(a, b); } #endregion #region Logic [Test] public static void SerializeAndExpression() { var v = new BooleanLiteral(true); var a = new AndExpression(v, v); var b = SerializationUtil.Reserialize(a); Assert.AreEqual(a, b); } [Test] public static void SerializeOrExpression() { var v = new BooleanLiteral(true); var a = new OrExpression(v, v); var b = SerializationUtil.Reserialize(a); Assert.AreEqual(a, b); } [Test] public static void SerializeXorExpression() { var v = new BooleanLiteral(true); var a = new XorExpression(v, v); var b = SerializationUtil.Reserialize(a); Assert.AreEqual(a, b); } #endregion #region Math [Test] public static void SerializeAddExpression() { var v = new NumberLiteral(2); var a = new AddExpression(v, v); var b = SerializationUtil.Reserialize(a); Assert.AreEqual(a, b); } [Test] public static void SerializeDivideExpression() { var v = new NumberLiteral(2); var a = new DivideExpression(v, v); var b = SerializationUtil.Reserialize(a); Assert.AreEqual(a, b); } [Test] public static void SerializeMultiplyExpression() { var v = new NumberLiteral(2); var a = new MultiplyExpression(v, v); var b = SerializationUtil.Reserialize(a); Assert.AreEqual(a, b); } [Test] public static void SerializeSubtractExpression() { var v = new NumberLiteral(2); var a = new SubtractExpression(v, v); var b = SerializationUtil.Reserialize(a); Assert.AreEqual(a, b); } #endregion #region String [Test] public static void SerializeConcatExpression() { var v = new StringLiteral("Hello"); var a = new ConcatExpression(v, v); var b = SerializationUtil.Reserialize(a); Assert.AreEqual(a, b); } [Test] public static void SerializeSubstitutionExpression() { var a = new SubstitutionExpression(new NumberLiteral(2)); var b = SerializationUtil.Reserialize(a); Assert.AreEqual(a, b); } [Test] public static void SerializeToStringExpression() { var a = new ToStringExpression(new NumberLiteral(2)); var b = SerializationUtil.Reserialize(a); Assert.AreEqual(a, b); } #endregion #region Value [Test] public static void SerializeBooleanValue() { var a = new BooleanValue(true); var b = SerializationUtil.Reserialize(a); Assert.AreEqual(a, b); } [Test] public static void SerializeNumberValue() { var a = new NumberValue(12345.6); var b = SerializationUtil.Reserialize(a); Assert.AreEqual(a, b); } [Test] public static void SerializeStringValue() { var a = new StringValue("Hello world!"); var b = SerializationUtil.Reserialize(a); Assert.AreEqual(a, b); } #endregion #region Variable [Test] public static void SerializeBooleanVariable() { var a = new BooleanVariable("foobar"); var b = SerializationUtil.Reserialize(a); Assert.AreEqual(a, b); } [Test] public static void SerializeNumberVariable() { var a = new NumberVariable("foobar"); var b = SerializationUtil.Reserialize(a); Assert.AreEqual(a, b); } [Test] public static void SerializeStringVariable() { var a = new StringVariable("foobar"); var b = SerializationUtil.Reserialize(a); Assert.AreEqual(a, b); } [Test] public static void SerializeVariableExpression() { var a = new VariableExpression("foobar"); var b = SerializationUtil.Reserialize(a); Assert.AreEqual(a, b); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Xml; using System.Data.SqlTypes; using System.Diagnostics; using System.IO; using System.Xml.Serialization; using System.Collections; namespace System.Data.Common { internal sealed class SqlByteStorage : DataStorage { private SqlByte[] _values; public SqlByteStorage(DataColumn column) : base(column, typeof(SqlByte), SqlByte.Null, SqlByte.Null, StorageType.SqlByte) { } public override object Aggregate(int[] records, AggregateType kind) { bool hasData = false; try { switch (kind) { case AggregateType.Sum: SqlInt64 sum = 0; foreach (int record in records) { if (IsNull(record)) continue; checked { sum += _values[record]; } hasData = true; } if (hasData) { return sum; } return _nullValue; case AggregateType.Mean: SqlInt64 meanSum = 0; int meanCount = 0; foreach (int record in records) { if (IsNull(record)) continue; checked { meanSum += _values[record].ToSqlInt64(); } meanCount++; hasData = true; } if (hasData) { SqlByte mean = 0; checked { mean = (meanSum / meanCount).ToSqlByte(); } return mean; } return _nullValue; case AggregateType.Var: case AggregateType.StDev: int count = 0; SqlDouble var = 0; SqlDouble prec = 0; SqlDouble dsum = 0; SqlDouble sqrsum = 0; foreach (int record in records) { if (IsNull(record)) continue; dsum += _values[record].ToSqlDouble(); sqrsum += _values[record].ToSqlDouble() * _values[record].ToSqlDouble(); count++; } if (count > 1) { var = count * sqrsum - (dsum * dsum); prec = var / (dsum * dsum); // we are dealing with the risk of a cancellation error // double is guaranteed only for 15 digits so a difference // with a result less than 1e-15 should be considered as zero if ((prec < 1e-15) || (var < 0)) var = 0; else var = var / (count * (count - 1)); if (kind == AggregateType.StDev) { return Math.Sqrt(var.Value); } return var; } return _nullValue; case AggregateType.Min: SqlByte min = SqlByte.MaxValue; for (int i = 0; i < records.Length; i++) { int record = records[i]; if (IsNull(record)) continue; if ((SqlByte.LessThan(_values[record], min)).IsTrue) min = _values[record]; hasData = true; } if (hasData) { return min; } return _nullValue; case AggregateType.Max: SqlByte max = SqlByte.MinValue; for (int i = 0; i < records.Length; i++) { int record = records[i]; if (IsNull(record)) continue; if ((SqlByte.GreaterThan(_values[record], max)).IsTrue) max = _values[record]; hasData = true; } if (hasData) { return max; } return _nullValue; case AggregateType.First: if (records.Length > 0) { return _values[records[0]]; } return null;// no data => null case AggregateType.Count: count = 0; for (int i = 0; i < records.Length; i++) { if (!IsNull(records[i])) count++; } return count; } } catch (OverflowException) { throw ExprException.Overflow(typeof(SqlByte)); } throw ExceptionBuilder.AggregateException(kind, _dataType); } public override int Compare(int recordNo1, int recordNo2) { return _values[recordNo1].CompareTo(_values[recordNo2]); } public override int CompareValueTo(int recordNo, object value) { return _values[recordNo].CompareTo((SqlByte)value); } public override object ConvertValue(object value) { if (null != value) { return SqlConvert.ConvertToSqlByte(value); } return _nullValue; } public override void Copy(int recordNo1, int recordNo2) { _values[recordNo2] = _values[recordNo1]; } public override object Get(int record) { return _values[record]; } public override bool IsNull(int record) { return (_values[record].IsNull); } public override void Set(int record, object value) { _values[record] = SqlConvert.ConvertToSqlByte(value); } public override void SetCapacity(int capacity) { SqlByte[] newValues = new SqlByte[capacity]; if (null != _values) { Array.Copy(_values, 0, newValues, 0, Math.Min(capacity, _values.Length)); } _values = newValues; } public override object ConvertXmlToObject(string s) { SqlByte newValue = new SqlByte(); string tempStr = string.Concat("<col>", s, "</col>"); // this is done since you can give fragmet to reader StringReader strReader = new StringReader(tempStr); IXmlSerializable tmp = newValue; using (XmlTextReader xmlTextReader = new XmlTextReader(strReader)) { tmp.ReadXml(xmlTextReader); } return ((SqlByte)tmp); } public override string ConvertObjectToXml(object value) { Debug.Assert(!DataStorage.IsObjectNull(value), "we shouldn't have null here"); Debug.Assert((value.GetType() == typeof(SqlByte)), "wrong input type"); StringWriter strwriter = new StringWriter(FormatProvider); using (XmlTextWriter xmlTextWriter = new XmlTextWriter(strwriter)) { ((IXmlSerializable)value).WriteXml(xmlTextWriter); } return (strwriter.ToString()); } protected override object GetEmptyStorage(int recordCount) { return new SqlByte[recordCount]; } protected override void CopyValue(int record, object store, BitArray nullbits, int storeIndex) { SqlByte[] typedStore = (SqlByte[])store; typedStore[storeIndex] = _values[record]; nullbits.Set(record, IsNull(record)); } protected override void SetStorage(object store, BitArray nullbits) { _values = (SqlByte[])store; //SetNullStorage(nullbits); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Collections.Generic; using System.Security.Cryptography.X509Certificates; namespace System.DirectoryServices.AccountManagement { [DirectoryRdnPrefix("CN")] public class AuthenticablePrincipal : Principal { // // Public Properties // // Enabled property private bool _enabled = false; // the actual property value private LoadState _enabledChanged = LoadState.NotSet; // change-tracking public Nullable<bool> Enabled { get { // Make sure we're not disposed or deleted. Although HandleGet/HandleSet will check this, // we need to check these before we do anything else. CheckDisposedOrDeleted(); // Different stores have different defaults as to the Enabled setting // (AD: creates disabled by default; SAM: creates enabled by default). // So if the principal is unpersisted (and thus we may not know what store it's // going to end up in), we'll just return null unless they previously // set an explicit value. if (this.unpersisted && (_enabledChanged != LoadState.Changed)) { GlobalDebug.WriteLineIf( GlobalDebug.Info, "AuthenticablePrincipal", "Enabled: returning null, unpersisted={0}, enabledChanged={1}", this.unpersisted, _enabledChanged); return null; } return HandleGet<bool>(ref _enabled, PropertyNames.AuthenticablePrincipalEnabled, ref _enabledChanged); } set { // Make sure we're not disposed or deleted. Although HandleGet/HandleSet will check this, // we need to check these before we do anything else. CheckDisposedOrDeleted(); // We don't want to let them set a null value. if (!value.HasValue) throw new ArgumentNullException(nameof(value)); HandleSet<bool>(ref _enabled, value.Value, ref _enabledChanged, PropertyNames.AuthenticablePrincipalEnabled); } } // // AccountInfo-related properties/methods // private AccountInfo _accountInfo = null; private AccountInfo AccountInfo { get { // Make sure we're not disposed or deleted. CheckDisposedOrDeleted(); if (_accountInfo == null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthenticablePrincipal", "AccountInfo: creating new AccountInfo"); _accountInfo = new AccountInfo(this); } return _accountInfo; } } public Nullable<DateTime> AccountLockoutTime { get { return this.AccountInfo.AccountLockoutTime; } } public Nullable<DateTime> LastLogon { get { return this.AccountInfo.LastLogon; } } public PrincipalValueCollection<string> PermittedWorkstations { get { return this.AccountInfo.PermittedWorkstations; } } public byte[] PermittedLogonTimes { get { return this.AccountInfo.PermittedLogonTimes; } set { this.AccountInfo.PermittedLogonTimes = value; } } public Nullable<DateTime> AccountExpirationDate { get { return this.AccountInfo.AccountExpirationDate; } set { this.AccountInfo.AccountExpirationDate = value; } } public bool SmartcardLogonRequired { get { return this.AccountInfo.SmartcardLogonRequired; } set { this.AccountInfo.SmartcardLogonRequired = value; } } public bool DelegationPermitted { get { return this.AccountInfo.DelegationPermitted; } set { this.AccountInfo.DelegationPermitted = value; } } public int BadLogonCount { get { return this.AccountInfo.BadLogonCount; } } public string HomeDirectory { get { return this.AccountInfo.HomeDirectory; } set { this.AccountInfo.HomeDirectory = value; } } public string HomeDrive { get { return this.AccountInfo.HomeDrive; } set { this.AccountInfo.HomeDrive = value; } } public string ScriptPath { get { return this.AccountInfo.ScriptPath; } set { this.AccountInfo.ScriptPath = value; } } public bool IsAccountLockedOut() { return this.AccountInfo.IsAccountLockedOut(); } public void UnlockAccount() { this.AccountInfo.UnlockAccount(); } // // PasswordInfo-related properties/methods // private PasswordInfo _passwordInfo = null; private PasswordInfo PasswordInfo { get { // Make sure we're not disposed or deleted. CheckDisposedOrDeleted(); if (_passwordInfo == null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthenticablePrincipal", "PasswordInfo: creating new PasswordInfo"); _passwordInfo = new PasswordInfo(this); } return _passwordInfo; } } public Nullable<DateTime> LastPasswordSet { get { return this.PasswordInfo.LastPasswordSet; } } public Nullable<DateTime> LastBadPasswordAttempt { get { return this.PasswordInfo.LastBadPasswordAttempt; } } public bool PasswordNotRequired { get { return this.PasswordInfo.PasswordNotRequired; } set { this.PasswordInfo.PasswordNotRequired = value; } } public bool PasswordNeverExpires { get { return this.PasswordInfo.PasswordNeverExpires; } set { this.PasswordInfo.PasswordNeverExpires = value; } } public bool UserCannotChangePassword { get { return this.PasswordInfo.UserCannotChangePassword; } set { this.PasswordInfo.UserCannotChangePassword = value; } } public bool AllowReversiblePasswordEncryption { get { return this.PasswordInfo.AllowReversiblePasswordEncryption; } set { this.PasswordInfo.AllowReversiblePasswordEncryption = value; } } internal AdvancedFilters rosf; public virtual AdvancedFilters AdvancedSearchFilter { get { return rosf; } } public void SetPassword(string newPassword) { this.PasswordInfo.SetPassword(newPassword); } public void ChangePassword(string oldPassword, string newPassword) { this.PasswordInfo.ChangePassword(oldPassword, newPassword); } public void ExpirePasswordNow() { this.PasswordInfo.ExpirePasswordNow(); } public void RefreshExpiredPassword() { this.PasswordInfo.RefreshExpiredPassword(); } // Certificates property private X509Certificate2Collection _certificates = new X509Certificate2Collection(); private List<string> _certificateOriginalThumbprints = new List<string>(); private LoadState _X509Certificate2CollectionLoaded = LoadState.NotSet; public X509Certificate2Collection Certificates { get { return HandleGet<X509Certificate2Collection>(ref _certificates, PropertyNames.AuthenticablePrincipalCertificates, ref _X509Certificate2CollectionLoaded); } } // // Public Methods // public static PrincipalSearchResult<AuthenticablePrincipal> FindByLockoutTime(PrincipalContext context, DateTime time, MatchType type) { return FindByLockoutTime<AuthenticablePrincipal>(context, time, type); } public static PrincipalSearchResult<AuthenticablePrincipal> FindByLogonTime(PrincipalContext context, DateTime time, MatchType type) { return FindByLogonTime<AuthenticablePrincipal>(context, time, type); } public static PrincipalSearchResult<AuthenticablePrincipal> FindByExpirationTime(PrincipalContext context, DateTime time, MatchType type) { return FindByExpirationTime<AuthenticablePrincipal>(context, time, type); } public static PrincipalSearchResult<AuthenticablePrincipal> FindByBadPasswordAttempt(PrincipalContext context, DateTime time, MatchType type) { return FindByBadPasswordAttempt<AuthenticablePrincipal>(context, time, type); } public static PrincipalSearchResult<AuthenticablePrincipal> FindByPasswordSetTime(PrincipalContext context, DateTime time, MatchType type) { return FindByPasswordSetTime<AuthenticablePrincipal>(context, time, type); } // // Protected implementations // protected static PrincipalSearchResult<T> FindByLockoutTime<T>(PrincipalContext context, DateTime time, MatchType type) { CheckFindByArgs(context, time, type, typeof(T)); return new PrincipalSearchResult<T>(context.QueryCtx.FindByLockoutTime(time, type, typeof(T))); } protected static PrincipalSearchResult<T> FindByLogonTime<T>(PrincipalContext context, DateTime time, MatchType type) { CheckFindByArgs(context, time, type, typeof(T)); return new PrincipalSearchResult<T>(context.QueryCtx.FindByLogonTime(time, type, typeof(T))); } protected static PrincipalSearchResult<T> FindByExpirationTime<T>(PrincipalContext context, DateTime time, MatchType type) { CheckFindByArgs(context, time, type, typeof(T)); return new PrincipalSearchResult<T>(context.QueryCtx.FindByExpirationTime(time, type, typeof(T))); } protected static PrincipalSearchResult<T> FindByBadPasswordAttempt<T>(PrincipalContext context, DateTime time, MatchType type) { CheckFindByArgs(context, time, type, typeof(T)); return new PrincipalSearchResult<T>(context.QueryCtx.FindByBadPasswordAttempt(time, type, typeof(T))); } protected static PrincipalSearchResult<T> FindByPasswordSetTime<T>(PrincipalContext context, DateTime time, MatchType type) { CheckFindByArgs(context, time, type, typeof(T)); return new PrincipalSearchResult<T>(context.QueryCtx.FindByPasswordSetTime(time, type, typeof(T))); } // // Private implementation // internal protected AuthenticablePrincipal(PrincipalContext context) { if (context == null) throw new ArgumentException(SR.NullArguments); this.ContextRaw = context; this.unpersisted = true; this.rosf = new AdvancedFilters(this); } internal protected AuthenticablePrincipal(PrincipalContext context, string samAccountName, string password, bool enabled) : this(context) { if (samAccountName != null) { this.SamAccountName = samAccountName; } if (password != null) { this.SetPassword(password); } this.Enabled = enabled; } static internal AuthenticablePrincipal MakeAuthenticablePrincipal(PrincipalContext ctx) { AuthenticablePrincipal ap = new AuthenticablePrincipal(ctx); ap.unpersisted = false; return ap; } private static void CheckFindByArgs(PrincipalContext context, DateTime time, MatchType type, Type subtype) { if ((subtype != typeof(AuthenticablePrincipal)) && (!subtype.IsSubclassOf(typeof(AuthenticablePrincipal)))) throw new ArgumentException(SR.AuthenticablePrincipalMustBeSubtypeOfAuthPrinc); if (context == null) throw new ArgumentNullException(nameof(context)); if (subtype == null) throw new ArgumentNullException(nameof(subtype)); } // // Load/Store // // // Loading with query results // internal override void LoadValueIntoProperty(string propertyName, object value) { switch (propertyName) { case PropertyNames.AuthenticablePrincipalCertificates: LoadCertificateCollection((List<byte[]>)value); RefreshOriginalThumbprintList(); _X509Certificate2CollectionLoaded = LoadState.Loaded; break; case PropertyNames.AuthenticablePrincipalEnabled: _enabled = (bool)value; _enabledChanged = LoadState.Loaded; break; default: if (propertyName.StartsWith(PropertyNames.AcctInfoPrefix, StringComparison.Ordinal)) { // If this is the first AccountInfo attribute we're loading, // we'll need to create the AccountInfo to hold it if (_accountInfo == null) _accountInfo = new AccountInfo(this); _accountInfo.LoadValueIntoProperty(propertyName, value); } else if (propertyName.StartsWith(PropertyNames.PwdInfoPrefix, StringComparison.Ordinal)) { // If this is the first PasswordInfo attribute we're loading, // we'll need to create the PasswordInfo to hold it if (_passwordInfo == null) _passwordInfo = new PasswordInfo(this); _passwordInfo.LoadValueIntoProperty(propertyName, value); } else { base.LoadValueIntoProperty(propertyName, value); } break; } } // // Getting changes to persist (or to build a query from a QBE filter) // // Given a property name, returns true if that property has changed since it was loaded, false otherwise. internal override bool GetChangeStatusForProperty(string propertyName) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthenticablePrincipal", "GetChangeStatusForProperty: name=" + propertyName); switch (propertyName) { case PropertyNames.AuthenticablePrincipalCertificates: return HasCertificateCollectionChanged(); case PropertyNames.AuthenticablePrincipalEnabled: return _enabledChanged == LoadState.Changed; default: // Check if the property is supported by AdvancedFilter class. // If writeable properties are added to the rosf class then we will need // to add some type of tag to the property names to differentiate them here bool? val = rosf.GetChangeStatusForProperty(propertyName); if (val.HasValue == true) return val.Value; if (propertyName.StartsWith(PropertyNames.AcctInfoPrefix, StringComparison.Ordinal)) { if (_accountInfo == null) return false; return _accountInfo.GetChangeStatusForProperty(propertyName); } else if (propertyName.StartsWith(PropertyNames.PwdInfoPrefix, StringComparison.Ordinal)) { if (_passwordInfo == null) return false; return _passwordInfo.GetChangeStatusForProperty(propertyName); } else { return base.GetChangeStatusForProperty(propertyName); } } } // Given a property name, returns the current value for the property. internal override object GetValueForProperty(string propertyName) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthenticablePrincipal", "GetValueForProperty: name=" + propertyName); switch (propertyName) { case PropertyNames.AuthenticablePrincipalCertificates: return _certificates; case PropertyNames.AuthenticablePrincipalEnabled: return _enabled; default: object val = rosf.GetValueForProperty(propertyName); if (null != val) return val; if (propertyName.StartsWith(PropertyNames.AcctInfoPrefix, StringComparison.Ordinal)) { if (_accountInfo == null) { // Should never happen, since GetChangeStatusForProperty returned false Debug.Fail("AuthenticablePrincipal.GetValueForProperty(AcctInfo): shouldn't be here"); throw new InvalidOperationException(); } return _accountInfo.GetValueForProperty(propertyName); } else if (propertyName.StartsWith(PropertyNames.PwdInfoPrefix, StringComparison.Ordinal)) { if (_passwordInfo == null) { // Should never happen, since GetChangeStatusForProperty returned false Debug.Fail("AuthenticablePrincipal.GetValueForProperty(PwdInfo): shouldn't be here"); throw new InvalidOperationException(); } return _passwordInfo.GetValueForProperty(propertyName); } else { return base.GetValueForProperty(propertyName); } } } // Reset all change-tracking status for all properties on the object to "unchanged". internal override void ResetAllChangeStatus() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthenticablePrincipal", "ResetAllChangeStatus"); _enabledChanged = (_enabledChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; RefreshOriginalThumbprintList(); if (_accountInfo != null) { _accountInfo.ResetAllChangeStatus(); } if (_passwordInfo != null) { _passwordInfo.ResetAllChangeStatus(); } rosf.ResetAllChangeStatus(); base.ResetAllChangeStatus(); } // // Certificate support routines // // Given a list of certs (expressed as byte[]s), loads them into // the certificate collection private void LoadCertificateCollection(List<byte[]> certificatesToLoad) { // To support reload _certificates.Clear(); Debug.Assert(_certificates.Count == 0); GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthenticablePrincipal", "LoadCertificateCollection: loading {0} certs", certificatesToLoad.Count); foreach (byte[] rawCert in certificatesToLoad) { try { _certificates.Import(rawCert); } catch (System.Security.Cryptography.CryptographicException) { // skip the invalid certificate GlobalDebug.WriteLineIf(GlobalDebug.Warn, "AuthenticablePrincipal", "LoadCertificateCollection: skipped bad cert"); continue; } } } // Regenerates the certificateOriginalThumbprints list based on what's // currently in the certificate collection private void RefreshOriginalThumbprintList() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthenticablePrincipal", "RefreshOriginalThumbprintList: resetting thumbprints"); _certificateOriginalThumbprints.Clear(); foreach (X509Certificate2 certificate in _certificates) { _certificateOriginalThumbprints.Add(certificate.Thumbprint); } } // Returns true if the certificate collection has changed since the last time // certificateOriginalThumbprints was refreshed (i.e., since the last time // RefreshOriginalThumbprintList was called) private bool HasCertificateCollectionChanged() { // If the size isn't the same, the collection has certainly changed if (_certificates.Count != _certificateOriginalThumbprints.Count) { GlobalDebug.WriteLineIf( GlobalDebug.Info, "AuthenticablePrincipal", "HasCertificateCollectionChanged: original count {0}, current count{1}", _certificateOriginalThumbprints.Count, _certificates.Count); return true; } // Make a copy of the thumbprint list, so we can alter the copy without effecting the original. List<string> remainingOriginalThumbprints = new List<string>(_certificateOriginalThumbprints); foreach (X509Certificate2 certificate in _certificates) { string thumbprint = certificate.Thumbprint; // If we found a cert whose thumbprint wasn't in the thumbprints list, // it was inserted --> collection has changed if (!remainingOriginalThumbprints.Contains(thumbprint)) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthenticablePrincipal", "RefreshOriginalThumbprintList: found inserted cert"); return true; } // We remove the thumbprint from the list so that if, for some reason, they inserted // a duplicate of a certificate that was already in the list, we'll detect it as an insert // when we encounter that cert a second time remainingOriginalThumbprints.Remove(thumbprint); } // If a certificate was deleted, there are two possibilities: // (1) The removal caused the size to change. We'll have caught it above and returned true. // (2) The size didn't change (because there was also an insert). We'll have caught the insert // above and returned true. Note that even if they insert a duplicate of a cert that was // already in the collection, we'll catch it because we remove the thumbprint from the // local copy of the thumbprint list each time we use that thumbprint. Debug.Assert(remainingOriginalThumbprints.Count == 0); return false; } } }
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using System.Text; using System.Collections.Generic; using Adaptive.Agrona; namespace Adaptive.Cluster.Codecs { public class ClusterSessionEncoder { public const ushort BLOCK_LENGTH = 40; public const ushort TEMPLATE_ID = 103; public const ushort SCHEMA_ID = 111; public const ushort SCHEMA_VERSION = 7; private ClusterSessionEncoder _parentMessage; private IMutableDirectBuffer _buffer; protected int _offset; protected int _limit; public ClusterSessionEncoder() { _parentMessage = this; } public ushort SbeBlockLength() { return BLOCK_LENGTH; } public ushort SbeTemplateId() { return TEMPLATE_ID; } public ushort SbeSchemaId() { return SCHEMA_ID; } public ushort SbeSchemaVersion() { return SCHEMA_VERSION; } public string SbeSemanticType() { return ""; } public IMutableDirectBuffer Buffer() { return _buffer; } public int Offset() { return _offset; } public ClusterSessionEncoder Wrap(IMutableDirectBuffer buffer, int offset) { this._buffer = buffer; this._offset = offset; Limit(offset + BLOCK_LENGTH); return this; } public ClusterSessionEncoder WrapAndApplyHeader( IMutableDirectBuffer buffer, int offset, MessageHeaderEncoder headerEncoder) { headerEncoder .Wrap(buffer, offset) .BlockLength(BLOCK_LENGTH) .TemplateId(TEMPLATE_ID) .SchemaId(SCHEMA_ID) .Version(SCHEMA_VERSION); return Wrap(buffer, offset + MessageHeaderEncoder.ENCODED_LENGTH); } public int EncodedLength() { return _limit - _offset; } public int Limit() { return _limit; } public void Limit(int limit) { this._limit = limit; } public static int ClusterSessionIdEncodingOffset() { return 0; } public static int ClusterSessionIdEncodingLength() { return 8; } public static long ClusterSessionIdNullValue() { return -9223372036854775808L; } public static long ClusterSessionIdMinValue() { return -9223372036854775807L; } public static long ClusterSessionIdMaxValue() { return 9223372036854775807L; } public ClusterSessionEncoder ClusterSessionId(long value) { _buffer.PutLong(_offset + 0, value, ByteOrder.LittleEndian); return this; } public static int CorrelationIdEncodingOffset() { return 8; } public static int CorrelationIdEncodingLength() { return 8; } public static long CorrelationIdNullValue() { return -9223372036854775808L; } public static long CorrelationIdMinValue() { return -9223372036854775807L; } public static long CorrelationIdMaxValue() { return 9223372036854775807L; } public ClusterSessionEncoder CorrelationId(long value) { _buffer.PutLong(_offset + 8, value, ByteOrder.LittleEndian); return this; } public static int OpenedLogPositionEncodingOffset() { return 16; } public static int OpenedLogPositionEncodingLength() { return 8; } public static long OpenedLogPositionNullValue() { return -9223372036854775808L; } public static long OpenedLogPositionMinValue() { return -9223372036854775807L; } public static long OpenedLogPositionMaxValue() { return 9223372036854775807L; } public ClusterSessionEncoder OpenedLogPosition(long value) { _buffer.PutLong(_offset + 16, value, ByteOrder.LittleEndian); return this; } public static int TimeOfLastActivityEncodingOffset() { return 24; } public static int TimeOfLastActivityEncodingLength() { return 8; } public static long TimeOfLastActivityNullValue() { return -9223372036854775808L; } public static long TimeOfLastActivityMinValue() { return -9223372036854775807L; } public static long TimeOfLastActivityMaxValue() { return 9223372036854775807L; } public ClusterSessionEncoder TimeOfLastActivity(long value) { _buffer.PutLong(_offset + 24, value, ByteOrder.LittleEndian); return this; } public static int CloseReasonEncodingOffset() { return 32; } public static int CloseReasonEncodingLength() { return 4; } public ClusterSessionEncoder CloseReason(CloseReason value) { _buffer.PutInt(_offset + 32, (int)value, ByteOrder.LittleEndian); return this; } public static int ResponseStreamIdEncodingOffset() { return 36; } public static int ResponseStreamIdEncodingLength() { return 4; } public static int ResponseStreamIdNullValue() { return -2147483648; } public static int ResponseStreamIdMinValue() { return -2147483647; } public static int ResponseStreamIdMaxValue() { return 2147483647; } public ClusterSessionEncoder ResponseStreamId(int value) { _buffer.PutInt(_offset + 36, value, ByteOrder.LittleEndian); return this; } public static int ResponseChannelId() { return 7; } public static string ResponseChannelCharacterEncoding() { return "US-ASCII"; } public static string ResponseChannelMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static int ResponseChannelHeaderLength() { return 4; } public ClusterSessionEncoder PutResponseChannel(IDirectBuffer src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public ClusterSessionEncoder PutResponseChannel(byte[] src, int srcOffset, int length) { if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutBytes(limit + headerLength, src, srcOffset, length); return this; } public ClusterSessionEncoder ResponseChannel(string value) { int length = value.Length; if (length > 1073741824) { throw new InvalidOperationException("length > maxValue for type: " + length); } int headerLength = 4; int limit = _parentMessage.Limit(); _parentMessage.Limit(limit + headerLength + length); _buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian); _buffer.PutStringWithoutLengthAscii(limit + headerLength, value); return this; } public override string ToString() { return AppendTo(new StringBuilder(100)).ToString(); } public StringBuilder AppendTo(StringBuilder builder) { ClusterSessionDecoder writer = new ClusterSessionDecoder(); writer.Wrap(_buffer, _offset, BLOCK_LENGTH, SCHEMA_VERSION); return writer.AppendTo(builder); } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !MONO && !NETSTANDARD namespace NLog.UnitTests.Targets { using System; using System.Collections.Generic; using System.Diagnostics.Eventing.Reader; using System.Linq; using System.Diagnostics; using NLog.Config; using NLog.Layouts; using NLog.Targets; using Xunit; public class EventLogTargetTests : NLogTestBase { private const int MaxMessageLength = EventLogTarget.EventLogMaxMessageLength; [Fact] public void MaxMessageLengthShouldBe16384_WhenNotSpecifyAnyOption() { LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog ThrowExceptions='true'> <targets> <target type='EventLog' name='eventLog1' layout='${message}' /> </targets> <rules> <logger name='*' writeTo='eventLog1'> </logger> </rules> </nlog>"); var eventLog1 = c.FindTargetByName<EventLogTarget>("eventLog1"); Assert.Equal(MaxMessageLength, eventLog1.MaxMessageLength); } [Fact] public void MaxMessageLengthShouldBeAsSpecifiedOption() { const int expectedMaxMessageLength = 1000; LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString($@" <nlog ThrowExceptions='true'> <targets> <target type='EventLog' name='eventLog1' layout='${{message}}' maxmessagelength='{ expectedMaxMessageLength }' /> </targets> <rules> <logger name='*' writeTo='eventLog1'> </logger> </rules> </nlog>"); var eventLog1 = c.FindTargetByName<EventLogTarget>("eventLog1"); Assert.Equal(expectedMaxMessageLength, eventLog1.MaxMessageLength); } [Theory] [InlineData(0)] [InlineData(-1)] public void ConfigurationShouldThrowException_WhenMaxMessageLengthIsNegativeOrZero(int maxMessageLength) { string configrationText = $@" <nlog ThrowExceptions='true'> <targets> <target type='EventLog' name='eventLog1' layout='${{message}}' maxmessagelength='{ maxMessageLength }' /> </targets> <rules> <logger name='*' writeTo='eventLog1'> </logger> </rules> </nlog>"; NLogConfigurationException ex = Assert.Throws<NLogConfigurationException>(() => XmlLoggingConfiguration.CreateFromXmlString(configrationText)); Assert.Equal("MaxMessageLength cannot be zero or negative.", ex.InnerException.InnerException.Message); } [Theory] [InlineData(0)] // Is multiple of 64, but less than the min value of 64 [InlineData(65)] // Isn't multiple of 64 [InlineData(4194304)] // Is multiple of 64, but bigger than the max value of 4194240 public void Configuration_ShouldThrowException_WhenMaxKilobytesIsInvalid(long? maxKilobytes) { string configrationText = $@" <nlog ThrowExceptions='true'> <targets> <target type='EventLog' name='eventLog1' layout='${{message}}' maxKilobytes='{maxKilobytes}' /> </targets> <rules> <logger name='*' writeTo='eventLog1' /> </rules> </nlog>"; NLogConfigurationException ex = Assert.Throws<NLogConfigurationException>(() => XmlLoggingConfiguration.CreateFromXmlString(configrationText)); Assert.Equal("MaxKilobytes must be a multiple of 64, and between 64 and 4194240", ex.InnerException.InnerException.Message); } [Theory] [InlineData(0)] // Is multiple of 64, but less than the min value of 64 [InlineData(65)] // Isn't multiple of 64 [InlineData(4194304)] // Is multiple of 64, but bigger than the max value of 4194240 public void MaxKilobytes_ShouldThrowException_WhenMaxKilobytesIsInvalid(long? maxKilobytes) { ArgumentException ex = Assert.Throws<ArgumentException>(() => { var target = new EventLogTarget(); target.MaxKilobytes = maxKilobytes; }); Assert.Equal("MaxKilobytes must be a multiple of 64, and between 64 and 4194240", ex.Message); } [Theory] // 'null' case is omitted, as it isn't a valid value for Int64 XML property. [InlineData(64)] // Min value [InlineData(4194240)] // Max value [InlineData(16384)] // Acceptable value public void ConfigurationMaxKilobytes_ShouldBeAsSpecified_WhenMaxKilobytesIsValid(long? maxKilobytes) { var expectedMaxKilobytes = maxKilobytes; string configrationText = $@" <nlog ThrowExceptions='true'> <targets> <target type='EventLog' name='eventLog1' layout='${{message}}' maxKilobytes='{maxKilobytes}' /> </targets> <rules> <logger name='*' writeTo='eventLog1' /> </rules> </nlog>"; LoggingConfiguration configuration = XmlLoggingConfiguration.CreateFromXmlString(configrationText); var eventLog1 = configuration.FindTargetByName<EventLogTarget>("eventLog1"); Assert.Equal(expectedMaxKilobytes, eventLog1.MaxKilobytes); } [Theory] [InlineData(null)] // A possible value, that should not change anything [InlineData(64)] // Min value [InlineData(4194240)] // Max value [InlineData(16384)] // Acceptable value public void MaxKilobytes_ShouldBeAsSpecified_WhenValueIsValid(long? maxKilobytes) { var expectedMaxKilobytes = maxKilobytes; var target = new EventLogTarget(); target.MaxKilobytes = maxKilobytes; Assert.Equal(expectedMaxKilobytes, target.MaxKilobytes); } [Theory] [InlineData(32768, 16384, 32768)] // Should set MaxKilobytes when value is set and valid [InlineData(16384, 32768, 32768)] // Should not change MaxKilobytes when initial MaximumKilobytes is bigger [InlineData(null, EventLogMock.EventLogDefaultMaxKilobytes, EventLogMock.EventLogDefaultMaxKilobytes)] // Should not change MaxKilobytes when the value is null public void ShouldSetMaxKilobytes_WhenNeeded(long? newValue, long initialValue, long expectedValue) { string targetLog = "application"; // The Log to write to is intentionally lower case!! var eventLogMock = new EventLogMock( deleteEventSourceFunction: (source, machineName) => { }, sourceExistsFunction: (source, machineName) => false, logNameFromSourceNameFunction: (source, machineName) => targetLog, createEventSourceFunction: (sourceData) => { }) { MaximumKilobytes = initialValue }; var target = new EventLogTarget(eventLogMock, null) { Log = targetLog, Source = "NLog.UnitTests" + Guid.NewGuid().ToString("N"), // set the source explicitly to prevent random AppDomain name being used as the source name Layout = new SimpleLayout("${message}"), // Be able to check message length and content, the Layout is intentionally only ${message}. OnOverflow = EventLogTargetOverflowAction.Truncate, MaxMessageLength = MaxMessageLength, MaxKilobytes = newValue, }; eventLogMock.AssociateNewEventLog(target.Log, target.MachineName, target.GetFixedSource()); target.Install(new InstallationContext()); Assert.Equal(expectedValue, eventLogMock.MaximumKilobytes); } [Theory] [InlineData(0)] [InlineData(-1)] public void ShouldThrowException_WhenMaxMessageLengthSetNegativeOrZero(int maxMessageLength) { ArgumentException ex = Assert.Throws<ArgumentException>(() => { var target = new EventLogTarget(); target.MaxMessageLength = maxMessageLength; }); Assert.Equal("MaxMessageLength cannot be zero or negative.", ex.Message); } [Theory] [InlineData(0, EventLogEntryType.Information, "AtInformationLevel_WhenNLogLevelIsTrace", null)] [InlineData(1, EventLogEntryType.Information, "AtInformationLevel_WhenNLogLevelIsDebug", null)] [InlineData(2, EventLogEntryType.Information, "AtInformationLevel_WhenNLogLevelIsInfo", null)] [InlineData(3, EventLogEntryType.Warning, "AtWarningLevel_WhenNLogLevelIsWarn", null)] [InlineData(4, EventLogEntryType.Error, "AtErrorLevel_WhenNLogLevelIsError", null)] [InlineData(5, EventLogEntryType.Error, "AtErrorLevel_WhenNLogLevelIsFatal", null)] [InlineData(3, EventLogEntryType.SuccessAudit, "AtSuccessAuditLevel_WhenEntryTypeLayoutSpecifiedAsSuccessAudit", "SuccessAudit")] [InlineData(3, EventLogEntryType.SuccessAudit, "AtSuccessAuditLevel_WhenEntryTypeLayoutSpecifiedAsSuccessAudit_Uppercase", "SUCCESSAUDIT")] [InlineData(1, EventLogEntryType.FailureAudit, "AtFailureAuditLevel_WhenEntryTypeLayoutSpecifiedAsFailureAudit_Space", "FailureAudit ")] [InlineData(1, EventLogEntryType.Error, "AtErrorLevel_WhenEntryTypeLayoutSpecifiedAsErrorLowerCase", "error")] [InlineData(3, EventLogEntryType.Warning, "AtSpecifiedNLogLevel_WhenWrongEntryTypeLayoutSupplied", "fallback to auto determined")] public void TruncatedMessagesShouldBeWrittenAtCorrenpondingNLogLevel(int logLevelOrdinal, EventLogEntryType expectedEventLogEntryType, string expectedMessage, string layoutString) { LogLevel logLevel = LogLevel.FromOrdinal(logLevelOrdinal); Layout entryTypeLayout = layoutString != null ? new SimpleLayout(layoutString) : null; var eventRecords = WriteWithMock(logLevel, expectedEventLogEntryType, expectedMessage, entryTypeLayout).ToList(); Assert.Single(eventRecords); AssertWrittenMessage(eventRecords, expectedMessage); } [Theory] [InlineData(0, EventLogEntryType.Information, null)] // AtInformationLevel_WhenNLogLevelIsTrace [InlineData(1, EventLogEntryType.Information, null)] // AtInformationLevel_WhenNLogLevelIsDebug [InlineData(2, EventLogEntryType.Information, null)] // AtInformationLevel_WhenNLogLevelIsInfo [InlineData(3, EventLogEntryType.Warning, null)] // AtWarningLevel_WhenNLogLevelIsWarn [InlineData(4, EventLogEntryType.Error, null)] // AtErrorLevel_WhenNLogLevelIsError [InlineData(5, EventLogEntryType.Error, null)] // AtErrorLevel_WhenNLogLevelIsFatal [InlineData(1, EventLogEntryType.SuccessAudit, "SuccessAudit")] // AtSuccessAuditLevel_WhenEntryTypeLayoutSpecifiedAsSuccessAudit [InlineData(1, EventLogEntryType.FailureAudit, "FailureAudit")] // AtFailureLevel_WhenEntryTypeLayoutSpecifiedAsFailureAudit [InlineData(1, EventLogEntryType.Error, "error")] // AtErrorLevel_WhenEntryTypeLayoutSpecifiedAsError [InlineData(2, EventLogEntryType.Information, "wrong entry type level")] // AtSpecifiedNLogLevel_WhenWrongEntryTypeLayoutSupplied public void SplitMessagesShouldBeWrittenAtCorrenpondingNLogLevel(int logLevelOrdinal, EventLogEntryType expectedEventLogEntryType, string layoutString) { LogLevel logLevel = LogLevel.FromOrdinal(logLevelOrdinal); Layout entryTypeLayout = layoutString != null ? new SimpleLayout(layoutString) : null; const int expectedEntryCount = 2; string messagePart1 = string.Join("", Enumerable.Repeat("l", MaxMessageLength)); string messagePart2 = "this part must be split"; string testMessage = messagePart1 + messagePart2; var entries = WriteWithMock(logLevel, expectedEventLogEntryType, testMessage, entryTypeLayout, EventLogTargetOverflowAction.Split).ToList(); Assert.Equal(expectedEntryCount, entries.Count); } [Fact] public void WriteEventLogEntryLargerThanMaxMessageLengthWithOverflowTruncate_TruncatesTheMessage() { string expectedMessage = string.Join("", Enumerable.Repeat("t", MaxMessageLength)); string expectedToTruncateMessage = " this part will be truncated"; string testMessage = expectedMessage + expectedToTruncateMessage; var entries = WriteWithMock(LogLevel.Info, EventLogEntryType.Information, testMessage).ToList(); Assert.Single(entries); AssertWrittenMessage(entries, expectedMessage); } [Fact] public void WriteEventLogEntryEqualToMaxMessageLengthWithOverflowTruncate_TheMessageIsNotTruncated() { string expectedMessage = string.Join("", Enumerable.Repeat("t", MaxMessageLength)); var entries = WriteWithMock(LogLevel.Info, EventLogEntryType.Information, expectedMessage).ToList(); Assert.Single(entries); AssertWrittenMessage(entries, expectedMessage); } [Fact] public void WriteEventLogEntryLargerThanMaxMessageLengthWithOverflowSplitEntries_TheMessageShouldBeSplit() { const int expectedEntryCount = 5; string messagePart1 = string.Join("", Enumerable.Repeat("a", MaxMessageLength)); string messagePart2 = string.Join("", Enumerable.Repeat("b", MaxMessageLength)); string messagePart3 = string.Join("", Enumerable.Repeat("c", MaxMessageLength)); string messagePart4 = string.Join("", Enumerable.Repeat("d", MaxMessageLength)); string messagePart5 = "this part must be split too"; string testMessage = messagePart1 + messagePart2 + messagePart3 + messagePart4 + messagePart5; var entries = WriteWithMock(LogLevel.Info, EventLogEntryType.Information, testMessage, null, EventLogTargetOverflowAction.Split).ToList(); Assert.Equal(expectedEntryCount, entries.Count); AssertWrittenMessage(entries, messagePart1); AssertWrittenMessage(entries, messagePart2); AssertWrittenMessage(entries, messagePart3); AssertWrittenMessage(entries, messagePart4); AssertWrittenMessage(entries, messagePart5); } [Fact] public void WriteEventLogEntryEqualToMaxMessageLengthWithOverflowSplitEntries_TheMessageShouldBeSplitInTwoChunks() { const int expectedEntryCount = 2; string messagePart1 = string.Join("", Enumerable.Repeat("a", MaxMessageLength)); string messagePart2 = string.Join("", Enumerable.Repeat("b", MaxMessageLength)); string testMessage = messagePart1 + messagePart2; var entries = WriteWithMock(LogLevel.Info, EventLogEntryType.Information, testMessage, null, EventLogTargetOverflowAction.Split).ToList(); Assert.Equal(expectedEntryCount, entries.Count); AssertWrittenMessage(entries, messagePart1); AssertWrittenMessage(entries, messagePart2); } [Fact] public void WriteEventLogEntryEqualToMaxMessageLengthWithOverflowSplitEntries_TheMessageIsNotSplit() { string expectedMessage = string.Join("", Enumerable.Repeat("a", MaxMessageLength)); var entries = WriteWithMock(LogLevel.Info, EventLogEntryType.Information, expectedMessage, null, EventLogTargetOverflowAction.Split).ToList(); Assert.Single(entries); AssertWrittenMessage(entries, expectedMessage); } [Fact] public void WriteEventLogEntryEqualToMaxMessageLengthWithOverflowDiscard_TheMessageIsWritten() { string expectedMessage = string.Join("", Enumerable.Repeat("a", MaxMessageLength)); var entries = WriteWithMock(LogLevel.Info, EventLogEntryType.Information, expectedMessage, null, EventLogTargetOverflowAction.Discard).ToList(); Assert.Single(entries); AssertWrittenMessage(entries, expectedMessage); } [Fact] public void WriteEventLogEntryLargerThanMaxMessageLengthWithOverflowDiscard_TheMessageIsNotWritten() { string messagePart1 = string.Join("", Enumerable.Repeat("a", MaxMessageLength)); string messagePart2 = "b"; string testMessage = messagePart1 + messagePart2; bool wasWritten = WriteWithMock(LogLevel.Info, EventLogEntryType.Information, testMessage, null, EventLogTargetOverflowAction.Discard).Any(); Assert.False(wasWritten); } [Fact] public void WriteEventLogEntry_WithoutSource_WillBeDiscarded() { // Arrange var eventLogMock = new EventLogMock( deleteEventSourceFunction: (source, machineName) => { }, sourceExistsFunction: (source, machineName) => true, logNameFromSourceNameFunction: (source, machineName) => string.Empty, createEventSourceFunction: (sourceData) => { }); var target = new EventLogTarget(eventLogMock, null); target.Source = "${event-properties:item=DynamicSource}"; var logFactory = new LogFactory(); var logConfig = new LoggingConfiguration(logFactory); logConfig.AddRuleForAllLevels(target); logFactory.Configuration = logConfig; // Act var logger = logFactory.GetLogger("EventLogCorrectLog"); logger.Info("Hello"); // Assert Assert.Empty(eventLogMock.WrittenEntries); } [Fact] public void WriteEventLogEntry_WillRecreate_WhenWrongLogName() { // Arrange string sourceName = "NLog.UnitTests" + Guid.NewGuid().ToString("N"); string deletedSourceName = string.Empty; string createdLogName = string.Empty; var eventLogMock = new EventLogMock( deleteEventSourceFunction: (source, machineName) => deletedSourceName = source, sourceExistsFunction: (source, machineName) => true, logNameFromSourceNameFunction: (source, machineName) => "FaultyLog", createEventSourceFunction: (sourceData) => createdLogName = sourceData.LogName); var target = new EventLogTarget(eventLogMock, null); target.Log = "CorrectLog"; target.Source = sourceName; target.Layout = "${message}"; var logFactory = new LogFactory(); var logConfig = new LoggingConfiguration(logFactory); logConfig.AddRuleForAllLevels(target); logFactory.Configuration = logConfig; // Act var logger = logFactory.GetLogger("EventLogCorrectLog"); logger.Info("Hello"); // Assert Assert.Equal(sourceName, deletedSourceName); Assert.Equal(target.Log, createdLogName); Assert.Single(eventLogMock.WrittenEntries); Assert.Equal(target.Log, eventLogMock.WrittenEntries[0].Log); Assert.Equal(sourceName, eventLogMock.WrittenEntries[0].Source); Assert.Equal("Hello", eventLogMock.WrittenEntries[0].Message); } [Fact] public void WriteEventLogEntry_WillComplain_WhenWrongLogName() { // Arrange string sourceName = "NLog.UnitTests" + Guid.NewGuid().ToString("N"); string deletedSourceName = string.Empty; string createdLogName = string.Empty; var eventLogMock = new EventLogMock( deleteEventSourceFunction: (source, machineName) => deletedSourceName = source, sourceExistsFunction: (source, machineName) => true, logNameFromSourceNameFunction: (source, machineName) => "FaultyLog", createEventSourceFunction: (sourceData) => createdLogName = sourceData.LogName); var target = new EventLogTarget(eventLogMock, null); target.Log = "CorrectLog"; target.Source = "${event-properties:item=DynamicSource}"; target.Layout = "${message}"; var logFactory = new LogFactory(); var logConfig = new LoggingConfiguration(logFactory); logConfig.AddRuleForAllLevels(target); logFactory.Configuration = logConfig; // Act var logger = logFactory.GetLogger("EventLogCorrectLog"); logger.Info("Hello {DynamicSource:l}", sourceName); // Assert Assert.Equal(string.Empty, deletedSourceName); Assert.Equal(string.Empty, createdLogName); Assert.Equal(target.Log, eventLogMock.WrittenEntries[0].Log); Assert.Equal(sourceName, eventLogMock.WrittenEntries[0].Source); Assert.Equal($"Hello {sourceName}", eventLogMock.WrittenEntries[0].Message); } [Fact] public void WriteEventLogEntryWithDynamicSource() { const int maxMessageLength = 10; string expectedMessage = string.Join("", Enumerable.Repeat("a", maxMessageLength)); var target = CreateEventLogTarget("NLog.UnitTests" + Guid.NewGuid().ToString("N"), EventLogTargetOverflowAction.Split, maxMessageLength); target.Layout = new SimpleLayout("${message}"); target.Source = new SimpleLayout("${event-properties:item=DynamicSource}"); SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace); var logger = LogManager.GetLogger("WriteEventLogEntry"); var sourceName = "NLog.UnitTests" + Guid.NewGuid().ToString("N"); var logEvent = CreateLogEventWithDynamicSource(expectedMessage, LogLevel.Trace, "DynamicSource", sourceName); logger.Log(logEvent); var eventLog = new EventLog(target.Log); var entries = GetEventRecords(eventLog.Log).ToList(); entries = entries.Where(a => a.ProviderName == sourceName).ToList(); Assert.Single(entries); AssertWrittenMessage(entries, expectedMessage); sourceName = "NLog.UnitTests" + Guid.NewGuid().ToString("N"); expectedMessage = string.Join("", Enumerable.Repeat("b", maxMessageLength)); logEvent = CreateLogEventWithDynamicSource(expectedMessage, LogLevel.Trace, "DynamicSource", sourceName); logger.Log(logEvent); entries = GetEventRecords(eventLog.Log).ToList(); entries = entries.Where(a => a.ProviderName == sourceName).ToList(); Assert.Single(entries); AssertWrittenMessage(entries, expectedMessage); } [Fact] public void LogEntryWithStaticEventIdAndCategoryInTargetLayout() { var rnd = new Random(); int eventId = rnd.Next(1, short.MaxValue); int category = rnd.Next(1, short.MaxValue); var target = CreateEventLogTarget("NLog.UnitTests" + Guid.NewGuid().ToString("N"), EventLogTargetOverflowAction.Truncate, 5000); target.EventId = new SimpleLayout(eventId.ToString()); target.Category = new SimpleLayout(category.ToString()); SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace); var logger = LogManager.GetLogger("WriteEventLogEntry"); logger.Log(LogLevel.Error, "Simple Test Message"); var eventLog = new EventLog(target.Log); var entries = GetEventRecords(eventLog.Log).ToList(); var expectedProviderName = target.GetFixedSource(); var filtered = entries.Where(entry => entry.ProviderName == expectedProviderName && HasEntryType(entry, EventLogEntryType.Error) ); Assert.Single(filtered); var record = filtered.First(); Assert.Equal(eventId, record.Id); Assert.Equal(category, record.Task); } [Fact] public void LogEntryWithDynamicEventIdAndCategory() { var rnd = new Random(); int eventId = rnd.Next(1, short.MaxValue); int category = rnd.Next(1, short.MaxValue); var target = CreateEventLogTarget("NLog.UnitTests" + Guid.NewGuid().ToString("N"), EventLogTargetOverflowAction.Truncate, 5000); target.EventId = new SimpleLayout("${event-properties:EventId}"); target.Category = new SimpleLayout("${event-properties:Category}"); SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace); var logger = LogManager.GetLogger("WriteEventLogEntry"); LogEventInfo theEvent = new LogEventInfo(LogLevel.Error, "TestLoggerName", "Simple Message"); theEvent.Properties["EventId"] = eventId; theEvent.Properties["Category"] = category; logger.Log(theEvent); var eventLog = new EventLog(target.Log); var entries = GetEventRecords(eventLog.Log).ToList(); var expectedProviderName = target.GetFixedSource(); var filtered = entries.Where(entry => entry.ProviderName == expectedProviderName && HasEntryType(entry, EventLogEntryType.Error) ); Assert.Single(filtered); var record = filtered.First(); Assert.Equal(eventId, record.Id); Assert.Equal(category, record.Task); } private static IEnumerable<EventLogMock.EventRecord> WriteWithMock(LogLevel logLevel, EventLogEntryType expectedEventLogEntryType, string logMessage, Layout entryType = null, EventLogTargetOverflowAction overflowAction = EventLogTargetOverflowAction.Truncate, int maxMessageLength = MaxMessageLength) { var sourceName = "NLog.UnitTests" + Guid.NewGuid().ToString("N"); var eventLogMock = new EventLogMock( deleteEventSourceFunction: (source, machineName) => { }, sourceExistsFunction: (source, machineName) => false, logNameFromSourceNameFunction: (source, machineName) => string.Empty, createEventSourceFunction: (sourceData) => { }); var target = new EventLogTarget(eventLogMock, null); InitializeEventLogTarget(target, sourceName, overflowAction, maxMessageLength, entryType); SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace); var logger = LogManager.GetLogger("WriteEventLogEntry"); logger.Log(logLevel, logMessage); var entries = eventLogMock.WrittenEntries; var expectedSource = target.GetFixedSource(); var filteredEntries = entries.Where(entry => entry.Source == expectedSource && entry.EntryType == expectedEventLogEntryType ); if (overflowAction == EventLogTargetOverflowAction.Discard && logMessage.Length > maxMessageLength) { Assert.False(filteredEntries.Any(), $"No message is expected. But {filteredEntries.Count()} message(s) found entry of type '{expectedEventLogEntryType}' from source '{expectedSource}'."); } else { Assert.True(filteredEntries.Any(), $"Failed to find entry of type '{expectedEventLogEntryType}' from source '{expectedSource}'"); } return filteredEntries; } private void AssertWrittenMessage(IEnumerable<EventRecord> eventLogs, string expectedMessage) { var messages = eventLogs.Where(entry => entry.Properties.Any(prop => Convert.ToString(prop.Value) == expectedMessage)); Assert.True(messages.Any(), $"Event records has not the expected message: '{expectedMessage}'"); } private void AssertWrittenMessage(IEnumerable<EventLogMock.EventRecord> eventLogs, string expectedMessage) { var messages = eventLogs.Where(entry => entry.Message == expectedMessage); Assert.True(messages.Any(), $"Event records has not the expected message: '{expectedMessage}'"); } private static EventLogTarget CreateEventLogTarget(string sourceName, EventLogTargetOverflowAction overflowAction, int maxMessageLength, Layout entryType = null) { return InitializeEventLogTarget(new EventLogTarget(), sourceName, overflowAction, maxMessageLength, entryType); } private static EventLogTarget InitializeEventLogTarget(EventLogTarget target, string sourceName, EventLogTargetOverflowAction overflowAction, int maxMessageLength, Layout entryType) { target.Name = "eventlog"; target.Log = "application"; // The Log to write to is intentionally lower case!! target.Source = sourceName; // set the source explicitly to prevent random AppDomain name being used as the source name target.Layout = new SimpleLayout("${message}"); //Be able to check message length and content, the Layout is intentionally only ${message}. target.OnOverflow = overflowAction; target.MaxMessageLength = maxMessageLength; if (entryType != null) { target.EntryType = entryType; } return target; } private LogEventInfo CreateLogEventWithDynamicSource(string message, LogLevel level, string propertyKey, string proertyValue) { var logEvent = new LogEventInfo(); logEvent.Message = message; logEvent.Level = level; logEvent.Properties[propertyKey] = proertyValue; return logEvent; } private static IEnumerable<EventRecord> GetEventRecords(string logName) { var query = new EventLogQuery(logName, PathType.LogName) { ReverseDirection = true }; using (var reader = new EventLogReader(query)) for (var eventInstance = reader.ReadEvent(); eventInstance != null; eventInstance = reader.ReadEvent()) yield return eventInstance; } private static bool HasEntryType(EventRecord eventRecord, EventLogEntryType entryType) { var keywords = (StandardEventKeywords)(eventRecord.Keywords ?? 0); var level = (StandardEventLevel)(eventRecord.Level ?? 0); bool isClassicEvent = keywords.HasFlag(StandardEventKeywords.EventLogClassic); switch (entryType) { case EventLogEntryType.Error: return isClassicEvent && level == StandardEventLevel.Error; case EventLogEntryType.Warning: return isClassicEvent && level == StandardEventLevel.Warning; case EventLogEntryType.Information: return isClassicEvent && level == StandardEventLevel.Informational; case EventLogEntryType.SuccessAudit: return keywords.HasFlag(StandardEventKeywords.AuditSuccess); case EventLogEntryType.FailureAudit: return keywords.HasFlag(StandardEventKeywords.AuditFailure); } return false; } private class EventLogMock : EventLogTarget.IEventLogWrapper { public const int EventLogDefaultMaxKilobytes = 512; public EventLogMock( Action<string, string> deleteEventSourceFunction, Func<string, string, bool> sourceExistsFunction, Func<string, string, string> logNameFromSourceNameFunction, Action<EventSourceCreationData> createEventSourceFunction) { DeleteEventSourceFunction = deleteEventSourceFunction ?? throw new ArgumentNullException(nameof(deleteEventSourceFunction)); SourceExistsFunction = sourceExistsFunction ?? throw new ArgumentNullException(nameof(sourceExistsFunction)); LogNameFromSourceNameFunction = logNameFromSourceNameFunction ?? throw new ArgumentNullException(nameof(logNameFromSourceNameFunction)); CreateEventSourceFunction = createEventSourceFunction ?? throw new ArgumentNullException(nameof(createEventSourceFunction)); } private Action<string, string> DeleteEventSourceFunction { get; } private Func<string, string, bool> SourceExistsFunction { get; } private Func<string, string, string> LogNameFromSourceNameFunction { get; } private Action<EventSourceCreationData> CreateEventSourceFunction { get; } public class EventRecord { public string Message { get; set; } public EventLogEntryType EntryType { get; set; } public string Log { get; set; } public string Source { get; set; } public string MachineName { get; set; } public int EventId { get; set; } public short Category { get; set; } } internal List<EventRecord> WrittenEntries { get; } = new List<EventRecord>(); /// <inheritdoc /> public string Source { get; set; } /// <inheritdoc /> public string Log { get; set; } /// <inheritdoc /> public string MachineName { get; set; } /// <inheritdoc /> public long MaximumKilobytes { get; set; } = EventLogDefaultMaxKilobytes; /// <inheritdoc /> public void WriteEntry(string message, EventLogEntryType entryType, int eventId, short category) { if (!IsEventLogAssociated) throw new InvalidOperationException("Missing initialization using AssociateNewEventLog"); WrittenEntries.Add(new EventRecord() { Message = message, EntryType = entryType, EventId = eventId, Category = category, Source = Source, Log = Log, MachineName = MachineName, }); } /// <inheritdoc /> public bool IsEventLogAssociated { get; private set; } /// <inheritdoc /> public void AssociateNewEventLog(string logName, string machineName, string source) { Log = logName; MachineName = machineName; Source = source; if (!IsEventLogAssociated) { IsEventLogAssociated = true; } } /// <inheritdoc /> public void DeleteEventSource(string source, string machineName) => DeleteEventSourceFunction(source, machineName); /// <inheritdoc /> public bool SourceExists(string source, string machineName) => SourceExistsFunction(source, machineName); /// <inheritdoc /> public string LogNameFromSourceName(string source, string machineName) => LogNameFromSourceNameFunction(source, machineName); /// <inheritdoc /> public void CreateEventSource(EventSourceCreationData sourceData) => CreateEventSourceFunction(sourceData); } } } #endif
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Injector.UI.Areas.HelpPage.ModelDescriptions; using Injector.UI.Areas.HelpPage.Models; namespace Injector.UI.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } if (complexTypeDescription != null) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
/* * Copyright (c) 2007-2009, openmetaverse.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. * - Neither the name of the openmetaverse.org nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Threading; using System.Collections; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Globalization; using System.IO; using OpenMetaverse.Packets; using OpenMetaverse.StructuredData; using OpenMetaverse.Interfaces; using OpenMetaverse.Messages.Linden; namespace OpenMetaverse { /// <summary> /// NetworkManager is responsible for managing the network layer of /// OpenMetaverse. It tracks all the server connections, serializes /// outgoing traffic and deserializes incoming traffic, and provides /// instances of delegates for network-related events. /// </summary> public partial class NetworkManager { #region Enums /// <summary> /// Explains why a simulator or the grid disconnected from us /// </summary> public enum DisconnectType { /// <summary>The client requested the logout or simulator disconnect</summary> ClientInitiated, /// <summary>The server notified us that it is disconnecting</summary> ServerInitiated, /// <summary>Either a socket was closed or network traffic timed out</summary> NetworkTimeout, /// <summary>The last active simulator shut down</summary> SimShutdown } #endregion Enums #region Structs /// <summary> /// Holds a simulator reference and a decoded packet, these structs are put in /// the packet inbox for event handling /// </summary> public struct IncomingPacket { /// <summary>Reference to the simulator that this packet came from</summary> public Simulator Simulator; /// <summary>Packet that needs to be processed</summary> public Packet Packet; public IncomingPacket(Simulator simulator, Packet packet) { Simulator = simulator; Packet = packet; } } /// <summary> /// Holds a simulator reference and a serialized packet, these structs are put in /// the packet outbox for sending /// </summary> public class OutgoingPacket { /// <summary>Reference to the simulator this packet is destined for</summary> public readonly Simulator Simulator; /// <summary>Packet that needs to be sent</summary> public readonly UDPPacketBuffer Buffer; /// <summary>Sequence number of the wrapped packet</summary> public uint SequenceNumber; /// <summary>Number of times this packet has been resent</summary> public int ResendCount; /// <summary>Environment.TickCount when this packet was last sent over the wire</summary> public int TickCount; /// <summary>Type of the packet</summary> public PacketType Type; public OutgoingPacket(Simulator simulator, UDPPacketBuffer buffer, PacketType type) { Simulator = simulator; Buffer = buffer; this.Type = type; } } #endregion Structs #region Delegates /// <summary>The event subscribers, null of no subscribers</summary> private EventHandler<PacketSentEventArgs> m_PacketSent; ///<summary>Raises the PacketSent Event</summary> /// <param name="e">A PacketSentEventArgs object containing /// the data sent from the simulator</param> protected virtual void OnPacketSent(PacketSentEventArgs e) { EventHandler<PacketSentEventArgs> handler = m_PacketSent; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_PacketSentLock = new object(); /// <summary>Raised when the simulator sends us data containing /// ...</summary> public event EventHandler<PacketSentEventArgs> PacketSent { add { lock (m_PacketSentLock) { m_PacketSent += value; } } remove { lock (m_PacketSentLock) { m_PacketSent -= value; } } } /// <summary>The event subscribers, null of no subscribers</summary> private EventHandler<LoggedOutEventArgs> m_LoggedOut; ///<summary>Raises the LoggedOut Event</summary> /// <param name="e">A LoggedOutEventArgs object containing /// the data sent from the simulator</param> protected virtual void OnLoggedOut(LoggedOutEventArgs e) { EventHandler<LoggedOutEventArgs> handler = m_LoggedOut; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_LoggedOutLock = new object(); /// <summary>Raised when the simulator sends us data containing /// ...</summary> public event EventHandler<LoggedOutEventArgs> LoggedOut { add { lock (m_LoggedOutLock) { m_LoggedOut += value; } } remove { lock (m_LoggedOutLock) { m_LoggedOut -= value; } } } /// <summary>The event subscribers, null of no subscribers</summary> private EventHandler<SimConnectingEventArgs> m_SimConnecting; ///<summary>Raises the SimConnecting Event</summary> /// <param name="e">A SimConnectingEventArgs object containing /// the data sent from the simulator</param> protected virtual void OnSimConnecting(SimConnectingEventArgs e) { EventHandler<SimConnectingEventArgs> handler = m_SimConnecting; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_SimConnectingLock = new object(); /// <summary>Raised when the simulator sends us data containing /// ...</summary> public event EventHandler<SimConnectingEventArgs> SimConnecting { add { lock (m_SimConnectingLock) { m_SimConnecting += value; } } remove { lock (m_SimConnectingLock) { m_SimConnecting -= value; } } } /// <summary>The event subscribers, null of no subscribers</summary> private EventHandler<SimConnectedEventArgs> m_SimConnected; ///<summary>Raises the SimConnected Event</summary> /// <param name="e">A SimConnectedEventArgs object containing /// the data sent from the simulator</param> protected virtual void OnSimConnected(SimConnectedEventArgs e) { EventHandler<SimConnectedEventArgs> handler = m_SimConnected; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_SimConnectedLock = new object(); /// <summary>Raised when the simulator sends us data containing /// ...</summary> public event EventHandler<SimConnectedEventArgs> SimConnected { add { lock (m_SimConnectedLock) { m_SimConnected += value; } } remove { lock (m_SimConnectedLock) { m_SimConnected -= value; } } } /// <summary>The event subscribers, null of no subscribers</summary> private EventHandler<SimDisconnectedEventArgs> m_SimDisconnected; ///<summary>Raises the SimDisconnected Event</summary> /// <param name="e">A SimDisconnectedEventArgs object containing /// the data sent from the simulator</param> protected virtual void OnSimDisconnected(SimDisconnectedEventArgs e) { EventHandler<SimDisconnectedEventArgs> handler = m_SimDisconnected; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_SimDisconnectedLock = new object(); /// <summary>Raised when the simulator sends us data containing /// ...</summary> public event EventHandler<SimDisconnectedEventArgs> SimDisconnected { add { lock (m_SimDisconnectedLock) { m_SimDisconnected += value; } } remove { lock (m_SimDisconnectedLock) { m_SimDisconnected -= value; } } } /// <summary>The event subscribers, null of no subscribers</summary> private EventHandler<DisconnectedEventArgs> m_Disconnected; ///<summary>Raises the Disconnected Event</summary> /// <param name="e">A DisconnectedEventArgs object containing /// the data sent from the simulator</param> protected virtual void OnDisconnected(DisconnectedEventArgs e) { EventHandler<DisconnectedEventArgs> handler = m_Disconnected; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_DisconnectedLock = new object(); /// <summary>Raised when the simulator sends us data containing /// ...</summary> public event EventHandler<DisconnectedEventArgs> Disconnected { add { lock (m_DisconnectedLock) { m_Disconnected += value; } } remove { lock (m_DisconnectedLock) { m_Disconnected -= value; } } } /// <summary>The event subscribers, null of no subscribers</summary> private EventHandler<SimChangedEventArgs> m_SimChanged; ///<summary>Raises the SimChanged Event</summary> /// <param name="e">A SimChangedEventArgs object containing /// the data sent from the simulator</param> protected virtual void OnSimChanged(SimChangedEventArgs e) { EventHandler<SimChangedEventArgs> handler = m_SimChanged; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_SimChangedLock = new object(); /// <summary>Raised when the simulator sends us data containing /// ...</summary> public event EventHandler<SimChangedEventArgs> SimChanged { add { lock (m_SimChangedLock) { m_SimChanged += value; } } remove { lock (m_SimChangedLock) { m_SimChanged -= value; } } } /// <summary>The event subscribers, null of no subscribers</summary> private EventHandler<EventQueueRunningEventArgs> m_EventQueueRunning; ///<summary>Raises the EventQueueRunning Event</summary> /// <param name="e">A EventQueueRunningEventArgs object containing /// the data sent from the simulator</param> protected virtual void OnEventQueueRunning(EventQueueRunningEventArgs e) { EventHandler<EventQueueRunningEventArgs> handler = m_EventQueueRunning; if (handler != null) handler(this, e); } /// <summary>Thread sync lock object</summary> private readonly object m_EventQueueRunningLock = new object(); /// <summary>Raised when the simulator sends us data containing /// ...</summary> public event EventHandler<EventQueueRunningEventArgs> EventQueueRunning { add { lock (m_EventQueueRunningLock) { m_EventQueueRunning += value; } } remove { lock (m_EventQueueRunningLock) { m_EventQueueRunning -= value; } } } #endregion Delegates #region Properties /// <summary>Unique identifier associated with our connections to /// simulators</summary> public uint CircuitCode { get { return _CircuitCode; } set { _CircuitCode = value; } } /// <summary>The simulator that the logged in avatar is currently /// occupying</summary> public Simulator CurrentSim { get { return _CurrentSim; } set { _CurrentSim = value; } } /// <summary>Shows whether the network layer is logged in to the /// grid or not</summary> public bool Connected { get { return connected; } } /// <summary>Number of packets in the incoming queue</summary> public int InboxCount { get { return PacketInbox.Count; } } /// <summary>Number of packets in the outgoing queue</summary> public int OutboxCount { get { return PacketOutbox.Count; } } #endregion Properties /// <summary>All of the simulators we are currently connected to</summary> public List<Simulator> Simulators = new List<Simulator>(); /// <summary>Handlers for incoming capability events</summary> internal CapsEventDictionary CapsEvents; /// <summary>Handlers for incoming packets</summary> internal PacketEventDictionary PacketEvents; /// <summary>Incoming packets that are awaiting handling</summary> internal BlockingQueue<IncomingPacket> PacketInbox = new BlockingQueue<IncomingPacket>(Settings.PACKET_INBOX_SIZE); /// <summary>Outgoing packets that are awaiting handling</summary> internal BlockingQueue<OutgoingPacket> PacketOutbox = new BlockingQueue<OutgoingPacket>(Settings.PACKET_INBOX_SIZE); private GridClient Client; private Timer DisconnectTimer; private uint _CircuitCode; private Simulator _CurrentSim = null; private bool connected = false; /// <summary> /// Default constructor /// </summary> /// <param name="client">Reference to the GridClient object</param> public NetworkManager(GridClient client) { Client = client; PacketEvents = new PacketEventDictionary(client); CapsEvents = new CapsEventDictionary(client); // Register internal CAPS callbacks RegisterEventCallback("EnableSimulator", new Caps.EventQueueCallback(EnableSimulatorHandler)); // Register the internal callbacks RegisterCallback(PacketType.RegionHandshake, RegionHandshakeHandler); RegisterCallback(PacketType.StartPingCheck, StartPingCheckHandler, false); RegisterCallback(PacketType.DisableSimulator, DisableSimulatorHandler); RegisterCallback(PacketType.KickUser, KickUserHandler); RegisterCallback(PacketType.LogoutReply, LogoutReplyHandler); RegisterCallback(PacketType.CompletePingCheck, CompletePingCheckHandler, false); RegisterCallback(PacketType.SimStats, SimStatsHandler, false); // GLOBAL SETTING: Don't force Expect-100: Continue headers on HTTP POST calls ServicePointManager.Expect100Continue = false; } /// <summary> /// Register an event handler for a packet. This is a low level event /// interface and should only be used if you are doing something not /// supported in the library /// </summary> /// <param name="type">Packet type to trigger events for</param> /// <param name="callback">Callback to fire when a packet of this type /// is received</param> public void RegisterCallback(PacketType type, EventHandler<PacketReceivedEventArgs> callback) { RegisterCallback(type, callback, true); } /// <summary> /// Register an event handler for a packet. This is a low level event /// interface and should only be used if you are doing something not /// supported in the library /// </summary> /// <param name="type">Packet type to trigger events for</param> /// <param name="callback">Callback to fire when a packet of this type /// is received</param> /// <param name="isAsync">True if the callback should be ran /// asynchronously. Only set this to false (synchronous for callbacks /// that will always complete quickly)</param> /// <remarks>If any callback for a packet type is marked as /// asynchronous, all callbacks for that packet type will be fired /// asynchronously</remarks> public void RegisterCallback(PacketType type, EventHandler<PacketReceivedEventArgs> callback, bool isAsync) { PacketEvents.RegisterEvent(type, callback, isAsync); } /// <summary> /// Unregister an event handler for a packet. This is a low level event /// interface and should only be used if you are doing something not /// supported in the library /// </summary> /// <param name="type">Packet type this callback is registered with</param> /// <param name="callback">Callback to stop firing events for</param> public void UnregisterCallback(PacketType type, EventHandler<PacketReceivedEventArgs> callback) { PacketEvents.UnregisterEvent(type, callback); } /// <summary> /// Register a CAPS event handler. This is a low level event interface /// and should only be used if you are doing something not supported in /// the library /// </summary> /// <param name="capsEvent">Name of the CAPS event to register a handler for</param> /// <param name="callback">Callback to fire when a CAPS event is received</param> public void RegisterEventCallback(string capsEvent, Caps.EventQueueCallback callback) { CapsEvents.RegisterEvent(capsEvent, callback); } /// <summary> /// Unregister a CAPS event handler. This is a low level event interface /// and should only be used if you are doing something not supported in /// the library /// </summary> /// <param name="capsEvent">Name of the CAPS event this callback is /// registered with</param> /// <param name="callback">Callback to stop firing events for</param> public void UnregisterEventCallback(string capsEvent, Caps.EventQueueCallback callback) { CapsEvents.UnregisterEvent(capsEvent, callback); } /// <summary> /// Send a packet to the simulator the avatar is currently occupying /// </summary> /// <param name="packet">Packet to send</param> public void SendPacket(Packet packet) { // try CurrentSim, however directly after login this will // be null, so if it is, we'll try to find the first simulator // we're connected to in order to send the packet. Simulator simulator = CurrentSim; if (simulator == null && Client.Network.Simulators.Count >= 1) { Logger.DebugLog("CurrentSim object was null, using first found connected simulator", Client); simulator = Client.Network.Simulators[0]; } if (simulator != null && simulator.Connected) { simulator.SendPacket(packet); } else { //throw new NotConnectedException("Packet received before simulator packet processing threads running, make certain you are completely logged in"); Logger.Log("Packet received before simulator packet processing threads running, make certain you are completely logged in.", Helpers.LogLevel.Error); } } /// <summary> /// Send a packet to a specified simulator /// </summary> /// <param name="packet">Packet to send</param> /// <param name="simulator">Simulator to send the packet to</param> public void SendPacket(Packet packet, Simulator simulator) { if (simulator != null) { simulator.SendPacket(packet); } else { Logger.Log("Packet received before simulator packet processing threads running, make certain you are completely logged in", Helpers.LogLevel.Error); } } /// <summary> /// Connect to a simulator /// </summary> /// <param name="ip">IP address to connect to</param> /// <param name="port">Port to connect to</param> /// <param name="handle">Handle for this simulator, to identify its /// location in the grid</param> /// <param name="setDefault">Whether to set CurrentSim to this new /// connection, use this if the avatar is moving in to this simulator</param> /// <param name="seedcaps">URL of the capabilities server to use for /// this sim connection</param> /// <returns>A Simulator object on success, otherwise null</returns> public Simulator Connect(IPAddress ip, ushort port, ulong handle, bool setDefault, string seedcaps) { IPEndPoint endPoint = new IPEndPoint(ip, (int)port); return Connect(endPoint, handle, setDefault, seedcaps); } /// <summary> /// Connect to a simulator /// </summary> /// <param name="endPoint">IP address and port to connect to</param> /// <param name="handle">Handle for this simulator, to identify its /// location in the grid</param> /// <param name="setDefault">Whether to set CurrentSim to this new /// connection, use this if the avatar is moving in to this simulator</param> /// <param name="seedcaps">URL of the capabilities server to use for /// this sim connection</param> /// <returns>A Simulator object on success, otherwise null</returns> public Simulator Connect(IPEndPoint endPoint, ulong handle, bool setDefault, string seedcaps) { Simulator simulator = FindSimulator(endPoint); if (simulator == null) { // We're not tracking this sim, create a new Simulator object simulator = new Simulator(Client, endPoint, handle); // Immediately add this simulator to the list of current sims. It will be removed if the // connection fails lock (Simulators) Simulators.Add(simulator); } if (!simulator.Connected) { if (!connected) { // Mark that we are connecting/connected to the grid // connected = true; // Open the queues in case this is a reconnect and they were shut down PacketInbox.Open(); PacketOutbox.Open(); // Start the packet decoding thread Thread decodeThread = new Thread(new ThreadStart(IncomingPacketHandler)); decodeThread.Name = "Incoming UDP packet dispatcher"; decodeThread.Start(); // Start the packet sending thread Thread sendThread = new Thread(new ThreadStart(OutgoingPacketHandler)); sendThread.Name = "Outgoing UDP packet dispatcher"; sendThread.Start(); } // raise the SimConnecting event and allow any event // subscribers to cancel the connection if (m_SimConnecting != null) { SimConnectingEventArgs args = new SimConnectingEventArgs(simulator); OnSimConnecting(args); if (args.Cancel) { // Callback is requesting that we abort this connection lock (Simulators) { Simulators.Remove(simulator); } return null; } } // Attempt to establish a connection to the simulator if (simulator.Connect(setDefault)) { if (DisconnectTimer == null) { // Start a timer that checks if we've been disconnected DisconnectTimer = new Timer(new TimerCallback(DisconnectTimer_Elapsed), null, Client.Settings.SIMULATOR_TIMEOUT, Client.Settings.SIMULATOR_TIMEOUT); } if (setDefault) { SetCurrentSim(simulator, seedcaps); } // Raise the SimConnected event if (m_SimConnected != null) { OnSimConnected(new SimConnectedEventArgs(simulator)); } // If enabled, send an AgentThrottle packet to the server to increase our bandwidth if (Client.Settings.SEND_AGENT_THROTTLE) { Client.Throttle.Set(simulator); } return simulator; } else { // Connection failed, remove this simulator from our list and destroy it lock (Simulators) { Simulators.Remove(simulator); } return null; } } else if (setDefault) { // Move in to this simulator simulator.handshakeComplete = false; simulator.UseCircuitCode(true); Client.Self.CompleteAgentMovement(simulator); // We're already connected to this server, but need to set it to the default SetCurrentSim(simulator, seedcaps); // Send an initial AgentUpdate to complete our movement in to the sim if (Client.Settings.SEND_AGENT_UPDATES) { Client.Self.Movement.SendUpdate(true, simulator); } return simulator; } else { // Already connected to this simulator and wasn't asked to set it as the default, // just return a reference to the existing object return simulator; } } /// <summary> /// Initiate a blocking logout request. This will return when the logout /// handshake has completed or when <code>Settings.LOGOUT_TIMEOUT</code> /// has expired and the network layer is manually shut down /// </summary> public void Logout() { AutoResetEvent logoutEvent = new AutoResetEvent(false); EventHandler<LoggedOutEventArgs> callback = delegate(object sender, LoggedOutEventArgs e) { logoutEvent.Set(); }; LoggedOut += callback; // Send the packet requesting a clean logout RequestLogout(); // Wait for a logout response. If the response is received, shutdown // will be fired in the callback. Otherwise we fire it manually with // a NetworkTimeout type if (!logoutEvent.WaitOne(Client.Settings.LOGOUT_TIMEOUT, false)) Shutdown(DisconnectType.NetworkTimeout); LoggedOut -= callback; } /// <summary> /// Initiate the logout process. Check if logout succeeded with the /// <code>OnLogoutReply</code> event, and if this does not fire the /// <code>Shutdown()</code> function needs to be manually called /// </summary> public void RequestLogout() { // No need to run the disconnect timer any more if (DisconnectTimer != null) { DisconnectTimer.Dispose(); DisconnectTimer = null; } // This will catch a Logout when the client is not logged in if (CurrentSim == null || !connected) { Logger.Log("Ignoring RequestLogout(), client is already logged out", Helpers.LogLevel.Warning, Client); return; } Logger.Log("Logging out", Helpers.LogLevel.Info, Client); // Send a logout request to the current sim LogoutRequestPacket logout = new LogoutRequestPacket(); logout.AgentData.AgentID = Client.Self.AgentID; logout.AgentData.SessionID = Client.Self.SessionID; SendPacket(logout); } /// <summary> /// Close a connection to the given simulator /// </summary> /// <param name="simulator"></param> /// <param name="sendCloseCircuit"></param> public void DisconnectSim(Simulator simulator, bool sendCloseCircuit) { if (simulator != null) { simulator.Disconnect(sendCloseCircuit); // Fire the SimDisconnected event if a handler is registered if (m_SimDisconnected != null) { OnSimDisconnected(new SimDisconnectedEventArgs(simulator, DisconnectType.NetworkTimeout)); } lock (Simulators) Simulators.Remove(simulator); if (Simulators.Count == 0) Shutdown(DisconnectType.SimShutdown); } else { Logger.Log("DisconnectSim() called with a null Simulator reference", Helpers.LogLevel.Warning, Client); } } /// <summary> /// Shutdown will disconnect all the sims except for the current sim /// first, and then kill the connection to CurrentSim. This should only /// be called if the logout process times out on <code>RequestLogout</code> /// </summary> /// <param name="type">Type of shutdown</param> public void Shutdown(DisconnectType type) { Shutdown(type, type.ToString()); } /// <summary> /// Shutdown will disconnect all the sims except for the current sim /// first, and then kill the connection to CurrentSim. This should only /// be called if the logout process times out on <code>RequestLogout</code> /// </summary> /// <param name="type">Type of shutdown</param> /// <param name="message">Shutdown message</param> public void Shutdown(DisconnectType type, string message) { Logger.Log("NetworkManager shutdown initiated", Helpers.LogLevel.Info, Client); // Send a CloseCircuit packet to simulators if we are initiating the disconnect bool sendCloseCircuit = (type == DisconnectType.ClientInitiated || type == DisconnectType.NetworkTimeout); lock (Simulators) { // Disconnect all simulators except the current one for (int i = 0; i < Simulators.Count; i++) { if (Simulators[i] != null && Simulators[i] != CurrentSim) { Simulators[i].Disconnect(sendCloseCircuit); // Fire the SimDisconnected event if a handler is registered if (m_SimDisconnected != null) { OnSimDisconnected(new SimDisconnectedEventArgs(Simulators[i], type)); } } } Simulators.Clear(); } if (CurrentSim != null) { // Kill the connection to the curent simulator CurrentSim.Disconnect(sendCloseCircuit); // Fire the SimDisconnected event if a handler is registered if (m_SimDisconnected != null) { OnSimDisconnected(new SimDisconnectedEventArgs(CurrentSim, type)); } } // Clear out all of the packets that never had time to process PacketInbox.Close(); PacketOutbox.Close(); connected = false; // Fire the disconnected callback if (m_Disconnected != null) { OnDisconnected(new DisconnectedEventArgs(type, message)); } } /// <summary> /// Searches through the list of currently connected simulators to find /// one attached to the given IPEndPoint /// </summary> /// <param name="endPoint">IPEndPoint of the Simulator to search for</param> /// <returns>A Simulator reference on success, otherwise null</returns> public Simulator FindSimulator(IPEndPoint endPoint) { lock (Simulators) { for (int i = 0; i < Simulators.Count; i++) { if (Simulators[i].IPEndPoint.Equals(endPoint)) return Simulators[i]; } } return null; } internal void RaisePacketSentEvent(byte[] data, int bytesSent, Simulator simulator) { if (m_PacketSent != null) { OnPacketSent(new PacketSentEventArgs(data, bytesSent, simulator)); } } /// <summary> /// Fire an event when an event queue connects for capabilities /// </summary> /// <param name="simulator">Simulator the event queue is attached to</param> internal void RaiseConnectedEvent(Simulator simulator) { if (m_EventQueueRunning != null) { OnEventQueueRunning(new EventQueueRunningEventArgs(simulator)); } } private void OutgoingPacketHandler() { OutgoingPacket outgoingPacket = null; Simulator simulator; // FIXME: This is kind of ridiculous. Port the HTB code from Simian over ASAP! System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); while (connected) { if (PacketOutbox.Dequeue(100, ref outgoingPacket)) { simulator = outgoingPacket.Simulator; // Very primitive rate limiting, keeps a fixed buffer of time between each packet stopwatch.Stop(); if (stopwatch.ElapsedMilliseconds < 10) { //Logger.DebugLog(String.Format("Rate limiting, last packet was {0}ms ago", ms)); Thread.Sleep(10 - (int)stopwatch.ElapsedMilliseconds); } simulator.SendPacketFinal(outgoingPacket); stopwatch.Start(); } } } private void IncomingPacketHandler() { IncomingPacket incomingPacket = new IncomingPacket(); Packet packet = null; Simulator simulator = null; while (connected) { // Reset packet to null for the check below packet = null; if (PacketInbox.Dequeue(100, ref incomingPacket)) { packet = incomingPacket.Packet; simulator = incomingPacket.Simulator; if (packet != null) { // Skip blacklisted packets if (UDPBlacklist.Contains(packet.Type.ToString())) { Logger.Log(String.Format("Discarding Blacklisted packet {0} from {1}", packet.Type, simulator.IPEndPoint), Helpers.LogLevel.Warning); return; } // Fire the callback(s), if any PacketEvents.RaiseEvent(packet.Type, packet, simulator); } } } } private void SetCurrentSim(Simulator simulator, string seedcaps) { if (simulator != CurrentSim) { Simulator oldSim = CurrentSim; lock (Simulators) CurrentSim = simulator; // CurrentSim is synchronized against Simulators simulator.SetSeedCaps(seedcaps); // If the current simulator changed fire the callback if (m_SimChanged != null && simulator != oldSim) { OnSimChanged(new SimChangedEventArgs(oldSim)); } } } #region Timers private void DisconnectTimer_Elapsed(object obj) { if (!connected || CurrentSim == null) { if (DisconnectTimer != null) { DisconnectTimer.Dispose(); DisconnectTimer = null; } connected = false; } else if (CurrentSim.DisconnectCandidate) { // The currently occupied simulator hasn't sent us any traffic in a while, shutdown Logger.Log("Network timeout for the current simulator (" + CurrentSim.ToString() + "), logging out", Helpers.LogLevel.Warning, Client); if (DisconnectTimer != null) { DisconnectTimer.Dispose(); DisconnectTimer = null; } connected = false; // Shutdown the network layer Shutdown(DisconnectType.NetworkTimeout); } else { // Mark the current simulator as potentially disconnected each time this timer fires. // If the timer is fired again before any packets are received, an actual disconnect // sequence will be triggered CurrentSim.DisconnectCandidate = true; } } #endregion Timers #region Packet Callbacks /// <summary>Process an incoming packet and raise the appropriate events</summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> protected void LogoutReplyHandler(object sender, PacketReceivedEventArgs e) { LogoutReplyPacket logout = (LogoutReplyPacket)e.Packet; if ((logout.AgentData.SessionID == Client.Self.SessionID) && (logout.AgentData.AgentID == Client.Self.AgentID)) { Logger.DebugLog("Logout reply received", Client); // Deal with callbacks, if any if (m_LoggedOut != null) { List<UUID> itemIDs = new List<UUID>(); foreach (LogoutReplyPacket.InventoryDataBlock InventoryData in logout.InventoryData) { itemIDs.Add(InventoryData.ItemID); } OnLoggedOut(new LoggedOutEventArgs(itemIDs)); } // If we are receiving a LogoutReply packet assume this is a client initiated shutdown Shutdown(DisconnectType.ClientInitiated); } else { Logger.Log("Invalid Session or Agent ID received in Logout Reply... ignoring", Helpers.LogLevel.Warning, Client); } } /// <summary>Process an incoming packet and raise the appropriate events</summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> protected void StartPingCheckHandler(object sender, PacketReceivedEventArgs e) { StartPingCheckPacket incomingPing = (StartPingCheckPacket)e.Packet; CompletePingCheckPacket ping = new CompletePingCheckPacket(); ping.PingID.PingID = incomingPing.PingID.PingID; ping.Header.Reliable = false; // TODO: We can use OldestUnacked to correct transmission errors // I don't think that's right. As far as I can tell, the Viewer // only uses this to prune its duplicate-checking buffer. -bushing SendPacket(ping, e.Simulator); } /// <summary>Process an incoming packet and raise the appropriate events</summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> protected void CompletePingCheckHandler(object sender, PacketReceivedEventArgs e) { CompletePingCheckPacket pong = (CompletePingCheckPacket)e.Packet; //String retval = "Pong2: " + (Environment.TickCount - e.Simulator.Stats.LastPingSent); //if ((pong.PingID.PingID - e.Simulator.Stats.LastPingID + 1) != 0) // retval += " (gap of " + (pong.PingID.PingID - e.Simulator.Stats.LastPingID + 1) + ")"; e.Simulator.Stats.LastLag = Environment.TickCount - e.Simulator.Stats.LastPingSent; e.Simulator.Stats.ReceivedPongs++; // Client.Log(retval, Helpers.LogLevel.Info); } /// <summary>Process an incoming packet and raise the appropriate events</summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> protected void SimStatsHandler(object sender, PacketReceivedEventArgs e) { if (!Client.Settings.ENABLE_SIMSTATS) { return; } SimStatsPacket stats = (SimStatsPacket)e.Packet; for (int i = 0; i < stats.Stat.Length; i++) { SimStatsPacket.StatBlock s = stats.Stat[i]; switch (s.StatID) { case 0: e.Simulator.Stats.Dilation = s.StatValue; break; case 1: e.Simulator.Stats.FPS = Convert.ToInt32(s.StatValue); break; case 2: e.Simulator.Stats.PhysicsFPS = s.StatValue; break; case 3: e.Simulator.Stats.AgentUpdates = s.StatValue; break; case 4: e.Simulator.Stats.FrameTime = s.StatValue; break; case 5: e.Simulator.Stats.NetTime = s.StatValue; break; case 6: e.Simulator.Stats.OtherTime = s.StatValue; break; case 7: e.Simulator.Stats.PhysicsTime = s.StatValue; break; case 8: e.Simulator.Stats.AgentTime = s.StatValue; break; case 9: e.Simulator.Stats.ImageTime = s.StatValue; break; case 10: e.Simulator.Stats.ScriptTime = s.StatValue; break; case 11: e.Simulator.Stats.Objects = Convert.ToInt32(s.StatValue); break; case 12: e.Simulator.Stats.ScriptedObjects = Convert.ToInt32(s.StatValue); break; case 13: e.Simulator.Stats.Agents = Convert.ToInt32(s.StatValue); break; case 14: e.Simulator.Stats.ChildAgents = Convert.ToInt32(s.StatValue); break; case 15: e.Simulator.Stats.ActiveScripts = Convert.ToInt32(s.StatValue); break; case 16: e.Simulator.Stats.LSLIPS = Convert.ToInt32(s.StatValue); break; case 17: e.Simulator.Stats.INPPS = Convert.ToInt32(s.StatValue); break; case 18: e.Simulator.Stats.OUTPPS = Convert.ToInt32(s.StatValue); break; case 19: e.Simulator.Stats.PendingDownloads = Convert.ToInt32(s.StatValue); break; case 20: e.Simulator.Stats.PendingUploads = Convert.ToInt32(s.StatValue); break; case 21: e.Simulator.Stats.VirtualSize = Convert.ToInt32(s.StatValue); break; case 22: e.Simulator.Stats.ResidentSize = Convert.ToInt32(s.StatValue); break; case 23: e.Simulator.Stats.PendingLocalUploads = Convert.ToInt32(s.StatValue); break; case 24: e.Simulator.Stats.UnackedBytes = Convert.ToInt32(s.StatValue); break; } } } /// <summary>Process an incoming packet and raise the appropriate events</summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> protected void RegionHandshakeHandler(object sender, PacketReceivedEventArgs e) { RegionHandshakePacket handshake = (RegionHandshakePacket)e.Packet; Simulator simulator = e.Simulator; e.Simulator.ID = handshake.RegionInfo.CacheID; simulator.IsEstateManager = handshake.RegionInfo.IsEstateManager; simulator.Name = Utils.BytesToString(handshake.RegionInfo.SimName); simulator.SimOwner = handshake.RegionInfo.SimOwner; simulator.TerrainBase0 = handshake.RegionInfo.TerrainBase0; simulator.TerrainBase1 = handshake.RegionInfo.TerrainBase1; simulator.TerrainBase2 = handshake.RegionInfo.TerrainBase2; simulator.TerrainBase3 = handshake.RegionInfo.TerrainBase3; simulator.TerrainDetail0 = handshake.RegionInfo.TerrainDetail0; simulator.TerrainDetail1 = handshake.RegionInfo.TerrainDetail1; simulator.TerrainDetail2 = handshake.RegionInfo.TerrainDetail2; simulator.TerrainDetail3 = handshake.RegionInfo.TerrainDetail3; simulator.TerrainHeightRange00 = handshake.RegionInfo.TerrainHeightRange00; simulator.TerrainHeightRange01 = handshake.RegionInfo.TerrainHeightRange01; simulator.TerrainHeightRange10 = handshake.RegionInfo.TerrainHeightRange10; simulator.TerrainHeightRange11 = handshake.RegionInfo.TerrainHeightRange11; simulator.TerrainStartHeight00 = handshake.RegionInfo.TerrainStartHeight00; simulator.TerrainStartHeight01 = handshake.RegionInfo.TerrainStartHeight01; simulator.TerrainStartHeight10 = handshake.RegionInfo.TerrainStartHeight10; simulator.TerrainStartHeight11 = handshake.RegionInfo.TerrainStartHeight11; simulator.WaterHeight = handshake.RegionInfo.WaterHeight; simulator.Flags = (RegionFlags)handshake.RegionInfo.RegionFlags; simulator.BillableFactor = handshake.RegionInfo.BillableFactor; simulator.Access = (SimAccess)handshake.RegionInfo.SimAccess; simulator.RegionID = handshake.RegionInfo2.RegionID; simulator.ColoLocation = Utils.BytesToString(handshake.RegionInfo3.ColoName); simulator.CPUClass = handshake.RegionInfo3.CPUClassID; simulator.CPURatio = handshake.RegionInfo3.CPURatio; simulator.ProductName = Utils.BytesToString(handshake.RegionInfo3.ProductName); simulator.ProductSku = Utils.BytesToString(handshake.RegionInfo3.ProductSKU); if (handshake.RegionInfo4 != null && handshake.RegionInfo4.Length > 0) { simulator.Protocols = (RegionProtocols)handshake.RegionInfo4[0].RegionProtocols; // Yes, overwrite region flags if we have extended version of them simulator.Flags = (RegionFlags)handshake.RegionInfo4[0].RegionFlagsExtended; } // Send a RegionHandshakeReply RegionHandshakeReplyPacket reply = new RegionHandshakeReplyPacket(); reply.AgentData.AgentID = Client.Self.AgentID; reply.AgentData.SessionID = Client.Self.SessionID; reply.RegionInfo.Flags = 0; SendPacket(reply, simulator); // We're officially connected to this sim simulator.connected = true; simulator.handshakeComplete = true; simulator.ConnectedEvent.Set(); } protected void EnableSimulatorHandler(string capsKey, IMessage message, Simulator simulator) { if (!Client.Settings.MULTIPLE_SIMS) return; EnableSimulatorMessage msg = (EnableSimulatorMessage)message; for (int i = 0; i < msg.Simulators.Length; i++) { IPAddress ip = msg.Simulators[i].IP; ushort port = (ushort)msg.Simulators[i].Port; ulong handle = msg.Simulators[i].RegionHandle; IPEndPoint endPoint = new IPEndPoint(ip, port); if (FindSimulator(endPoint) != null) return; if (Connect(ip, port, handle, false, null) == null) { Logger.Log("Unabled to connect to new sim " + ip + ":" + port, Helpers.LogLevel.Error, Client); } } } /// <summary>Process an incoming packet and raise the appropriate events</summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> protected void DisableSimulatorHandler(object sender, PacketReceivedEventArgs e) { DisconnectSim(e.Simulator, false); } /// <summary>Process an incoming packet and raise the appropriate events</summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> protected void KickUserHandler(object sender, PacketReceivedEventArgs e) { string message = Utils.BytesToString(((KickUserPacket)e.Packet).UserInfo.Reason); // Shutdown the network layer Shutdown(DisconnectType.ServerInitiated, message); } #endregion Packet Callbacks } #region EventArgs public class PacketReceivedEventArgs : EventArgs { private readonly Packet m_Packet; private readonly Simulator m_Simulator; public Packet Packet { get { return m_Packet; } } public Simulator Simulator { get { return m_Simulator; } } public PacketReceivedEventArgs(Packet packet, Simulator simulator) { this.m_Packet = packet; this.m_Simulator = simulator; } } public class LoggedOutEventArgs : EventArgs { private readonly List<UUID> m_InventoryItems; public List<UUID> InventoryItems; public LoggedOutEventArgs(List<UUID> inventoryItems) { this.m_InventoryItems = inventoryItems; } } public class PacketSentEventArgs : EventArgs { private readonly byte[] m_Data; private readonly int m_SentBytes; private readonly Simulator m_Simulator; public byte[] Data { get { return m_Data; } } public int SentBytes { get { return m_SentBytes; } } public Simulator Simulator { get { return m_Simulator; } } public PacketSentEventArgs(byte[] data, int bytesSent, Simulator simulator) { this.m_Data = data; this.m_SentBytes = bytesSent; this.m_Simulator = simulator; } } public class SimConnectingEventArgs : EventArgs { private readonly Simulator m_Simulator; private bool m_Cancel; public Simulator Simulator { get { return m_Simulator; } } public bool Cancel { get { return m_Cancel; } set { m_Cancel = value; } } public SimConnectingEventArgs(Simulator simulator) { this.m_Simulator = simulator; this.m_Cancel = false; } } public class SimConnectedEventArgs : EventArgs { private readonly Simulator m_Simulator; public Simulator Simulator { get { return m_Simulator; } } public SimConnectedEventArgs(Simulator simulator) { this.m_Simulator = simulator; } } public class SimDisconnectedEventArgs : EventArgs { private readonly Simulator m_Simulator; private readonly NetworkManager.DisconnectType m_Reason; public Simulator Simulator { get { return m_Simulator; } } public NetworkManager.DisconnectType Reason { get { return m_Reason; } } public SimDisconnectedEventArgs(Simulator simulator, NetworkManager.DisconnectType reason) { this.m_Simulator = simulator; this.m_Reason = reason; } } public class DisconnectedEventArgs : EventArgs { private readonly NetworkManager.DisconnectType m_Reason; private readonly String m_Message; public NetworkManager.DisconnectType Reason { get { return m_Reason; } } public String Message { get { return m_Message; } } public DisconnectedEventArgs(NetworkManager.DisconnectType reason, String message) { this.m_Reason = reason; this.m_Message = message; } } public class SimChangedEventArgs : EventArgs { private readonly Simulator m_PreviousSimulator; public Simulator PreviousSimulator { get { return m_PreviousSimulator; } } public SimChangedEventArgs(Simulator previousSimulator) { this.m_PreviousSimulator = previousSimulator; } } public class EventQueueRunningEventArgs : EventArgs { private readonly Simulator m_Simulator; public Simulator Simulator { get { return m_Simulator; } } public EventQueueRunningEventArgs(Simulator simulator) { this.m_Simulator = simulator; } } #endregion }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.Net.Sockets; namespace System.Net { /// <devdoc> /// <para> /// Provides an internet protocol (IP) address. /// </para> /// </devdoc> public class IPAddress { public static readonly IPAddress Any = new IPAddress(0x0000000000000000); public static readonly IPAddress Loopback = new IPAddress(0x000000000100007F); public static readonly IPAddress Broadcast = new IPAddress(0x00000000FFFFFFFF); public static readonly IPAddress None = Broadcast; internal const long LoopbackMask = 0x00000000000000FF; public static readonly IPAddress IPv6Any = new IPAddress(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 0); public static readonly IPAddress IPv6Loopback = new IPAddress(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }, 0); public static readonly IPAddress IPv6None = new IPAddress(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 0); /// <summary> /// For IPv4 addresses, this field stores the Address. /// For IPv6 addresses, this field stores the ScopeId. /// Instead of accessing this field directly, use the <see cref="PrivateAddress"/> or <see cref="PrivateScopeId"/> properties. /// </summary> private uint _addressOrScopeId; /// <summary> /// This field is only used for IPv6 addresses. A null value indicates that this instance is an IPv4 address. /// </summary> private readonly ushort[] _numbers; /// <summary> /// A lazily initialized cache of the result of calling <see cref="ToString"/>. /// </summary> private string _toString; /// <summary> /// This field is only used for IPv6 addresses. A lazily initialized cache of the <see cref="GetHashCode"/> value. /// </summary> private int _hashCode; // Maximum length of address literals (potentially including a port number) // generated by any address-to-string conversion routine. This length can // be used when declaring buffers used with getnameinfo, WSAAddressToString, // inet_ntoa, etc. We just provide one define, rather than one per api, // to avoid confusion. // // The totals are derived from the following data: // 15: IPv4 address // 45: IPv6 address including embedded IPv4 address // 11: Scope Id // 2: Brackets around IPv6 address when port is present // 6: Port (including colon) // 1: Terminating null byte internal const int NumberOfLabels = IPAddressParserStatics.IPv6AddressBytes / 2; private bool IsIPv4 { get { return _numbers == null; } } private bool IsIPv6 { get { return _numbers != null; } } private uint PrivateAddress { get { Debug.Assert(IsIPv4); return _addressOrScopeId; } set { Debug.Assert(IsIPv4); _addressOrScopeId = value; } } private uint PrivateScopeId { get { Debug.Assert(IsIPv6); return _addressOrScopeId; } set { Debug.Assert(IsIPv6); _addressOrScopeId = value; } } /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Net.IPAddress'/> /// class with the specified address. /// </para> /// </devdoc> public IPAddress(long newAddress) { if (newAddress < 0 || newAddress > 0x00000000FFFFFFFF) { throw new ArgumentOutOfRangeException("newAddress"); } PrivateAddress = (uint)newAddress; } /// <devdoc> /// <para> /// Constructor for an IPv6 Address with a specified Scope. /// </para> /// </devdoc> public IPAddress(byte[] address, long scopeid) { if (address == null) { throw new ArgumentNullException("address"); } if (address.Length != IPAddressParserStatics.IPv6AddressBytes) { throw new ArgumentException(SR.dns_bad_ip_address, "address"); } _numbers = new ushort[NumberOfLabels]; for (int i = 0; i < NumberOfLabels; i++) { _numbers[i] = (ushort)(address[i * 2] * 256 + address[i * 2 + 1]); } // Consider: Since scope is only valid for link-local and site-local // addresses we could implement some more robust checking here if (scopeid < 0 || scopeid > 0x00000000FFFFFFFF) { throw new ArgumentOutOfRangeException("scopeid"); } PrivateScopeId = (uint)scopeid; } private IPAddress(ushort[] numbers, uint scopeid) { Debug.Assert(numbers != null); _numbers = numbers; PrivateScopeId = scopeid; } /// <devdoc> /// <para> /// Constructor for IPv4 and IPv6 Address. /// </para> /// </devdoc> public IPAddress(byte[] address) { if (address == null) { throw new ArgumentNullException("address"); } if (address.Length != IPAddressParserStatics.IPv4AddressBytes && address.Length != IPAddressParserStatics.IPv6AddressBytes) { throw new ArgumentException(SR.dns_bad_ip_address, "address"); } if (address.Length == IPAddressParserStatics.IPv4AddressBytes) { PrivateAddress = (uint)((address[3] << 24 | address[2] << 16 | address[1] << 8 | address[0]) & 0x0FFFFFFFF); } else { _numbers = new ushort[NumberOfLabels]; for (int i = 0; i < NumberOfLabels; i++) { _numbers[i] = (ushort)(address[i * 2] * 256 + address[i * 2 + 1]); } } } // We need this internally since we need to interface with winsock, // and winsock only understands Int32. internal IPAddress(int newAddress) { PrivateAddress = (uint)newAddress; } /// <devdoc> /// <para> /// Converts an IP address string to an <see cref='System.Net.IPAddress'/> instance. /// </para> /// </devdoc> public static bool TryParse(string ipString, out IPAddress address) { address = IPAddressParser.Parse(ipString, true); return (address != null); } public static IPAddress Parse(string ipString) { return IPAddressParser.Parse(ipString, false); } /// <devdoc> /// <para> /// Provides a copy of the IPAddress internals as an array of bytes. /// </para> /// </devdoc> public byte[] GetAddressBytes() { byte[] bytes; if (IsIPv6) { bytes = new byte[NumberOfLabels * 2]; int j = 0; for (int i = 0; i < NumberOfLabels; i++) { bytes[j++] = (byte)((_numbers[i] >> 8) & 0xFF); bytes[j++] = (byte)((_numbers[i]) & 0xFF); } } else { uint address = PrivateAddress; bytes = new byte[IPAddressParserStatics.IPv4AddressBytes]; bytes[0] = (byte)(address); bytes[1] = (byte)(address >> 8); bytes[2] = (byte)(address >> 16); bytes[3] = (byte)(address >> 24); } return bytes; } public AddressFamily AddressFamily { get { return IsIPv4 ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6; } } // When IPv6 support was added to the .NET Framework, the public Address property was marked as Obsolete. // The public obsolete Address property has not been carried forward in .NET Core, but remains here as // internal to allow internal types that understand IPv4 to still access it without obsolete warnings. internal long Address { get { return PrivateAddress; } } /// <devdoc> /// <para> /// IPv6 Scope identifier. This is really a uint32, but that isn't CLS compliant /// </para> /// </devdoc> public long ScopeId { get { // Not valid for IPv4 addresses if (IsIPv4) { throw new SocketException(SocketError.OperationNotSupported); } return PrivateScopeId; } set { // Not valid for IPv4 addresses if (IsIPv4) { throw new SocketException(SocketError.OperationNotSupported); } // Consider: Since scope is only valid for link-local and site-local // addresses we could implement some more robust checking here if (value < 0 || value > 0x00000000FFFFFFFF) { throw new ArgumentOutOfRangeException("value"); } PrivateScopeId = (uint)value; } } /// <devdoc> /// <para> /// Converts the Internet address to either standard dotted quad format /// or standard IPv6 representation. /// </para> /// </devdoc> public override string ToString() { if (_toString == null) { _toString = IsIPv4 ? IPAddressParser.IPv4AddressToString(GetAddressBytes()) : IPAddressParser.IPv6AddressToString(GetAddressBytes(), PrivateScopeId); } return _toString; } public static long HostToNetworkOrder(long host) { #if BIGENDIAN return host; #else return (((long)HostToNetworkOrder((int)host) & 0xFFFFFFFF) << 32) | ((long)HostToNetworkOrder((int)(host >> 32)) & 0xFFFFFFFF); #endif } public static int HostToNetworkOrder(int host) { #if BIGENDIAN return host; #else return (((int)HostToNetworkOrder((short)host) & 0xFFFF) << 16) | ((int)HostToNetworkOrder((short)(host >> 16)) & 0xFFFF); #endif } public static short HostToNetworkOrder(short host) { #if BIGENDIAN return host; #else return (short)((((int)host & 0xFF) << 8) | (int)((host >> 8) & 0xFF)); #endif } public static long NetworkToHostOrder(long network) { return HostToNetworkOrder(network); } public static int NetworkToHostOrder(int network) { return HostToNetworkOrder(network); } public static short NetworkToHostOrder(short network) { return HostToNetworkOrder(network); } public static bool IsLoopback(IPAddress address) { if (address == null) { throw new ArgumentNullException("address"); } if (address.IsIPv6) { // Do Equals test for IPv6 addresses return address.Equals(IPv6Loopback); } else { return ((address.PrivateAddress & LoopbackMask) == (Loopback.PrivateAddress & LoopbackMask)); } } /// <devdoc> /// <para> /// Determines if an address is an IPv6 Multicast address /// </para> /// </devdoc> public bool IsIPv6Multicast { get { return IsIPv6 && ((_numbers[0] & 0xFF00) == 0xFF00); } } /// <devdoc> /// <para> /// Determines if an address is an IPv6 Link Local address /// </para> /// </devdoc> public bool IsIPv6LinkLocal { get { return IsIPv6 && ((_numbers[0] & 0xFFC0) == 0xFE80); } } /// <devdoc> /// <para> /// Determines if an address is an IPv6 Site Local address /// </para> /// </devdoc> public bool IsIPv6SiteLocal { get { return IsIPv6 && ((_numbers[0] & 0xFFC0) == 0xFEC0); } } public bool IsIPv6Teredo { get { return IsIPv6 && (_numbers[0] == 0x2001) && (_numbers[1] == 0); } } // 0:0:0:0:0:FFFF:x.x.x.x public bool IsIPv4MappedToIPv6 { get { if (IsIPv4) { return false; } for (int i = 0; i < 5; i++) { if (_numbers[i] != 0) { return false; } } return (_numbers[5] == 0xFFFF); } } internal bool Equals(object comparandObj, bool compareScopeId) { IPAddress comparand = comparandObj as IPAddress; if (comparand == null) { return false; } // Compare families before address representations if (AddressFamily != comparand.AddressFamily) { return false; } if (IsIPv6) { // For IPv6 addresses, we must compare the full 128-bit representation. for (int i = 0; i < NumberOfLabels; i++) { if (comparand._numbers[i] != _numbers[i]) { return false; } } // The scope IDs must also match return comparand.PrivateScopeId == PrivateScopeId || !compareScopeId; } else { // For IPv4 addresses, compare the integer representation. return comparand.PrivateAddress == PrivateAddress; } } /// <devdoc> /// <para> /// Compares two IP addresses. /// </para> /// </devdoc> public override bool Equals(object comparand) { return Equals(comparand, true); } public override int GetHashCode() { // For IPv6 addresses, we cannot simply return the integer // representation as the hashcode. Instead, we calculate // the hashcode from the string representation of the address. if (IsIPv6) { if (_hashCode == 0) { _hashCode = StringComparer.OrdinalIgnoreCase.GetHashCode(ToString()); } return _hashCode; } else { // For IPv4 addresses, we can simply use the integer representation. return unchecked((int)PrivateAddress); } } // For security, we need to be able to take an IPAddress and make a copy that's immutable and not derived. internal IPAddress Snapshot() { return IsIPv4 ? new IPAddress(PrivateAddress) : new IPAddress(_numbers, PrivateScopeId); } // IPv4 192.168.1.1 maps as ::FFFF:192.168.1.1 public IPAddress MapToIPv6() { if (IsIPv6) { return this; } uint address = PrivateAddress; ushort[] labels = new ushort[NumberOfLabels]; labels[5] = 0xFFFF; labels[6] = (ushort)(((address & 0x0000FF00) >> 8) | ((address & 0x000000FF) << 8)); labels[7] = (ushort)(((address & 0xFF000000) >> 24) | ((address & 0x00FF0000) >> 8)); return new IPAddress(labels, 0); } // Takes the last 4 bytes of an IPv6 address and converts it to an IPv4 address. // This does not restrict to address with the ::FFFF: prefix because other types of // addresses display the tail segments as IPv4 like Terado. public IPAddress MapToIPv4() { if (IsIPv4) { return this; } // Cast the ushort values to a uint and mask with unsigned literal before bit shifting. // Otherwise, we can end up getting a negative value for any IPv4 address that ends with // a byte higher than 127 due to sign extension of the most significant 1 bit. long address = ((((uint)_numbers[6] & 0x0000FF00u) >> 8) | (((uint)_numbers[6] & 0x000000FFu) << 8)) | (((((uint)_numbers[7] & 0x0000FF00u) >> 8) | (((uint)_numbers[7] & 0x000000FFu) << 8)) << 16); return new IPAddress(address); } } }
using Orleans.Serialization.Codecs; using Orleans.Serialization.Utilities; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; namespace Orleans.Serialization.Session { public sealed class ReferencedObjectCollection { private readonly struct ReferencePair { public ReferencePair(uint id, object @object) { Id = id; Object = @object; } public uint Id { get; } public object Object { get; } } public int ReferenceToObjectCount { get; set; } private readonly ReferencePair[] _referenceToObject = new ReferencePair[64]; private int _objectToReferenceCount; private readonly ReferencePair[] _objectToReference = new ReferencePair[64]; private Dictionary<uint, object> _referenceToObjectOverflow; private Dictionary<object, uint> _objectToReferenceOverflow; [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryGetReferencedObject(uint reference, out object value) { // Reference 0 is always null. if (reference == 0) { value = null; return true; } for (int i = 0; i < ReferenceToObjectCount; ++i) { if (_referenceToObject[i].Id == reference) { value = _referenceToObject[i].Object; return true; } } if (_referenceToObjectOverflow is { } overflow) { return overflow.TryGetValue(reference, out value); } value = default; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void MarkValueField() => ++CurrentReferenceId; [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool GetOrAddReference(object value, out uint reference) { // Unconditionally bump the reference counter since a call to this method signifies a potential reference. var nextReference = ++CurrentReferenceId; // Null is always at reference 0 if (value is null) { reference = 0; return true; } for (int i = 0; i < _objectToReferenceCount; ++i) { if (ReferenceEquals(_objectToReference[i].Object, value)) { reference = _objectToReference[i].Id; return true; } } if (_objectToReferenceOverflow is { } overflow) { if (overflow.TryGetValue(value, out var existing)) { reference = existing; return true; } else { reference = nextReference; overflow[value] = reference; } } // Add the reference. reference = nextReference; AddToReferenceToIdMap(value, reference); return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public int GetReferenceIndex(object value) { if (value is null) { return -1; } for (var i = 0; i < ReferenceToObjectCount; ++i) { if (ReferenceEquals(_referenceToObject[i].Object, value)) { return i; } } return -1; } private void AddToReferenceToIdMap(object value, uint reference) { if (_objectToReferenceOverflow is { } overflow) { overflow[value] = reference; } else { _objectToReference[_objectToReferenceCount++] = new ReferencePair(reference, value); if (_objectToReferenceCount >= _objectToReference.Length) { CreateObjectToReferenceOverflow(); } } [MethodImpl(MethodImplOptions.NoInlining)] void CreateObjectToReferenceOverflow() { var result = new Dictionary<object, uint>(_objectToReferenceCount * 2, ReferenceEqualsComparer.Default); for (var i = 0; i < _objectToReferenceCount; i++) { var record = _objectToReference[i]; result[record.Object] = record.Id; _objectToReference[i] = default; } _objectToReferenceCount = 0; _objectToReferenceOverflow = result; } } private void AddToReferences(object value, uint reference) { if (TryGetReferencedObject(reference, out var existing) && !(existing is UnknownFieldMarker) && !(value is UnknownFieldMarker)) { // Unknown field markers can be replaced once the type is known. ThrowReferenceExistsException(reference); return; } if (_referenceToObjectOverflow is { } overflow) { overflow[reference] = value; } else { _referenceToObject[ReferenceToObjectCount++] = new ReferencePair(reference, value); if (ReferenceToObjectCount >= _referenceToObject.Length) { CreateReferenceToObjectOverflow(); } } [MethodImpl(MethodImplOptions.NoInlining)] void CreateReferenceToObjectOverflow() { var result = new Dictionary<uint, object>(); for (var i = 0; i < ReferenceToObjectCount; i++) { var record = _referenceToObject[i]; result[record.Id] = record.Object; _referenceToObject[i] = default; } ReferenceToObjectCount = 0; _referenceToObjectOverflow = result; } } [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowReferenceExistsException(uint reference) => throw new InvalidOperationException($"Reference {reference} already exists"); [MethodImpl(MethodImplOptions.AggressiveInlining)] public void RecordReferenceField(object value) => RecordReferenceField(value, ++CurrentReferenceId); [MethodImpl(MethodImplOptions.AggressiveInlining)] public void RecordReferenceField(object value, uint referenceId) { if (value is null) { return; } AddToReferences(value, referenceId); } public Dictionary<uint, object> CopyReferenceTable() => _referenceToObject.Take(ReferenceToObjectCount).ToDictionary(r => r.Id, r => r.Object); public Dictionary<object, uint> CopyIdTable() => _objectToReference.Take(_objectToReferenceCount).ToDictionary(r => r.Object, r => r.Id); public uint CurrentReferenceId { get; set; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Reset() { var refToObj = _referenceToObject.AsSpan(0, Math.Min(_referenceToObject.Length, ReferenceToObjectCount)); for (var i = 0; i < refToObj.Length; i++) { refToObj[i] = default; } var objToRef = _objectToReference.AsSpan(0, Math.Min(_objectToReference.Length, _objectToReferenceCount)); for (var i = 0; i < objToRef.Length; i++) { objToRef[i] = default; } ReferenceToObjectCount = 0; _objectToReferenceCount = 0; CurrentReferenceId = 0; _referenceToObjectOverflow = null; _objectToReferenceOverflow = null; } } }
namespace NEventStore.Persistence.InMemory { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using NEventStore.Logging; public class InMemoryPersistenceEngine : IPersistStreams { private static readonly ILog Logger = LogFactory.BuildLogger(typeof (InMemoryPersistenceEngine)); private readonly ConcurrentDictionary<string, Bucket> _buckets = new ConcurrentDictionary<string, Bucket>(); private bool _disposed; private int _checkpoint; private Bucket this[string bucketId] { get { return _buckets.GetOrAdd(bucketId, _ => new Bucket()); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public void Initialize() { Logger.Info(Resources.InitializingEngine); } public IEnumerable<ICommit> GetFrom(string bucketId, string streamId, int minRevision, int maxRevision) { ThrowWhenDisposed(); Logger.Debug(Resources.GettingAllCommitsFromRevision, streamId, minRevision, maxRevision); return this[bucketId].GetFrom(streamId, minRevision, maxRevision); } public IEnumerable<ICommit> GetFrom(string bucketId, DateTime start) { ThrowWhenDisposed(); Logger.Debug(Resources.GettingAllCommitsFromTime, bucketId, start); return this[bucketId].GetFrom(start); } public IEnumerable<ICommit> GetFrom(string bucketId, string checkpointToken) { ThrowWhenDisposed(); Logger.Debug(Resources.GettingAllCommitsFromBucketAndCheckpoint, bucketId, checkpointToken); return this[bucketId].GetFrom(GetCheckpoint(checkpointToken)); } public IEnumerable<ICommit> GetFrom(string checkpointToken) { Logger.Debug(Resources.GettingAllCommitsFromCheckpoint, checkpointToken); ICheckpoint checkpoint = LongCheckpoint.Parse(checkpointToken); return _buckets .Values .SelectMany(b => b.GetCommits()) .Where(c => c.Checkpoint.CompareTo(checkpoint) > 0) .OrderBy(c => c.Checkpoint) .ToArray(); } public ICheckpoint GetCheckpoint(string checkpointToken = null) { return LongCheckpoint.Parse(checkpointToken); } public IEnumerable<ICommit> GetFromTo(string bucketId, DateTime start, DateTime end) { ThrowWhenDisposed(); Logger.Debug(Resources.GettingAllCommitsFromToTime, start, end); return this[bucketId].GetFromTo(start, end); } public ICommit Commit(CommitAttempt attempt) { ThrowWhenDisposed(); Logger.Debug(Resources.AttemptingToCommit, attempt.CommitId, attempt.StreamId, attempt.CommitSequence); return this[attempt.BucketId].Commit(attempt, new LongCheckpoint(Interlocked.Increment(ref _checkpoint))); } public IEnumerable<ICommit> GetUndispatchedCommits() { ThrowWhenDisposed(); return _buckets.Values.SelectMany(b => b.GetUndispatchedCommits()); } public void MarkCommitAsDispatched(ICommit commit) { ThrowWhenDisposed(); Logger.Debug(Resources.MarkingAsDispatched, commit.CommitId); this[commit.BucketId].MarkCommitAsDispatched(commit); } public IEnumerable<IStreamHead> GetStreamsToSnapshot(string bucketId, int maxThreshold) { ThrowWhenDisposed(); Logger.Debug(Resources.GettingStreamsToSnapshot, bucketId, maxThreshold); return this[bucketId].GetStreamsToSnapshot(maxThreshold); } public ISnapshot GetSnapshot(string bucketId, string streamId, int maxRevision) { ThrowWhenDisposed(); Logger.Debug(Resources.GettingSnapshotForStream, bucketId, streamId, maxRevision); return this[bucketId].GetSnapshot(streamId, maxRevision); } public bool AddSnapshot(ISnapshot snapshot) { ThrowWhenDisposed(); Logger.Debug(Resources.AddingSnapshot, snapshot.StreamId, snapshot.StreamRevision); return this[snapshot.BucketId].AddSnapshot(snapshot); } public void Purge() { ThrowWhenDisposed(); Logger.Warn(Resources.PurgingStore); foreach (var bucket in _buckets.Values) { bucket.Purge(); } } public void Purge(string bucketId) { Bucket _; _buckets.TryRemove(bucketId, out _); } public void Drop() { _buckets.Clear(); } public void DeleteStream(string bucketId, string streamId) { Logger.Warn(Resources.DeletingStream, streamId, bucketId); Bucket bucket; if (!_buckets.TryGetValue(bucketId, out bucket)) { return; } bucket.DeleteStream(streamId); } public bool IsDisposed { get { return _disposed; } } private void Dispose(bool disposing) { _disposed = true; Logger.Info(Resources.DisposingEngine); } private void ThrowWhenDisposed() { if (!_disposed) { return; } Logger.Warn(Resources.AlreadyDisposed); throw new ObjectDisposedException(Resources.AlreadyDisposed); } private class InMemoryCommit : Commit { private readonly ICheckpoint _checkpoint; public InMemoryCommit( string bucketId, string streamId, int streamRevision, Guid commitId, int commitSequence, DateTime commitStamp, string checkpointToken, IDictionary<string, object> headers, IEnumerable<EventMessage> events, ICheckpoint checkpoint) : base(bucketId, streamId, streamRevision, commitId, commitSequence, commitStamp, checkpointToken, headers, events) { _checkpoint = checkpoint; } public ICheckpoint Checkpoint { get { return _checkpoint; } } } private class IdentityForDuplicationDetection { protected bool Equals(IdentityForDuplicationDetection other) { return string.Equals(this.streamId, other.streamId) && string.Equals(this.bucketId, other.bucketId) && this.commitSequence == other.commitSequence && this.commitId.Equals(other.commitId); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != this.GetType()) { return false; } return Equals((IdentityForDuplicationDetection)obj); } public override int GetHashCode() { unchecked { int hashCode = this.streamId.GetHashCode(); hashCode = (hashCode * 397) ^ this.bucketId.GetHashCode(); hashCode = (hashCode * 397) ^ this.commitSequence; hashCode = (hashCode * 397) ^ this.commitId.GetHashCode(); return hashCode; } } private int commitSequence; private Guid commitId; private string bucketId; private string streamId; public IdentityForDuplicationDetection(CommitAttempt commitAttempt) { bucketId = commitAttempt.BucketId; streamId = commitAttempt.StreamId; commitId = commitAttempt.CommitId; commitSequence = commitAttempt.CommitSequence; } public IdentityForDuplicationDetection(Commit commit) { bucketId = commit.BucketId; streamId = commit.StreamId; commitId = commit.CommitId; commitSequence = commit.CommitSequence; } } private class IdentityForConcurrencyConflictDetection { protected bool Equals(IdentityForConcurrencyConflictDetection other) { return this.commitSequence == other.commitSequence && string.Equals(this.streamId, other.streamId); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != this.GetType()) { return false; } return Equals((IdentityForConcurrencyConflictDetection)obj); } public override int GetHashCode() { unchecked { return (this.commitSequence * 397) ^ this.streamId.GetHashCode(); } } private int commitSequence; private string streamId; public IdentityForConcurrencyConflictDetection(Commit commit) { streamId = commit.StreamId; commitSequence = commit.CommitSequence; } } private class Bucket { private readonly IList<InMemoryCommit> _commits = new List<InMemoryCommit>(); private readonly ICollection<IdentityForDuplicationDetection> _potentialDuplicates = new HashSet<IdentityForDuplicationDetection>(); private readonly ICollection<IdentityForConcurrencyConflictDetection> _potentialConflicts = new HashSet<IdentityForConcurrencyConflictDetection>(); public IEnumerable<InMemoryCommit> GetCommits() { lock (_commits) { return _commits.ToArray(); } } private readonly ICollection<IStreamHead> _heads = new LinkedList<IStreamHead>(); private readonly ICollection<ISnapshot> _snapshots = new LinkedList<ISnapshot>(); private readonly IDictionary<Guid, DateTime> _stamps = new Dictionary<Guid, DateTime>(); private readonly ICollection<ICommit> _undispatched = new LinkedList<ICommit>(); public IEnumerable<ICommit> GetFrom(string streamId, int minRevision, int maxRevision) { lock (_commits) { return _commits .Where(x => x.StreamId == streamId && x.StreamRevision >= minRevision && (x.StreamRevision - x.Events.Count + 1) <= maxRevision) .OrderBy(c => c.CommitSequence) .ToArray(); } } public IEnumerable<ICommit> GetFrom(DateTime start) { Guid commitId = _stamps.Where(x => x.Value >= start).Select(x => x.Key).FirstOrDefault(); if (commitId == Guid.Empty) { return Enumerable.Empty<ICommit>(); } InMemoryCommit startingCommit = _commits.FirstOrDefault(x => x.CommitId == commitId); return _commits.Skip(_commits.IndexOf(startingCommit)); } public IEnumerable<ICommit> GetFrom(ICheckpoint checkpoint) { InMemoryCommit startingCommit = _commits.FirstOrDefault(x => x.Checkpoint.CompareTo(checkpoint) == 0); return _commits.Skip(_commits.IndexOf(startingCommit) + 1 /* GetFrom => after the checkpoint*/); } public IEnumerable<ICommit> GetFromTo(DateTime start, DateTime end) { IEnumerable<Guid> selectedCommitIds = _stamps.Where(x => x.Value >= start && x.Value < end).Select(x => x.Key).ToArray(); Guid firstCommitId = selectedCommitIds.FirstOrDefault(); Guid lastCommitId = selectedCommitIds.LastOrDefault(); if (lastCommitId == Guid.Empty && lastCommitId == Guid.Empty) { return Enumerable.Empty<ICommit>(); } InMemoryCommit startingCommit = _commits.FirstOrDefault(x => x.CommitId == firstCommitId); InMemoryCommit endingCommit = _commits.FirstOrDefault(x => x.CommitId == lastCommitId); int startingCommitIndex = (startingCommit == null) ? 0 : _commits.IndexOf(startingCommit); int endingCommitIndex = (endingCommit == null) ? _commits.Count - 1 : _commits.IndexOf(endingCommit); int numberToTake = endingCommitIndex - startingCommitIndex + 1; return _commits.Skip(_commits.IndexOf(startingCommit)).Take(numberToTake); } public ICommit Commit(CommitAttempt attempt, ICheckpoint checkpoint) { lock (_commits) { DetectDuplicate(attempt); var commit = new InMemoryCommit(attempt.BucketId, attempt.StreamId, attempt.StreamRevision, attempt.CommitId, attempt.CommitSequence, attempt.CommitStamp, checkpoint.Value, attempt.Headers, attempt.Events, checkpoint); if (_potentialConflicts.Contains(new IdentityForConcurrencyConflictDetection(commit))) { throw new ConcurrencyException(); } _stamps[commit.CommitId] = commit.CommitStamp; _commits.Add(commit); _potentialDuplicates.Add(new IdentityForDuplicationDetection(commit)); _potentialConflicts.Add(new IdentityForConcurrencyConflictDetection(commit)); _undispatched.Add(commit); IStreamHead head = _heads.FirstOrDefault(x => x.StreamId == commit.StreamId); _heads.Remove(head); Logger.Debug(Resources.UpdatingStreamHead, commit.StreamId); int snapshotRevision = head == null ? 0 : head.SnapshotRevision; _heads.Add(new StreamHead(commit.BucketId, commit.StreamId, commit.StreamRevision, snapshotRevision)); return commit; } } private void DetectDuplicate(CommitAttempt attempt) { if (_potentialDuplicates.Contains(new IdentityForDuplicationDetection(attempt))) { throw new DuplicateCommitException(); } } public IEnumerable<ICommit> GetUndispatchedCommits() { lock (_commits) { Logger.Debug(Resources.RetrievingUndispatchedCommits, _commits.Count); return _commits.Where(c => _undispatched.Contains(c)).OrderBy(c => c.CommitSequence); } } public void MarkCommitAsDispatched(ICommit commit) { lock (_commits) { _undispatched.Remove(commit); } } public IEnumerable<IStreamHead> GetStreamsToSnapshot(int maxThreshold) { lock (_commits) { return _heads .Where(x => x.HeadRevision >= x.SnapshotRevision + maxThreshold) .Select(stream => new StreamHead(stream.BucketId, stream.StreamId, stream.HeadRevision, stream.SnapshotRevision)); } } public ISnapshot GetSnapshot(string streamId, int maxRevision) { lock (_commits) { return _snapshots .Where(x => x.StreamId == streamId && x.StreamRevision <= maxRevision) .OrderByDescending(x => x.StreamRevision) .FirstOrDefault(); } } public bool AddSnapshot(ISnapshot snapshot) { lock (_commits) { IStreamHead currentHead = _heads.FirstOrDefault(h => h.StreamId == snapshot.StreamId); if (currentHead == null) { return false; } _snapshots.Add(snapshot); _heads.Remove(currentHead); _heads.Add(new StreamHead(currentHead.BucketId, currentHead.StreamId, currentHead.HeadRevision, snapshot.StreamRevision)); } return true; } public void Purge() { lock (_commits) { _commits.Clear(); _snapshots.Clear(); _heads.Clear(); _potentialConflicts.Clear(); _potentialDuplicates.Clear(); } } public void DeleteStream(string streamId) { lock (_commits) { InMemoryCommit[] commits = _commits.Where(c => c.StreamId == streamId).ToArray(); foreach (var commit in commits) { _commits.Remove(commit); } ISnapshot[] snapshots = _snapshots.Where(s => s.StreamId == streamId).ToArray(); foreach (var snapshot in snapshots) { _snapshots.Remove(snapshot); } IStreamHead streamHead = _heads.SingleOrDefault(s => s.StreamId == streamId); if (streamHead != null) { _heads.Remove(streamHead); } } } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using UnityEditor; using UnityEditor.Compilation; using UnityEditor.PackageManager; using UnityEditorInternal; using UnityEngine; using UnityEngine.Profiling; namespace VSCodeEditor { public interface IGenerator { bool SyncIfNeeded(IEnumerable<string> affectedFiles, IEnumerable<string> reimportedFiles); void Sync(); bool HasSolutionBeenGenerated(); string SolutionFile(); string ProjectDirectory { get; } void GenerateAll(bool generateAll); } public interface IAssemblyNameProvider { string GetAssemblyNameFromScriptPath(string path); IEnumerable<Assembly> GetAssemblies(Func<string, bool> shouldFileBePartOfSolution); IEnumerable<string> GetAllAssetPaths(); UnityEditor.PackageManager.PackageInfo FindForAssetPath(string assetPath); } public struct TestSettings { public bool ShouldSync; public Dictionary<string, string> SyncPath; } class AssemblyNameProvider : IAssemblyNameProvider { public string GetAssemblyNameFromScriptPath(string path) { return CompilationPipeline.GetAssemblyNameFromScriptPath(path); } public IEnumerable<Assembly> GetAssemblies(Func<string, bool> shouldFileBePartOfSolution) { // CompilationPipeline.GetAssemblies(AssembliesType.Player).Where(i => 0 < i.sourceFiles.Length && i.sourceFiles.Any(shouldFileBePartOfSolution)); return CompilationPipeline.GetAssemblies().Where(i => 0 < i.sourceFiles.Length && i.sourceFiles.Any(shouldFileBePartOfSolution)); } public IEnumerable<string> GetAllAssetPaths() { return AssetDatabase.GetAllAssetPaths(); } public UnityEditor.PackageManager.PackageInfo FindForAssetPath(string assetPath) { return UnityEditor.PackageManager.PackageInfo.FindForAssetPath(assetPath); } } public class ProjectGeneration : IGenerator { enum ScriptingLanguage { None, CSharp } public static readonly string MSBuildNamespaceUri = "http://schemas.microsoft.com/developer/msbuild/2003"; const string k_WindowsNewline = "\r\n"; const string k_SettingsJson = @"{ ""files.exclude"": { ""**/.DS_Store"":true, ""**/.git"":true, ""**/.gitignore"":true, ""**/.gitmodules"":true, ""**/*.booproj"":true, ""**/*.pidb"":true, ""**/*.suo"":true, ""**/*.user"":true, ""**/*.userprefs"":true, ""**/*.unityproj"":true, ""**/*.dll"":true, ""**/*.exe"":true, ""**/*.pdf"":true, ""**/*.mid"":true, ""**/*.midi"":true, ""**/*.wav"":true, ""**/*.gif"":true, ""**/*.ico"":true, ""**/*.jpg"":true, ""**/*.jpeg"":true, ""**/*.png"":true, ""**/*.psd"":true, ""**/*.tga"":true, ""**/*.tif"":true, ""**/*.tiff"":true, ""**/*.3ds"":true, ""**/*.3DS"":true, ""**/*.fbx"":true, ""**/*.FBX"":true, ""**/*.lxo"":true, ""**/*.LXO"":true, ""**/*.ma"":true, ""**/*.MA"":true, ""**/*.obj"":true, ""**/*.OBJ"":true, ""**/*.asset"":true, ""**/*.cubemap"":true, ""**/*.flare"":true, ""**/*.mat"":true, ""**/*.meta"":true, ""**/*.prefab"":true, ""**/*.unity"":true, ""build/"":true, ""Build/"":true, ""Library/"":true, ""library/"":true, ""obj/"":true, ""Obj/"":true, ""ProjectSettings/"":true, ""temp/"":true, ""Temp/"":true } }"; /// <summary> /// Map source extensions to ScriptingLanguages /// </summary> static readonly Dictionary<string, ScriptingLanguage> k_BuiltinSupportedExtensions = new Dictionary<string, ScriptingLanguage> { { "cs", ScriptingLanguage.CSharp }, { "uxml", ScriptingLanguage.None }, { "uss", ScriptingLanguage.None }, { "shader", ScriptingLanguage.None }, { "compute", ScriptingLanguage.None }, { "cginc", ScriptingLanguage.None }, { "hlsl", ScriptingLanguage.None }, { "glslinc", ScriptingLanguage.None } }; string m_SolutionProjectEntryTemplate = string.Join("\r\n", @"Project(""{{{0}}}"") = ""{1}"", ""{2}"", ""{{{3}}}""", @"EndProject").Replace(" ", "\t"); string m_SolutionProjectConfigurationTemplate = string.Join("\r\n", @" {{{0}}}.Debug|Any CPU.ActiveCfg = Debug|Any CPU", @" {{{0}}}.Debug|Any CPU.Build.0 = Debug|Any CPU", @" {{{0}}}.Release|Any CPU.ActiveCfg = Release|Any CPU", @" {{{0}}}.Release|Any CPU.Build.0 = Release|Any CPU").Replace(" ", "\t"); static readonly string[] k_ReimportSyncExtensions = { ".dll", ".asmdef" }; /// <summary> /// Map ScriptingLanguages to project extensions /// </summary> /*static readonly Dictionary<ScriptingLanguage, string> k_ProjectExtensions = new Dictionary<ScriptingLanguage, string> { { ScriptingLanguage.CSharp, ".csproj" }, { ScriptingLanguage.None, ".csproj" }, };*/ static readonly Regex k_ScriptReferenceExpression = new Regex( @"^Library.ScriptAssemblies.(?<dllname>(?<project>.*)\.dll$)", RegexOptions.Compiled | RegexOptions.IgnoreCase); string[] m_ProjectSupportedExtensions = new string[0]; public string ProjectDirectory { get; } bool m_ShouldGenerateAll; public void GenerateAll(bool generateAll) { m_ShouldGenerateAll = generateAll; } public TestSettings Settings { get; set; } readonly string m_ProjectName; readonly IAssemblyNameProvider m_AssemblyNameProvider; const string k_ToolsVersion = "4.0"; const string k_ProductVersion = "10.0.20506"; const string k_BaseDirectory = "."; const string k_TargetFrameworkVersion = "v4.7.1"; const string k_TargetLanguageVersion = "latest"; public ProjectGeneration() : this(Directory.GetParent(Application.dataPath).FullName, new AssemblyNameProvider()) { } public ProjectGeneration(string tempDirectory) : this(tempDirectory, new AssemblyNameProvider()) { } public ProjectGeneration(string tempDirectory, IAssemblyNameProvider assemblyNameProvider) { Settings = new TestSettings { ShouldSync = true }; ProjectDirectory = tempDirectory.Replace('\\', '/'); m_ProjectName = Path.GetFileName(ProjectDirectory); m_AssemblyNameProvider = assemblyNameProvider; } /// <summary> /// Syncs the scripting solution if any affected files are relevant. /// </summary> /// <returns> /// Whether the solution was synced. /// </returns> /// <param name='affectedFiles'> /// A set of files whose status has changed /// </param> /// <param name="reimportedFiles"> /// A set of files that got reimported /// </param> public bool SyncIfNeeded(IEnumerable<string> affectedFiles, IEnumerable<string> reimportedFiles) { Profiler.BeginSample("SolutionSynchronizerSync"); SetupProjectSupportedExtensions(); // Don't sync if we haven't synced before if (HasSolutionBeenGenerated() && HasFilesBeenModified(affectedFiles, reimportedFiles)) { Sync(); Profiler.EndSample(); return true; } Profiler.EndSample(); return false; } bool HasFilesBeenModified(IEnumerable<string> affectedFiles, IEnumerable<string> reimportedFiles) { return affectedFiles.Any(ShouldFileBePartOfSolution) || reimportedFiles.Any(ShouldSyncOnReimportedAsset); } static bool ShouldSyncOnReimportedAsset(string asset) { return k_ReimportSyncExtensions.Contains(new FileInfo(asset).Extension); } public void Sync() { SetupProjectSupportedExtensions(); GenerateAndWriteSolutionAndProjects(); } public bool HasSolutionBeenGenerated() { return File.Exists(SolutionFile()); } void SetupProjectSupportedExtensions() { m_ProjectSupportedExtensions = EditorSettings.projectGenerationUserExtensions; } bool ShouldFileBePartOfSolution(string file) { string extension = Path.GetExtension(file); // Exclude files coming from packages except if they are internalized. if (!m_ShouldGenerateAll && IsInternalizedPackagePath(file)) { return false; } // Dll's are not scripts but still need to be included.. if (extension == ".dll") return true; if (file.ToLower().EndsWith(".asmdef")) return true; return IsSupportedExtension(extension); } bool IsSupportedExtension(string extension) { extension = extension.TrimStart('.'); if (k_BuiltinSupportedExtensions.ContainsKey(extension)) return true; if (m_ProjectSupportedExtensions.Contains(extension)) return true; return false; } static ScriptingLanguage ScriptingLanguageFor(Assembly island) { return ScriptingLanguageFor(GetExtensionOfSourceFiles(island.sourceFiles)); } static string GetExtensionOfSourceFiles(string[] files) { return files.Length > 0 ? GetExtensionOfSourceFile(files[0]) : "NA"; } static string GetExtensionOfSourceFile(string file) { var ext = Path.GetExtension(file).ToLower(); ext = ext.Substring(1); //strip dot return ext; } static ScriptingLanguage ScriptingLanguageFor(string extension) { return k_BuiltinSupportedExtensions.TryGetValue(extension.TrimStart('.'), out var result) ? result : ScriptingLanguage.None; } public void GenerateAndWriteSolutionAndProjects() { // Only synchronize islands that have associated source files and ones that we actually want in the project. // This also filters out DLLs coming from .asmdef files in packages. var assemblies = m_AssemblyNameProvider.GetAssemblies(ShouldFileBePartOfSolution); var allAssetProjectParts = GenerateAllAssetProjectParts(); SyncSolution(assemblies); var allProjectIslands = RelevantIslandsForMode(assemblies).ToList(); foreach (Assembly assembly in allProjectIslands) { var responseFileData = ParseResponseFileData(assembly); SyncProject(assembly, allAssetProjectParts, responseFileData, allProjectIslands); } if (Settings.ShouldSync) { WriteVSCodeSettingsFiles(); } } IEnumerable<ResponseFileData> ParseResponseFileData(Assembly assembly) { var systemReferenceDirectories = CompilationPipeline.GetSystemAssemblyDirectories(assembly.compilerOptions.ApiCompatibilityLevel); Dictionary<string, ResponseFileData> responseFilesData = assembly.compilerOptions.ResponseFiles.ToDictionary(x => x, x => CompilationPipeline.ParseResponseFile( Path.Combine(ProjectDirectory, x), ProjectDirectory, systemReferenceDirectories )); Dictionary<string, ResponseFileData> responseFilesWithErrors = responseFilesData.Where(x => x.Value.Errors.Any()) .ToDictionary(x => x.Key, x => x.Value); if (responseFilesWithErrors.Any()) { foreach (var error in responseFilesWithErrors) foreach (var valueError in error.Value.Errors) { Debug.LogError($"{error.Key} Parse Error : {valueError}"); } } return responseFilesData.Select(x => x.Value); } Dictionary<string, string> GenerateAllAssetProjectParts() { Dictionary<string, StringBuilder> stringBuilders = new Dictionary<string, StringBuilder>(); foreach (string asset in m_AssemblyNameProvider.GetAllAssetPaths()) { // Exclude files coming from packages except if they are internalized. // TODO: We need assets from the assembly API if (!m_ShouldGenerateAll && IsInternalizedPackagePath(asset)) { continue; } string extension = Path.GetExtension(asset); if (IsSupportedExtension(extension) && ScriptingLanguage.None == ScriptingLanguageFor(extension)) { // Find assembly the asset belongs to by adding script extension and using compilation pipeline. var assemblyName = m_AssemblyNameProvider.GetAssemblyNameFromScriptPath(asset + ".cs"); if (string.IsNullOrEmpty(assemblyName)) { continue; } assemblyName = Utility.FileNameWithoutExtension(assemblyName); if (!stringBuilders.TryGetValue(assemblyName, out var projectBuilder)) { projectBuilder = new StringBuilder(); stringBuilders[assemblyName] = projectBuilder; } projectBuilder.Append(" <None Include=\"").Append(EscapedRelativePathFor(asset)).Append("\" />").Append(k_WindowsNewline); } } var result = new Dictionary<string, string>(); foreach (var entry in stringBuilders) result[entry.Key] = entry.Value.ToString(); return result; } bool IsInternalizedPackagePath(string file) { if (string.IsNullOrWhiteSpace(file)) { return false; } var packageInfo = m_AssemblyNameProvider.FindForAssetPath(file); if (packageInfo == null) { return false; } var packageSource = packageInfo.source; return packageSource != PackageSource.Embedded && packageSource != PackageSource.Local; } void SyncProject( Assembly island, Dictionary<string, string> allAssetsProjectParts, IEnumerable<ResponseFileData> responseFilesData, List<Assembly> allProjectIslands) { SyncProjectFileIfNotChanged(ProjectFile(island), ProjectText(island, allAssetsProjectParts, responseFilesData, allProjectIslands)); } void SyncProjectFileIfNotChanged(string path, string newContents) { if (Path.GetExtension(path) == ".csproj") { //newContents = AssetPostprocessingInternal.CallOnGeneratedCSProject(path, newContents); TODO: Call specific code here } SyncFileIfNotChanged(path, newContents); } void SyncSolutionFileIfNotChanged(string path, string newContents) { //newContents = AssetPostprocessingInternal.CallOnGeneratedSlnSolution(path, newContents); TODO: Call specific code here SyncFileIfNotChanged(path, newContents); } void SyncFileIfNotChanged(string filename, string newContents) { if (Settings.ShouldSync) { if (File.Exists(filename) && newContents == File.ReadAllText(filename)) { return; } File.WriteAllText(filename, newContents, Encoding.UTF8); } else { var utf8 = Encoding.UTF8; byte[] utfBytes = utf8.GetBytes(newContents); Settings.SyncPath[filename] = utf8.GetString(utfBytes, 0, utfBytes.Length); } } string ProjectText(Assembly assembly, Dictionary<string, string> allAssetsProjectParts, IEnumerable<ResponseFileData> responseFilesData, List<Assembly> allProjectIslands) { var projectBuilder = new StringBuilder(ProjectHeader(assembly, responseFilesData)); var references = new List<string>(); var projectReferences = new List<Match>(); foreach (string file in assembly.sourceFiles) { if (!ShouldFileBePartOfSolution(file)) continue; var extension = Path.GetExtension(file).ToLower(); var fullFile = EscapedRelativePathFor(file); if (".dll" != extension) { projectBuilder.Append(" <Compile Include=\"").Append(fullFile).Append("\" />").Append(k_WindowsNewline); } else { references.Add(fullFile); } } var assemblyName = Utility.FileNameWithoutExtension(assembly.outputPath); // Append additional non-script files that should be included in project generation. if (allAssetsProjectParts.TryGetValue(assemblyName, out var additionalAssetsForProject)) projectBuilder.Append(additionalAssetsForProject); var islandRefs = references.Union(assembly.allReferences); foreach (string reference in islandRefs) { var match = k_ScriptReferenceExpression.Match(reference); if (match.Success) { // assume csharp language // Add a reference to a project except if it's a reference to a script assembly // that we are not generating a project for. This will be the case for assemblies // coming from .assembly.json files in non-internalized packages. var dllName = match.Groups["dllname"].Value; if (allProjectIslands.Any(i => Path.GetFileName(i.outputPath) == dllName)) { projectReferences.Add(match); continue; } } string fullReference = Path.IsPathRooted(reference) ? reference : Path.Combine(ProjectDirectory, reference); AppendReference(fullReference, projectBuilder); } var responseRefs = responseFilesData.SelectMany(x => x.FullPathReferences.Select(r => r)); foreach (var reference in responseRefs) { AppendReference(reference, projectBuilder); } if (0 < projectReferences.Count) { projectBuilder.AppendLine(" </ItemGroup>"); projectBuilder.AppendLine(" <ItemGroup>"); foreach (Match reference in projectReferences) { var referencedProject = reference.Groups["project"].Value; projectBuilder.Append(" <ProjectReference Include=\"").Append(referencedProject).Append(GetProjectExtension()).Append("\">").Append(k_WindowsNewline); projectBuilder.Append(" <Project>{").Append(ProjectGuid(Path.Combine("Temp", reference.Groups["project"].Value + ".dll"))).Append("}</Project>").Append(k_WindowsNewline); projectBuilder.Append(" <Name>").Append(referencedProject).Append("</Name>").Append(k_WindowsNewline); projectBuilder.AppendLine(" </ProjectReference>"); } } projectBuilder.Append(ProjectFooter()); return projectBuilder.ToString(); } static void AppendReference(string fullReference, StringBuilder projectBuilder) { //replace \ with / and \\ with / var escapedFullPath = SecurityElement.Escape(fullReference); escapedFullPath = escapedFullPath.Replace("\\", "/"); escapedFullPath = escapedFullPath.Replace("\\\\", "/"); projectBuilder.Append(" <Reference Include=\"").Append(Utility.FileNameWithoutExtension(escapedFullPath)).Append("\">").Append(k_WindowsNewline); projectBuilder.Append(" <HintPath>").Append(escapedFullPath).Append("</HintPath>").Append(k_WindowsNewline); projectBuilder.Append(" </Reference>").Append(k_WindowsNewline); } public string ProjectFile(Assembly assembly) { var fileBuilder = new StringBuilder(Utility.FileNameWithoutExtension(assembly.outputPath)); // if (!assembly.flags.HasFlag(AssemblyFlags.EditorAssembly) && m_PlayerAssemblies.Contains(assembly)) // { // fileBuilder.Append("-player"); // } fileBuilder.Append(".csproj"); return Path.Combine(ProjectDirectory, fileBuilder.ToString()); } public string SolutionFile() { return Path.Combine(ProjectDirectory, $"{m_ProjectName}.sln"); } string ProjectHeader( Assembly island, IEnumerable<ResponseFileData> responseFilesData ) { var arguments = new object[] { k_ToolsVersion, k_ProductVersion, ProjectGuid(island.outputPath), string.Join(";", new[] { "DEBUG", "TRACE" }.Concat(EditorUserBuildSettings.activeScriptCompilationDefines).Concat(island.defines).Concat(responseFilesData.SelectMany(x => x.Defines)).Distinct().ToArray()), MSBuildNamespaceUri, Utility.FileNameWithoutExtension(island.outputPath), EditorSettings.projectGenerationRootNamespace, k_TargetFrameworkVersion, k_TargetLanguageVersion, k_BaseDirectory, island.compilerOptions.AllowUnsafeCode | responseFilesData.Any(x => x.Unsafe) }; try { return string.Format(GetProjectHeaderTemplate(), arguments); } catch (Exception) { throw new NotSupportedException("Failed creating c# project because the c# project header did not have the correct amount of arguments, which is " + arguments.Length); } } static string GetSolutionText() { return string.Join("\r\n", @"", @"Microsoft Visual Studio Solution File, Format Version {0}", @"# Visual Studio {1}", @"{2}", @"Global", @" GlobalSection(SolutionConfigurationPlatforms) = preSolution", @" Debug|Any CPU = Debug|Any CPU", @" Release|Any CPU = Release|Any CPU", @" EndGlobalSection", @" GlobalSection(ProjectConfigurationPlatforms) = postSolution", @"{3}", @" EndGlobalSection", @" GlobalSection(SolutionProperties) = preSolution", @" HideSolutionNode = FALSE", @" EndGlobalSection", @"EndGlobal", @"").Replace(" ", "\t"); } static string GetProjectFooterTemplate() { return string.Join("\r\n", @" </ItemGroup>", @" <Import Project=""$(MSBuildToolsPath)\Microsoft.CSharp.targets"" />", @" <!-- To modify your build process, add your task inside one of the targets below and uncomment it. ", @" Other similar extension points exist, see Microsoft.Common.targets.", @" <Target Name=""BeforeBuild"">", @" </Target>", @" <Target Name=""AfterBuild"">", @" </Target>", @" -->", @"</Project>", @""); } static string GetProjectHeaderTemplate() { var header = new[] { @"<?xml version=""1.0"" encoding=""utf-8""?>", @"<Project ToolsVersion=""{0}"" DefaultTargets=""Build"" xmlns=""{4}"">", @" <PropertyGroup>", @" <LangVersion>{8}</LangVersion>", @" </PropertyGroup>", @" <PropertyGroup>", @" <Configuration Condition="" '$(Configuration)' == '' "">Debug</Configuration>", @" <Platform Condition="" '$(Platform)' == '' "">AnyCPU</Platform>", @" <ProductVersion>{1}</ProductVersion>", @" <SchemaVersion>2.0</SchemaVersion>", @" <RootNamespace>{6}</RootNamespace>", @" <ProjectGuid>{{{2}}}</ProjectGuid>", @" <OutputType>Library</OutputType>", @" <AppDesignerFolder>Properties</AppDesignerFolder>", @" <AssemblyName>{5}</AssemblyName>", @" <TargetFrameworkVersion>{7}</TargetFrameworkVersion>", @" <FileAlignment>512</FileAlignment>", @" <BaseDirectory>{9}</BaseDirectory>", @" </PropertyGroup>", @" <PropertyGroup Condition="" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "">", @" <DebugSymbols>true</DebugSymbols>", @" <DebugType>full</DebugType>", @" <Optimize>false</Optimize>", @" <OutputPath>Temp\bin\Debug\</OutputPath>", @" <DefineConstants>{3}</DefineConstants>", @" <ErrorReport>prompt</ErrorReport>", @" <WarningLevel>4</WarningLevel>", @" <NoWarn>0169</NoWarn>", @" <AllowUnsafeBlocks>{10}</AllowUnsafeBlocks>", @" </PropertyGroup>", @" <PropertyGroup Condition="" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "">", @" <DebugType>pdbonly</DebugType>", @" <Optimize>true</Optimize>", @" <OutputPath>Temp\bin\Release\</OutputPath>", @" <ErrorReport>prompt</ErrorReport>", @" <WarningLevel>4</WarningLevel>", @" <NoWarn>0169</NoWarn>", @" <AllowUnsafeBlocks>{10}</AllowUnsafeBlocks>", @" </PropertyGroup>" }; var forceExplicitReferences = new[] { @" <PropertyGroup>", @" <NoConfig>true</NoConfig>", @" <NoStdLib>true</NoStdLib>", @" <AddAdditionalExplicitAssemblyReferences>false</AddAdditionalExplicitAssemblyReferences>", @" <ImplicitlyExpandNETStandardFacades>false</ImplicitlyExpandNETStandardFacades>", @" <ImplicitlyExpandDesignTimeFacades>false</ImplicitlyExpandDesignTimeFacades>", @" </PropertyGroup>" }; var itemGroupStart = new[] { @" <ItemGroup>" }; var text = header.Concat(forceExplicitReferences).Concat(itemGroupStart).ToArray(); return string.Join("\r\n", text); } void SyncSolution(IEnumerable<Assembly> islands) { SyncSolutionFileIfNotChanged(SolutionFile(), SolutionText(islands)); } string SolutionText(IEnumerable<Assembly> islands) { var fileversion = "11.00"; var vsversion = "2010"; var relevantIslands = RelevantIslandsForMode(islands); string projectEntries = GetProjectEntries(relevantIslands); string projectConfigurations = string.Join(k_WindowsNewline, relevantIslands.Select(i => GetProjectActiveConfigurations(ProjectGuid(i.outputPath))).ToArray()); return string.Format(GetSolutionText(), fileversion, vsversion, projectEntries, projectConfigurations); } static IEnumerable<Assembly> RelevantIslandsForMode(IEnumerable<Assembly> islands) { IEnumerable<Assembly> relevantIslands = islands.Where(i => ScriptingLanguage.CSharp == ScriptingLanguageFor(i)); return relevantIslands; } /// <summary> /// Get a Project("{guid}") = "MyProject", "MyProject.unityproj", "{projectguid}" /// entry for each relevant language /// </summary> string GetProjectEntries(IEnumerable<Assembly> islands) { var projectEntries = islands.Select(i => string.Format( m_SolutionProjectEntryTemplate, SolutionGuid(i), Utility.FileNameWithoutExtension(i.outputPath), Path.GetFileName(ProjectFile(i)), ProjectGuid(i.outputPath) )); return string.Join(k_WindowsNewline, projectEntries.ToArray()); } /// <summary> /// Generate the active configuration string for a given project guid /// </summary> string GetProjectActiveConfigurations(string projectGuid) { return string.Format( m_SolutionProjectConfigurationTemplate, projectGuid); } string EscapedRelativePathFor(string file) { var projectDir = ProjectDirectory.Replace('/', '\\'); file = file.Replace('/', '\\'); var path = SkipPathPrefix(file, projectDir); var packageInfo = m_AssemblyNameProvider.FindForAssetPath(path.Replace('\\', '/')); if (packageInfo != null) { // We have to normalize the path, because the PackageManagerRemapper assumes // dir seperators will be os specific. var absolutePath = Path.GetFullPath(NormalizePath(path)).Replace('/', '\\'); path = SkipPathPrefix(absolutePath, projectDir); } return SecurityElement.Escape(path); } static string SkipPathPrefix(string path, string prefix) { if (path.Replace("\\","/").StartsWith($"{prefix}/")) return path.Substring(prefix.Length + 1); return path; } static string NormalizePath(string path) { if (Path.DirectorySeparatorChar == '\\') return path.Replace('/', Path.DirectorySeparatorChar); return path.Replace('\\', Path.DirectorySeparatorChar); } string ProjectGuid(string assembly) { return SolutionGuidGenerator.GuidForProject(m_ProjectName + Utility.FileNameWithoutExtension(assembly)); } string SolutionGuid(Assembly island) { return SolutionGuidGenerator.GuidForSolution(m_ProjectName, GetExtensionOfSourceFiles(island.sourceFiles)); } static string ProjectFooter() { return GetProjectFooterTemplate(); } static string GetProjectExtension() { return ".csproj"; } void WriteVSCodeSettingsFiles() { var vsCodeDirectory = Path.Combine(ProjectDirectory, ".vscode"); if (!Directory.Exists(vsCodeDirectory)) Directory.CreateDirectory(vsCodeDirectory); var vsCodeSettingsJson = Path.Combine(vsCodeDirectory, "settings.json"); if (!File.Exists(vsCodeSettingsJson)) File.WriteAllText(vsCodeSettingsJson, k_SettingsJson); } } public static class SolutionGuidGenerator { public static string GuidForProject(string projectName) { return ComputeGuidHashFor(projectName + "salt"); } public static string GuidForSolution(string projectName, string sourceFileExtension) { if (sourceFileExtension.ToLower() == "cs") // GUID for a C# class library: http://www.codeproject.com/Reference/720512/List-of-Visual-Studio-Project-Type-GUIDs return "FAE04EC0-301F-11D3-BF4B-00C04F79EFBC"; return ComputeGuidHashFor(projectName); } static string ComputeGuidHashFor(string input) { var hash = MD5.Create().ComputeHash(Encoding.Default.GetBytes(input)); return HashAsGuid(HashToString(hash)); } static string HashAsGuid(string hash) { var guid = hash.Substring(0, 8) + "-" + hash.Substring(8, 4) + "-" + hash.Substring(12, 4) + "-" + hash.Substring(16, 4) + "-" + hash.Substring(20, 12); return guid.ToUpper(); } static string HashToString(byte[] bs) { var sb = new StringBuilder(); foreach (byte b in bs) sb.Append(b.ToString("x2")); return sb.ToString(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // using System; using System.Runtime; using System.Security; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; namespace System.Runtime.InteropServices.WindowsRuntime { // This is a set of stub methods implementing the support for the IList interface on WinRT // objects that support IBindableVector. Used by the interop mashaling infrastructure. // // The methods on this class must be written VERY carefully to avoid introducing security holes. // That's because they are invoked with special "this"! The "this" object // for all of these methods are not BindableVectorToListAdapter objects. Rather, they are // of type IBindableVector. No actual BindableVectorToListAdapter object is ever instantiated. // Thus, you will see a lot of expressions that cast "this" to "IBindableVector". internal sealed class BindableVectorToListAdapter { private BindableVectorToListAdapter() { Debug.Assert(false, "This class is never instantiated"); } // object this[int index] { get } internal object Indexer_Get(int index) { if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); IBindableVector _this = Unsafe.As<IBindableVector>(this); return GetAt(_this, (uint)index); } // object this[int index] { set } internal void Indexer_Set(int index, object value) { if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); IBindableVector _this = Unsafe.As<IBindableVector>(this); SetAt(_this, (uint)index, value); } // int Add(object value) internal int Add(object value) { IBindableVector _this = Unsafe.As<IBindableVector>(this); _this.Append(value); uint size = _this.Size; if (((uint)Int32.MaxValue) < size) { throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge); } return (int)(size - 1); } // bool Contains(object item) internal bool Contains(object item) { IBindableVector _this = Unsafe.As<IBindableVector>(this); uint index; return _this.IndexOf(item, out index); } // void Clear() internal void Clear() { IBindableVector _this = Unsafe.As<IBindableVector>(this); _this.Clear(); } // bool IsFixedSize { get } internal bool IsFixedSize() { return false; } // bool IsReadOnly { get } internal bool IsReadOnly() { return false; } // int IndexOf(object item) internal int IndexOf(object item) { IBindableVector _this = Unsafe.As<IBindableVector>(this); uint index; bool exists = _this.IndexOf(item, out index); if (!exists) return -1; if (((uint)Int32.MaxValue) < index) { throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge); } return (int)index; } // void Insert(int index, object item) internal void Insert(int index, object item) { if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); IBindableVector _this = Unsafe.As<IBindableVector>(this); InsertAtHelper(_this, (uint)index, item); } // bool Remove(object item) internal void Remove(object item) { IBindableVector _this = Unsafe.As<IBindableVector>(this); uint index; bool exists = _this.IndexOf(item, out index); if (exists) { if (((uint)Int32.MaxValue) < index) { throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge); } RemoveAtHelper(_this, index); } } // void RemoveAt(int index) internal void RemoveAt(int index) { if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); IBindableVector _this = Unsafe.As<IBindableVector>(this); RemoveAtHelper(_this, (uint)index); } // Helpers: private static object GetAt(IBindableVector _this, uint index) { try { return _this.GetAt(index); // We delegate bounds checking to the underlying collection and if it detected a fault, // we translate it to the right exception: } catch (Exception ex) { if (HResults.E_BOUNDS == ex._HResult) throw new ArgumentOutOfRangeException(nameof(index)); throw; } } private static void SetAt(IBindableVector _this, uint index, object value) { try { _this.SetAt(index, value); // We delegate bounds checking to the underlying collection and if it detected a fault, // we translate it to the right exception: } catch (Exception ex) { if (HResults.E_BOUNDS == ex._HResult) throw new ArgumentOutOfRangeException(nameof(index)); throw; } } private static void InsertAtHelper(IBindableVector _this, uint index, object item) { try { _this.InsertAt(index, item); // We delegate bounds checking to the underlying collection and if it detected a fault, // we translate it to the right exception: } catch (Exception ex) { if (HResults.E_BOUNDS == ex._HResult) throw new ArgumentOutOfRangeException(nameof(index)); throw; } } private static void RemoveAtHelper(IBindableVector _this, uint index) { try { _this.RemoveAt(index); // We delegate bounds checking to the underlying collection and if it detected a fault, // we translate it to the right exception: } catch (Exception ex) { if (HResults.E_BOUNDS == ex._HResult) throw new ArgumentOutOfRangeException(nameof(index)); throw; } } } }
/* Copyright(c) Microsoft Open Technologies, Inc. All rights reserved. The MIT License(MIT) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Shield.Communication { using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Threading.Tasks; using System.Xml.Linq; using Windows.Web.Http; public class BlobHelper : RESTHelper { // Constructor. public BlobHelper(string storageAccount, string storageKey) : base("http://" + storageAccount + ".blob.core.windows.net/", storageAccount, storageKey) { } public async Task<List<string>> ListContainers() { var containers = new List<string>(); try { var request = this.CreateRESTRequest("GET", "?comp=list"); var httpClient = new HttpClient(); var response = await httpClient.SendRequestAsync(request); if ((int)response.StatusCode == 200) { var inputStream = await response.Content.ReadAsInputStreamAsync(); var memStream = new MemoryStream(); var testStream = inputStream.AsStreamForRead(); await testStream.CopyToAsync(memStream); memStream.Position = 0; using (var reader = new StreamReader(memStream)) { var result = reader.ReadToEnd(); var x = XElement.Parse(result); foreach (var container in x.Element("Containers").Elements("Container")) { containers.Add(container.Element("Name").Value); // Debug.WriteLine(container.Element("Name").Value); } } } else { Debug.WriteLine("Request: " + response.RequestMessage.ToString()); Debug.WriteLine("Response: " + response); } return containers; } catch (Exception e) { Debug.WriteLine(e.Message); return null; } } // Create a blob container. // Return true on success, false if already exists, throw exception on error. public async Task<bool> CreateContainer(string container) { try { var request = this.CreateRESTRequest("PUT", container + "?restype=container"); var httpClient = new HttpClient(); var response = await httpClient.SendRequestAsync(request); if (response.StatusCode == HttpStatusCode.Created) { return true; } Debug.WriteLine("ERROR: " + response.StatusCode + " - " + response.ReasonPhrase); return false; } catch (Exception ex) { Debug.WriteLine(ex.Message); return false; throw; } } //// List blobs in a container. public async Task<List<string>> ListBlobs(string container) { var blobs = new List<string>(); try { var request = this.CreateRESTRequest( "GET", container + "?restype=container&comp=list&include=snapshots&include=metadata"); var httpClient = new HttpClient(); var response = await httpClient.SendRequestAsync(request); if ((int)response.StatusCode == 200) { var inputStream = await response.Content.ReadAsInputStreamAsync(); var memStream = new MemoryStream(); var testStream = inputStream.AsStreamForRead(); await testStream.CopyToAsync(memStream); memStream.Position = 0; using (var reader = new StreamReader(memStream)) { var result = reader.ReadToEnd(); var x = XElement.Parse(result); foreach (var blob in x.Element("Blobs").Elements("Blob")) { blobs.Add(blob.Element("Name").Value); // Debug.WriteLine(blob.Element("Name").Value); } } } else { Debug.WriteLine("ERROR: " + response.StatusCode + " - " + response.ReasonPhrase); return null; } return blobs; } catch (Exception ex) { Debug.WriteLine(ex.Message); return null; throw; } } // Retrieve the content of a blob. // Return true on success, false if not found, throw exception on error. public async Task<string> GetBlob(string container, string blob) { string content = null; try { var request = this.CreateRESTRequest("GET", container + "/" + blob); var httpClient = new HttpClient(); var response = await httpClient.SendRequestAsync(request); if ((int)response.StatusCode == 200) { var inputStream = await response.Content.ReadAsInputStreamAsync(); var memStream = new MemoryStream(); var testStream = inputStream.AsStreamForRead(); await testStream.CopyToAsync(memStream); memStream.Position = 0; using (var reader = new StreamReader(memStream)) { content = reader.ReadToEnd(); } return content; } Debug.WriteLine("ERROR: " + response.StatusCode + " - " + response.ReasonPhrase); return null; } catch (Exception ex) { Debug.WriteLine(ex.Message); return null; throw; } } public async Task<MemoryStream> GetBlobStream(string container, string blob) { try { var request = this.CreateRESTRequest("GET", container + "/" + blob); var httpClient = new HttpClient(); var response = await httpClient.SendRequestAsync(request); if ((int)response.StatusCode == 200) { var inputStream = await response.Content.ReadAsInputStreamAsync(); var memStream = new MemoryStream(); var testStream = inputStream.AsStreamForRead(); await testStream.CopyToAsync(memStream); memStream.Position = 0; return memStream; } Debug.WriteLine("ERROR: " + response.StatusCode + " - " + response.ReasonPhrase); return null; } catch (Exception ex) { Debug.WriteLine(ex.Message); return null; throw; } } // Create or update a blob. // Return true on success, false if not found, throw exception on error. public async Task<bool> PutBlob(string container, string blob, string content) { try { var headers = new Dictionary<string, string>(); headers.Add("x-ms-blob-type", "BlockBlob"); var request = this.CreateRESTRequest("PUT", container + "/" + blob, content, headers); var httpClient = new HttpClient(); var response = await httpClient.SendRequestAsync(request); if (response.StatusCode == HttpStatusCode.Created) { return true; } Debug.WriteLine("ERROR: " + response.StatusCode + " - " + response.ReasonPhrase); return false; } catch (Exception ex) { Debug.WriteLine(ex.Message); return false; throw; } } // Create or update a blob (Image). // Return true on success, false if not found, throw exception on error. public async Task<bool> PutBlob(string container, string blob, MemoryStream content) { try { var headers = new Dictionary<string, string>(); headers.Add("x-ms-blob-type", "BlockBlob"); var request = this.CreateStreamRESTRequest("PUT", container + "/" + blob, content, headers); var httpClient = new HttpClient(); var response = await httpClient.SendRequestAsync(request); if (response.StatusCode == HttpStatusCode.Created) { return true; } Debug.WriteLine("ERROR: " + response.StatusCode + " - " + response.ReasonPhrase); return false; } catch (Exception ex) { Debug.WriteLine(ex.Message); return false; throw; } } // Retrieve a blob's properties. // Return true on success, false if not found, throw exception on error. public async Task<Dictionary<string, string>> GetBlobProperties(string container, string blob) { var propertiesList = new Dictionary<string, string>(); try { var request = this.CreateStreamRESTRequest("HEAD", container + "/" + blob); var httpClient = new HttpClient(); var response = await httpClient.SendRequestAsync(request); if ((int)response.StatusCode == 200) { if (response.Headers != null) { foreach (var kvp in response.Headers) { propertiesList.Add(kvp.Key, kvp.Value); } } } else { Debug.WriteLine("ERROR: " + response.StatusCode + " - " + response.ReasonPhrase); return null; } return propertiesList; } catch (Exception ex) { Debug.WriteLine(ex.Message); return null; throw; } } // Retrieve a blob's metadata. // Return true on success, false if not found, throw exception on error. public async Task<Dictionary<string, string>> GetBlobMetadata(string container, string blob) { var metadata = new Dictionary<string, string>(); try { var request = this.CreateStreamRESTRequest("HEAD", container + "/" + blob + "?comp=metadata"); var httpClient = new HttpClient(); var response = await httpClient.SendRequestAsync(request); if ((int)response.StatusCode == 200) { if (response.Headers != null) { foreach (var kvp in response.Headers) { if (kvp.Key.StartsWith("x-ms-meta-")) { metadata.Add(kvp.Key, kvp.Value); } } } } return metadata; } catch (Exception ex) { Debug.WriteLine(ex.Message); return null; throw; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using AllReady.Areas.Admin.Features.Tasks; using AllReady.Controllers; using AllReady.Features.Events; using AllReady.Features.Tasks; using AllReady.Models; using AllReady.UnitTest.Extensions; using AllReady.ViewModels.Shared; using AllReady.ViewModels.Task; using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Moq; using Xunit; using DeleteVolunteerTaskCommand = AllReady.Features.Tasks.DeleteVolunteerTaskCommand; namespace AllReady.UnitTest.Controllers { public class TaskApiControllerTests { #region Post [Fact] public async Task PostReturnsHttpUnauthorizedWhenUserDoesNotHaveTheAuthorizationToEditTheTaskOrTheTaskIsNotInAnEditableState() { var mediator = new Mock<IMediator>(); mediator.Setup(x => x.SendAsync(It.IsAny<EventByEventIdQuery>())).ReturnsAsync(new Event()); var determineIfATaskIsEditable = new Mock<IDetermineIfATaskIsEditable>(); determineIfATaskIsEditable.Setup(x => x.For(It.IsAny<ClaimsPrincipal>(), It.IsAny<VolunteerTask>(), null)).Returns(false); var sut = new TaskApiController(mediator.Object, determineIfATaskIsEditable.Object, null); var result = await sut.Post(new VolunteerTaskViewModel { EventId = 1 }); Assert.IsType<UnauthorizedResult>(result); } [Fact] public async Task PostReturnsBadRequestResultWhenTaskAlreadyExists() { var mediator = new Mock<IMediator>(); mediator.Setup(x => x.SendAsync(It.IsAny<EventByEventIdQuery>())).ReturnsAsync(new Event()); mediator.Setup(x => x.SendAsync(It.IsAny<VolunteerTaskByVolunteerTaskIdQuery>())).ReturnsAsync(new VolunteerTask()); var determineIfATaskIsEditable = new Mock<IDetermineIfATaskIsEditable>(); determineIfATaskIsEditable.Setup(x => x.For(It.IsAny<ClaimsPrincipal>(), It.IsAny<VolunteerTask>(), null)).Returns(true); var sut = new TaskApiController(mediator.Object, determineIfATaskIsEditable.Object, null); var result = await sut.Post(new VolunteerTaskViewModel { EventId = 1 }); Assert.IsType<BadRequestResult>(result); } [Fact] public async Task PostReturnsBadRequestObjectResultWithCorrectErrorMessageWhenEventIsNull() { var determineIfATaskIsEditable = new Mock<IDetermineIfATaskIsEditable>(); determineIfATaskIsEditable.Setup(x => x.For(It.IsAny<ClaimsPrincipal>(), It.IsAny<VolunteerTask>(), null)).Returns(true); var sut = new TaskApiController(Mock.Of<IMediator>(), determineIfATaskIsEditable.Object, null); var result = await sut.Post(new VolunteerTaskViewModel()) as BadRequestObjectResult; Assert.IsType<BadRequestObjectResult>(result); Assert.Equal(400, result.StatusCode); } [Fact] public async Task PostSendsAddTaskCommandAsyncWithCorrectData() { var model = new VolunteerTaskViewModel { EventId = 1, Id = 1 }; var volunteerTask = new VolunteerTask(); var mediator = new Mock<IMediator>(); mediator.Setup(x => x.SendAsync(It.IsAny<EventByEventIdQuery>())).ReturnsAsync(new Event()); mediator.SetupSequence(x => x.SendAsync(It.IsAny<VolunteerTaskByVolunteerTaskIdQuery>())) .ReturnsAsync(volunteerTask).ReturnsAsync(null); var determineIfATaskIsEditable = new Mock<IDetermineIfATaskIsEditable>(); determineIfATaskIsEditable.Setup(x => x.For(It.IsAny<ClaimsPrincipal>(), It.IsAny<VolunteerTask>(), null)).Returns(true); var sut = new TaskApiController(mediator.Object, determineIfATaskIsEditable.Object, null); await sut.Post(model); mediator.Verify(x => x.SendAsync(It.Is<AddVolunteerTaskCommand>(y => y.VolunteerTask == volunteerTask)), Times.Once); } [Fact] public async Task PostSendsTaskByTaskIdQueryWithCorrectTaskId() { var model = new VolunteerTaskViewModel { EventId = 1, Id = 1 }; var mediator = new Mock<IMediator>(); mediator.Setup(x => x.SendAsync(It.IsAny<EventByEventIdQuery>())).ReturnsAsync(new Event()); mediator.Setup(x => x.SendAsync(It.IsAny<VolunteerTaskByVolunteerTaskIdQuery>())).ReturnsAsync(new VolunteerTask()); var provider = new Mock<IDetermineIfATaskIsEditable>(); provider.Setup(x => x.For(It.IsAny<ClaimsPrincipal>(), It.IsAny<VolunteerTask>(), null)).Returns(true); var sut = new TaskApiController(mediator.Object, provider.Object, null); await sut.Post(model); mediator.Verify(x => x.SendAsync(It.Is<VolunteerTaskByVolunteerTaskIdQuery>(y => y.VolunteerTaskId == model.Id))); } [Fact] public async Task PostReturnsHttpStatusCodeResultOf201() { var model = new VolunteerTaskViewModel { EventId = 1, Id = 0 }; var mediator = new Mock<IMediator>(); mediator.Setup(x => x.SendAsync(It.IsAny<EventByEventIdQuery>())).ReturnsAsync(new Event()); var provider = new Mock<IDetermineIfATaskIsEditable>(); provider.Setup(x => x.For(It.IsAny<ClaimsPrincipal>(), It.IsAny<VolunteerTask>(), null)).Returns(true); var sut = new TaskApiController(mediator.Object, provider.Object, null); var result = await sut.Post(model) as CreatedResult; Assert.IsType<CreatedResult>(result); Assert.Equal(201, result.StatusCode); } [Fact] public void PostHasHttpPostAttribute() { var sut = new TaskApiController(null, null, null); var attribute = sut.GetAttributesOn(x => x.Post(It.IsAny<VolunteerTaskViewModel>())).OfType<HttpPostAttribute>().SingleOrDefault(); Assert.NotNull(attribute); } [Fact] public void PostHasValidateAntiForgeryTokenAttribute() { var sut = new TaskApiController(null, null, null); var attribute = sut.GetAttributesOn(x => x.Post(It.IsAny<VolunteerTaskViewModel>())).OfType<ValidateAntiForgeryTokenAttribute>().SingleOrDefault(); Assert.NotNull(attribute); } #endregion #region Put [Fact] public async Task PutSendsTaskByTaskIdQueryWithCorrectTaskId() { const int volunteerTaskId = 1; var mediator = new Mock<IMediator>(); var sut = new TaskApiController(mediator.Object, null, null); await sut.Put(volunteerTaskId, It.IsAny<VolunteerTaskViewModel>()); mediator.Verify(x => x.SendAsync(It.Is<VolunteerTaskByVolunteerTaskIdQuery>(y => y.VolunteerTaskId == volunteerTaskId))); } [Fact] public async Task PutReturnsBadRequestResultWhenCannotFindTaskByTaskId() { var sut = new TaskApiController(Mock.Of<IMediator>(), null, null); var result = await sut.Put(It.IsAny<int>(), It.IsAny<VolunteerTaskViewModel>()); Assert.IsType<BadRequestResult>(result); } [Fact] public async Task PutReturnsHttpUnauthorizedResultWhenAUserDoesNotHavePermissionToEditTheTaskOrTheTaskIsNotEditable() { const int volunteerTaskId = 1; var mediator = new Mock<IMediator>(); mediator.Setup(x => x.SendAsync(It.IsAny<VolunteerTaskByVolunteerTaskIdQuery>())).ReturnsAsync(new VolunteerTask()); var determineIfATaskIsEditable = new Mock<IDetermineIfATaskIsEditable>(); determineIfATaskIsEditable.Setup(x => x.For(It.IsAny<ClaimsPrincipal>(), It.IsAny<VolunteerTask>(), null)).Returns(false); var sut = new TaskApiController(mediator.Object, determineIfATaskIsEditable.Object, null); var result = await sut.Put(volunteerTaskId, It.IsAny<VolunteerTaskViewModel>()); Assert.IsType<UnauthorizedResult>(result); } [Fact] public async Task PutSendsUpdateTaskCommandWithCorrectAllReadyTask() { var volunteerTask = new VolunteerTask(); var model = new VolunteerTaskViewModel { Name = "name", Description = "description", StartDateTime = DateTime.UtcNow, EndDateTime = DateTime.UtcNow }; var mediator = new Mock<IMediator>(); mediator.Setup(x => x.SendAsync(It.IsAny<VolunteerTaskByVolunteerTaskIdQuery>())).ReturnsAsync(volunteerTask); var determineIfATaskIsEditable = new Mock<IDetermineIfATaskIsEditable>(); determineIfATaskIsEditable.Setup(x => x.For(It.IsAny<ClaimsPrincipal>(), It.IsAny<VolunteerTask>(), null)).Returns(true); var sut = new TaskApiController(mediator.Object, determineIfATaskIsEditable.Object, null); await sut.Put(It.IsAny<int>(), model); mediator.Verify(x => x.SendAsync(It.Is<UpdateVolunteerTaskCommand>(y => y.VolunteerTask == volunteerTask)), Times.Once); } [Fact] public async Task PutReturnsHttpStatusCodeResultOf204() { var volunteerTask = new VolunteerTask(); var model = new VolunteerTaskViewModel { Name = "name", Description = "description", StartDateTime = DateTime.UtcNow, EndDateTime = DateTime.UtcNow }; var mediator = new Mock<IMediator>(); mediator.Setup(x => x.SendAsync(It.IsAny<VolunteerTaskByVolunteerTaskIdQuery>())).ReturnsAsync(volunteerTask); var determineIfATaskIsEditable = new Mock<IDetermineIfATaskIsEditable>(); determineIfATaskIsEditable.Setup(x => x.For(It.IsAny<ClaimsPrincipal>(), It.IsAny<VolunteerTask>(), null)).Returns(true); var sut = new TaskApiController(mediator.Object, determineIfATaskIsEditable.Object, null); var result = await sut.Put(It.IsAny<int>(), model) as NoContentResult; Assert.IsType<NoContentResult>(result); Assert.Equal(204, result.StatusCode); } [Fact] public void PutHasHttpPutAttributeWithCorrectTemplate() { var sut = new TaskApiController(null, null, null); var attribute = sut.GetAttributesOn(x => x.Put(It.IsAny<int>(), It.IsAny<VolunteerTaskViewModel>())).OfType<HttpPutAttribute>().SingleOrDefault(); Assert.NotNull(attribute); Assert.Equal("{id}", attribute.Template); } #endregion #region Delete [Fact] public async Task DeleteSendsTaskByTaskIdQueryWithCorrectTaskId() { const int volunteerTaskId = 1; var mediator = new Mock<IMediator>(); var sut = new TaskApiController(mediator.Object, null, null); await sut.Delete(volunteerTaskId); mediator.Verify(x => x.SendAsync(It.Is<VolunteerTaskByVolunteerTaskIdQuery>(y => y.VolunteerTaskId == volunteerTaskId))); } [Fact] public async Task DeleteReturnsBadRequestResultWhenCannotFindTaskByTaskId() { var sut = new TaskApiController(Mock.Of<IMediator>(), null, null); var result = await sut.Delete(It.IsAny<int>()); Assert.IsType<BadRequestResult>(result); } [Fact] public async Task DeleteReturnsHttpUnauthorizedResultWhenAUserDoesNotHavePermissionToEditTheTaskOrTheTaskIsNotEditable() { var mediator = new Mock<IMediator>(); mediator.Setup(x => x.SendAsync(It.IsAny<VolunteerTaskByVolunteerTaskIdQuery>())).ReturnsAsync(new VolunteerTask()); var determineIfATaskIsEditable = new Mock<IDetermineIfATaskIsEditable>(); determineIfATaskIsEditable.Setup(x => x.For(It.IsAny<ClaimsPrincipal>(), It.IsAny<VolunteerTask>(), null)).Returns(false); var sut = new TaskApiController(mediator.Object, determineIfATaskIsEditable.Object, null); var result = await sut.Delete(It.IsAny<int>()); Assert.IsType<UnauthorizedResult>(result); } [Fact] public async Task DeleteSendsDeleteTaskCommandWithCorrectTaskId() { var volunteerTask = new VolunteerTask { Id = 1 }; var mediator = new Mock<IMediator>(); mediator.Setup(x => x.SendAsync(It.IsAny<VolunteerTaskByVolunteerTaskIdQuery>())).ReturnsAsync(volunteerTask); var determineIfATaskIsEditable = new Mock<IDetermineIfATaskIsEditable>(); determineIfATaskIsEditable.Setup(x => x.For(It.IsAny<ClaimsPrincipal>(), It.IsAny<VolunteerTask>(), null)).Returns(true); var sut = new TaskApiController(mediator.Object, determineIfATaskIsEditable.Object, null); await sut.Delete(It.IsAny<int>()); mediator.Verify(x => x.SendAsync(It.Is<DeleteVolunteerTaskCommand>(y => y.VolunteerTaskId == volunteerTask.Id))); } [Fact] public void DeleteHasHttpDeleteAttributeWithCorrectTemplate() { var sut = new TaskApiController(null, null, null); var attribute = sut.GetAttributesOn(x => x.Delete(It.IsAny<int>())).OfType<HttpDeleteAttribute>().SingleOrDefault(); Assert.NotNull(attribute); Assert.Equal("{id}", attribute.Template); } #endregion #region RegisterTask [Fact] public async Task RegisterTaskReturnsHttpBadRequestWhenModelIsNull() { var sut = new TaskApiController(null, null, null); var result = await sut.RegisterTask(null); Assert.IsType<BadRequestResult>(result); } [Fact] public async Task RegisterTaskReturnsJsonWhenThereIsModelStateError() { const string modelStateErrorMessage = "modelStateErrorMessage"; var sut = new TaskApiController(null, null, null); sut.AddModelStateErrorWithErrorMessage(modelStateErrorMessage); var jsonResult = await sut.RegisterTask(new VolunteerTaskSignupViewModel()) as JsonResult; var result = jsonResult.GetValueForProperty<List<string>>("errors"); Assert.IsType<JsonResult>(jsonResult); Assert.IsType<List<string>>(result); Assert.Equal(result.First(), modelStateErrorMessage); } [Fact] public async Task RegisterTaskSendsTaskSignupCommandWithCorrectTaskSignupModel() { var model = new VolunteerTaskSignupViewModel(); var mediator = new Mock<IMediator>(); mediator.Setup(x => x.SendAsync(It.Is<VolunteerTaskSignupCommand>(y => y.TaskSignupModel == model))).ReturnsAsync(new VolunteerTaskSignupResult()); var sut = new TaskApiController(mediator.Object, null, null); await sut.RegisterTask(model); mediator.Verify(x => x.SendAsync(It.Is<VolunteerTaskSignupCommand>(command => command.TaskSignupModel.Equals(model)))); } [Fact] public async Task Register_ReturnsCorrectJson_WhenApiResult_IsSuccess() { const TaskResultStatus volunteerTaskSignUpResultStatus = TaskResultStatus.Success; var model = new VolunteerTaskSignupViewModel(); var mediator = new Mock<IMediator>(); mediator.Setup(x => x.SendAsync(It.Is<VolunteerTaskSignupCommand>(y => y.TaskSignupModel == model))) .ReturnsAsync(new VolunteerTaskSignupResult { Status = volunteerTaskSignUpResultStatus, VolunteerTask = new VolunteerTask { Id = 1, Name = "Task" } }); var sut = new TaskApiController(mediator.Object, null, null); var jsonResult = await sut.RegisterTask(model) as JsonResult; var successStatus = jsonResult.GetValueForProperty<bool>("isSuccess"); var volunteerTaskModel = jsonResult.GetValueForProperty<VolunteerTaskViewModel>("task"); Assert.True(successStatus); Assert.NotNull(volunteerTaskModel); } [Fact] public async Task Register_ReturnsCorrectJson_WhenEventNotFound() { const TaskResultStatus volunteerTaskSignUpResultStatus = TaskResultStatus.Failure_EventNotFound; var model = new VolunteerTaskSignupViewModel(); var mediator = new Mock<IMediator>(); mediator.Setup(x => x.SendAsync(It.Is<VolunteerTaskSignupCommand>(y => y.TaskSignupModel == model))) .ReturnsAsync(new VolunteerTaskSignupResult { Status = volunteerTaskSignUpResultStatus }); var sut = new TaskApiController(mediator.Object, null, null); var jsonResult = await sut.RegisterTask(model) as JsonResult; var successStatus = jsonResult.GetValueForProperty<bool>("isSuccess"); var errors = jsonResult.GetValueForProperty<string[]>("errors"); Assert.False(successStatus); Assert.NotNull(errors); Assert.Single(errors); Assert.Equal("Signup failed - The event could not be found", errors[0]); } [Fact] public async Task Register_ReturnsCorrectJson_WhenTaskNotFound() { const TaskResultStatus volunteerTaskSignUpResultStatus = TaskResultStatus.Failure_TaskNotFound; var model = new VolunteerTaskSignupViewModel(); var mediator = new Mock<IMediator>(); mediator.Setup(x => x.SendAsync(It.Is<VolunteerTaskSignupCommand>(y => y.TaskSignupModel == model))) .ReturnsAsync(new VolunteerTaskSignupResult { Status = volunteerTaskSignUpResultStatus }); var sut = new TaskApiController(mediator.Object, null, null); var jsonResult = await sut.RegisterTask(model) as JsonResult; var successStatus = jsonResult.GetValueForProperty<bool>("isSuccess"); var errors = jsonResult.GetValueForProperty<string[]>("errors"); Assert.False(successStatus); Assert.NotNull(errors); Assert.Single(errors); Assert.Equal("Signup failed - The task could not be found", errors[0]); } [Fact] public async Task Register_ReturnsCorrectJson_WhenTaskIsClosed() { const TaskResultStatus volunteerTaskSignUpResultStatus = TaskResultStatus.Failure_ClosedTask; var model = new VolunteerTaskSignupViewModel(); var mediator = new Mock<IMediator>(); mediator.Setup(x => x.SendAsync(It.Is<VolunteerTaskSignupCommand>(y => y.TaskSignupModel == model))) .ReturnsAsync(new VolunteerTaskSignupResult { Status = volunteerTaskSignUpResultStatus }); var sut = new TaskApiController(mediator.Object, null, null); var jsonResult = await sut.RegisterTask(model) as JsonResult; var successStatus = jsonResult.GetValueForProperty<bool>("isSuccess"); var errors = jsonResult.GetValueForProperty<string[]>("errors"); Assert.False(successStatus); Assert.NotNull(errors); Assert.Single(errors); Assert.Equal("Signup failed - Task is closed", errors[0]); } [Fact] public void RegisterTaskHasValidateAntiForgeryTokenAttrbiute() { var sut = new TaskApiController(null, null, null); var attribute = sut.GetAttributesOn(x => x.RegisterTask(It.IsAny<VolunteerTaskSignupViewModel>())).OfType<ValidateAntiForgeryTokenAttribute>().SingleOrDefault(); Assert.NotNull(attribute); } [Fact] public void RegisterTaskHasHttpPostAttributeWithCorrectTemplate() { var sut = new TaskApiController(null, null, null); var attribute = sut.GetAttributesOn(x => x.RegisterTask(It.IsAny<VolunteerTaskSignupViewModel>())).OfType<HttpPostAttribute>().SingleOrDefault(); Assert.NotNull(attribute); Assert.Equal("signup", attribute.Template); } [Fact] public void RegisterTaskHasAuthorizeAttrbiute() { var sut = new TaskApiController(null, null, null); var attribute = sut.GetAttributesOn(x => x.RegisterTask(It.IsAny<VolunteerTaskSignupViewModel>())).OfType<AuthorizeAttribute>().SingleOrDefault(); Assert.NotNull(attribute); } [Fact] public void RegisterTaskHasHasProducesAtttributeWithTheCorrectContentType() { var sut = new TaskApiController(null, null, null); var attribute = sut.GetAttributesOn(x => x.RegisterTask(It.IsAny<VolunteerTaskSignupViewModel>())).OfType<ProducesAttribute>().SingleOrDefault(); Assert.NotNull(attribute); Assert.Equal("application/json", attribute.ContentTypes.Select(x => x).First()); } #endregion #region UnregisterTask [Fact] public async Task UnregisterTaskSendsTaskUnenrollCommandWithCorrectTaskIdAndUserId() { const string userId = "1"; const int volunteerTaskId = 1; var mediator = new Mock<IMediator>(); mediator.Setup(x => x.SendAsync(It.IsAny<VolunteerTaskUnenrollCommand>())).ReturnsAsync(new VolunteerTaskUnenrollResult()); var userManager = UserManagerMockHelper.CreateUserManagerMock(); userManager.Setup(x => x.GetUserId(It.IsAny<ClaimsPrincipal>())).Returns(userId); var sut = new TaskApiController(mediator.Object, null, userManager.Object); sut.SetFakeUser(userId); await sut.UnregisterTask(volunteerTaskId); mediator.Verify(x => x.SendAsync(It.Is<VolunteerTaskUnenrollCommand>(y => y.VolunteerTaskId == volunteerTaskId && y.UserId == userId))); } [Fact] public async Task UnregisterTaskReturnsCorrectStatus() { const string status = "status"; var mediator = new Mock<IMediator>(); mediator.Setup(x => x.SendAsync(It.IsAny<VolunteerTaskUnenrollCommand>())).ReturnsAsync(new VolunteerTaskUnenrollResult { Status = status }); var userManager = UserManagerMockHelper.CreateUserManagerMock(); userManager.Setup(x => x.GetUserId(It.IsAny<ClaimsPrincipal>())).Returns(It.IsAny<string>()); var sut = new TaskApiController(mediator.Object, null, userManager.Object); sut.SetDefaultHttpContext(); var jsonResult = await sut.UnregisterTask(It.IsAny<int>()); var result = jsonResult.GetValueForProperty<string>("Status"); Assert.IsType<JsonResult>(jsonResult); Assert.IsType<string>(result); Assert.Equal(result, status); } [Fact] public async Task UnregisterTaskReturnsNullForTaskWhenResultTaskIsNull() { var mediator = new Mock<IMediator>(); mediator.Setup(x => x.SendAsync(It.IsAny<VolunteerTaskUnenrollCommand>())).ReturnsAsync(new VolunteerTaskUnenrollResult()); var userManager = UserManagerMockHelper.CreateUserManagerMock(); userManager.Setup(x => x.GetUserId(It.IsAny<ClaimsPrincipal>())).Returns(It.IsAny<string>()); var sut = new TaskApiController(mediator.Object, null, userManager.Object); sut.SetDefaultHttpContext(); var jsonResult = await sut.UnregisterTask(It.IsAny<int>()); var result = jsonResult.GetValueForProperty<string>("Task"); Assert.IsType<JsonResult>(jsonResult); Assert.Null(result); } [Fact] public async Task UnregisterTaskReturnsTaskViewModelWhenResultTaskIsNotNull() { var mediator = new Mock<IMediator>(); mediator.Setup(x => x.SendAsync(It.IsAny<VolunteerTaskUnenrollCommand>())).ReturnsAsync(new VolunteerTaskUnenrollResult { VolunteerTask = new VolunteerTask() }); var userManager = UserManagerMockHelper.CreateUserManagerMock(); userManager.Setup(x => x.GetUserId(It.IsAny<ClaimsPrincipal>())).Returns(It.IsAny<string>()); var sut = new TaskApiController(mediator.Object, null, userManager.Object); sut.SetDefaultHttpContext(); var jsonResult = await sut.UnregisterTask(It.IsAny<int>()); var result = jsonResult.GetValueForProperty<VolunteerTaskViewModel>("Task"); Assert.IsType<JsonResult>(jsonResult); Assert.IsType<VolunteerTaskViewModel>(result); } [Fact] public void UnregisterTaskHasAuthorizeAttrbiute() { var sut = new TaskApiController(null, null, null); var attribute = sut.GetAttributesOn(x => x.UnregisterTask(It.IsAny<int>())).OfType<AuthorizeAttribute>().SingleOrDefault(); Assert.NotNull(attribute); } [Fact] public void UnregisterTaskHasHttpDeleteAttributeWithCorrectTemplate() { var sut = new TaskApiController(null, null, null); var attribute = sut.GetAttributesOn(x => x.UnregisterTask(It.IsAny<int>())).OfType<HttpDeleteAttribute>().SingleOrDefault(); Assert.NotNull(attribute); Assert.Equal("{id}/signup", attribute.Template); } #endregion #region ChangeStatus [Fact] public async Task ChangeStatusInvokesSendAsyncWithCorrectTaskStatusChangeCommand() { var model = new VolunteerTaskChangeModel { VolunteerTaskId = 1, UserId = "1", Status = VolunteerTaskStatus.Accepted, StatusDescription = "statusDescription" }; var mediator = new Mock<IMediator>(); mediator.Setup(x => x.SendAsync(It.IsAny<ChangeVolunteerTaskStatusCommand>())).ReturnsAsync(new VolunteerTaskChangeResult()); var sut = new TaskApiController(mediator.Object, null, null); await sut.ChangeStatus(model); mediator.Verify(x => x.SendAsync(It.Is<ChangeVolunteerTaskStatusCommand>(y => y.VolunteerTaskId == model.VolunteerTaskId && y.VolunteerTaskStatus == model.Status && y.VolunteerTaskStatusDescription == model.StatusDescription && y.UserId == model.UserId))); } [Fact] public async Task ChangeStatusReturnsCorrectStatus() { const string status = "status"; var mediator = new Mock<IMediator>(); mediator.Setup(x => x.SendAsync(It.IsAny<ChangeVolunteerTaskStatusCommand>())).ReturnsAsync(new VolunteerTaskChangeResult { Status = status }); var sut = new TaskApiController(mediator.Object, null, null); sut.SetDefaultHttpContext(); var jsonResult = await sut.ChangeStatus(new VolunteerTaskChangeModel()); var result = jsonResult.GetValueForProperty<string>("Status"); Assert.IsType<JsonResult>(jsonResult); Assert.IsType<string>(result); Assert.Equal(result, status); } [Fact] public async Task ChangeStatusReturnsNullForTaskWhenResultTaskIsNull() { var mediator = new Mock<IMediator>(); mediator.Setup(x => x.SendAsync(It.IsAny<ChangeVolunteerTaskStatusCommand>())).ReturnsAsync(new VolunteerTaskChangeResult { Status = "status" }); var sut = new TaskApiController(mediator.Object, null, null); sut.SetDefaultHttpContext(); var jsonResult = await sut.ChangeStatus(new VolunteerTaskChangeModel()); var result = jsonResult.GetValueForProperty<string>("Task"); Assert.IsType<JsonResult>(jsonResult); Assert.Null(result); } [Fact] public async Task ChangeStatusReturnsTaskViewModelWhenResultTaskIsNotNull() { var mediator = new Mock<IMediator>(); mediator.Setup(x => x.SendAsync(It.IsAny<ChangeVolunteerTaskStatusCommand>())).ReturnsAsync(new VolunteerTaskChangeResult { VolunteerTask = new VolunteerTask() }); var sut = new TaskApiController(mediator.Object, null, null); sut.SetDefaultHttpContext(); var jsonResult = await sut.ChangeStatus(new VolunteerTaskChangeModel()); var result = jsonResult.GetValueForProperty<VolunteerTaskViewModel>("Task"); Assert.IsType<JsonResult>(jsonResult); Assert.IsType<VolunteerTaskViewModel>(result); } [Fact] public void ChangeStatusHasHttpPostAttribute() { var sut = new TaskApiController(null, null, null); var attribute = sut.GetAttributesOn(x => x.ChangeStatus(It.IsAny<VolunteerTaskChangeModel>())).OfType<HttpPostAttribute>().SingleOrDefault(); Assert.NotNull(attribute); } [Fact] public void ChangeStatusHasAuthorizeAttribute() { var sut = new TaskApiController(null, null, null); var attribute = sut.GetAttributesOn(x => x.ChangeStatus(It.IsAny<VolunteerTaskChangeModel>())).OfType<AuthorizeAttribute>().SingleOrDefault(); Assert.NotNull(attribute); } [Fact] public void ChangeStatusHasValidateAntiForgeryTokenAttribute() { var sut = new TaskApiController(null, null, null); var attribute = sut.GetAttributesOn(x => x.ChangeStatus(It.IsAny<VolunteerTaskChangeModel>())).OfType<ValidateAntiForgeryTokenAttribute>().SingleOrDefault(); Assert.NotNull(attribute); } [Fact] public void ChangeStatusHasRouteAttributeWithCorrectTemplate() { var sut = new TaskApiController(null, null, null); var attribute = sut.GetAttributesOn(x => x.ChangeStatus(It.IsAny<VolunteerTaskChangeModel>())).OfType<RouteAttribute>().SingleOrDefault(); Assert.NotNull(attribute); Assert.Equal("changestatus", attribute.Template); } #endregion [Fact] public void ControllerHasRouteAtttributeWithTheCorrectRoute() { var sut = new TaskApiController(null, null, null); var attribute = sut.GetAttributes().OfType<RouteAttribute>().SingleOrDefault(); Assert.NotNull(attribute); Assert.Equal("api/task", attribute.Template); } [Fact] public void ControllerHasProducesAtttributeWithTheCorrectContentType() { var sut = new TaskApiController(null, null, null); var attribute = sut.GetAttributes().OfType<ProducesAttribute>().SingleOrDefault(); Assert.NotNull(attribute); Assert.Equal("application/json", attribute.ContentTypes.Select(x => x).First()); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Grackle.Areas.HelpPage.ModelDescriptions; using Grackle.Areas.HelpPage.Models; namespace Grackle.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.DocumentationCommentFormatting; using Microsoft.CodeAnalysis.Editor.SignatureHelp; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.SignatureHelp { [ExportSignatureHelpProvider("ElementAccessExpressionSignatureHelpProvider", LanguageNames.CSharp)] internal sealed class ElementAccessExpressionSignatureHelpProvider : AbstractCSharpSignatureHelpProvider { public override bool IsTriggerCharacter(char ch) { return IsTriggerCharacterInternal(ch); } private static bool IsTriggerCharacterInternal(char ch) { return ch == '[' || ch == ','; } public override bool IsRetriggerCharacter(char ch) { return ch == ']'; } private static bool TryGetElementAccessExpression(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, out ExpressionSyntax identifier, out SyntaxToken openBrace) { return CompleteElementAccessExpression.TryGetSyntax(root, position, syntaxFacts, triggerReason, cancellationToken, out identifier, out openBrace) || IncompleteElementAccessExpression.TryGetSyntax(root, position, syntaxFacts, triggerReason, cancellationToken, out identifier, out openBrace); } protected override async Task<SignatureHelpItems> GetItemsWorkerAsync(Document document, int position, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken) { var root = await document.GetCSharpSyntaxRootAsync(cancellationToken).ConfigureAwait(false); ExpressionSyntax expression; SyntaxToken openBrace; if (!TryGetElementAccessExpression(root, position, document.GetLanguageService<ISyntaxFactsService>(), triggerInfo.TriggerReason, cancellationToken, out expression, out openBrace)) { return null; } var semanticModel = await document.GetCSharpSemanticModelAsync(cancellationToken).ConfigureAwait(false); var expressionSymbol = semanticModel.GetSymbolInfo(expression, cancellationToken).GetAnySymbol(); if (expressionSymbol is INamedTypeSymbol) { // foo?[$$] var namedType = (INamedTypeSymbol)expressionSymbol; if (namedType.ConstructedFrom.SpecialType == SpecialType.System_Nullable_T && expression.IsKind(SyntaxKind.NullableType) && expression.IsChildNode<ArrayTypeSyntax>(a => a.ElementType)) { // Speculatively bind the type part of the nullable as an expression var nullableTypeSyntax = (NullableTypeSyntax)expression; var speculativeBinding = semanticModel.GetSpeculativeSymbolInfo(position, nullableTypeSyntax.ElementType, SpeculativeBindingOption.BindAsExpression); expressionSymbol = speculativeBinding.GetAnySymbol(); expression = nullableTypeSyntax.ElementType; } } if (expressionSymbol != null && expressionSymbol is INamedTypeSymbol) { return null; } IEnumerable<IPropertySymbol> indexers; ITypeSymbol expressionType; if (!TryGetIndexers(position, semanticModel, expression, cancellationToken, out indexers, out expressionType) && !TryGetComIndexers(semanticModel, expression, cancellationToken, out indexers, out expressionType)) { return null; } var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken); if (within == null) { return null; } var accessibleIndexers = indexers.Where(m => m.IsAccessibleWithin(within, throughTypeOpt: expressionType)); if (!accessibleIndexers.Any()) { return null; } var symbolDisplayService = document.Project.LanguageServices.GetService<ISymbolDisplayService>(); accessibleIndexers = accessibleIndexers.FilterToVisibleAndBrowsableSymbols(document.ShouldHideAdvancedMembers(), semanticModel.Compilation) .Sort(symbolDisplayService, semanticModel, expression.SpanStart); var anonymousTypeDisplayService = document.Project.LanguageServices.GetService<IAnonymousTypeDisplayService>(); var documentationCommentFormattingService = document.Project.LanguageServices.GetService<IDocumentationCommentFormattingService>(); var textSpan = GetTextSpan(expression, openBrace); var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); return CreateSignatureHelpItems(accessibleIndexers.Select(p => Convert(p, openBrace, semanticModel, symbolDisplayService, anonymousTypeDisplayService, documentationCommentFormattingService, cancellationToken)), textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken)); } private TextSpan GetTextSpan(ExpressionSyntax expression, SyntaxToken openBracket) { if (openBracket.Parent is BracketedArgumentListSyntax) { return CompleteElementAccessExpression.GetTextSpan(expression, openBracket); } else if (openBracket.Parent is ArrayRankSpecifierSyntax) { return IncompleteElementAccessExpression.GetTextSpan(expression, openBracket); } throw ExceptionUtilities.Unreachable; } public override SignatureHelpState GetCurrentArgumentState(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, TextSpan currentSpan, CancellationToken cancellationToken) { ExpressionSyntax expression; SyntaxToken openBracket; if (!TryGetElementAccessExpression( root, position, syntaxFacts, SignatureHelpTriggerReason.InvokeSignatureHelpCommand, cancellationToken, out expression, out openBracket) || currentSpan.Start != expression.SpanStart) { return null; } ElementAccessExpressionSyntax elementAccessExpression = SyntaxFactory.ElementAccessExpression( expression, SyntaxFactory.ParseBracketedArgumentList(openBracket.Parent.ToString())); // Because we synthesized the elementAccessExpression, it will have an index starting at 0 // instead of at the actual position it's at in the text. Because of this, we need to // offset the position we are checking accordingly. var offset = expression.SpanStart - elementAccessExpression.SpanStart; position -= offset; return SignatureHelpUtilities.GetSignatureHelpState(elementAccessExpression.ArgumentList, position); } private bool TryGetComIndexers(SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken, out IEnumerable<IPropertySymbol> indexers, out ITypeSymbol expressionType) { indexers = semanticModel.GetMemberGroup(expression, cancellationToken).OfType<IPropertySymbol>(); if (indexers.Any() && expression is MemberAccessExpressionSyntax) { expressionType = semanticModel.GetTypeInfo(((MemberAccessExpressionSyntax)expression).Expression, cancellationToken).Type; return true; } expressionType = null; return false; } private bool TryGetIndexers(int position, SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken, out IEnumerable<IPropertySymbol> indexers, out ITypeSymbol expressionType) { expressionType = semanticModel.GetTypeInfo(expression, cancellationToken).Type; if (expressionType == null) { indexers = null; return false; } if (expressionType is IErrorTypeSymbol) { expressionType = (expressionType as IErrorTypeSymbol).CandidateSymbols.FirstOrDefault().GetSymbolType(); } indexers = semanticModel.LookupSymbols(position, expressionType, WellKnownMemberNames.Indexer).OfType<IPropertySymbol>(); return true; } private SignatureHelpItem Convert( IPropertySymbol indexer, SyntaxToken openToken, SemanticModel semanticModel, ISymbolDisplayService symbolDisplayService, IAnonymousTypeDisplayService anonymousTypeDisplayService, IDocumentationCommentFormattingService documentationCommentFormattingService, CancellationToken cancellationToken) { var position = openToken.SpanStart; var item = CreateItem(indexer, semanticModel, position, symbolDisplayService, anonymousTypeDisplayService, indexer.IsParams(), indexer.GetDocumentationPartsFactory(semanticModel, position, documentationCommentFormattingService), GetPreambleParts(indexer, position, semanticModel), GetSeparatorParts(), GetPostambleParts(indexer), indexer.Parameters.Select(p => Convert(p, semanticModel, position, documentationCommentFormattingService, cancellationToken))); return item; } private IEnumerable<SymbolDisplayPart> GetPreambleParts( IPropertySymbol indexer, int position, SemanticModel semanticModel) { var result = new List<SymbolDisplayPart>(); result.AddRange(indexer.Type.ToMinimalDisplayParts(semanticModel, position)); result.Add(Space()); result.AddRange(indexer.ContainingType.ToMinimalDisplayParts(semanticModel, position)); if (indexer.Name != WellKnownMemberNames.Indexer) { result.Add(Punctuation(SyntaxKind.DotToken)); result.Add(new SymbolDisplayPart(SymbolDisplayPartKind.PropertyName, indexer, indexer.Name)); } result.Add(Punctuation(SyntaxKind.OpenBracketToken)); return result; } private IEnumerable<SymbolDisplayPart> GetPostambleParts(IPropertySymbol indexer) { yield return Punctuation(SyntaxKind.CloseBracketToken); } private static class CompleteElementAccessExpression { internal static bool IsTriggerToken(SyntaxToken token) { return !token.IsKind(SyntaxKind.None) && token.ValueText.Length == 1 && IsTriggerCharacterInternal(token.ValueText[0]) && token.Parent is BracketedArgumentListSyntax && token.Parent.Parent is ElementAccessExpressionSyntax; } internal static bool IsArgumentListToken(ElementAccessExpressionSyntax expression, SyntaxToken token) { return expression.ArgumentList.Span.Contains(token.SpanStart) && token != expression.ArgumentList.CloseBracketToken; } internal static TextSpan GetTextSpan(SyntaxNode expression, SyntaxToken openBracket) { Contract.ThrowIfFalse(openBracket.Parent is BracketedArgumentListSyntax && openBracket.Parent.Parent is ElementAccessExpressionSyntax); return SignatureHelpUtilities.GetSignatureHelpSpan((BracketedArgumentListSyntax)openBracket.Parent); } internal static bool TryGetSyntax(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, out ExpressionSyntax identifier, out SyntaxToken openBrace) { ElementAccessExpressionSyntax elementAccessExpression; if (CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, IsTriggerToken, IsArgumentListToken, cancellationToken, out elementAccessExpression)) { identifier = elementAccessExpression.Expression; openBrace = elementAccessExpression.ArgumentList.OpenBracketToken; return true; } identifier = null; openBrace = default(SyntaxToken); return false; } } /// Error tolerance case for /// "foo[]" /// which is parsed as an ArrayTypeSyntax variable declaration instead of an ElementAccessExpression private static class IncompleteElementAccessExpression { internal static bool IsArgumentListToken(ArrayTypeSyntax node, SyntaxToken token) { return node.RankSpecifiers.Span.Contains(token.SpanStart) && token != node.RankSpecifiers.First().CloseBracketToken; } internal static bool IsTriggerToken(SyntaxToken token) { return !token.IsKind(SyntaxKind.None) && token.ValueText.Length == 1 && IsTriggerCharacterInternal(token.ValueText[0]) && token.Parent is ArrayRankSpecifierSyntax; } internal static TextSpan GetTextSpan(SyntaxNode expression, SyntaxToken openBracket) { Contract.ThrowIfFalse(openBracket.Parent is ArrayRankSpecifierSyntax && openBracket.Parent.Parent is ArrayTypeSyntax); return TextSpan.FromBounds(expression.SpanStart, openBracket.Parent.Span.End); } internal static bool TryGetSyntax(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, out ExpressionSyntax identifier, out SyntaxToken openBrace) { ArrayTypeSyntax arrayTypeSyntax; if (CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, IsTriggerToken, IsArgumentListToken, cancellationToken, out arrayTypeSyntax)) { identifier = arrayTypeSyntax.ElementType; openBrace = arrayTypeSyntax.RankSpecifiers.First().OpenBracketToken; return true; } identifier = null; openBrace = default(SyntaxToken); return false; } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Reflection; using System.Threading.Tasks; using Orleans; using Orleans.Concurrency; using Orleans.Providers; using Orleans.Runtime; using UnitTests.GrainInterfaces; namespace UnitTests.Grains { [Serializable] public class SimpleGenericGrainState<T> { public T A { get; set; } public T B { get; set; } } [StorageProvider(ProviderName = "MemoryStore")] public class SimpleGenericGrain1<T> : Grain<SimpleGenericGrainState<T>>, ISimpleGenericGrain1<T> { public Task<T> GetA() { return Task.FromResult(State.A); } public Task SetA(T a) { State.A = a; return Task.CompletedTask; } public Task SetB(T b) { State.B = b; return Task.CompletedTask; } public Task<string> GetAxB() { string retValue = string.Format("{0}x{1}", State.A, State.B); return Task.FromResult(retValue); } public Task<string> GetAxB(T a, T b) { string retValue = string.Format("{0}x{1}", a, b); return Task.FromResult(retValue); } } [StorageProvider(ProviderName = "AzureStore")] public class SimpleGenericGrainUsingAzureStorageAndLongGrainName<T> : Grain<SimpleGenericGrainState<T>>, ISimpleGenericGrainUsingAzureStorageAndLongGrainName<T> { public async Task<T> EchoAsync(T entity) { State.A = entity; await WriteStateAsync(); return entity; } public async Task ClearState() { await ClearStateAsync(); } } [StorageProvider(ProviderName = "AzureStore")] public class TinyNameGrain<T> : Grain<SimpleGenericGrainState<T>>, ITinyNameGrain<T> { public async Task<T> EchoAsync(T entity) { State.A = entity; await WriteStateAsync(); return entity; } public async Task ClearState() { await ClearStateAsync(); } } [Serializable] public class SimpleGenericGrainUState<U> { public U A { get; set; } public U B { get; set; } } [StorageProvider(ProviderName = "MemoryStore")] public class SimpleGenericGrainU<U> : Grain<SimpleGenericGrainUState<U>>, ISimpleGenericGrainU<U> { public Task<U> GetA() { return Task.FromResult(State.A); } public Task SetA(U a) { State.A = a; return Task.CompletedTask; } public Task SetB(U b) { State.B = b; return Task.CompletedTask; } public Task<string> GetAxB() { string retValue = string.Format("{0}x{1}", State.A, State.B); return Task.FromResult(retValue); } public Task<string> GetAxB(U a, U b) { string retValue = string.Format("{0}x{1}", a, b); return Task.FromResult(retValue); } } [Serializable] public class SimpleGenericGrain2State<T, U> { public T A { get; set; } public U B { get; set; } } [StorageProvider(ProviderName = "MemoryStore")] public class SimpleGenericGrain2<T, U> : Grain<SimpleGenericGrain2State<T, U>>, ISimpleGenericGrain2<T, U> { public Task<T> GetA() { return Task.FromResult(State.A); } public Task SetA(T a) { State.A = a; return Task.CompletedTask; } public Task SetB(U b) { State.B = b; return Task.CompletedTask; } public Task<string> GetAxB() { string retValue = string.Format(CultureInfo.InvariantCulture, "{0}x{1}", State.A, State.B); return Task.FromResult(retValue); } public Task<string> GetAxB(T a, U b) { string retValue = string.Format(CultureInfo.InvariantCulture, "{0}x{1}", a, b); return Task.FromResult(retValue); } } public class GenericGrainWithNoProperties<T> : Grain, IGenericGrainWithNoProperties<T> { public Task<string> GetAxB(T a, T b) { string retValue = string.Format("{0}x{1}", a, b); return Task.FromResult(retValue); } } public class GrainWithNoProperties : Grain, IGrainWithNoProperties { public Task<string> GetAxB(int a, int b) { string retValue = string.Format("{0}x{1}", a, b); return Task.FromResult(retValue); } } [Serializable] public class IGrainWithListFieldsState { public IList<string> Items { get; set; } } [StorageProvider(ProviderName = "MemoryStore")] public class GrainWithListFields : Grain<IGrainWithListFieldsState>, IGrainWithListFields { public override Task OnActivateAsync() { if (State.Items == null) State.Items = new List<string>(); return base.OnActivateAsync(); } public Task AddItem(string item) { State.Items.Add(item); return Task.CompletedTask; } public Task<IList<string>> GetItems() { return Task.FromResult((State.Items)); } } [Serializable] public class GenericGrainWithListFieldsState<T> { public IList<T> Items { get; set; } } [StorageProvider(ProviderName = "MemoryStore")] public class GenericGrainWithListFields<T> : Grain<GenericGrainWithListFieldsState<T>>, IGenericGrainWithListFields<T> { public override Task OnActivateAsync() { if (State.Items == null) State.Items = new List<T>(); return base.OnActivateAsync(); } public Task AddItem(T item) { State.Items.Add(item); return Task.CompletedTask; } public Task<IList<T>> GetItems() { return Task.FromResult(State.Items); } } [Serializable] public class GenericReaderWriterState<T> { public T Value { get; set; } } [Serializable] public class GenericReader2State<TOne, TTwo> { public TOne Value1 { get; set; } public TTwo Value2 { get; set; } } [Serializable] public class GenericReaderWriterGrain2State<TOne, TTwo> { public TOne Value1 { get; set; } public TTwo Value2 { get; set; } } [Serializable] public class GenericReader3State<TOne, TTwo, TThree> { public TOne Value1 { get; set; } public TTwo Value2 { get; set; } public TThree Value3 { get; set; } } [StorageProvider(ProviderName = "MemoryStore")] public class GenericReaderWriterGrain1<T> : Grain<GenericReaderWriterState<T>>, IGenericReaderWriterGrain1<T> { public Task SetValue(T value) { State.Value = value; return Task.CompletedTask; } public Task<T> GetValue() { return Task.FromResult(State.Value); } } [StorageProvider(ProviderName = "MemoryStore")] public class GenericReaderWriterGrain2<TOne, TTwo> : Grain<GenericReaderWriterGrain2State<TOne, TTwo>>, IGenericReaderWriterGrain2<TOne, TTwo> { public Task SetValue1(TOne value) { State.Value1 = value; return Task.CompletedTask; } public Task SetValue2(TTwo value) { State.Value2 = value; return Task.CompletedTask; } public Task<TOne> GetValue1() { return Task.FromResult(State.Value1); } public Task<TTwo> GetValue2() { return Task.FromResult(State.Value2); } } [StorageProvider(ProviderName = "MemoryStore")] public class GenericReaderWriterGrain3<TOne, TTwo, TThree> : Grain<GenericReader3State<TOne, TTwo, TThree>>, IGenericReaderWriterGrain3<TOne, TTwo, TThree> { public Task SetValue1(TOne value) { State.Value1 = value; return Task.CompletedTask; } public Task SetValue2(TTwo value) { State.Value2 = value; return Task.CompletedTask; } public Task SetValue3(TThree value) { State.Value3 = value; return Task.CompletedTask; } public Task<TThree> GetValue3() { return Task.FromResult(State.Value3); } public Task<TOne> GetValue1() { return Task.FromResult(State.Value1); } public Task<TTwo> GetValue2() { return Task.FromResult(State.Value2); } } public class BasicGenericGrain<T, U> : Grain, IBasicGenericGrain<T, U> { private T _a; private U _b; public Task<T> GetA() { return Task.FromResult(_a); } public Task<string> GetAxB() { string retValue = string.Format(CultureInfo.InvariantCulture, "{0}x{1}", _a, _b); return Task.FromResult(retValue); } public Task<string> GetAxB(T a, U b) { string retValue = string.Format(CultureInfo.InvariantCulture, "{0}x{1}", a, b); return Task.FromResult(retValue); } public Task SetA(T a) { this._a = a; return Task.CompletedTask; } public Task SetB(U b) { this._b = b; return Task.CompletedTask; } } public class HubGrain<TKey, T1, T2> : Grain, IHubGrain<TKey, T1, T2> { public virtual Task Bar(TKey key, T1 message1, T2 message2) { throw new System.NotImplementedException(); } } public class EchoHubGrain<TKey, TMessage> : HubGrain<TKey, TMessage, TMessage>, IEchoHubGrain<TKey, TMessage> { private int _x; public Task Foo(TKey key, TMessage message, int x) { _x = x; return Task.CompletedTask; } public override Task Bar(TKey key, TMessage message1, TMessage message2) { return Task.CompletedTask; } public Task<int> GetX() { return Task.FromResult(_x); } } public class EchoGenericChainGrain<T> : Grain, IEchoGenericChainGrain<T> { public async Task<T> Echo(T item) { long pk = this.GetPrimaryKeyLong(); var otherGrain = GrainFactory.GetGrain<ISimpleGenericGrain1<T>>(pk); await otherGrain.SetA(item); return await otherGrain.GetA(); } public async Task<T> Echo2(T item) { long pk = this.GetPrimaryKeyLong() + 1; var otherGrain = GrainFactory.GetGrain<IEchoGenericChainGrain<T>>(pk); return await otherGrain.Echo(item); } public async Task<T> Echo3(T item) { long pk = this.GetPrimaryKeyLong() + 1; var otherGrain = GrainFactory.GetGrain<IEchoGenericChainGrain<T>>(pk); return await otherGrain.Echo2(item); } public async Task<T> Echo4(T item) { long pk = this.GetPrimaryKeyLong() + 1; var otherGrain = GrainFactory.GetGrain<ISimpleGenericGrain1<T>>(pk); await otherGrain.SetA(item); return await otherGrain.GetA(); } public async Task<T> Echo5(T item) { long pk = this.GetPrimaryKeyLong() + 1; var otherGrain = GrainFactory.GetGrain<IEchoGenericChainGrain<T>>(pk); return await otherGrain.Echo4(item); } public async Task<T> Echo6(T item) { long pk = this.GetPrimaryKeyLong() + 1; var otherGrain = GrainFactory.GetGrain<IEchoGenericChainGrain<T>>(pk); return await otherGrain.Echo5(item); } } public class NonGenericBaseGrain : Grain, INonGenericBase { public Task Ping() { return Task.CompletedTask; } } public class Generic1ArgumentGrain<T> : NonGenericBaseGrain, IGeneric1Argument<T> { public Task<T> Ping(T t) { return Task.FromResult(t); } } public class Generic1ArgumentDerivedGrain<T> : NonGenericBaseGrain, IGeneric1Argument<T> { public Task<T> Ping(T t) { return Task.FromResult(t); } } public class Generic2ArgumentGrain<T, U> : Grain, IGeneric2Arguments<T, U> { public Task<Tuple<T, U>> Ping(T t, U u) { return Task.FromResult(new Tuple<T, U>(t, u)); } public Task Ping() { return Task.CompletedTask; } } public class Generic2ArgumentsDerivedGrain<T, U> : NonGenericBaseGrain, IGeneric2Arguments<T, U> { public Task<Tuple<T, U>> Ping(T t, U u) { return Task.FromResult(new Tuple<T, U>(t, u)); } } public class DbGrain<T> : Grain, IDbGrain<T> { private T _value; public Task SetValue(T value) { _value = value; return Task.CompletedTask; } public Task<T> GetValue() { return Task.FromResult(_value); } } [Reentrant] public class PingSelfGrain<T> : Grain, IGenericPingSelf<T> { private T _lastValue; public Task<T> Ping(T t) { _lastValue = t; return Task.FromResult(t); } public Task<T> PingOther(IGenericPingSelf<T> target, T t) { return target.Ping(t); } public Task<T> PingSelf(T t) { return PingOther(this, t); } public Task<T> PingSelfThroughOther(IGenericPingSelf<T> target, T t) { return target.PingOther(this, t); } public Task ScheduleDelayedPing(IGenericPingSelf<T> target, T t, TimeSpan delay) { RegisterTimer(o => { this.GetLogger().Verbose("***Timer fired for pinging {0}***", target.GetPrimaryKey()); return target.Ping(t); }, null, delay, TimeSpan.FromMilliseconds(-1)); return Task.CompletedTask; } public Task<T> GetLastValue() { return Task.FromResult(_lastValue); } public async Task ScheduleDelayedPingToSelfAndDeactivate(IGenericPingSelf<T> target, T t, TimeSpan delay) { await target.ScheduleDelayedPing(this, t, delay); DeactivateOnIdle(); } public override Task OnActivateAsync() { GetLogger().Verbose("***Activating*** {0}", this.GetPrimaryKey()); return Task.CompletedTask; } public override Task OnDeactivateAsync() { GetLogger().Verbose("***Deactivating*** {0}", this.GetPrimaryKey()); return Task.CompletedTask; } } public class LongRunningTaskGrain<T> : Grain, ILongRunningTaskGrain<T> { private T lastValue; public Task CancellationTokenCallbackThrow(GrainCancellationToken tc) { tc.CancellationToken.Register(() => { throw new InvalidOperationException("From cancellation token callback"); }); return Task.CompletedTask; } public Task<T> GetLastValue() { return Task.FromResult(lastValue); } public async Task<bool> CallOtherCancellationTokenCallbackResolve(ILongRunningTaskGrain<T> target) { var tc = new GrainCancellationTokenSource(); var grainTask = target.CancellationTokenCallbackResolve(tc.Token); await Task.Delay(300); await tc.Cancel(); return await grainTask; } public Task<bool> CancellationTokenCallbackResolve(GrainCancellationToken tc) { var tcs = new TaskCompletionSource<bool>(); var orleansTs = TaskScheduler.Current; tc.CancellationToken.Register(() => { if (TaskScheduler.Current != orleansTs) { tcs.SetException(new Exception("Callback executed on wrong thread")); } else { tcs.SetResult(true); } }); return tcs.Task; } public async Task<T> CallOtherLongRunningTask(ILongRunningTaskGrain<T> target, T t, TimeSpan delay) { return await target.LongRunningTask(t, delay); } public async Task CallOtherLongRunningTask(ILongRunningTaskGrain<T> target, GrainCancellationToken tc, TimeSpan delay) { await target.LongWait(tc, delay); } public async Task CallOtherLongRunningTaskWithLocalToken(ILongRunningTaskGrain<T> target, TimeSpan delay, TimeSpan delayBeforeCancel) { var tcs = new GrainCancellationTokenSource(); var task = target.LongWait(tcs.Token, delay); await Task.Delay(delayBeforeCancel); await tcs.Cancel(); await task; } public async Task LongWait(GrainCancellationToken tc, TimeSpan delay) { await Task.Delay(delay, tc.CancellationToken); } public async Task<T> LongRunningTask(T t, TimeSpan delay) { await Task.Delay(delay); this.lastValue = t; return await Task.FromResult(t); } public Task<string> GetRuntimeInstanceId() { return Task.FromResult(RuntimeIdentity); } } public class GenericGrainWithContraints<A, B, C>: Grain, IGenericGrainWithConstraints<A, B, C> where A : ICollection<B>, new() where B : struct where C : class { private A collection; public override Task OnActivateAsync() { collection = new A(); return Task.CompletedTask; } public Task<int> GetCount() { return Task.FromResult(collection.Count); } public Task Add(B item) { collection.Add(item); return Task.CompletedTask; } public Task<C> RoundTrip(C value) { return Task.FromResult(value); } } public class NonGenericCastableGrain : Grain, INonGenericCastableGrain, ISomeGenericGrain<string>, IIndependentlyConcretizedGenericGrain<string>, IIndependentlyConcretizedGrain { public Task DoSomething() { return Task.CompletedTask; } public Task<string> Hello() { return Task.FromResult("Hello!"); } } public class GenericCastableGrain<T> : Grain, IGenericCastableGrain<T>, INonGenericCastGrain { public Task<string> Hello() { return Task.FromResult("Hello!"); } } public class IndepedentlyConcretizedGenericGrain : Grain, IIndependentlyConcretizedGenericGrain<string>, IIndependentlyConcretizedGrain { public Task<string> Hello() { return Task.FromResult("I have been independently concretized!"); } } namespace Generic.EdgeCases { using System.Linq; using UnitTests.GrainInterfaces.Generic.EdgeCases; public abstract class BasicGrain : Grain { public Task<string> Hello() { return Task.FromResult("Hello!"); } public Task<string[]> ConcreteGenArgTypeNames() { var grainType = GetImmediateSubclass(this.GetType()); return Task.FromResult( grainType.GetGenericArguments() .Select(t => t.FullName) .ToArray() ); } Type GetImmediateSubclass(Type subject) { if(subject.GetTypeInfo().BaseType == typeof(BasicGrain)) { return subject; } return GetImmediateSubclass(subject.GetTypeInfo().BaseType); } } public class PartiallySpecifyingGrain<T> : BasicGrain, IGrainWithTwoGenArgs<string, T> { } public class GrainWithPartiallySpecifyingInterface<T> : BasicGrain, IPartiallySpecifyingInterface<T> { } public class GrainSpecifyingSameGenArgTwice<T> : BasicGrain, IGrainReceivingRepeatedGenArgs<T, T> { } public class SpecifyingRepeatedGenArgsAmongstOthers<T1, T2> : BasicGrain, IReceivingRepeatedGenArgsAmongstOthers<T2, T1, T2> { } public class GrainForTestingCastingBetweenInterfacesWithReusedGenArgs : BasicGrain, ISpecifyingGenArgsRepeatedlyToParentInterface<bool> { } public class SpecifyingSameGenArgsButRearranged<T1, T2> : BasicGrain, IReceivingRearrangedGenArgs<T2, T1> { } public class GrainForTestingCastingWithRearrangedGenArgs<T1, T2> : BasicGrain, ISpecifyingRearrangedGenArgsToParentInterface<T1, T2> { } public class GrainWithGenArgsUnrelatedToFullySpecifiedGenericInterface<T1, T2> : BasicGrain, IArbitraryInterface<T1, T2>, IInterfaceUnrelatedToConcreteGenArgs<float> { } public class GrainSupplyingFurtherSpecializedGenArg<T> : BasicGrain, IInterfaceTakingFurtherSpecializedGenArg<List<T>> { } public class GrainSupplyingGenArgSpecializedIntoArray<T> : BasicGrain, IInterfaceTakingFurtherSpecializedGenArg<T[]> { } public class GrainForCastingBetweenInterfacesOfFurtherSpecializedGenArgs<T> : BasicGrain, IAnotherReceivingFurtherSpecializedGenArg<List<T>>, IYetOneMoreReceivingFurtherSpecializedGenArg<T[]> { } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ // This file contains the definitions for the objects // used in the communication protocol between formatting // and output commands. the format/xxx commands instantiate // these objects and write them to the pipeline. The out-xxx // commands read them from the pipeline. // // NOTE: // Since format/xxx and out-xxx commands can be separated by // serialization boundaries, the structure of these objects // must adhere to the Monad serialization constraints. // // Since the out-xxx commands heavily access these objects and // there is an up front need for protocol validation, the out-xxx // commands do deserialize the objects back from the property bag // representation that mig have been introduced by serialization. // // There is also the need to preserve type information across serialization // boudaries, therefore the objects provide a GUID based machanism to // preserve the information. // using System.Collections.Generic; namespace Microsoft.PowerShell.Commands.Internal.Format { #region Root of Class Hierarchy /// <summary> /// base class from which all the formatting objects /// will derive from. /// It provides the mechanism to preserve type information. /// </summary> internal abstract partial class FormatInfoData { /// <summary> /// name of the "get" property that allows access to CLSID information. /// This is needed by the ERS API's /// </summary> internal const string classidProperty = "ClassId2e4f51ef21dd47e99d3c952918aff9cd"; /// <summary> /// string containing a GUID, to be set by each derived class /// "get" property to get CLSID information. /// It is named with a GUID like name to avoid potential collisions with /// properties of payload objects /// </summary> public abstract string ClassId2e4f51ef21dd47e99d3c952918aff9cd { get; } } #endregion #region Top Level Messages internal abstract class PacketInfoData : FormatInfoData { } internal abstract partial class ControlInfoData : PacketInfoData { /// <summary> /// null by default, present only if grouping specified /// </summary> public GroupingEntry groupingEntry = null; } internal abstract partial class StartData : ControlInfoData { /// <summary> /// it needs to be either on FormatStartData or GroupStartData /// but not both or neither. /// </summary> public ShapeInfo shapeInfo; } /// <summary> /// sequence start: the very first message sent /// </summary> internal sealed partial class FormatStartData : StartData { internal const string CLSID = "033ecb2bc07a4d43b5ef94ed5a35d280"; public override string ClassId2e4f51ef21dd47e99d3c952918aff9cd { get { return CLSID; } } /// <summary> /// optional /// </summary> public PageHeaderEntry pageHeaderEntry; /// <summary> /// optional /// </summary> public PageFooterEntry pageFooterEntry; /// <summary> /// autosize formatting directive. If present, the output command is instructed /// to get the autosize "best fit" for the device screen according to the flags /// this object contains. /// </summary> public AutosizeInfo autosizeInfo; } /// <summary> /// sequence end: the very last message sent /// </summary> internal sealed class FormatEndData : ControlInfoData { internal const string CLSID = "cf522b78d86c486691226b40aa69e95c"; public override string ClassId2e4f51ef21dd47e99d3c952918aff9cd { get { return CLSID; } } } /// <summary> /// group start: message marking the beginning of a group /// </summary> internal sealed class GroupStartData : StartData { internal const string CLSID = "9e210fe47d09416682b841769c78b8a3"; public override string ClassId2e4f51ef21dd47e99d3c952918aff9cd { get { return CLSID; } } } /// <summary> /// group end: message marking the end of a group /// </summary> internal sealed class GroupEndData : ControlInfoData { internal const string CLSID = "4ec4f0187cb04f4cb6973460dfe252df"; public override string ClassId2e4f51ef21dd47e99d3c952918aff9cd { get { return CLSID; } } } /// <summary> /// generic entry containing payload data and related formatting info /// </summary> internal sealed partial class FormatEntryData : PacketInfoData { internal const string CLSID = "27c87ef9bbda4f709f6b4002fa4af63c"; public override string ClassId2e4f51ef21dd47e99d3c952918aff9cd { get { return CLSID; } } /// <summary> /// mandatory, but depending on the shape we send in /// it must match what got sent in the format start message /// </summary> public FormatEntryInfo formatEntryInfo = null; public bool outOfBand = false; public WriteStreamType writeStream = WriteStreamType.None; internal bool isHelpObject = false; /// <summary> /// Helper method to set the WriteStreamType property /// based on note properties of a PSObject object. /// </summary> /// <param name="so">PSObject</param> internal void SetStreamTypeFromPSObject( System.Management.Automation.PSObject so) { if (PSObjectHelper.IsWriteErrorStream(so)) { writeStream = WriteStreamType.Error; } else if (PSObjectHelper.IsWriteWarningStream(so)) { writeStream = WriteStreamType.Warning; } else if (PSObjectHelper.IsWriteVerboseStream(so)) { writeStream = WriteStreamType.Verbose; } else if (PSObjectHelper.IsWriteDebugStream(so)) { writeStream = WriteStreamType.Debug; } else if (PSObjectHelper.IsWriteInformationStream(so)) { writeStream = WriteStreamType.Information; } else { writeStream = WriteStreamType.None; } } } #endregion #region Shape Info Classes internal abstract class ShapeInfo : FormatInfoData { } internal sealed partial class WideViewHeaderInfo : ShapeInfo { internal const string CLSID = "b2e2775d33d544c794d0081f27021b5c"; public override string ClassId2e4f51ef21dd47e99d3c952918aff9cd { get { return CLSID; } } /// <summary> /// desired number of columns on the screen. /// Advisory, the outputter can decide otherwise /// /// A zero value signifies let the outputter get the /// best fit on the screen (possibily blocking until the end) /// </summary> public int columns = 0; } internal sealed partial class TableHeaderInfo : ShapeInfo { internal const string CLSID = "e3b7a39c089845d388b2e84c5d38f5dd"; public TableHeaderInfo() { tableColumnInfoList = new List<TableColumnInfo>(); } public override string ClassId2e4f51ef21dd47e99d3c952918aff9cd { get { return CLSID; } } public bool hideHeader; public List<TableColumnInfo> tableColumnInfoList; } internal sealed partial class TableColumnInfo : FormatInfoData { internal const string CLSID = "7572aa4155ec4558817a615acf7dd92e"; public override string ClassId2e4f51ef21dd47e99d3c952918aff9cd { get { return CLSID; } } /// <summary> /// width of the column: /// == 0 -> let the outputter decide /// > 0 -> user provided value /// </summary> public int width = 0; public int alignment = TextAlignment.Left; public string label = null; public string propertyName = null; } internal sealed class ListViewHeaderInfo : ShapeInfo { internal const string CLSID = "830bdcb24c1642258724e441512233a4"; public override string ClassId2e4f51ef21dd47e99d3c952918aff9cd { get { return CLSID; } } } internal sealed class ComplexViewHeaderInfo : ShapeInfo { internal const string CLSID = "5197dd85ca6f4cce9ae9e6fd6ded9d76"; public override string ClassId2e4f51ef21dd47e99d3c952918aff9cd { get { return CLSID; } } } #endregion #region Formatting Entries Classes internal abstract class FormatEntryInfo : FormatInfoData { } internal sealed partial class RawTextFormatEntry : FormatEntryInfo { internal const string CLSID = "29ED81BA914544d4BC430F027EE053E9"; public override string ClassId2e4f51ef21dd47e99d3c952918aff9cd { get { return CLSID; } } public string text = null; } internal abstract partial class FreeFormatEntry : FormatEntryInfo { public List<FormatValue> formatValueList = new List<FormatValue>(); } internal sealed partial class ListViewEntry : FormatEntryInfo { internal const string CLSID = "cf58f450baa848ef8eb3504008be6978"; public override string ClassId2e4f51ef21dd47e99d3c952918aff9cd { get { return CLSID; } } public List<ListViewField> listViewFieldList = new List<ListViewField>(); } internal sealed partial class ListViewField : FormatInfoData { internal const string CLSID = "b761477330ce4fb2a665999879324d73"; public override string ClassId2e4f51ef21dd47e99d3c952918aff9cd { get { return CLSID; } } public string label = null; public string propertyName = null; public FormatPropertyField formatPropertyField = new FormatPropertyField(); } internal sealed partial class TableRowEntry : FormatEntryInfo { internal const string CLSID = "0e59526e2dd441aa91e7fc952caf4a36"; public override string ClassId2e4f51ef21dd47e99d3c952918aff9cd { get { return CLSID; } } public List<FormatPropertyField> formatPropertyFieldList = new List<FormatPropertyField>(); public bool multiLine = false; } internal sealed partial class WideViewEntry : FormatEntryInfo { internal const string CLSID = "59bf79de63354a7b9e4d1697940ff188"; public override string ClassId2e4f51ef21dd47e99d3c952918aff9cd { get { return CLSID; } } public FormatPropertyField formatPropertyField = new FormatPropertyField(); } internal sealed class ComplexViewEntry : FreeFormatEntry { internal const string CLSID = "22e7ef3c896449d4a6f2dedea05dd737"; public override string ClassId2e4f51ef21dd47e99d3c952918aff9cd { get { return CLSID; } } } internal sealed class GroupingEntry : FreeFormatEntry { internal const string CLSID = "919820b7eadb48be8e202c5afa5c2716"; public override string ClassId2e4f51ef21dd47e99d3c952918aff9cd { get { return CLSID; } } } internal sealed class PageHeaderEntry : FreeFormatEntry { internal const string CLSID = "dd1290a5950b4b27aa76d9f06199c3b3"; public override string ClassId2e4f51ef21dd47e99d3c952918aff9cd { get { return CLSID; } } } internal sealed class PageFooterEntry : FreeFormatEntry { internal const string CLSID = "93565e84730645c79d4af091123eecbc"; public override string ClassId2e4f51ef21dd47e99d3c952918aff9cd { get { return CLSID; } } } internal sealed partial class AutosizeInfo : FormatInfoData { internal const string CLSID = "a27f094f0eec4d64845801a4c06a32ae"; public override string ClassId2e4f51ef21dd47e99d3c952918aff9cd { get { return CLSID; } } /// <summary> /// number of objects to compute the best fit. /// Zero: all the objects /// a positive number N: use the first N /// </summary> public int objectCount = 0; } #endregion #region Format Values internal abstract class FormatValue : FormatInfoData { } internal sealed class FormatNewLine : FormatValue { internal const string CLSID = "de7e8b96fbd84db5a43aa82eb34580ec"; public override string ClassId2e4f51ef21dd47e99d3c952918aff9cd { get { return CLSID; } } } internal sealed partial class FormatTextField : FormatValue { internal const string CLSID = "b8d9e369024a43a580b9e0c9279e3354"; public override string ClassId2e4f51ef21dd47e99d3c952918aff9cd { get { return CLSID; } } public string text; } internal sealed partial class FormatPropertyField : FormatValue { internal const string CLSID = "78b102e894f742aca8c1d6737b6ff86a"; public override string ClassId2e4f51ef21dd47e99d3c952918aff9cd { get { return CLSID; } } public string propertyValue = null; public int alignment = TextAlignment.Undefined; } internal sealed partial class FormatEntry : FormatValue { internal const string CLSID = "fba029a113a5458d932a2ed4871fadf2"; public FormatEntry() { formatValueList = new List<FormatValue>(); } public override string ClassId2e4f51ef21dd47e99d3c952918aff9cd { get { return CLSID; } } public List<FormatValue> formatValueList; /// <summary> /// optional information of frame data (indentation, etc.) /// </summary> public FrameInfo frameInfo; } internal sealed partial class FrameInfo : FormatInfoData { internal const string CLSID = "091C9E762E33499eBE318901B6EFB733"; public override string ClassId2e4f51ef21dd47e99d3c952918aff9cd { get { return CLSID; } } public int leftIndentation = 0; public int rightIndentation = 0; public int firstLine = 0; } #endregion }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Imaging.Interop; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions { /// <summary> /// Base class for all Roslyn light bulb menu items. /// </summary> internal partial class SuggestedAction : ForegroundThreadAffinitizedObject, ISuggestedAction, IEquatable<ISuggestedAction> { protected readonly Workspace Workspace; protected readonly ITextBuffer SubjectBuffer; protected readonly ICodeActionEditHandlerService EditHandler; protected readonly object Provider; protected readonly CodeAction CodeAction; protected SuggestedAction( Workspace workspace, ITextBuffer subjectBuffer, ICodeActionEditHandlerService editHandler, CodeAction codeAction, object provider) { Contract.ThrowIfTrue(provider == null); this.Workspace = workspace; this.SubjectBuffer = subjectBuffer; this.CodeAction = codeAction; this.EditHandler = editHandler; this.Provider = provider; } public bool TryGetTelemetryId(out Guid telemetryId) { // TODO: this is temporary. Diagnostic team needs to figure out how to provide unique id per a fix. // for now, we will use type of CodeAction, but there are some predefined code actions that are used by multiple fixes // and this will not distinguish those // AssemblyQualifiedName will change across version numbers, FullName won't var type = CodeAction.GetType(); type = type.IsConstructedGenericType ? type.GetGenericTypeDefinition() : type; telemetryId = new Guid(type.FullName.GetHashCode(), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); return true; } // NOTE: We want to avoid computing the operations on the UI thread. So we use Task.Run() to do this work on the background thread. protected Task<ImmutableArray<CodeActionOperation>> GetOperationsAsync(CancellationToken cancellationToken) { return Task.Run( async () => await CodeAction.GetOperationsAsync(cancellationToken).ConfigureAwait(false), cancellationToken); } protected Task<IEnumerable<CodeActionOperation>> GetOperationsAsync(CodeActionWithOptions actionWithOptions, object options, CancellationToken cancellationToken) { return Task.Run( async () => await actionWithOptions.GetOperationsAsync(options, cancellationToken).ConfigureAwait(false), cancellationToken); } protected Task<ImmutableArray<CodeActionOperation>> GetPreviewOperationsAsync(CancellationToken cancellationToken) { return Task.Run( async () => await CodeAction.GetPreviewOperationsAsync(cancellationToken).ConfigureAwait(false), cancellationToken); } public virtual void Invoke(CancellationToken cancellationToken) { var snapshot = this.SubjectBuffer.CurrentSnapshot; using (new CaretPositionRestorer(this.SubjectBuffer, this.EditHandler.AssociatedViewService)) { var extensionManager = this.Workspace.Services.GetService<IExtensionManager>(); extensionManager.PerformAction(Provider, () => { IEnumerable<CodeActionOperation> operations = null; // NOTE: As mentoned above, we want to avoid computing the operations on the UI thread. // However, for CodeActionWithOptions, GetOptions() might involve spinning up a dialog // to compute the options and must be done on the UI thread. var actionWithOptions = this.CodeAction as CodeActionWithOptions; if (actionWithOptions != null) { var options = actionWithOptions.GetOptions(cancellationToken); if (options != null) { operations = GetOperationsAsync(actionWithOptions, options, cancellationToken).WaitAndGetResult(cancellationToken); } } else { operations = GetOperationsAsync(cancellationToken).WaitAndGetResult(cancellationToken); } if (operations != null) { var document = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); EditHandler.Apply(Workspace, document, operations, CodeAction.Title, cancellationToken); } }); } } public string DisplayText { get { // Underscores will become an accelerator in the VS smart tag. So we double all // underscores so they actually get represented as an underscore in the UI. var extensionManager = this.Workspace.Services.GetService<IExtensionManager>(); var text = extensionManager.PerformFunction(Provider, () => CodeAction.Title, string.Empty); return text.Replace("_", "__"); } } protected async Task<SolutionPreviewResult> GetPreviewResultAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // We will always invoke this from the UI thread. AssertIsForeground(); // We use ConfigureAwait(true) to stay on the UI thread. var operations = await GetPreviewOperationsAsync(cancellationToken).ConfigureAwait(true); return EditHandler.GetPreviews(Workspace, operations, cancellationToken); } public virtual bool HasPreview { get { // HasPreview is called synchronously on the UI thread. In order to avoid blocking the UI thread, // we need to provide a 'quick' answer here as opposed to the 'right' answer. Providing the 'right' // answer is expensive (because we will need to call CodeAction.GetPreivewOperationsAsync() for this // and this will involve computing the changed solution for the ApplyChangesOperation for the fix / // refactoring). So we always return 'true' here (so that platform will call GetActionSetsAsync() // below). Platform guarantees that nothing bad will happen if we return 'true' here and later return // 'null' / empty collection from within GetPreviewAsync(). return true; } } public virtual async Task<object> GetPreviewAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Light bulb will always invoke this function on the UI thread. AssertIsForeground(); var extensionManager = this.Workspace.Services.GetService<IExtensionManager>(); var previewContent = await extensionManager.PerformFunctionAsync(Provider, async () => { // We need to stay on UI thread after GetPreviewResultAsync() so that TakeNextPreviewAsync() // below can execute on UI thread. We use ConfigureAwait(true) to stay on the UI thread. var previewResult = await GetPreviewResultAsync(cancellationToken).ConfigureAwait(true); if (previewResult == null) { return null; } else { var preferredDocumentId = Workspace.GetDocumentIdInCurrentContext(SubjectBuffer.AsTextContainer()); var preferredProjectid = preferredDocumentId == null ? null : preferredDocumentId.ProjectId; // TakeNextPreviewAsync() needs to run on UI thread. AssertIsForeground(); return await previewResult.TakeNextPreviewAsync(preferredDocumentId, preferredProjectid, cancellationToken).ConfigureAwait(true); } // GetPreviewPane() below needs to run on UI thread. We use ConfigureAwait(true) to stay on the UI thread. }).ConfigureAwait(true); var previewPaneService = Workspace.Services.GetService<IPreviewPaneService>(); if (previewPaneService == null) { return null; } cancellationToken.ThrowIfCancellationRequested(); // GetPreviewPane() needs to run on the UI thread. AssertIsForeground(); return previewPaneService.GetPreviewPane(GetDiagnostic(), previewContent); } protected virtual Diagnostic GetDiagnostic() { return null; } #region not supported void IDisposable.Dispose() { // do nothing } public virtual bool HasActionSets { get { return false; } } public virtual Task<IEnumerable<SuggestedActionSet>> GetActionSetsAsync(CancellationToken cancellationToken) { return SpecializedTasks.Default<IEnumerable<SuggestedActionSet>>(); } string ISuggestedAction.IconAutomationText { get { // same as display text return DisplayText; } } ImageMoniker ISuggestedAction.IconMoniker { get { // no icon support return default(ImageMoniker); } } string ISuggestedAction.InputGestureText { get { // no shortcut support return null; } } #endregion #region IEquatable<ISuggestedAction> public bool Equals(ISuggestedAction other) { return Equals(other as SuggestedAction); } public override bool Equals(object obj) { return Equals(obj as SuggestedAction); } public bool Equals(SuggestedAction otherSuggestedAction) { if (otherSuggestedAction == null) { return false; } if (ReferenceEquals(this, otherSuggestedAction)) { return true; } if (!ReferenceEquals(Provider, otherSuggestedAction.Provider)) { return false; } var otherCodeAction = otherSuggestedAction.CodeAction; if (CodeAction.EquivalenceKey == null || otherCodeAction.EquivalenceKey == null) { return false; } return CodeAction.EquivalenceKey == otherCodeAction.EquivalenceKey; } public override int GetHashCode() { if (CodeAction.EquivalenceKey == null) { return base.GetHashCode(); } return Hash.Combine(Provider.GetHashCode(), CodeAction.EquivalenceKey.GetHashCode()); } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace iOS.WebServiceExample.WebAPI.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using CppSharp.AST; using CppSharp.AST.Extensions; using CppSharp.Generators.C; using CppSharp.Generators.NAPI; namespace CppSharp.Generators.Cpp { public class NAPICodeGenerator : CCodeGenerator { public override string FileExtension => "cpp"; public NAPICodeGenerator(BindingContext context, IEnumerable<TranslationUnit> units) : base(context, units) { } public override void VisitDeclContextFunctions(DeclarationContext context) { if (!VisitOptions.VisitNamespaceFunctions) return; var functions = context.Functions.Where(f => !ASTUtils.CheckIgnoreFunction(f)).ToList(); var unique = functions.GroupBy(m => m.Name); foreach (var group in unique) GenerateFunctionGroup(group.ToList()); } public virtual void GenerateFunctionGroup(List<Function> group) { foreach (var function in group) { function.Visit(this); return; } } public override bool VisitClassDecl(Class @class) { return VisitClassDeclContext(@class); } public override void VisitClassConstructors(Class @class) { var constructors = @class.Constructors.Where(c => c.IsGenerated && !c.IsCopyConstructor) .ToList(); if (!constructors.Any()) return; GenerateMethodGroup(constructors); } public static bool ShouldGenerate(Function function) { if (!function.IsGenerated) return false; if (!(function is Method method)) return true; if (method.IsConstructor || method.IsDestructor) return false; if (method.IsOperator) { if (method.OperatorKind == CXXOperatorKind.Conversion || method.OperatorKind == CXXOperatorKind.Equal) return false; } return true; } public override void VisitClassMethods(Class @class) { var methods = @class.Methods.Where(ShouldGenerate); var uniqueMethods = methods.GroupBy(m => m.Name); foreach (var group in uniqueMethods) GenerateMethodGroup(group.ToList()); } public virtual void GenerateMethodGroup(List<Method> @group) { foreach (var method in @group) { method.Visit(this); return; } } public virtual MarshalPrinter<MarshalContext, CppTypePrinter> GetMarshalManagedToNativePrinter(MarshalContext ctx) { return new NAPIMarshalManagedToNativePrinter(ctx); } public virtual MarshalPrinter<MarshalContext, CppTypePrinter> GetMarshalNativeToManagedPrinter(MarshalContext ctx) { return new NAPIMarshalNativeToManagedPrinter(ctx); } public struct ParamMarshal { public string Name; public string Prefix; public Parameter Param; public MarshalContext Context; } public virtual List<ParamMarshal> GenerateFunctionParamsMarshal(IEnumerable<Parameter> @params, Function function = null) { var marshals = new List<ParamMarshal>(); var paramIndex = 0; foreach (var param in @params) { marshals.Add(GenerateFunctionParamMarshal(param, paramIndex, function)); paramIndex++; } return marshals; } public virtual ParamMarshal GenerateFunctionParamMarshal(Parameter param, int paramIndex, Function function = null) { var paramMarshal = new ParamMarshal { Name = param.Name, Param = param }; var argName = Generator.GeneratedIdentifier("arg") + paramIndex.ToString(CultureInfo.InvariantCulture); Parameter effectiveParam = param; var isRef = param.IsOut || param.IsInOut; var paramType = param.Type; // TODO: Use same name between generators var typeArgName = $"args[{paramIndex}]"; if (this is QuickJSInvokes) typeArgName = $"argv[{paramIndex}]"; var ctx = new MarshalContext(Context, CurrentIndentation) { Parameter = effectiveParam, ParameterIndex = paramIndex, ArgName = typeArgName, Function = function }; paramMarshal.Context = ctx; var marshal = GetMarshalManagedToNativePrinter(ctx); effectiveParam.Visit(marshal); if (string.IsNullOrEmpty(marshal.Context.Return)) throw new Exception($"Cannot marshal argument of function '{function.QualifiedOriginalName}'"); if (isRef) { var type = paramType.Visit(CTypePrinter); if (param.IsInOut) { if (!string.IsNullOrWhiteSpace(marshal.Context.Before)) { Write(marshal.Context.Before); NeedNewLine(); } WriteLine($"{type} {argName} = {marshal.Context.Return};"); } else WriteLine($"{type} {argName};"); } else { if (!string.IsNullOrWhiteSpace(marshal.Context.Before)) { Write(marshal.Context.Before); } WriteLine($"auto {marshal.Context.VarPrefix}{argName} = {marshal.Context.Return};"); paramMarshal.Prefix = marshal.Context.ArgumentPrefix; NewLine(); } paramMarshal.Name = argName; return paramMarshal; } public virtual void GenerateFunctionCallReturnMarshal(Function function) { var ctx = new MarshalContext(Context, CurrentIndentation) { ArgName = Helpers.ReturnIdentifier, ReturnVarName = Helpers.ReturnIdentifier, ReturnType = function.ReturnType }; // TODO: Move this into the marshaler if (function.ReturnType.Type.Desugar().IsClass()) ctx.ArgName = $"&{ctx.ArgName}"; var marshal = GetMarshalNativeToManagedPrinter(ctx); function.ReturnType.Visit(marshal); if (!string.IsNullOrWhiteSpace(marshal.Context.Before)) { Write(marshal.Context.Before); NewLine(); } WriteLine($"return {marshal.Context.Return};"); } public virtual void GenerateFunctionParamsMarshalCleanups(List<ParamMarshal> @params) { var marshalers = new List<MarshalPrinter<MarshalContext, CppTypePrinter>>(); PushBlock(); { foreach (var paramInfo in @params) { var param = paramInfo.Param; if (param.Usage != ParameterUsage.Out && param.Usage != ParameterUsage.InOut) continue; if (param.Type.IsPointer() && !param.Type.GetFinalPointee().IsPrimitiveType()) param.QualifiedType = new QualifiedType(param.Type.GetFinalPointee()); var ctx = new MarshalContext(Context, CurrentIndentation) { ArgName = paramInfo.Name, ReturnVarName = paramInfo.Name, ReturnType = param.QualifiedType }; var marshal = GetMarshalNativeToManagedPrinter(ctx); marshalers.Add(marshal); param.Visit(marshal); if (!string.IsNullOrWhiteSpace(marshal.Context.Before)) Write(marshal.Context.Before); WriteLine($"{param.Name} = {marshal.Context.Return};"); } } PopBlock(NewLineKind.IfNotEmpty); PushBlock(); { foreach (var marshal in marshalers) { if (!string.IsNullOrWhiteSpace(marshal.Context.Cleanup)) Write(marshal.Context.Cleanup); } foreach (var marshal in @params) { if (!string.IsNullOrWhiteSpace(marshal.Context.Cleanup)) Write(marshal.Context.Cleanup); } } PopBlock(NewLineKind.IfNotEmpty); } } /// <summary> /// Generates a common Node N-API C/C++ common files. /// N-API documentation: https://nodejs.org/api/n-api.html /// </summary> public class NAPIHelpers : CppHeaders { public NAPIHelpers(BindingContext context) : base(context, null) { } public override void Process() { GenerateFilePreamble(CommentKind.BCPL); WriteLine("#pragma once"); NewLine(); WriteInclude("math.h", CInclude.IncludeKind.Angled); WriteInclude("limits.h", CInclude.IncludeKind.Angled); NewLine(); GenerateHelpers(); return; } private void GenerateHelpers() { WriteLine(@"#define NAPI_CALL(env, call) \ do { \ napi_status status = (call); \ if (status != napi_ok) { \ const napi_extended_error_info* error_info = NULL; \ napi_get_last_error_info((env), &error_info); \ bool is_pending; \ napi_is_exception_pending((env), &is_pending); \ if (!is_pending) { \ const char* message = (error_info->error_message == NULL) \ ? ""empty error message"" \ : error_info->error_message; \ napi_throw_error((env), NULL, message); \ return NULL; \ } \ } \ } while(0)"); NewLine(); WriteLine(@"#define NAPI_CALL_NORET(env, call) \ do { \ napi_status status = (call); \ if (status != napi_ok) { \ const napi_extended_error_info* error_info = NULL; \ napi_get_last_error_info((env), &error_info); \ bool is_pending; \ napi_is_exception_pending((env), &is_pending); \ if (!is_pending) { \ const char* message = (error_info->error_message == NULL) \ ? ""empty error message"" \ : error_info->error_message; \ napi_throw_error((env), NULL, message); \ return; \ } \ } \ } while(0)"); NewLine(); WriteLine(@"static int napi_is_int32(napi_env env, napi_value value, int* integer) { double temp = 0; if ( // We get the value as a double so we can check for NaN, Infinity and float: // https://github.com/nodejs/node/issues/26323 napi_get_value_double(env, value, &temp) != napi_ok || // Reject NaN: isnan(temp) || // Reject Infinity and avoid undefined behavior when casting double to int: // https://groups.google.com/forum/#!topic/comp.lang.c/rhPzd4bgKJk temp < INT_MIN || temp > INT_MAX || // Reject float by casting double to int: (double) ((int) temp) != temp ) { //napi_throw_error(env, NULL, ""argument must be an integer""); return 0; } if (integer) *integer = (int) temp; return 1; }"); NewLine(); WriteLine(@"static int napi_is_uint32(napi_env env, napi_value value, int* integer) { double temp = 0; if ( // We get the value as a double so we can check for NaN, Infinity and float: // https://github.com/nodejs/node/issues/26323 napi_get_value_double(env, value, &temp) != napi_ok || // Reject NaN: isnan(temp) || // Reject Infinity and avoid undefined behavior when casting double to int: // https://groups.google.com/forum/#!topic/comp.lang.c/rhPzd4bgKJk temp < 0 || temp > ULONG_MAX || // Reject float by casting double to int: (double) ((unsigned long) temp) != temp ) { //napi_throw_error(env, NULL, ""argument must be an integer""); return 0; } if (integer) *integer = (int) temp; return 1; }"); NewLine(); WriteLine(@"#define NAPI_IS_BOOL(valuetype) (valuetype == napi_boolean)"); WriteLine(@"#define NAPI_IS_NULL(valuetype) (valuetype == napi_null)"); WriteLine(@"#define NAPI_IS_NUMBER(valuetype) (valuetype == napi_number)"); WriteLine(@"#define NAPI_IS_BIGINT(valuetype) (valuetype == napi_bigint)"); WriteLine(@"#define NAPI_IS_INT32(valuetype, value) (NAPI_IS_NUMBER(valuetype) && napi_is_int32(env, value, nullptr))"); WriteLine(@"#define NAPI_IS_UINT32(valuetype, value) (NAPI_IS_NUMBER(valuetype) && napi_is_uint32(env, value, nullptr))"); WriteLine(@"#define NAPI_IS_INT64(valuetype, value) (NAPI_IS_BIGINT(valuetype))"); WriteLine(@"#define NAPI_IS_UINT64(valuetype, value) (NAPI_IS_BIGINT(valuetype))"); WriteLine(@"#define NAPI_IS_ARRAY(valuetype) (valuetype == napi_object)"); WriteLine(@"#define NAPI_IS_OBJECT(valuetype) (valuetype == napi_object)"); NewLine(); } } }
using System; using System.IO; using System.Net; using System.Text; using System.Linq; using System.Threading.Tasks; using System.Collections.Generic; using Xamarin.SSO.Client; namespace XamarinStore { public class WebService { public static readonly WebService Shared = new WebService (); public User CurrentUser { get; set; } public Order CurrentOrder { get; set; } XamarinSSOClient client = new XamarinSSOClient ("https://auth.xamarin.com", "0c833t3w37jq58dj249dt675a465k6b0rz090zl3jpoa9jw8vz7y6awpj5ox0qmb"); public WebService () { CurrentOrder = new Order (); } public async Task<bool> Login (string username, string password) { AccountResponse response; try { var request = Task.Run (() => response = client.CreateToken (username, password)); response = await request; if (response.Success) { var user = response.User; CurrentUser = new User { LastName = user.LastName, FirstName = user.FirstName, Email = username, Token = response.Token }; return true; } else { Console.WriteLine ("Login failed: {0}", response.Error); } } catch (Exception ex) { Console.WriteLine ("Login failed for some reason...: {0}", ex.Message); } return false; } List<Product> products; public async Task<List<Product>> GetProducts() { if (products == null) { products = await Task.Factory.StartNew (() => { try { string extraParams = ""; //TODO: Get a Monkey!!! //extraParams = "?includeMonkeys=true"; var request = CreateRequest ("products" + extraParams); string response = ReadResponseText (request); var items = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Product>>(response); foreach (var i in items) { if (i.ProductType == ProductType.MensCSharpShirt) { foreach (var c in i.Colors) { if (c.Name == "Navy") { c.ImageUrls = new[] { "http://www.itwriting.com/blog/wp-content/uploads/2013/06/image8.png" }; } else if (c.Name == "Green") { c.ImageUrls = new[] { "http://blog.xamarin.com/wp-content/uploads/2014/04/Screen-Shot-2014-04-03-at-13.31.34.png" }; } } } } return items; } catch (Exception ex) { Console.WriteLine (ex); return new List<Product> (); } }); } return products; } bool hasPreloadedImages; public async Task PreloadImages(float imageWidth) { if (hasPreloadedImages) return; hasPreloadedImages = true; //Lets precach the countries too #pragma warning disable 4014 GetCountries (); #pragma warning restore 4014 await Task.Factory.StartNew (() => { var imagUrls = products.SelectMany (x => x.ImageUrls.Select (y => Product.ImageForSize (y, imageWidth))).ToList (); imagUrls.ForEach( async (x) => await FileCache.Download(x)); }); } List<Country> countries = new List<Country>(); public Task<List<Country>> GetCountries() { return Task.Factory.StartNew (() => { try { if(countries.Count > 0) return countries; var request = CreateRequest ("Countries"); string response = ReadResponseText (request); countries = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Country>> (response); return countries; } catch (Exception ex) { Console.WriteLine (ex); return new List<Country> (); } }); } public async Task<string> GetCountryCode(string country) { var c = (await GetCountries ()).FirstOrDefault (x => x.Name == country) ?? new Country(); return c.Code; } public async Task<string> GetCountryFromCode(string code) { var c = (await GetCountries ()).FirstOrDefault (x => x.Code == code) ?? new Country(); return c.Name; } //No need to await anything, and no need to spawn a task to return a list. #pragma warning disable 1998 public async Task<List<string>> GetStates(string country) { if (country.ToLower () == "united states") return new List<string> { "Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "District of Columbia", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming", }; return new List<string> (); } #pragma warning restore 1998 static HttpWebRequest CreateRequest(string location) { var request = (HttpWebRequest)WebRequest.Create ("https://xamarin-store-app.xamarin.com/api/"+ location); request.Method = "GET"; request.ContentType = "application/json"; request.Accept = "application/json"; return request; } public Task<OrderResult> PlaceOrder (User user, bool verify = false) { return Task.Factory.StartNew (() => { try { var content = Encoding.UTF8.GetBytes (CurrentOrder.GetJson (user)); var request = CreateRequest ("order" + (verify ? "?verify=1" : "")); request.Method = "POST"; request.ContentLength = content.Length; using (Stream s = request.GetRequestStream ()) { s.Write (content, 0, content.Length); } string response = ReadResponseText (request); var result = Newtonsoft.Json.JsonConvert.DeserializeObject<OrderResult> (response); if(!verify && result.Success) CurrentOrder = new Order(); return result; } catch (Exception ex) { return new OrderResult { Success = false, Message = ex.Message, }; } }); } protected static string ReadResponseText (HttpWebRequest req) { using (WebResponse resp = req.GetResponse ()) { using (Stream s = (resp).GetResponseStream ()) { using (var r = new StreamReader (s, Encoding.UTF8)) { return r.ReadToEnd (); } } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace SecurityTests.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// *** // Do not edit this file. It has been generated by the ClassDynamizer tool. // *** #pragma warning disable 0108 using PHP.Core.Reflection; using System; using System.Collections.Generic; using System.Linq; using System.Text; using PHP.Core; using System.Runtime.InteropServices; namespace PHP.Library.Soap { [Serializable()] public partial class SoapClient { /// <summary></summary> protected SoapClient(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } /// <summary></summary> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public SoapClient(ScriptContext context, bool newInstance) : base(context, newInstance) { } /// <summary></summary> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public SoapClient(ScriptContext context, DTypeDesc caller) : this(context, true) { this.InvokeConstructor(context, caller); } /// <summary></summary> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public object __call(ScriptContext __context, object function_name, object arguments) { string tmp1 = PhpVariable.AsString(function_name); if (tmp1 == null) { PhpException.InvalidImplicitCast(function_name, "string", "__call"); return null; } PhpArray tmp2 = arguments as PhpArray; if (tmp2 == null) { PhpException.InvalidImplicitCast(arguments, "PhpArray", "__call"); return null; } return __call(tmp1, tmp2); } /// <summary></summary> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static object __call(object instance, PhpStack stack) { stack.CalleeName = "__call"; object arg1 = stack.PeekValue(1); object arg2 = stack.PeekValue(2); stack.RemoveFrame(); return ((SoapClient)instance).__call(stack.Context, arg1, arg2); } /// <summary></summary> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public object __doRequest(ScriptContext __context) { return __doRequest(); } /// <summary></summary> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static object __doRequest(object instance, PhpStack stack) { stack.CalleeName = "__doRequest"; stack.RemoveFrame(); return ((SoapClient)instance).__doRequest(stack.Context); } /// <summary></summary> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public object __getFunctions(ScriptContext __context) { return __getFunctions(); } /// <summary></summary> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static object __getFunctions(object instance, PhpStack stack) { stack.CalleeName = "__getFunctions"; stack.RemoveFrame(); return ((SoapClient)instance).__getFunctions(stack.Context); } /// <summary></summary> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public object __getLastRequest(ScriptContext __context) { return __getLastRequest(); } /// <summary></summary> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static object __getLastRequest(object instance, PhpStack stack) { stack.CalleeName = "__getLastRequest"; stack.RemoveFrame(); return ((SoapClient)instance).__getLastRequest(stack.Context); } /// <summary></summary> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public object __getLastRequestHeaders(ScriptContext __context) { return __getLastRequestHeaders(); } /// <summary></summary> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static object __getLastRequestHeaders(object instance, PhpStack stack) { stack.CalleeName = "__getLastRequestHeaders"; stack.RemoveFrame(); return ((SoapClient)instance).__getLastRequestHeaders(stack.Context); } /// <summary></summary> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public object __getLastResponse(ScriptContext __context) { return __getLastResponse(); } /// <summary></summary> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static object __getLastResponse(object instance, PhpStack stack) { stack.CalleeName = "__getLastResponse"; stack.RemoveFrame(); return ((SoapClient)instance).__getLastResponse(stack.Context); } /// <summary></summary> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public object __getLastResponseHeaders(ScriptContext __context) { return __getLastResponseHeaders(); } /// <summary></summary> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static object __getLastResponseHeaders(object instance, PhpStack stack) { stack.CalleeName = "__getLastResponseHeaders"; stack.RemoveFrame(); return ((SoapClient)instance).__getLastResponseHeaders(stack.Context); } /// <summary></summary> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public object __getTypes(ScriptContext __context) { return __getTypes(); } /// <summary></summary> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static object __getTypes(object instance, PhpStack stack) { stack.CalleeName = "__getTypes"; stack.RemoveFrame(); return ((SoapClient)instance).__getTypes(stack.Context); } /// <summary></summary> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public object __setCookie(ScriptContext __context, object name, object value) { string tmp1 = PhpVariable.AsString(name); if (tmp1 == null) { PhpException.InvalidImplicitCast(name, "string", "__setCookie"); return null; } string tmp2 = PhpVariable.AsString(value); if (tmp2 == null) { PhpException.InvalidImplicitCast(value, "string", "__setCookie"); return null; } __setCookie(tmp1, tmp2); return null; } /// <summary></summary> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static object __setCookie(object instance, PhpStack stack) { stack.CalleeName = "__setCookie"; object arg1 = stack.PeekValue(1); object arg2 = stack.PeekValue(2); stack.RemoveFrame(); return ((SoapClient)instance).__setCookie(stack.Context, arg1, arg2); } /// <summary></summary> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public object __setLocation(ScriptContext __context, object new_location) { string tmp1 = PhpVariable.AsString(new_location); if (tmp1 == null) { PhpException.InvalidImplicitCast(new_location, "string", "__setLocation"); return null; } return __setLocation(tmp1); } /// <summary></summary> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static object __setLocation(object instance, PhpStack stack) { stack.CalleeName = "__setLocation"; object arg1 = stack.PeekValue(1); stack.RemoveFrame(); return ((SoapClient)instance).__setLocation(stack.Context, arg1); } /// <summary></summary> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public object __setSoapHeaders(ScriptContext __context, object SoapHeaders) { PhpArray tmp1 = SoapHeaders as PhpArray; if (tmp1 == null) { PhpException.InvalidImplicitCast(SoapHeaders, "PhpArray", "__setSoapHeaders"); return null; } __setSoapHeaders(tmp1); return null; } /// <summary></summary> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static object __setSoapHeaders(object instance, PhpStack stack) { stack.CalleeName = "__setSoapHeaders"; object arg1 = stack.PeekValue(1); stack.RemoveFrame(); return ((SoapClient)instance).__setSoapHeaders(stack.Context, arg1); } /// <summary></summary> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public object __construct(ScriptContext __context, object wsdl, [System.Runtime.InteropServices.OptionalAttribute()] object options) { string tmp1 = PhpVariable.AsString(wsdl); if (tmp1 == null) { PhpException.InvalidImplicitCast(wsdl, "string", "__construct"); return null; } PhpArray tmp2 = null; if (options != Arg.Default) { tmp2 = options as PhpArray; if (tmp2 == null) { PhpException.InvalidImplicitCast(options, "PhpArray", "__construct"); return null; } } __construct(tmp1, tmp2); return null; } /// <summary></summary> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static object __construct(object instance, PhpStack stack) { stack.CalleeName = "__construct"; object arg1 = stack.PeekValue(1); object arg2 = stack.PeekValueOptional(2); stack.RemoveFrame(); return ((SoapClient)instance).__construct(stack.Context, arg1, arg2); } /// <summary></summary> private static void __PopulateTypeDesc(PhpTypeDesc desc) { desc.AddMethod("__call", PhpMemberAttributes.Public, new RoutineDelegate(SoapClient.__call)); desc.AddMethod("__doRequest", PhpMemberAttributes.Public, new RoutineDelegate(SoapClient.__doRequest)); desc.AddMethod("__getFunctions", PhpMemberAttributes.Public, new RoutineDelegate(SoapClient.__getFunctions)); desc.AddMethod("__getLastRequest", PhpMemberAttributes.Public, new RoutineDelegate(SoapClient.__getLastRequest)); desc.AddMethod("__getLastRequestHeaders", PhpMemberAttributes.Public, new RoutineDelegate(SoapClient.__getLastRequestHeaders)); desc.AddMethod("__getLastResponse", PhpMemberAttributes.Public, new RoutineDelegate(SoapClient.__getLastResponse)); desc.AddMethod("__getLastResponseHeaders", PhpMemberAttributes.Public, new RoutineDelegate(SoapClient.__getLastResponseHeaders)); desc.AddMethod("__getTypes", PhpMemberAttributes.Public, new RoutineDelegate(SoapClient.__getTypes)); desc.AddMethod("__setCookie", PhpMemberAttributes.Public, new RoutineDelegate(SoapClient.__setCookie)); desc.AddMethod("__setLocation", PhpMemberAttributes.Public, new RoutineDelegate(SoapClient.__setLocation)); desc.AddMethod("__setSoapHeaders", PhpMemberAttributes.Public, new RoutineDelegate(SoapClient.__setSoapHeaders)); desc.AddMethod("__construct", PhpMemberAttributes.Public, new RoutineDelegate(SoapClient.__construct)); } } }
// Graph Engine // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.md file in the project root for full license information. // using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Trinity.Network; using Trinity; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Trinity.Network.Http; using System.Collections.Generic; namespace FanoutSearch.UnitTest { [TestClass] public class JsonDSLTest { [ClassInitialize] public static void Init(TestContext ctx) { Initializer.Initialize(); } [ClassCleanup] public static void Cleanup() { Initializer.Uninitialize(); } private void JsonQuery(string str) { var mod = Global.CommunicationInstance.GetCommunicationModule<FanoutSearchModule>(); mod.JsonQuery(str); } [TestMethod] public void JsonDSLTest_2hop() { JsonQuery(@" { path: ""paper/AuthorIDs/author"", paper: { ""select"" : [""*""], ""type"" : ""Paper"", ""NormalizedTitle"" : ""graph engine"" }, author: { } }"); } [TestMethod] public void JsonDSLTest_field_substring() { JsonQuery(@" { path: ""paper/AuthorIDs/author"", paper: { ""select"" : [""*""], ""type"" : ""Paper"", ""NormalizedTitle"" : ""graph engine"" }, author: { ""Name"" : { ""substring"" : ""bin"" } } }"); } [TestMethod] public void JsonDSLTest_field_count_eq() { JsonQuery(@" { path: ""paper/AuthorIDs/author"", paper: { ""select"" : [""*""], ""type"" : ""Paper"", ""NormalizedTitle"" : ""graph engine"" }, author: { ""Name"" : { ""count"" : 3 } } }"); } [TestMethod] public void JsonDSLTest_field_count_gt() { JsonQuery(@" { path: ""paper/AuthorIDs/author"", paper: { ""select"" : [""*""], ""type"" : ""Paper"", ""NormalizedTitle"" : ""graph engine"" }, author: { ""Name"" : { ""count"" : { ""gt"" : 3 } } } }"); } [TestMethod] public void JsonDSLTest_field_eq() { JsonQuery(@" { path: ""paper/AuthorIDs/author"", paper: { ""select"" : [""*""], ""type"" : ""Paper"", ""NormalizedTitle"" : ""graph engine"" }, author: { ""Name"" : ""bin shao"" } }"); } [TestMethod] public void JsonDSLTest_field_has() { JsonQuery(@" { path: ""paper/AuthorIDs/author"", paper: { ""select"" : [""*""], ""type"" : ""Paper"", ""NormalizedTitle"" : ""graph engine"" }, author: { ""has"" : ""Name"" } }"); } [TestMethod] public void JsonDSLTest_field_continue() { JsonQuery(@" { path: ""paper/AuthorIDs/author"", paper: { ""type"" : ""Paper"", ""NormalizedTitle"" : ""graph engine"" }, author: { ""continue"" : { ""Name"" : ""bin shao"" } } }"); } [TestMethod] public void JsonDSLTest_field_return() { JsonQuery(@" { path: ""paper/AuthorIDs/author"", paper: { ""type"" : ""Paper"", ""NormalizedTitle"" : ""graph engine"" }, author: { ""return"" : { ""Name"" : ""bin shao"" } } }"); } [TestMethod] public void JsonDSLTest_field_continue_return() { JsonQuery(@" { path: ""paper/AuthorIDs/author"", paper: { ""type"" : ""Paper"", ""NormalizedTitle"" : ""graph engine"" }, author: { ""return"" : { ""Name"" : ""bin shao"" }, ""continue"" : { ""Name"" : ""bin shao"" } } }"); } [TestMethod] public void JsonDSLTest_field_gt() { JsonQuery(@" { path: ""paper/AuthorIDs/author"", paper: { ""select"" : [""*""], ""type"" : ""Paper"", ""NormalizedTitle"" : ""graph engine"" }, author: { ""Name"" : { ""gt"" : 3 } } }"); } [TestMethod] public void JsonDSLTest_OR() { JsonQuery(@" { 'path': '/affiliation/PaperIDs/paper', 'affiliation': { 'type': 'Affiliation', 'select': [ 'Name' ], 'match': { 'Name': 'microsoft' } }, 'paper': { 'type': 'Paper', 'select': [ 'OriginalTitle' ], 'return': { 'or': { 'NormalizedTitle': { 'substring': 'graph' }, 'CitationCount': { 'gt': 100 } } } } } "); } [TestMethod] public void JsonDSLTest_nomatchcondition() { Expect.FanoutSearchQueryException(() => JsonQuery(@" { path: ""paper/AuthorIDs/author"", paper: { ""type"" : ""Paper"", }, author: { } }"), "No match conditions"); } [TestMethod] public void JsonDSLTest_field_count_eq_str() { Expect.FanoutSearchQueryException(() => JsonQuery(@" { path: ""paper/AuthorIDs/author"", paper: { ""select"" : [""*""], ""type"" : ""Paper"", ""NormalizedTitle"" : ""graph engine"" }, author: { ""Name"" : { ""count"" : ""3"" } } }"), "Invalid count operand"); } [TestMethod] public void JsonDSLTest_field_count_eq_str_2() { Expect.FanoutSearchQueryException(() => JsonQuery(@" { path: ""paper/AuthorIDs/author"", paper: { ""select"" : [""*""], ""type"" : ""Paper"", ""NormalizedTitle"" : ""graph engine"" }, author: { ""Name"" : { ""count"" : ""hey"" } } }"), "Invalid count operand"); } [TestMethod] public void JsonDSLTest_field_count_eq_float() { Expect.FanoutSearchQueryException(() => JsonQuery(@" { path: ""paper/AuthorIDs/author"", paper: { ""select"" : [""*""], ""type"" : ""Paper"", ""NormalizedTitle"" : ""graph engine"" }, author: { ""Name"" : { ""count"" : ""3.14"" } } }"), "Invalid count operand"); } [TestMethod] public void JsonDSLTest_field_invalid_op() { Expect.FanoutSearchQueryException(() => JsonQuery(@" { path: ""paper/AuthorIDs/author"", paper: { ""select"" : [""*""], ""type"" : ""Paper"", ""NormalizedTitle"" : ""graph engine"" }, author: { ""Name"" : { ""hey"" : ""you"" } } }"), "Unrecognized operator"); } [TestMethod] public void JsonDSLTest_field_invalid_property_integer() { Expect.FanoutSearchQueryException(() => JsonQuery(@" { path: ""paper/AuthorIDs/author"", paper: { ""select"" : [""*""], ""type"" : ""Paper"", ""NormalizedTitle"" : ""graph engine"" }, author: { ""Name"" : 123 } }"), "Invalid property value"); } [TestMethod] public void JsonDSLTest_field_invalid_property_array() { Expect.FanoutSearchQueryException(() => JsonQuery(@" { path: ""paper/AuthorIDs/author"", paper: { ""select"" : [""*""], ""type"" : ""Paper"", ""NormalizedTitle"" : ""graph engine"" }, author: { ""Name"" : [""you""] } }"), "Invalid property value"); } [TestMethod] public void JsonDSLTest_field_gt_throw() { Expect.FanoutSearchQueryException(() => JsonQuery(@" { path: ""paper/AuthorIDs/author"", paper: { ""select"" : [""*""], ""type"" : ""Paper"", ""NormalizedTitle"" : ""graph engine"" }, author: { ""Name"" : { ""gt"" : ""hey"" } } }"), "Invalid comparand"); } [TestMethod] public void JsonDSLTest_field_gt_throw_2() { Expect.FanoutSearchQueryException(() => JsonQuery(@" { path: ""paper/AuthorIDs/author"", paper: { ""select"" : [""*""], ""type"" : ""Paper"", ""NormalizedTitle"" : ""graph engine"" }, author: { ""Name"" : { ""gt"" : { ""hey"" : ""you"" } } } }"), "Invalid comparand"); } [TestMethod] public void JsonDSLTest_field_count_invalid() { Expect.FanoutSearchQueryException(() => JsonQuery(@" { path: ""paper/AuthorIDs/author"", paper: { ""select"" : [""*""], ""type"" : ""Paper"", ""NormalizedTitle"" : ""graph engine"" }, author: { ""Name"" : { ""count"" : { ""awef"" : [] } } } }"), "Invalid count value"); } [TestMethod] public void JsonDSLTest_field_return_invalid() { Expect.FanoutSearchQueryException(() => JsonQuery(@" { path: ""paper/AuthorIDs/author"", paper: { ""type"" : ""Paper"", ""NormalizedTitle"" : ""graph engine"" }, author: { ""return"" : { ""Name"" : ""bin shao"", ""select"" : [""*""] } } }"), "Invalid property"); } [TestMethod] public void JsonDSLTest_field_return_invalid_value() { Expect.FanoutSearchQueryException(() => JsonQuery(@" { path: ""paper/AuthorIDs/author"", paper: { ""type"" : ""Paper"", ""NormalizedTitle"" : ""graph engine"" }, author: { ""return"" : [] } }"), "Invalid return expression"); } [TestMethod] public void JsonDSLTest_field_return_invalid_value_2() { Expect.FanoutSearchQueryException(() => JsonQuery(@" { path: ""paper/AuthorIDs/author"", paper: { ""type"" : ""Paper"", ""NormalizedTitle"" : ""graph engine"" }, author: { ""return"" : 123 } }"), "Invalid return expression"); } [TestMethod] public void JsonDSLTest_field_continue_invalid_value() { Expect.FanoutSearchQueryException(() => JsonQuery(@" { path: ""paper/AuthorIDs/author"", paper: { ""type"" : ""Paper"", ""NormalizedTitle"" : ""graph engine"" }, author: { ""continue"" : 123 } }"), "Invalid continue expression"); } [TestMethod] public void JsonDSLTest_field_select_invalid() { Expect.FanoutSearchQueryException(() => JsonQuery(@" { path: ""paper"", paper: { ""type"" : ""Paper"", ""NormalizedTitle"" : ""graph engine"", ""select"" : 123 } }"), "Invalid select operand"); } [TestMethod] public void JsonDSLTest_field_has_invalid_operand_array() { Expect.FanoutSearchQueryException(()=> JsonQuery(@" { path: ""paper/AuthorIDs/author"", paper: { ""select"" : [""*""], ""type"" : ""Paper"", ""NormalizedTitle"" : ""graph engine"" }, author: { ""has"" : [""Name""] } }"), "Invalid has operand"); } [TestMethod] public void JsonDSLTest_field_has_invalid_operand_int() { Expect.FanoutSearchQueryException(()=> JsonQuery(@" { path: ""paper/AuthorIDs/author"", paper: { ""select"" : [""*""], ""type"" : ""Paper"", ""NormalizedTitle"" : ""graph engine"" }, author: { ""has"" : 123 } }"), "Invalid has operand"); } [TestMethod] public void JsonDSLTest_cannot_specify_not_or_together() { Expect.FanoutSearchQueryException(()=> JsonQuery(@" { path: ""paper/AuthorIDs/author"", paper: { ""select"" : [""*""], ""type"" : ""Paper"", ""NormalizedTitle"" : ""graph engine"" }, author: { or : { }, not : { } } }"), "Cannot specify not/or conditions together"); } [TestMethod] public void JsonDSLTest_no_predicates_found_in_or() { Expect.FanoutSearchQueryException(()=> JsonQuery(@" { path: ""paper/AuthorIDs/author"", paper: { ""select"" : [""*""], ""type"" : ""Paper"", ""NormalizedTitle"" : ""graph engine"" }, author: { or : { } } }"), "No predicates found in OR expression"); } [TestMethod] public void JsonDSLTest_the_origin_descriptor_cannot_be_null() { Expect.FanoutSearchQueryException(()=> JsonQuery(@" { path: ""paper/AuthorIDs/author"", author: { } }"), "The starting node descriptor cannot be null"); } } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC Copyright (C) 2011 Peter Gill <peter@majorsilence.com> This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email info@fyireporting.com or visit the website www.fyiReporting.com. */ using System; using System.Collections; using System.IO; using System.Reflection; using System.Text; using fyiReporting.RDL; namespace fyiReporting.RDL { /// <summary> /// The VBFunctions class holds a number of static functions for support VB functions. /// </summary> sealed public class VBFunctions { /// <summary> /// Obtains the year /// </summary> /// <param name="dt"></param> /// <returns>int year</returns> static public int Year(DateTime dt) { return dt.Year; } /// <summary> /// Returns the integer day of week: 1=Sunday, 2=Monday, ..., 7=Saturday /// </summary> /// <param name="dt"></param> /// <returns></returns> static public int Weekday(DateTime dt) { int dow; switch (dt.DayOfWeek) { case DayOfWeek.Sunday: dow=1; break; case DayOfWeek.Monday: dow=2; break; case DayOfWeek.Tuesday: dow=3; break; case DayOfWeek.Wednesday: dow=4; break; case DayOfWeek.Thursday: dow=5; break; case DayOfWeek.Friday: dow=6; break; case DayOfWeek.Saturday: dow=7; break; default: // should never happen dow=1; break; } return dow; } /// <summary> /// Returns the integer day of week: 1=Monday, 2=Tuesday, ..., 7=Sunday /// </summary> /// <param name="dt">DateTime</param> public static int WeekdayNonAmerican(DateTime dt) { var res = (int)dt.DayOfWeek; return res == 0 ? 7 : res; } /// <summary> /// Returns the integer day of week: 1=Monday, 2=Tuesday, ..., 7=Sunday /// </summary> /// <param name="dateString">String representation of a date and time</param> public static int WeekdayNonAmerican(string dateString) { if(DateTime.TryParse(dateString, out var dt)) { return WeekdayNonAmerican(dt); } throw new FormatException("parameter does not contain a valid string representation of a date and time"); } /// <summary> /// Returns the name of the day of week /// </summary> /// <param name="d"></param> /// <returns></returns> static public string WeekdayName(int d) { return WeekdayName(d, false); } /// <summary> /// Returns the name of the day of week /// </summary> /// <param name="d"></param> /// <param name="bAbbreviation">true for abbreviated name</param> /// <returns></returns> static public string WeekdayName(int d, bool bAbbreviation) { DateTime dt = new DateTime(2005, 5, d); // May 1, 2005 is a Sunday string wdn = bAbbreviation? string.Format("{0:ddd}", dt):string.Format("{0:dddd}", dt); return wdn; } /// <summary> /// Get the day of the month. /// </summary> /// <param name="dt"></param> /// <returns></returns> static public int Day(DateTime dt) { return dt.Day; } /// <summary> /// Gets the integer month /// </summary> /// <param name="dt"></param> /// <returns></returns> static public int Month(DateTime dt) { return dt.Month; } /// <summary> /// Get the month name /// </summary> /// <param name="m"></param> /// <returns></returns> static public string MonthName(object m) { return MonthName(m, false); } /// <summary> /// Gets the month name; optionally abbreviated /// </summary> /// <param name="m"></param> /// <param name="bAbbreviation"></param> /// <returns></returns> static public string MonthName(object m, bool bAbbreviation) { var monthNumber = CInt(m); DateTime dt = new DateTime(2005, monthNumber, 1); return bAbbreviation? string.Format("{0:MMM}", dt):string.Format("{0:MMMM}", dt); } /// <summary> /// Gets the hour /// </summary> /// <param name="dt"></param> /// <returns></returns> static public int Hour(DateTime dt) { return dt.Hour; } /// <summary> /// Get the minute /// </summary> /// <param name="dt"></param> /// <returns></returns> static public int Minute(DateTime dt) { return dt.Minute; } /// <summary> /// Get the second /// </summary> /// <param name="dt"></param> /// <returns></returns> static public int Second(DateTime dt) { return dt.Second; } /// <summary> /// Gets the current local date on this computer /// </summary> /// <returns></returns> static public DateTime Today() { DateTime dt = DateTime.Now; return new DateTime(dt.Year, dt.Month, dt.Day, 0, 0, 0, 0); } /// <summary> /// Converts the first letter in a string to ANSI code /// </summary> /// <param name="o"></param> /// <returns></returns> static public int Asc(string o) { if (o == null || o.Length == 0) return 0; return Convert.ToInt32(o[0]); } /// <summary> /// Converts an expression to Boolean /// </summary> /// <param name="o"></param> /// <returns></returns> static public bool CBool(object o) { return Convert.ToBoolean(o); } /// <summary> /// Converts an expression to type Byte /// </summary> /// <param name="o"></param> /// <returns></returns> static public Byte CByte(string o) { return Convert.ToByte(o); } /// <summary> /// Converts an expression to type Currency - really Decimal /// </summary> /// <param name="o"></param> /// <returns></returns> static public decimal CCur(string o) { return Convert.ToDecimal(o); } /// <summary> /// Converts an expression to type Date /// </summary> /// <param name="o"></param> /// <returns></returns> static public DateTime CDate(string o) { return Convert.ToDateTime(o); } /// <summary> /// Converts the specified ANSI code to a character /// </summary> /// <param name="o"></param> /// <returns></returns> static public char Chr(int o) { return Convert.ToChar(o); } /// <summary> /// Converts the expression to integer /// </summary> /// <param name="o"></param> /// <returns></returns> static public int CInt(object o) { return Convert.ToInt32(o); } /// <summary> /// Converts the expression to long /// </summary> /// <param name="o"></param> /// <returns></returns> static public long CLng(object o) { return Convert.ToInt64(o); } /// <summary> /// Converts the expression to Single /// </summary> /// <param name="o"></param> /// <returns></returns> static public Single CSng(object o) { return Convert.ToSingle(o); } /// <summary> /// Converts the expression to String /// </summary> /// <param name="o"></param> /// <returns></returns> static public string CStr(object o) { return Convert.ToString(o); } /// <summary> /// Returns the hexadecimal value of a specified number /// </summary> /// <param name="o"></param> /// <returns></returns> static public string Hex(long o) { return Convert.ToString(o, 16); } /// <summary> /// Returns the octal value of a specified number /// </summary> /// <param name="o"></param> /// <returns></returns> static public string Oct(long o) { return Convert.ToString(o, 8); } /// <summary> /// Converts the passed parameter to double /// </summary> /// <param name="o"></param> /// <returns></returns> static public double CDbl(Object o) { return Convert.ToDouble(o); } static public DateTime DateAdd(string interval, double number, string date) { return DateAdd(interval, number, DateTime.Parse(date)); } /// <summary> /// Returns a date to which a specified time interval has been added. /// </summary> /// <param name="interval">String expression that is the interval you want to add.</param> /// <param name="number">Numeric expression that is the number of interval you want to add. The numeric expression can either be positive, for dates in the future, or negative, for dates in the past.</param> /// <param name="date">The date to which interval is added.</param> /// <returns></returns> static public DateTime DateAdd(string interval, double number, DateTime date) { switch (interval) { case "yyyy": // year date = date.AddYears((int) Math.Round(number, 0)); break; case "m": // month date = date.AddMonths((int)Math.Round(number, 0)); break; case "d": // day date = date.AddDays(number); break; case "h": // hour date = date.AddHours(number); break; case "n": // minute date = date.AddMinutes(number); break; case "s": // second date = date.AddSeconds(number); break; case "y": // day of year date = date.AddDays(number); break; case "q": // quarter date = date.AddMonths((int)Math.Round(number, 0) * 3); break; case "w": // weekday date = date.AddDays(number); break; case "ww": // week of year date = date.AddDays((int)Math.Round(number, 0) * 7); break; default: throw new ArgumentException(string.Format("Interval '{0}' is invalid or unsupported.", interval)); } return date; } /// <summary> /// 1 based offset of string2 in string1 /// </summary> /// <param name="string1"></param> /// <param name="string2"></param> /// <returns></returns> static public int InStr(string string1, string string2) { return InStr(1, string1, string2, 0); } /// <summary> /// 1 based offset of string2 in string1 /// </summary> /// <param name="start"></param> /// <param name="string1"></param> /// <param name="string2"></param> /// <returns></returns> static public int InStr(int start, string string1, string string2) { return InStr(start, string1, string2, 0); } /// <summary> /// 1 based offset of string2 in string1; optionally case insensitive /// </summary> /// <param name="string1"></param> /// <param name="string2"></param> /// <param name="compare">1 if you want case insensitive compare</param> /// <returns></returns> static public int InStr(string string1, string string2, int compare) { return InStr(1, string1, string2, compare); } /// <summary> /// 1 based offset of string2 in string1; optionally case insensitive /// </summary> /// <param name="start"></param> /// <param name="string1"></param> /// <param name="string2"></param> /// <param name="compare"></param> /// <returns></returns> static public int InStr(int start, string string1, string string2, int compare) { if (string1 == null || string2 == null || string1.Length == 0 || start > string1.Length || start < 1) return 0; if (string2.Length == 0) return start; // Make start zero based start--; if (start < 0) start=0; if (compare == 1) // Make case insensitive comparison? { // yes; just make both strings lower case string1 = string1.ToLower(); string2 = string2.ToLower(); } int i = string1.IndexOf(string2, start); return i+1; // result is 1 based } /// <summary> /// 1 based offset of string2 in string1 starting from end of string /// </summary> /// <param name="string1"></param> /// <param name="string2"></param> /// <returns></returns> static public int InStrRev(string string1, string string2) { return InStrRev(string1, string2, -1, 0); } /// <summary> /// 1 based offset of string2 in string1 starting from end of string - start /// </summary> /// <param name="string1"></param> /// <param name="string2"></param> /// <param name="start"></param> /// <returns></returns> static public int InStrRev(string string1, string string2, int start) { return InStrRev(string1, string2, start, 0); } /// <summary> /// 1 based offset of string2 in string1 starting from end of string - start optionally case insensitive /// </summary> /// <param name="string1"></param> /// <param name="string2"></param> /// <param name="start"></param> /// <param name="compare">1 for case insensitive comparison</param> /// <returns></returns> static public int InStrRev(string string1, string string2, int start, int compare) { if (string1 == null || string2 == null || string1.Length == 0 || string2.Length > string1.Length) return 0; // TODO this is the brute force method of searching; should use better algorithm bool bCaseSensitive = compare == 1; int inc= start == -1? string1.Length: start; if (inc > string1.Length) inc = string1.Length; while (inc >= string2.Length) // go thru the string backwards; but string still needs to long enough to hold find string { int i=string2.Length-1; for ( ; i >= 0; i--) // match the find string backwards as well { if (bCaseSensitive) { if (Char.ToLower(string1[inc-string2.Length+i]) != string2[i]) break; } else { if (string1[inc-string2.Length+i] != string2[i]) break; } } if (i < 0) // We got a match return inc+1-string2.Length; inc--; // No match try next character } return 0; } /// <summary> /// IsNumeric returns True if the data type of Expression is Boolean, Byte, Decimal, Double, Integer, Long, /// SByte, Short, Single, UInteger, ULong, or UShort. /// It also returns True if Expression is a Char, String, or Object that can be successfully converted to a number. /// /// IsNumeric returns False if Expression is of data type Date. It returns False if Expression is a /// Char, String, or Object that cannot be successfully converted to a number. /// </summary> /// <param name="v"></param> /// <returns></returns> static public bool IsNumeric(object expression) { if (expression == null) return false; if (expression is string || expression is char) { } else if (expression is bool || expression is byte || expression is sbyte || expression is decimal || expression is double || expression is float || expression is Int16 || expression is Int32 || expression is Int64 || expression is UInt16 || expression is UInt32 || expression is UInt64) return true; try { Convert.ToDouble(expression); return true; } catch { return false; } } /// <summary> /// Returns the lower case of the passed string /// </summary> /// <param name="str"></param> /// <returns></returns> static public string LCase(string str) { return str == null? null: str.ToLower(); } /// <summary> /// Returns the left n characters from the string /// </summary> /// <param name="str"></param> /// <param name="count"></param> /// <returns></returns> static public string Left(string str, int count) { if (str == null || count >= str.Length) return str; else return str.Substring(0, count); } /// <summary> /// Returns the length of the string /// </summary> /// <param name="str"></param> /// <returns></returns> static public int Len(string str) { return str == null? 0: str.Length; } /// <summary> /// Removes leading blanks from string /// </summary> /// <param name="str"></param> /// <returns></returns> static public string LTrim(string str) { if (str == null || str.Length == 0) return str; return str.TrimStart(' '); } /// <summary> /// Returns the portion of the string denoted by the start. /// </summary> /// <param name="str"></param> /// <param name="start">1 based starting position</param> /// <returns></returns> static public string Mid(string str, int start) { if (str == null) return null; if (start > str.Length) return ""; return str.Substring(start - 1); } /// <summary> /// Returns the portion of the string denoted by the start and length. /// </summary> /// <param name="str"></param> /// <param name="start">1 based starting position</param> /// <param name="length">length to extract</param> /// <returns></returns> static public string Mid(string str, int start, int length) { if (str == null) return null; if (start > str.Length) return ""; if (str.Length < start - 1 + length) return str.Substring(start - 1); // Length specified is too large return str.Substring(start-1, length); } //Replace(string,find,replacewith[,start[,count[,compare]]]) /// <summary> /// Returns string replacing all instances of the searched for text with the replace text. /// </summary> /// <param name="str"></param> /// <param name="find"></param> /// <param name="replacewith"></param> /// <returns></returns> static public string Replace(string str, string find, string replacewith) { return Replace(str, find, replacewith, 1, -1, 0); } /// <summary> /// Returns string replacing all instances of the searched for text starting at position /// start with the replace text. /// </summary> /// <param name="str"></param> /// <param name="find"></param> /// <param name="replacewith"></param> /// <param name="start"></param> /// <returns></returns> static public string Replace(string str, string find, string replacewith, int start) { return Replace(str, find, replacewith, start, -1, 0); } /// <summary> /// Returns string replacing 'count' instances of the searched for text starting at position /// start with the replace text. /// </summary> /// <param name="str"></param> /// <param name="find"></param> /// <param name="replacewith"></param> /// <param name="start"></param> /// <param name="count"></param> /// <returns></returns> static public string Replace(string str, string find, string replacewith, int start, int count) { return Replace(str, find, replacewith, start, count, 0); } /// <summary> /// Returns string replacing 'count' instances of the searched for text (optionally /// case insensitive) starting at position start with the replace text. /// </summary> /// <param name="str"></param> /// <param name="find"></param> /// <param name="replacewith"></param> /// <param name="start"></param> /// <param name="count"></param> /// <param name="compare">1 for case insensitive search</param> /// <returns></returns> static public string Replace(string str, string find, string replacewith, int start, int count, int compare) { if (str == null || find == null || find.Length == 0 || count == 0) return str; if (count == -1) // user want all changed? count = int.MaxValue; StringBuilder sb = new StringBuilder(str); bool bCaseSensitive = compare != 0; // determine if case sensitive; compare = 0 for case sensitive if (bCaseSensitive) find = find.ToLower(); int inc=0; bool bReplace = (replacewith != null && replacewith.Length > 0); // TODO this is the brute force method of searching; should use better algorithm while (inc <= sb.Length - find.Length) { int i=0; for ( ; i < find.Length; i++) { if (bCaseSensitive) { if (Char.ToLower(sb[inc+i]) != find[i]) break; } else { if (sb[inc+i] != find[i]) break; } } if (i == find.Length) // We got a match { // replace the found string with the replacement string sb.Remove(inc, find.Length); if (bReplace) { sb.Insert(inc, replacewith); inc += (replacewith.Length + 1); } count--; if (count == 0) // have we done as many replaces as requested? return sb.ToString(); // yes, return } else inc++; // No match try next character } return sb.ToString(); } /// <summary> /// Returns the rightmost length of string. /// </summary> /// <param name="str"></param> /// <param name="length"></param> /// <returns></returns> static public string Right(string str, int length) { if (str == null || str.Length <= length) return str; if (length <= 0) return ""; return str.Substring(str.Length - length); } /// <summary> /// Removes trailing blanks from string. /// </summary> /// <param name="str"></param> /// <returns></returns> static public string RTrim(string str) { if (str == null || str.Length == 0) return str; return str.TrimEnd(' '); } /// <summary> /// Returns blank string of the specified length /// </summary> /// <param name="length"></param> /// <returns></returns> static public string Space(int length) { return String(length, ' '); } //StrComp(string1,string2[,compare]) /// <summary> /// Compares the strings. When string1 &lt; string2: -1, string1 = string2: 0, string1 > string2: 1 /// </summary> /// <param name="string1"></param> /// <param name="string2"></param> /// <returns></returns> static public int StrComp(string string1, string string2) { return StrComp(string1, string2, 0); } /// <summary> /// Compares the strings; optionally with case insensitivity. When string1 &lt; string2: -1, string1 = string2: 0, string1 > string2: 1 /// </summary> /// <param name="string1"></param> /// <param name="string2"></param> /// <param name="compare">1 for case insensitive comparison</param> /// <returns></returns> static public int StrComp(string string1, string string2, int compare) { if (string1 == null || string2 == null) return 0; // not technically correct; should return null return compare == 0? string1.CompareTo(string2): string1.ToLower().CompareTo(string2.ToLower()); } /// <summary> /// Return string with the character repeated for the length /// </summary> /// <param name="length"></param> /// <param name="c"></param> /// <returns></returns> static public string String(int length, string c) { if (length <= 0 || c == null || c.Length == 0) return ""; return String(length, c[0]); } /// <summary> /// Return string with the character repeated for the length /// </summary> /// <param name="length"></param> /// <param name="c"></param> /// <returns></returns> static public string String(int length, char c) { if (length <= 0) return ""; StringBuilder sb = new StringBuilder(length, length); for (int i = 0; i < length; i++) sb.Append(c); return sb.ToString(); } /// <summary> /// Returns a string with the characters reversed. /// </summary> /// <param name="str"></param> /// <returns></returns> static public string StrReverse(string str) { if (str == null || str.Length < 2) return str; StringBuilder sb = new StringBuilder(str, str.Length); int i = str.Length-1; foreach (char c in str) { sb[i--] = c; } return sb.ToString(); } /// <summary> /// Removes whitespace from beginning and end of string. /// </summary> /// <param name="str"></param> /// <returns></returns> static public string Trim(string str) { if (str == null || str.Length == 0) return str; return str.Trim(' '); } /// <summary> /// Returns the uppercase version of the string /// </summary> /// <param name="str"></param> /// <returns></returns> static public string UCase(string str) { return str == null? null: str.ToUpper(); } /// <summary> /// Rounds a number to zero decimal places /// </summary> /// <param name="n">Number to round</param> /// <returns></returns> static public double Round(double n) { return Math.Round(n); } /// <summary> /// Rounds a number to the specified decimal places /// </summary> /// <param name="n">Number to round</param> /// <param name="decimals">Number of decimal places</param> /// <returns></returns> static public double Round(double n, int decimals) { return Math.Round(n, decimals); } /// <summary> /// Rounds a number to zero decimal places /// </summary> /// <param name="n">Number to round</param> /// <returns></returns> static public decimal Round(decimal n) { return Math.Round(n); } /// <summary> /// Rounds a number to the specified decimal places /// </summary> /// <param name="n">Number to round</param> /// <param name="decimals">Number of decimal places</param> /// <returns></returns> static public decimal Round(decimal n, int decimals) { return Math.Round(n, decimals); } } }
/* ********************************************************************************************************** * The MIT License (MIT) * * * * Copyright (c) 2016 Hypermediasystems Ges. f. Software mbH * * Web: http://www.hypermediasystems.de * * This file is part of hmssp * * * * 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.Dynamic; using System.Reflection; using Newtonsoft.Json; namespace HMS.SP{ /// <summary> /// <para>https://msdn.microsoft.com/en-us/library/office/dn600183.aspx#bk_ChangeQuery</para> /// </summary> public class ChangeQuery : SPBase{ [JsonProperty("__HMSError")] public HMS.Util.__HMSError __HMSError_ { set; get; } [JsonProperty("__status")] public SP.__status __status_ { set; get; } [JsonProperty("__deferred")] public SP.__deferred __deferred_ { set; get; } [JsonProperty("__metadata")] public SP.__metadata __metadata_ { set; get; } public Dictionary<string, string> __rest; /// <summary> /// <para>Gets or sets a value that specifies whether add changes are included in the query.</para> /// <para>R/W: </para> /// <para>Returned with resource:</para> /// </summary> [JsonProperty("Add")] public Boolean Add_ { set; get; } /// <summary> /// <para>Gets or sets a value that specifies whether changes to alerts are included in the query.</para> /// <para>R/W: </para> /// <para>Returned with resource:</para> /// </summary> [JsonProperty("Alert")] public Boolean Alert_ { set; get; } /// <summary> /// <para>Gets or sets a value that specifies the end date and end time for changes that are returned through the query.</para> /// <para>R/W: </para> /// <para>Returned with resource:</para> /// </summary> [JsonProperty("ChangeTokenEnd")] public SP.ChangeToken ChangeTokenEnd_ { set; get; } /// <summary> /// <para>Gets or sets a value that specifies the start date and start time for changes that are returned through the query.</para> /// <para>R/W: </para> /// <para>Returned with resource:</para> /// </summary> [JsonProperty("ChangeTokenStart")] public SP.ChangeToken ChangeTokenStart_ { set; get; } /// <summary> /// <para>Gets or sets a value that specifies whether changes to content types are included in the query.</para> /// <para>R/W: </para> /// <para>Returned with resource:</para> /// </summary> [JsonProperty("ContentType")] public Boolean ContentType_ { set; get; } /// <summary> /// <para>Gets or sets a value that specifies whether changes to content types are included in the query.</para> /// <para>R/W: </para> /// <para>Returned with resource:</para> /// </summary> [JsonProperty("DeleteObject")] public Boolean DeleteObject_ { set; get; } /// <summary> /// <para>Gets or sets a value that specifies whether changes to content types are included in the query.</para> /// <para>R/W: </para> /// <para>Returned with resource:</para> /// </summary> [JsonProperty("Field")] public Boolean Field_ { set; get; } /// <summary> /// <para>Gets or sets a value that specifies whether changes to content types are included in the query.</para> /// <para>R/W: </para> /// <para>Returned with resource:</para> /// </summary> [JsonProperty("File")] public Boolean File_ { set; get; } /// <summary> /// <para>Gets or sets value that specifies whether changes to folders are included in the query.</para> /// <para>R/W: </para> /// <para>Returned with resource:</para> /// </summary> [JsonProperty("Folder")] public Boolean Folder_ { set; get; } /// <summary> /// <para>Gets or sets a value that specifies whether changes to groups are included in the query.</para> /// <para>R/W: </para> /// <para>Returned with resource:</para> /// </summary> [JsonProperty("Group")] public Boolean Group_ { set; get; } /// <summary> /// <para>Gets or sets a value that specifies whether adding users to groups is included in the query.</para> /// <para>R/W: </para> /// <para>Returned with resource:</para> /// </summary> [JsonProperty("GroupMembershipAdd")] public Boolean GroupMembershipAdd_ { set; get; } /// <summary> /// <para>Gets or sets a value that specifies whether deleting users from the groups is included in the query.</para> /// <para>R/W: </para> /// <para>Returned with resource:</para> /// </summary> [JsonProperty("GroupMembershipDelete")] public Boolean GroupMembershipDelete_ { set; get; } /// <summary> /// <para>Gets or sets a value that specifies whether general changes to list items are included in the query.</para> /// <para>R/W: </para> /// <para>Returned with resource:</para> /// </summary> [JsonProperty("Item")] public Boolean Item_ { set; get; } /// <summary> /// <para>Gets or sets a value that specifies whether changes to lists are included in the query.</para> /// <para>R/W: </para> /// <para>Returned with resource:</para> /// </summary> [JsonProperty("List")] public Boolean List_ { set; get; } /// <summary> /// <para>Gets or sets a value that specifies whether move changes are included in the query.</para> /// <para>R/W: </para> /// <para>Returned with resource:</para> /// </summary> [JsonProperty("Move")] public Boolean Move_ { set; get; } /// <summary> /// <para>Gets or sets a value that specifies whether changes to the navigation structure of a site collection are included in the query.</para> /// <para>R/W: </para> /// <para>Returned with resource:</para> /// </summary> [JsonProperty("Navigation")] public Boolean Navigation_ { set; get; } /// <summary> /// <para>Gets or sets a value that specifies whether renaming changes are included in the query.</para> /// <para>R/W: </para> /// <para>Returned with resource:</para> /// </summary> [JsonProperty("Rename")] public Boolean Rename_ { set; get; } /// <summary> /// <para>Gets or sets a value that specifies whether restoring items from the recycle bin or from backups is included in the query.</para> /// <para>R/W: </para> /// <para>Returned with resource:</para> /// </summary> [JsonProperty("Restore")] public Boolean Restore_ { set; get; } /// <summary> /// <para>Gets or sets a value that specifies whether adding role assignments is included in the query.</para> /// <para>R/W: </para> /// <para>Returned with resource:</para> /// </summary> [JsonProperty("RoleAssignmentAdd")] public Boolean RoleAssignmentAdd_ { set; get; } /// <summary> /// <para>Gets or sets a value that specifies whether adding role assignments is included in the query.</para> /// <para>R/W: </para> /// <para>Returned with resource:</para> /// </summary> [JsonProperty("RoleAssignmentDelete")] public Boolean RoleAssignmentDelete_ { set; get; } /// <summary> /// <para>Gets or sets a value that specifies whether adding role assignments is included in the query.</para> /// <para>R/W: </para> /// <para>Returned with resource:</para> /// </summary> [JsonProperty("RoleDefinitionAdd")] public Boolean RoleDefinitionAdd_ { set; get; } /// <summary> /// <para>Gets or sets a value that specifies whether adding role assignments is included in the query.</para> /// <para>R/W: </para> /// <para>Returned with resource:</para> /// </summary> [JsonProperty("RoleDefinitionDelete")] public Boolean RoleDefinitionDelete_ { set; get; } /// <summary> /// <para>Gets or sets a value that specifies whether adding role assignments is included in the query.</para> /// <para>R/W: </para> /// <para>Returned with resource:</para> /// </summary> [JsonProperty("RoleDefinitionUpdate")] public Boolean RoleDefinitionUpdate_ { set; get; } /// <summary> /// <para>Gets or sets a value that specifies whether modifications to security policies are included in the query.</para> /// <para>R/W: </para> /// <para>Returned with resource:</para> /// </summary> [JsonProperty("SecurityPolicy")] public Boolean SecurityPolicy_ { set; get; } /// <summary> /// <para>Gets or sets a value that specifies whether changes to site collections are included in the query.</para> /// <para>R/W: </para> /// <para>Returned with resource:</para> /// </summary> [JsonProperty("Site")] public Boolean Site_ { set; get; } /// <summary> /// <para>Gets or sets a value that specifies whether updates made using the item SystemUpdate method are included in the query.</para> /// <para>R/W: </para> /// <para>Returned with resource:</para> /// </summary> [JsonProperty("SystemUpdate")] public Boolean SystemUpdate_ { set; get; } /// <summary> /// <para>Gets or sets a value that specifies whether update changes are included in the query.</para> /// <para>R/W: </para> /// <para>Returned with resource:</para> /// </summary> [JsonProperty("Update")] public Boolean Update_ { set; get; } /// <summary> /// <para>Gets or sets a value that specifies whether changes to users are included in the query.</para> /// <para>R/W: </para> /// <para>Returned with resource:</para> /// </summary> [JsonProperty("User")] public Boolean User_ { set; get; } /// <summary> /// <para>Gets or sets a value that specifies whether changes to views are included in the query.</para> /// <para>R/W: </para> /// <para>Returned with resource:</para> /// </summary> [JsonProperty("View")] public Boolean View_ { set; get; } /// <summary> /// <para>Gets or sets a value that specifies whether changes to Web sites are included in the query.</para> /// <para>R/W: </para> /// <para>Returned with resource:</para> /// </summary> [JsonProperty("Web")] public Boolean Web_ { set; get; } /// <summary> /// <para> Endpoints </para> /// </summary> static string[] endpoints = { }; public ChangeQuery(ExpandoObject expObj) { try { var use_EO = ((dynamic)expObj).entry.content.properties; HMS.SP.SPUtil.expando2obj(use_EO, this, typeof(ChangeQuery)); } catch (Exception ex) { } } // used by Newtonsoft.JSON public ChangeQuery() { } public ChangeQuery(string json) { if( json == String.Empty ) return; dynamic jobject = Newtonsoft.Json.JsonConvert.DeserializeObject(json); dynamic refObj = jobject; if (jobject.d != null) refObj = jobject.d; string errInfo = ""; if (refObj.results != null) { if (refObj.results.Count > 1) errInfo = "Result is Collection, only 1. entry displayed."; refObj = refObj.results[0]; } List<string> usedFields = new List<string>(); usedFields.Add("__HMSError"); HMS.SP.SPUtil.dyn_ValueSet("__HMSError", refObj, this); usedFields.Add("__deferred"); this.__deferred_ = new SP.__deferred(HMS.SP.SPUtil.dyn_toString(refObj.__deferred)); usedFields.Add("__metadata"); this.__metadata_ = new SP.__metadata(HMS.SP.SPUtil.dyn_toString(refObj.__metadata)); usedFields.Add("Add"); HMS.SP.SPUtil.dyn_ValueSet("Add", refObj, this); usedFields.Add("Alert"); HMS.SP.SPUtil.dyn_ValueSet("Alert", refObj, this); usedFields.Add("ChangeTokenEnd"); this.ChangeTokenEnd_ = new SP.ChangeToken(HMS.SP.SPUtil.dyn_toString(refObj.ChangeTokenEnd)); usedFields.Add("ChangeTokenStart"); this.ChangeTokenStart_ = new SP.ChangeToken(HMS.SP.SPUtil.dyn_toString(refObj.ChangeTokenStart)); usedFields.Add("ContentType"); HMS.SP.SPUtil.dyn_ValueSet("ContentType", refObj, this); usedFields.Add("DeleteObject"); HMS.SP.SPUtil.dyn_ValueSet("DeleteObject", refObj, this); usedFields.Add("Field"); HMS.SP.SPUtil.dyn_ValueSet("Field", refObj, this); usedFields.Add("File"); HMS.SP.SPUtil.dyn_ValueSet("File", refObj, this); usedFields.Add("Folder"); HMS.SP.SPUtil.dyn_ValueSet("Folder", refObj, this); usedFields.Add("Group"); HMS.SP.SPUtil.dyn_ValueSet("Group", refObj, this); usedFields.Add("GroupMembershipAdd"); HMS.SP.SPUtil.dyn_ValueSet("GroupMembershipAdd", refObj, this); usedFields.Add("GroupMembershipDelete"); HMS.SP.SPUtil.dyn_ValueSet("GroupMembershipDelete", refObj, this); usedFields.Add("Item"); HMS.SP.SPUtil.dyn_ValueSet("Item", refObj, this); usedFields.Add("List"); HMS.SP.SPUtil.dyn_ValueSet("List", refObj, this); usedFields.Add("Move"); HMS.SP.SPUtil.dyn_ValueSet("Move", refObj, this); usedFields.Add("Navigation"); HMS.SP.SPUtil.dyn_ValueSet("Navigation", refObj, this); usedFields.Add("Rename"); HMS.SP.SPUtil.dyn_ValueSet("Rename", refObj, this); usedFields.Add("Restore"); HMS.SP.SPUtil.dyn_ValueSet("Restore", refObj, this); usedFields.Add("RoleAssignmentAdd"); HMS.SP.SPUtil.dyn_ValueSet("RoleAssignmentAdd", refObj, this); usedFields.Add("RoleAssignmentDelete"); HMS.SP.SPUtil.dyn_ValueSet("RoleAssignmentDelete", refObj, this); usedFields.Add("RoleDefinitionAdd"); HMS.SP.SPUtil.dyn_ValueSet("RoleDefinitionAdd", refObj, this); usedFields.Add("RoleDefinitionDelete"); HMS.SP.SPUtil.dyn_ValueSet("RoleDefinitionDelete", refObj, this); usedFields.Add("RoleDefinitionUpdate"); HMS.SP.SPUtil.dyn_ValueSet("RoleDefinitionUpdate", refObj, this); usedFields.Add("SecurityPolicy"); HMS.SP.SPUtil.dyn_ValueSet("SecurityPolicy", refObj, this); usedFields.Add("Site"); HMS.SP.SPUtil.dyn_ValueSet("Site", refObj, this); usedFields.Add("SystemUpdate"); HMS.SP.SPUtil.dyn_ValueSet("SystemUpdate", refObj, this); usedFields.Add("Update"); HMS.SP.SPUtil.dyn_ValueSet("Update", refObj, this); usedFields.Add("User"); HMS.SP.SPUtil.dyn_ValueSet("User", refObj, this); usedFields.Add("View"); HMS.SP.SPUtil.dyn_ValueSet("View", refObj, this); usedFields.Add("Web"); HMS.SP.SPUtil.dyn_ValueSet("Web", refObj, this); this.__rest = new Dictionary<string, string>(); var dyn = ((Newtonsoft.Json.Linq.JContainer)refObj).First; while (dyn != null) { string Name = ((Newtonsoft.Json.Linq.JProperty)dyn).Name; string Value = ((Newtonsoft.Json.Linq.JProperty)dyn).Value.ToString(); if ( !usedFields.Contains( Name )) this.__rest.Add( Name, Value); dyn = dyn.Next; } if( errInfo != "") this.__HMSError_.info = errInfo; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Net.Http.Headers; using System.Text; using Xunit; namespace System.Net.Http.Tests { public class ProductHeaderValueTest { [Fact] public void Ctor_SetValidHeaderValues_InstanceCreatedCorrectly() { ProductHeaderValue product = new ProductHeaderValue("HTTP", "2.0"); Assert.Equal("HTTP", product.Name); Assert.Equal("2.0", product.Version); product = new ProductHeaderValue("HTTP"); Assert.Equal("HTTP", product.Name); Assert.Null(product.Version); product = new ProductHeaderValue("HTTP", ""); // null and string.Empty are equivalent Assert.Equal("HTTP", product.Name); Assert.Null(product.Version); } [Fact] public void Ctor_UseInvalidValues_Throw() { Assert.Throws<ArgumentException>(() => { new ProductHeaderValue(null); }); Assert.Throws<ArgumentException>(() => { new ProductHeaderValue(string.Empty); }); Assert.Throws<FormatException>(() => { new ProductHeaderValue(" x"); }); Assert.Throws<FormatException>(() => { new ProductHeaderValue("x "); }); Assert.Throws<FormatException>(() => { new ProductHeaderValue("x y"); }); Assert.Throws<FormatException>(() => { new ProductHeaderValue("x", " y"); }); Assert.Throws<FormatException>(() => { new ProductHeaderValue("x", "y "); }); Assert.Throws<FormatException>(() => { new ProductHeaderValue("x", "y z"); }); } [Fact] public void ToString_UseDifferentRanges_AllSerializedCorrectly() { ProductHeaderValue product = new ProductHeaderValue("IRC", "6.9"); Assert.Equal("IRC/6.9", product.ToString()); product = new ProductHeaderValue("product"); Assert.Equal("product", product.ToString()); } [Fact] public void GetHashCode_UseSameAndDifferentRanges_SameOrDifferentHashCodes() { ProductHeaderValue product1 = new ProductHeaderValue("custom", "1.0"); ProductHeaderValue product2 = new ProductHeaderValue("custom"); ProductHeaderValue product3 = new ProductHeaderValue("CUSTOM", "1.0"); ProductHeaderValue product4 = new ProductHeaderValue("RTA", "x11"); ProductHeaderValue product5 = new ProductHeaderValue("rta", "X11"); Assert.NotEqual(product1.GetHashCode(), product2.GetHashCode()); Assert.Equal(product1.GetHashCode(), product3.GetHashCode()); Assert.NotEqual(product1.GetHashCode(), product4.GetHashCode()); Assert.Equal(product4.GetHashCode(), product5.GetHashCode()); } [Fact] public void Equals_UseSameAndDifferentRanges_EqualOrNotEqualNoExceptions() { ProductHeaderValue product1 = new ProductHeaderValue("custom", "1.0"); ProductHeaderValue product2 = new ProductHeaderValue("custom"); ProductHeaderValue product3 = new ProductHeaderValue("CUSTOM", "1.0"); ProductHeaderValue product4 = new ProductHeaderValue("RTA", "x11"); ProductHeaderValue product5 = new ProductHeaderValue("rta", "X11"); Assert.False(product1.Equals(null), "custom/1.0 vs. <null>"); Assert.False(product1.Equals(product2), "custom/1.0 vs. custom"); Assert.False(product2.Equals(product1), "custom/1.0 vs. custom"); Assert.True(product1.Equals(product3), "custom/1.0 vs. CUSTOM/1.0"); Assert.False(product1.Equals(product4), "custom/1.0 vs. rta/X11"); Assert.True(product4.Equals(product5), "RTA/x11 vs. rta/X11"); } [Fact] public void Clone_Call_CloneFieldsMatchSourceFields() { ProductHeaderValue source = new ProductHeaderValue("SHTTP", "1.3"); ProductHeaderValue clone = (ProductHeaderValue)((ICloneable)source).Clone(); Assert.Equal(source.Name, clone.Name); Assert.Equal(source.Version, clone.Version); source = new ProductHeaderValue("SHTTP", null); clone = (ProductHeaderValue)((ICloneable)source).Clone(); Assert.Equal(source.Name, clone.Name); Assert.Null(clone.Version); } [Fact] public void GetProductLength_DifferentValidScenarios_AllReturnNonZero() { ProductHeaderValue result = null; CallGetProductLength(" custom", 1, 6, out result); Assert.Equal("custom", result.Name); Assert.Null(result.Version); CallGetProductLength(" custom, ", 1, 6, out result); Assert.Equal("custom", result.Name); Assert.Null(result.Version); CallGetProductLength(" custom / 5.6 ", 1, 13, out result); Assert.Equal("custom", result.Name); Assert.Equal("5.6", result.Version); CallGetProductLength("RTA / x58 ,", 0, 10, out result); Assert.Equal("RTA", result.Name); Assert.Equal("x58", result.Version); CallGetProductLength("RTA / x58", 0, 9, out result); Assert.Equal("RTA", result.Name); Assert.Equal("x58", result.Version); CallGetProductLength("RTA / x58 XXX", 0, 10, out result); Assert.Equal("RTA", result.Name); Assert.Equal("x58", result.Version); } [Fact] public void GetProductLength_DifferentInvalidScenarios_AllReturnZero() { CheckInvalidGetProductLength(" custom", 0); // no leading whitespaces allowed CheckInvalidGetProductLength("custom/", 0); CheckInvalidGetProductLength("custom/[", 0); CheckInvalidGetProductLength("=", 0); CheckInvalidGetProductLength("", 0); CheckInvalidGetProductLength(null, 0); } [Fact] public void Parse_SetOfValidValueStrings_ParsedCorrectly() { CheckValidParse(" y/1 ", new ProductHeaderValue("y", "1")); CheckValidParse(" custom / 1.0 ", new ProductHeaderValue("custom", "1.0")); CheckValidParse("custom / 1.0 ", new ProductHeaderValue("custom", "1.0")); CheckValidParse("custom / 1.0", new ProductHeaderValue("custom", "1.0")); } [Fact] public void Parse_SetOfInvalidValueStrings_Throws() { CheckInvalidParse("product/version="); // only delimiter ',' allowed after last product CheckInvalidParse("product otherproduct"); CheckInvalidParse("product["); CheckInvalidParse("="); CheckInvalidParse(null); CheckInvalidParse(string.Empty); CheckInvalidParse(" "); CheckInvalidParse(" ,,"); } [Fact] public void TryParse_SetOfValidValueStrings_ParsedCorrectly() { CheckValidTryParse(" y/1 ", new ProductHeaderValue("y", "1")); CheckValidTryParse(" custom / 1.0 ", new ProductHeaderValue("custom", "1.0")); CheckValidTryParse("custom / 1.0 ", new ProductHeaderValue("custom", "1.0")); CheckValidTryParse("custom / 1.0", new ProductHeaderValue("custom", "1.0")); } [Fact] public void TryParse_SetOfInvalidValueStrings_ReturnsFalse() { CheckInvalidTryParse("product/version="); // only delimiter ',' allowed after last product CheckInvalidTryParse("product otherproduct"); CheckInvalidTryParse("product["); CheckInvalidTryParse("="); CheckInvalidTryParse(null); CheckInvalidTryParse(string.Empty); CheckInvalidTryParse(" "); CheckInvalidTryParse(" ,,"); } #region Helper methods private void CheckValidParse(string input, ProductHeaderValue expectedResult) { ProductHeaderValue result = ProductHeaderValue.Parse(input); Assert.Equal(expectedResult, result); } private void CheckInvalidParse(string input) { Assert.Throws<FormatException>(() => { ProductHeaderValue.Parse(input); }); } private void CheckValidTryParse(string input, ProductHeaderValue expectedResult) { ProductHeaderValue result = null; Assert.True(ProductHeaderValue.TryParse(input, out result)); Assert.Equal(expectedResult, result); } private void CheckInvalidTryParse(string input) { ProductHeaderValue result = null; Assert.False(ProductHeaderValue.TryParse(input, out result)); Assert.Null(result); } private static void CallGetProductLength(string input, int startIndex, int expectedLength, out ProductHeaderValue result) { Assert.Equal(expectedLength, ProductHeaderValue.GetProductLength(input, startIndex, out result)); } private static void CheckInvalidGetProductLength(string input, int startIndex) { ProductHeaderValue result = null; Assert.Equal(0, ProductHeaderValue.GetProductLength(input, startIndex, out result)); Assert.Null(result); } #endregion } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Net.Sockets; using System.Text; namespace EvoXP_Chat { /// <summary> /// Summary description for ChatClient. /// </summary> public class ChatClient : System.Windows.Forms.Form { private System.Windows.Forms.TextBox textBox_msg; private System.Windows.Forms.ListBox listBox_chat; private System.Windows.Forms.Button button_send; public EvoXP_Login _Login = null; public TcpClient _client = new TcpClient(); public NetworkStream _networkStream = null; private byte[] _BufferRead = new byte[8193]; private AsyncCallback _CallBackRead = new AsyncCallback( OnRead ); private AsyncCallback _CallBackWrite = new AsyncCallback( OnWrite ); private string _MessageIn; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public ChatClient() { try { _Login = new EvoXP_Login(this); _Login.ShowDialog(); } catch (Exception e) { MessageBox.Show(e.ToString()); } InitializeComponent(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #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.textBox_msg = new System.Windows.Forms.TextBox(); this.listBox_chat = new System.Windows.Forms.ListBox(); this.button_send = new System.Windows.Forms.Button(); this.SuspendLayout(); // // textBox_msg // this.textBox_msg.Location = new System.Drawing.Point(8, 216); this.textBox_msg.Name = "textBox_msg"; this.textBox_msg.Size = new System.Drawing.Size(232, 20); this.textBox_msg.TabIndex = 0; this.textBox_msg.Text = ""; // // listBox_chat // this.listBox_chat.Location = new System.Drawing.Point(8, 8); this.listBox_chat.Name = "listBox_chat"; this.listBox_chat.Size = new System.Drawing.Size(280, 199); this.listBox_chat.TabIndex = 1; // // button_send // this.button_send.Location = new System.Drawing.Point(248, 216); this.button_send.Name = "button_send"; this.button_send.Size = new System.Drawing.Size(40, 24); this.button_send.TabIndex = 2; this.button_send.Text = "Send"; this.button_send.Click += new System.EventHandler(this.button_send_Click); // // ChatClient // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(296, 245); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.button_send, this.listBox_chat, this.textBox_msg}); this.Name = "ChatClient"; this.Text = "EvoXP Chat Client"; this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.Run(new ChatClient()); } public void StartLogin(string server, string name, string password) { _client.Connect(server, 25000); _networkStream = _client.GetStream(); _networkStream.BeginRead(_BufferRead, 0, 8192, _CallBackRead, this); string Login = "NAME:" + name + ":PASSWORD:" + password + "<end>"; WriteString(Login); } private void OnMessageDetail(string[] str) { if(str[0]=="AUTH") { // ok, we are good } else if(str[0]=="ALLOW") { _Login.Close(); } else if(str[0]=="MSG") { listBox_chat.Items.Add(str[1] + ":" + str[2]); } } private void HandleMessage() { //_server.OnMessage(this, _MessageIn ); char[] sep = {':'}; try { int pos = _MessageIn.IndexOf("<end>"); while(pos>=0) { string Message = _MessageIn.Substring(0, pos); if(pos+5<_MessageIn.Length) { _MessageIn = _MessageIn.Substring(pos+5, _MessageIn.Length-pos-5); } else { _MessageIn = ""; } //_server.OnMessage(this, Message); string[] MessageBreakdown = Message.Split(sep); OnMessageDetail(MessageBreakdown); pos = _MessageIn.IndexOf("<end>"); } } catch (Exception e) { MessageBox.Show(e.ToString(), "error?"); } } private void HandleRead(IAsyncResult ar) { try { // end the old read int BytesRead = _networkStream.EndRead(ar); // make sure stream is still good if( _networkStream.CanRead && _networkStream.CanWrite && BytesRead > 0) { _BufferRead[BytesRead] = 0; string recv = Encoding.ASCII.GetString(_BufferRead,0,BytesRead); _MessageIn += recv; HandleMessage(); // Processing of the formatted message here //_server.OnMessage(this, recv); // start a new read _networkStream.BeginRead(_BufferRead, 0, 8192, _CallBackRead, this); } } catch (Exception e) { MessageBox.Show(e.ToString()); _client.Close(); } } public void HandleWrite(IAsyncResult ar) { try { // it was written _networkStream.EndWrite(ar); } catch (Exception e) { MessageBox.Show(e.ToString()); _client.Close(); } } public void WriteString(string x) { byte[] LocalBuffer = Encoding.ASCII.GetBytes(x); _networkStream.BeginWrite(LocalBuffer, 0, LocalBuffer.Length, _CallBackWrite, this); } // Asyncronous 'static' wrappers for the handling of the data private static void OnRead(IAsyncResult ar) { ChatClient T = (ChatClient) ar.AsyncState; T.HandleRead(ar); } private static void OnWrite(IAsyncResult ar) { ChatClient T = (ChatClient) ar.AsyncState; T.HandleWrite(ar); } private void button_send_Click(object sender, System.EventArgs e) { string send = "SAY:" + textBox_msg.Text + "<end>"; WriteString(send); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Drawing; using MonoMac.Foundation; using MonoMac.AppKit; namespace NeHeLesson7 { public partial class MainWindowController : MonoMac.AppKit.NSWindowController { bool isInFullScreenMode; // full-screen mode NSWindow fullScreenWindow; MyOpenGLView fullScreenView; Scene scene; bool isAnimating; // Call to load from the XIB/NIB file public MainWindowController () : base("MainWindow") { } //strongly typed window accessor public new MainWindow Window { get { return (MainWindow)base.Window; } } public override void AwakeFromNib () { // Allocate the scene object scene = new Scene (); // Assign the view's MainController to us openGLView.MainController = this; // reset the viewport and update OpenGL Context openGLView.UpdateView (); // Activate the display link now openGLView.StartAnimation (); isAnimating = true; } partial void goFullScreen (NSObject sender) { isInFullScreenMode = true; // Pause the non-fullscreen view openGLView.StopAnimation (); RectangleF mainDisplayRect; RectangleF viewRect; // Create a screen-sized window on the display you want to take over // Note, mainDisplayRect has a non-zero origin if the key window is on a secondary display mainDisplayRect = NSScreen.MainScreen.Frame; fullScreenWindow = new NSWindow (mainDisplayRect, NSWindowStyle.Borderless, NSBackingStore.Buffered, true); // Set the window level to be above the menu bar fullScreenWindow.Level = NSWindowLevel.MainMenu + 1; // Perform any other window configuration you desire fullScreenWindow.IsOpaque = true; fullScreenWindow.HidesOnDeactivate = true; // Create a view with a double-buffered OpenGL context and attach it to the window // By specifying the non-fullscreen context as the shareContext, we automatically inherit the // OpenGL objects (textures, etc) it has defined viewRect = new RectangleF (0, 0, mainDisplayRect.Size.Width, mainDisplayRect.Size.Height); fullScreenView = new MyOpenGLView (viewRect, openGLView.OpenGLContext); fullScreenWindow.ContentView = fullScreenView; // Show the window fullScreenWindow.MakeKeyAndOrderFront (this); // Set the scene with the full-screen viewport and viewing transformation Scene.ResizeGLScene (viewRect); // Assign the view's MainController to self fullScreenView.MainController = this; if (!isAnimating) { // Mark the view as needing drawing to initalize its contents fullScreenView.NeedsDisplay = true; } else { // Start playing the animation fullScreenView.StartAnimation (); } } public void goWindow () { isInFullScreenMode = false; // use OrderOut here instead of Close or nasty things will happen with Garbage Collection and a double free fullScreenWindow.OrderOut (this); fullScreenView.DeAllocate (); fullScreenWindow.Dispose (); fullScreenWindow = null; // Switch to the non-fullscreen context openGLView.OpenGLContext.MakeCurrentContext (); if (!isAnimating) { // Mark the view as needing drawing // The animation has advanced while we were in full-screen mode, so its current contents are stale openGLView.NeedsDisplay = true; } else { // continue playing the animation openGLView.StartAnimation (); } } public void startAnimation () { if (isAnimating) return; if (!isInFullScreenMode) openGLView.StartAnimation (); else fullScreenView.StartAnimation (); isAnimating = true; } public void stopAnimation () { if (!isAnimating) return; if (!isInFullScreenMode) openGLView.StopAnimation (); else fullScreenView.StopAnimation (); isAnimating = false; } public override void KeyDown (NSEvent theEvent) { var c = theEvent.KeyCode; switch (c) { // [Esc] exits full-screen mode case (ushort)NSKey.Escape: if (isInFullScreenMode) goWindow (); break; case (ushort)NSKey.L: Scene.IsLightOn = !Scene.IsLightOn; break; case (ushort)NSKey.F: Scene.Filter += 1; break; // up arrow key case 126: Scene.XSpeed -= 0.05f; break; // fn + up arrow key for page up case 116: Scene.Distance -= 0.10f; break; // down arrow key case 125: Scene.XSpeed += 0.05f; break; // fn + down arrow key for page down case 121: Scene.Distance += 0.10f; break; // left arrow key case 123: Scene.YSpeed -= 0.05f; break; // right arrow key case 124: Scene.YSpeed += 0.05f; break; default: break; } } // Accessor property for our scene object public Scene Scene { get { return scene; } } public void toggleFullScreen (NSObject sender) { if (!isInFullScreenMode) goFullScreen (sender); else goWindow (); } } }
//----------------------------------------------------------------------- // <copyright file="GraphInterpreterPortsSpec.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.TestKit.Tests; using FluentAssertions; using Xunit; using Xunit.Abstractions; using Cancel = Akka.Streams.Tests.Implementation.Fusing.GraphInterpreterSpecKit.TestSetup.Cancel; using OnComplete = Akka.Streams.Tests.Implementation.Fusing.GraphInterpreterSpecKit.TestSetup.OnComplete; using OnError = Akka.Streams.Tests.Implementation.Fusing.GraphInterpreterSpecKit.TestSetup.OnError; using OnNext = Akka.Streams.Tests.Implementation.Fusing.GraphInterpreterSpecKit.TestSetup.OnNext; using RequestOne = Akka.Streams.Tests.Implementation.Fusing.GraphInterpreterSpecKit.TestSetup.RequestOne; namespace Akka.Streams.Tests.Implementation.Fusing { public class GraphInterpreterPortsSpec : GraphInterpreterSpecKit { // ReSharper disable InconsistentNaming private PortTestSetup.DownstreamPortProbe<int> inlet; private PortTestSetup.UpstreamPortProbe<int> outlet; private Func<ISet<TestSetup.ITestEvent>> lastEvents; private Action stepAll; private Action step; private Action clearEvents; public GraphInterpreterPortsSpec(ITestOutputHelper output = null) : base(output) { } private void Setup(bool chasing) { var setup = new PortTestSetup(Sys, chasing); inlet = setup.In; outlet = setup.Out; lastEvents = setup.LastEvents; stepAll = setup.StepAll; step = setup.Step; clearEvents = setup.ClearEvents; } // TODO FIXME test failure scenarios [Theory] [InlineData(true)] [InlineData(false)] public void Port_states_should_properly_transition_on_push_and_pull(bool chasing) { Setup(chasing); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(false); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(false); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); inlet.Pull(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(false); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(true); inlet.IsClosed().Should().Be(false); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); stepAll(); lastEvents().Should().BeEquivalentTo(new RequestOne(outlet)); outlet.IsAvailable().Should().Be(true); outlet.IsClosed().Should().Be(false); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(true); inlet.IsClosed().Should().Be(false); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); outlet.Push(0); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(false); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(true); inlet.IsClosed().Should().Be(false); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); stepAll(); lastEvents().Should().BeEquivalentTo(new OnNext(inlet, 0)); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(false); inlet.IsAvailable().Should().Be(true); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(false); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Grab().Should().Be(0); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(false); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(false); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); // Cycle completed } [Theory] [InlineData(true)] [InlineData(false)] public void Port_states_should_drop_ungrabbed_element_on_pull(bool chasing) { Setup(chasing); inlet.Pull(); step(); clearEvents(); outlet.Push(0); step(); lastEvents().Should().BeEquivalentTo(new OnNext(inlet, 0)); inlet.Pull(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); } [Theory] [InlineData(true)] [InlineData(false)] public void Port_states_should_propagate_complete_while_downstream_is_active(bool chasing) { Setup(chasing); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(false); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(false); outlet.Complete(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(false); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); stepAll(); lastEvents().Should().BeEquivalentTo(new OnComplete(inlet)); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); inlet.Cancel(); // This should have no effect now stepAll(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); outlet.Complete(); // This should have no effect now stepAll(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); } [Theory] [InlineData(true)] [InlineData(false)] public void Port_states_should_propagate_complete_while_upstream_is_active(bool chasing) { Setup(chasing); inlet.Pull(); stepAll(); lastEvents().Should().BeEquivalentTo(new RequestOne(outlet)); outlet.IsAvailable().Should().Be(true); outlet.IsClosed().Should().Be(false); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(true); inlet.IsClosed().Should().Be(false); outlet.Complete(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(true); inlet.IsClosed().Should().Be(false); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); stepAll(); lastEvents().Should().BeEquivalentTo(new OnComplete(inlet)); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); inlet.Cancel(); // This should have no effect now stepAll(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); outlet.Complete(); // This should have no effect now stepAll(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); } [Theory] [InlineData(true)] [InlineData(false)] public void Port_states_should_propagate_complete_while_pull_is_in_flight(bool chasing) { Setup(chasing); inlet.Pull(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(false); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(true); inlet.IsClosed().Should().Be(false); outlet.Complete(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(true); inlet.IsClosed().Should().Be(false); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); stepAll(); lastEvents().Should().BeEquivalentTo(new OnComplete(inlet)); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); inlet.Cancel(); // This should have no effect now stepAll(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); outlet.Complete(); // This should have no effect now stepAll(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); } [Theory] [InlineData(true)] [InlineData(false)] public void Port_states_should_propagate_complete_while_push_is_in_flight(bool chasing) { Setup(chasing); inlet.Pull(); stepAll(); clearEvents(); outlet.Push(0); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(false); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(true); inlet.IsClosed().Should().Be(false); outlet.Complete(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(true); inlet.IsClosed().Should().Be(false); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); step(); lastEvents().Should().BeEquivalentTo(new OnNext(inlet, 0)); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(true); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(false); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Grab().Should().Be(0); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); step(); lastEvents().Should().BeEquivalentTo(new OnComplete(inlet)); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); outlet.Complete(); // This should have no effect now stepAll(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); } [Theory] [InlineData(true)] [InlineData(false)] public void Port_states_should_propagate_complete_while_push_is_in_flight_and_keep_ungrabbed_element(bool chasing) { Setup(chasing); inlet.Pull(); stepAll(); clearEvents(); outlet.Push(0); outlet.Complete(); step(); lastEvents().Should().BeEquivalentTo(new OnNext(inlet, 0)); step(); lastEvents().Should().BeEquivalentTo(new OnComplete(inlet)); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(true); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Grab().Should().Be(0); } [Theory] [InlineData(true)] [InlineData(false)] public void Port_states_should_propagate_complete_while_push_is_in_flight_and_pulled_after_the_push(bool chasing) { Setup(chasing); inlet.Pull(); stepAll(); clearEvents(); outlet.Push(0); outlet.Complete(); step(); lastEvents().Should().BeEquivalentTo(new OnNext(inlet, 0)); inlet.Grab().Should().Be(0); inlet.Pull(); stepAll(); lastEvents().Should().BeEquivalentTo(new OnComplete(inlet)); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); } [Theory] [InlineData(true)] [InlineData(false)] public void Port_states_should_ignore_pull_while_completing(bool chasing) { Setup(chasing); outlet.Complete(); inlet.Pull(); // While the pull event is not enqueue at this point, we should still report the state correctly inlet.HasBeenPulled().Should().Be(true); stepAll(); lastEvents().Should().BeEquivalentTo(new OnComplete(inlet)); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); } [Theory] [InlineData(true)] [InlineData(false)] public void Port_states_should_propagate_cancel_while_downstream_is_active(bool chasing) { Setup(chasing); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(false); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(false); inlet.Cancel(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(false); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); stepAll(); lastEvents().Should().BeEquivalentTo(new Cancel(outlet)); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); outlet.Complete(); // This should have no effect now stepAll(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); inlet.Cancel(); // This should have no effect now stepAll(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); } [Theory] [InlineData(true)] [InlineData(false)] public void Port_states_should_propagate_cancel_while_upstream_is_active(bool chasing) { Setup(chasing); inlet.Pull(); stepAll(); lastEvents().Should().BeEquivalentTo(new RequestOne(outlet)); outlet.IsAvailable().Should().Be(true); outlet.IsClosed().Should().Be(false); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(true); inlet.IsClosed().Should().Be(false); inlet.Cancel(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(true); outlet.IsClosed().Should().Be(false); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); stepAll(); lastEvents().Should().BeEquivalentTo(new Cancel(outlet)); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); outlet.Complete(); // This should have no effect now stepAll(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); inlet.Cancel(); // This should have no effect now stepAll(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); } [Theory] [InlineData(true)] [InlineData(false)] public void Port_states_should_propagate_cancel_while_pull_is_in_flight(bool chasing) { Setup(chasing); inlet.Pull(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(false); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(true); inlet.IsClosed().Should().Be(false); inlet.Cancel(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(false); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); stepAll(); lastEvents().Should().BeEquivalentTo(new Cancel(outlet)); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); outlet.Complete(); // This should have no effect now stepAll(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); inlet.Cancel(); // This should have no effect now stepAll(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); } [Theory] [InlineData(true)] [InlineData(false)] public void Port_states_should_propagate_cancel_while_push_is_in_flight(bool chasing) { Setup(chasing); inlet.Pull(); stepAll(); clearEvents(); outlet.Push(0); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(false); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(true); inlet.IsClosed().Should().Be(false); inlet.Cancel(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(false); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); stepAll(); lastEvents().Should().BeEquivalentTo(new Cancel(outlet)); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); outlet.Complete(); // This should have no effect now stepAll(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); inlet.Cancel(); // This should have no effect now stepAll(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); } [Theory] [InlineData(true)] [InlineData(false)] public void Port_states_should_ignore_push_while_cancelling(bool chasing) { Setup(chasing); inlet.Pull(); stepAll(); clearEvents(); inlet.Cancel(); outlet.Push(0); // While the push event is not enqueued at this point, we should still report the state correctly outlet.IsAvailable().Should().Be(false); stepAll(); lastEvents().Should().BeEquivalentTo(new Cancel(outlet)); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); } [Theory] [InlineData(true)] [InlineData(false)] public void Port_states_should_clear_ungrabbed_element_even_when_cancelled(bool chasing) { Setup(chasing); inlet.Pull(); stepAll(); clearEvents(); outlet.Push(0); stepAll(); lastEvents().Should().BeEquivalentTo(new OnNext(inlet, 0)); inlet.Cancel(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(false); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); stepAll(); lastEvents().Should().BeEquivalentTo(new Cancel(outlet)); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); } [Theory] [InlineData(true)] [InlineData(false)] public void Port_states_should_ignore_any_completion_if_they_are_concurrent_cancel_first(bool chasing) { Setup(chasing); inlet.Cancel(); outlet.Complete(); stepAll(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); } [Theory] [InlineData(true)] [InlineData(false)] public void Port_states_should_ignore_any_completion_if_they_are_concurrent_complete_first(bool chasing) { Setup(chasing); outlet.Complete(); inlet.Cancel(); stepAll(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); } [Theory] [InlineData(true)] [InlineData(false)] public void Port_states_should_ignore_completion_from_a_push_complete_if_cancelled_while_in_flight(bool chasing) { Setup(chasing); inlet.Pull(); stepAll(); clearEvents(); outlet.Push(0); outlet.Complete(); inlet.Cancel(); stepAll(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); } [Theory] [InlineData(true)] [InlineData(false)] public void Port_states_should_ignore_completion_from_a_push_complete_if_cancelled_after_OnPush(bool chasing) { Setup(chasing); inlet.Pull(); stepAll(); clearEvents(); outlet.Push(0); outlet.Complete(); step(); lastEvents().Should().BeEquivalentTo(new OnNext(inlet, 0)); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(true); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(false); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Grab().Should().Be(0); inlet.Cancel(); stepAll(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); } [Theory] [InlineData(true)] [InlineData(false)] public void Port_states_should_not_allow_to_grab_element_before_it_arrives(bool chasing) { Setup(chasing); inlet.Pull(); stepAll(); outlet.Push(0); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); } [Theory] [InlineData(true)] [InlineData(false)] public void Port_states_should_not_allow_to_grab_element_if_already_cancelled(bool chasing) { Setup(chasing); inlet.Pull(); stepAll(); outlet.Push(0); inlet.Cancel(); stepAll(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); } [Theory] [InlineData(true)] [InlineData(false)] public void Port_states_should_propagate_failure_while_downstream_is_active(bool chasing) { Setup(chasing); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(false); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(false); outlet.Fail(new TestException("test")); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(false); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); stepAll(); lastEvents().Should().BeEquivalentTo(new OnError(inlet, new TestException("test"))); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); inlet.Cancel(); // This should have no effect now stepAll(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); outlet.Complete(); // This should have no effect now stepAll(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); } [Theory] [InlineData(true)] [InlineData(false)] public void Port_states_should_propagate_failure_while_upstream_is_active(bool chasing) { Setup(chasing); inlet.Pull(); stepAll(); lastEvents().Should().BeEquivalentTo(new RequestOne(outlet)); outlet.IsAvailable().Should().Be(true); outlet.IsClosed().Should().Be(false); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(true); inlet.IsClosed().Should().Be(false); outlet.Fail(new TestException("test")); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(true); inlet.IsClosed().Should().Be(false); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); stepAll(); lastEvents().Should().BeEquivalentTo(new OnError(inlet, new TestException("test"))); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); inlet.Cancel(); // This should have no effect now stepAll(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); outlet.Complete(); // This should have no effect now stepAll(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); } [Theory] [InlineData(true)] [InlineData(false)] public void Port_states_should_propagate_failure_while_pull_is_in_flight(bool chasing) { Setup(chasing); inlet.Pull(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(false); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(true); inlet.IsClosed().Should().Be(false); outlet.Fail(new TestException("test")); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(true); inlet.IsClosed().Should().Be(false); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); stepAll(); lastEvents().Should().BeEquivalentTo(new OnError(inlet, new TestException("test"))); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); inlet.Cancel(); // This should have no effect now stepAll(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); outlet.Complete(); // This should have no effect now stepAll(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); } [Theory] [InlineData(true)] [InlineData(false)] public void Port_states_should_propagate_failure_while_push_is_in_flight(bool chasing) { Setup(chasing); inlet.Pull(); stepAll(); clearEvents(); outlet.Push(0); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(false); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(true); inlet.IsClosed().Should().Be(false); outlet.Fail(new TestException("test")); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(true); inlet.IsClosed().Should().Be(false); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); step(); lastEvents().Should().BeEquivalentTo(new OnNext(inlet, 0)); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(true); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(false); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Grab().Should().Be(0); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); step(); lastEvents().Should().BeEquivalentTo(new OnError(inlet, new TestException("test"))); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); outlet.Complete(); // This should have no effect now stepAll(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); } [Theory] [InlineData(true)] [InlineData(false)] public void Port_states_should_propagate_failure_while_push_is_in_flight_and_keep_ungrabbed_element(bool chasing) { Setup(chasing); inlet.Pull(); stepAll(); clearEvents(); outlet.Push(0); outlet.Fail(new TestException("test")); step(); lastEvents().Should().BeEquivalentTo(new OnNext(inlet, 0)); step(); lastEvents().Should().BeEquivalentTo(new OnError(inlet, new TestException("test"))); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(true); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Grab().Should().Be(0); } [Theory] [InlineData(true)] [InlineData(false)] public void Port_states_should_ignore_pull_while_failing(bool chasing) { Setup(chasing); outlet.Fail(new TestException("test")); inlet.Pull(); inlet.HasBeenPulled().Should().Be(true); stepAll(); lastEvents().Should().BeEquivalentTo(new OnError(inlet, new TestException("test"))); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); } [Theory] [InlineData(true)] [InlineData(false)] public void Port_states_should_ignore_any_failure_completion_if_they_are_concurrent_cancel_first(bool chasing) { Setup(chasing); inlet.Cancel(); outlet.Fail(new TestException("test")); stepAll(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); } [Theory] [InlineData(true)] [InlineData(false)] public void Port_states_should_ignore_any_failure_completion_if_they_are_concurrent_complete_first(bool chasing) { Setup(chasing); outlet.Fail(new TestException("test")); inlet.Cancel(); stepAll(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); } [Theory] [InlineData(true)] [InlineData(false)] public void Port_states_should_ignore_any_failure_from_a_push_then_fail_if_cancelled_while_in_flight(bool chasing) { Setup(chasing); inlet.Pull(); stepAll(); clearEvents(); outlet.Push(0); outlet.Fail(new TestException("test")); inlet.Cancel(); stepAll(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); } [Theory] [InlineData(true)] [InlineData(false)] public void Port_states_should_ignore_any_failure_from_a_push_then_fail_if_cancelled_after_OnPush(bool chasing) { Setup(chasing); inlet.Pull(); stepAll(); clearEvents(); outlet.Push(0); outlet.Fail(new TestException("test")); step(); lastEvents().Should().BeEquivalentTo(new OnNext(inlet, 0)); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(true); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(false); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Grab().Should().Be(0); inlet.Cancel(); stepAll(); lastEvents().Should().BeEmpty(); outlet.IsAvailable().Should().Be(false); outlet.IsClosed().Should().Be(true); inlet.IsAvailable().Should().Be(false); inlet.HasBeenPulled().Should().Be(false); inlet.IsClosed().Should().Be(true); inlet.Invoking(x => x.Pull()).ShouldThrow<ArgumentException>(); outlet.Invoking(x => x.Push(0)).ShouldThrow<ArgumentException>(); inlet.Invoking(x => x.Grab()).ShouldThrow<ArgumentException>(); } } }
namespace _03.TV_Company { using System; using System.Collections.Generic; using System.Text; public class Graph<T> { private readonly HashSet<Node<T>> visited; public Graph() { this.Nodes = new Dictionary<T, Node<T>>(); this.visited = new HashSet<Node<T>>(); } public IDictionary<T, Node<T>> Nodes { get; private set; } public void AddNode(T name) { var node = new Node<T>(name); if (Nodes.ContainsKey(name)) { throw new ArgumentException(string.Format("Node with name {0} is existing in the graph.", name)); } Nodes.Add(name, node); } public void AddNode(Node<T> node) { if (this.Nodes.ContainsKey(node.Name)) { throw new ArgumentException(string.Format("Node with name {0} is existing in the graph.", node.Name)); } this.Nodes.Add(node.Name, node); } public void AddConnection(T fromNode, T toNode, int distance, bool twoWay) { if (!Nodes.ContainsKey(fromNode)) { this.AddNode(fromNode); } if (!Nodes.ContainsKey(toNode)) { this.AddNode(toNode); } Nodes[fromNode].AddConnection(Nodes[toNode], distance, twoWay); } public List<Node<T>> FindShortestDistanceToAllNodes(T startNodeName) { if (!Nodes.ContainsKey(startNodeName)) { throw new ArgumentOutOfRangeException(string.Format("{0} is not containing in the graph.", startNodeName)); } SetShortestDistances(Nodes[startNodeName]); var nodes = new List<Node<T>>(); foreach (var item in Nodes) { if (!item.Key.Equals(startNodeName)) { nodes.Add(item.Value); } } return nodes; } private void SetShortestDistances(Node<T> startNode) { var queue = new PriorityQueue<Node<T>>(); // set to all nodes DijkstraDistance to PositiveInfinity foreach (var node in Nodes) { if (!startNode.Name.Equals(node.Key)) { node.Value.DijkstraDistance = double.PositiveInfinity; //queue.Enqueue(node.Value); } } startNode.DijkstraDistance = 0.0d; queue.Enqueue(startNode); while (queue.Count != 0) { Node<T> currentNode = queue.Dequeue(); if (double.IsPositiveInfinity(currentNode.DijkstraDistance)) { break; } foreach (var neighbour in Nodes[currentNode.Name].Connections) { double subDistance = currentNode.DijkstraDistance + neighbour.Distance; if (subDistance < neighbour.Target.DijkstraDistance) { neighbour.Target.DijkstraDistance = subDistance; queue.Enqueue(neighbour.Target); } } } } public void SetAllDijkstraDistanceValue(double value) { foreach (var node in Nodes) { node.Value.DijkstraDistance = value; } } public double GetSumOfAllDijkstraDistance() { foreach (var item in Nodes) { if (!visited.Contains(item.Value)) { EmployDfs(item.Value); } } double sum = 0; foreach (var node in Nodes) { sum += node.Value.DijkstraDistance; } return sum; } public void EmployDfs(Node<T> node) { visited.Add(node); foreach (var item in node.Connections) { if (!visited.Contains(item.Target)) { EmployDfs(item.Target); } node.DijkstraDistance += item.Target.DijkstraDistance; } if (node.DijkstraDistance == 0) { node.DijkstraDistance++; } } public void EmployBfs(T nodeName) { var nodes = new Queue<Node<T>>(); Node<T> node = Nodes[nodeName]; nodes.Enqueue(node); while (nodes.Count != 0) { Node<T> currentNode = nodes.Dequeue(); currentNode.DijkstraDistance++; foreach (var connection in Nodes[currentNode.Name].Connections) { nodes.Enqueue(connection.Target); } } } public List<Edge<T>> PrimeMinimumSpanningTree(T startNodeName) { if (!Nodes.ContainsKey(startNodeName)) { throw new ArgumentOutOfRangeException(string.Format("{0} is not containing in the graph.", startNodeName)); } var mpdTree = new List<Edge<T>>(); var queue = new PriorityQueue<Edge<T>>(); Node<T> node = Nodes[startNodeName]; foreach (var edge in node.Connections) { queue.Enqueue(edge); } visited.Add(node); while (queue.Count > 0) { Edge<T> edge = queue.Dequeue(); if (!visited.Contains(edge.Target)) { node = edge.Target; visited.Add(node); //we "visit" this node mpdTree.Add(edge); foreach (var item in node.Connections) { if (!mpdTree.Contains(item)) { if (!visited.Contains(item.Target)) { queue.Enqueue(item); } } } } } visited.Clear(); return mpdTree; } public override string ToString() { var result = new StringBuilder(); foreach (var node in this.Nodes) { result.Append("(" + node.Key + ") -> "); foreach (var conection in node.Value.Connections) { result.Append("(" + conection.Target + ") with:" + conection.Distance + " "); } result.AppendLine(); } return result.ToString(); } } }
#region License /* Copyright (c) 2006 Leslie Sanford * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Contact /* * Leslie Sanford * Email: jabberdabber@hotmail.com */ #endregion using System; using System.Collections.Generic; using System.ComponentModel; using Sanford.Multimedia.Timers; namespace Sanford.Multimedia.Midi { /// <summary> /// Generates clock events internally. /// </summary> public class MidiInternalClock : PpqnClock, IComponent { #region MidiInternalClock Members #region Fields // Used for generating tick events. private Timer timer = new Timer(); // Parses meta message tempo change messages. private TempoChangeBuilder builder = new TempoChangeBuilder(); // Tick accumulator. private int ticks = 0; // Indicates whether the clock has been disposed. private bool disposed = false; private ISite site = null; #endregion #region Construction /// <summary> /// Initializes a new instance of the MidiInternalClock class. /// </summary> public MidiInternalClock() : base(Timer.Capabilities.periodMin) { timer.Period = Timer.Capabilities.periodMin; timer.Tick += new EventHandler(HandleTick); } public MidiInternalClock(int timerPeriod) : base(timerPeriod) { timer.Period = timerPeriod; timer.Tick += new EventHandler(HandleTick); } /// <summary> /// Initializes a new instance of the MidiInternalClock class with the /// specified IContainer. /// </summary> /// <param name="container"> /// The IContainer to which the MidiInternalClock will add itself. /// </param> public MidiInternalClock(IContainer container) : base(Timer.Capabilities.periodMin) { /// /// Required for Windows.Forms Class Composition Designer support /// container.Add(this); timer.Period = Timer.Capabilities.periodMin; timer.Tick += new EventHandler(HandleTick); } #endregion #region Methods /// <summary> /// Starts the MidiInternalClock. /// </summary> public void Start() { #region Require if(disposed) { throw new ObjectDisposedException("MidiInternalClock"); } #endregion #region Guard if(running) { return; } #endregion ticks = 0; Reset(); OnStarted(EventArgs.Empty); // Start the multimedia timer in order to start generating ticks. timer.Start(); // Indicate that the clock is now running. running = true; } /// <summary> /// Resumes tick generation from the current position. /// </summary> public void Continue() { #region Require if(disposed) { throw new ObjectDisposedException("MidiInternalClock"); } #endregion #region Guard if(running) { return; } #endregion // Raise Continued event. OnContinued(EventArgs.Empty); // Start multimedia timer in order to start generating ticks. timer.Start(); // Indicate that the clock is now running. running = true; } /// <summary> /// Stops the MidiInternalClock. /// </summary> public void Stop() { #region Require if(disposed) { throw new ObjectDisposedException("MidiInternalClock"); } #endregion #region Guard if(!running) { return; } #endregion // Stop the multimedia timer. timer.Stop(); // Indicate that the clock is not running. running = false; OnStopped(EventArgs.Empty); } public void SetTicks(int ticks) { #region Require if(ticks < 0) { throw new ArgumentOutOfRangeException(); } #endregion if(IsRunning) { Stop(); } this.ticks = ticks; Reset(); } public void Process(MetaMessage message) { #region Require if(message == null) { throw new ArgumentNullException("message"); } #endregion #region Guard if(message.MetaType != MetaType.Tempo) { return; } #endregion TempoChangeBuilder builder = new TempoChangeBuilder(message); // Set the new tempo. Tempo = builder.Tempo; } #region Event Raiser Methods protected virtual void OnDisposed(EventArgs e) { EventHandler handler = Disposed; if(handler != null) { handler(this, e); } } #endregion #region Event Handler Methods // Handles Tick events generated by the multimedia timer. private void HandleTick(object sender, EventArgs e) { int t = GenerateTicks(); for(int i = 0; i < t; i++) { OnTick(EventArgs.Empty); ticks++; } } #endregion #endregion #region Properties /// <summary> /// Gets or sets the tempo in microseconds per beat. /// </summary> public int Tempo { get { #region Require if(disposed) { throw new ObjectDisposedException("MidiInternalClock"); } #endregion return GetTempo(); } set { #region Require if(disposed) { throw new ObjectDisposedException("MidiInternalClock"); } #endregion SetTempo(value); } } public override int Ticks { get { return ticks; } } #endregion #endregion #region IComponent Members public event EventHandler Disposed; public ISite Site { get { return site; } set { site = value; } } #endregion #region IDisposable Members public void Dispose() { #region Guard if(disposed) { return; } #endregion if(running) { // Stop the multimedia timer. timer.Stop(); } disposed = true; timer.Dispose(); GC.SuppressFinalize(this); OnDisposed(EventArgs.Empty); } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using TemplateWebApplication.Areas.HelpPage.ModelDescriptions; using TemplateWebApplication.Areas.HelpPage.Models; namespace TemplateWebApplication.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } if (complexTypeDescription != null) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.Extensions.Primitives; using Microsoft.Net.Http.Headers; namespace Microsoft.AspNetCore.Cors.Infrastructure { /// <summary> /// Default implementation of <see cref="ICorsService"/>. /// </summary> public class CorsService : ICorsService { private readonly CorsOptions _options; private readonly ILogger _logger; /// <summary> /// Creates a new instance of the <see cref="CorsService"/>. /// </summary> /// <param name="options">The option model representing <see cref="CorsOptions"/>.</param> /// <param name="loggerFactory">The <see cref="ILoggerFactory"/>.</param> public CorsService(IOptions<CorsOptions> options, ILoggerFactory loggerFactory) { if (options == null) { throw new ArgumentNullException(nameof(options)); } if (loggerFactory == null) { throw new ArgumentNullException(nameof(loggerFactory)); } _options = options.Value; _logger = loggerFactory.CreateLogger<CorsService>(); } /// <summary> /// Looks up a policy using the <paramref name="policyName"/> and then evaluates the policy using the passed in /// <paramref name="context"/>. /// </summary> /// <param name="context"></param> /// <param name="policyName"></param> /// <returns>A <see cref="CorsResult"/> which contains the result of policy evaluation and can be /// used by the caller to set appropriate response headers.</returns> public CorsResult EvaluatePolicy(HttpContext context, string policyName) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var policy = _options.GetPolicy(policyName); if (policy is null) { throw new InvalidOperationException(Resources.FormatPolicyNotFound(policyName)); } return EvaluatePolicy(context, policy); } /// <inheritdoc /> public CorsResult EvaluatePolicy(HttpContext context, CorsPolicy policy) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (policy == null) { throw new ArgumentNullException(nameof(policy)); } if (policy.AllowAnyOrigin && policy.SupportsCredentials) { throw new ArgumentException(Resources.InsecureConfiguration, nameof(policy)); } var requestHeaders = context.Request.Headers; var origin = requestHeaders.Origin; var isOptionsRequest = HttpMethods.IsOptions(context.Request.Method); var isPreflightRequest = isOptionsRequest && requestHeaders.ContainsKey(CorsConstants.AccessControlRequestMethod); if (isOptionsRequest && !isPreflightRequest) { _logger.IsNotPreflightRequest(); } var corsResult = new CorsResult { IsPreflightRequest = isPreflightRequest, IsOriginAllowed = IsOriginAllowed(policy, origin), }; if (isPreflightRequest) { EvaluatePreflightRequest(context, policy, corsResult); } else { EvaluateRequest(context, policy, corsResult); } return corsResult; } private static void PopulateResult(HttpContext context, CorsPolicy policy, CorsResult result) { var headers = context.Request.Headers; if (policy.AllowAnyOrigin) { result.AllowedOrigin = CorsConstants.AnyOrigin; result.VaryByOrigin = policy.SupportsCredentials; } else { var origin = headers.Origin; result.AllowedOrigin = origin; result.VaryByOrigin = policy.Origins.Count > 1 || !policy.IsDefaultIsOriginAllowed; } result.SupportsCredentials = policy.SupportsCredentials; result.PreflightMaxAge = policy.PreflightMaxAge; // https://fetch.spec.whatwg.org/#http-new-header-syntax AddHeaderValues(result.AllowedExposedHeaders, policy.ExposedHeaders); var allowedMethods = policy.AllowAnyMethod ? new[] { result.IsPreflightRequest ? headers.AccessControlRequestMethod.ToString() : context.Request.Method } : policy.Methods; AddHeaderValues(result.AllowedMethods, allowedMethods); var allowedHeaders = policy.AllowAnyHeader ? headers.GetCommaSeparatedValues(CorsConstants.AccessControlRequestHeaders) : policy.Headers; AddHeaderValues(result.AllowedHeaders, allowedHeaders); } /// <summary> /// Evaluate a request using the specified policy. The result is set on the specified <see cref="CorsResult"/> instance. /// </summary> /// <param name="context">The current HTTP context.</param> /// <param name="policy">The <see cref="CorsPolicy"/> to evaluate.</param> /// <param name="result">The <see cref="CorsResult"/> to set the result on.</param> public virtual void EvaluateRequest(HttpContext context, CorsPolicy policy, CorsResult result) { PopulateResult(context, policy, result); } /// <summary> /// Evaluate a preflight request using the specified policy. The result is set on the specified <see cref="CorsResult"/> instance. /// </summary> /// <param name="context">The current HTTP context.</param> /// <param name="policy">The <see cref="CorsPolicy"/> to evaluate.</param> /// <param name="result">The <see cref="CorsResult"/> to set the result on.</param> public virtual void EvaluatePreflightRequest(HttpContext context, CorsPolicy policy, CorsResult result) { PopulateResult(context, policy, result); } /// <inheritdoc /> public virtual void ApplyResult(CorsResult result, HttpResponse response) { if (result == null) { throw new ArgumentNullException(nameof(result)); } if (response == null) { throw new ArgumentNullException(nameof(response)); } if (!result.IsOriginAllowed) { // In case a server does not wish to participate in the CORS protocol, its HTTP response to the // CORS or CORS-preflight request must not include any of the above headers. return; } var headers = response.Headers; headers.AccessControlAllowOrigin = result.AllowedOrigin; if (result.SupportsCredentials) { headers.AccessControlAllowCredentials = "true"; } if (result.IsPreflightRequest) { _logger.IsPreflightRequest(); // An HTTP response to a CORS-preflight request can include the following headers: // `Access-Control-Allow-Methods`, `Access-Control-Allow-Headers`, `Access-Control-Max-Age` if (result.AllowedHeaders.Count > 0) { headers.SetCommaSeparatedValues(CorsConstants.AccessControlAllowHeaders, result.AllowedHeaders.ToArray()); } if (result.AllowedMethods.Count > 0) { headers.SetCommaSeparatedValues(CorsConstants.AccessControlAllowMethods, result.AllowedMethods.ToArray()); } if (result.PreflightMaxAge.HasValue) { headers.AccessControlMaxAge = result.PreflightMaxAge.Value.TotalSeconds.ToString(CultureInfo.InvariantCulture); } } else { // An HTTP response to a CORS request that is not a CORS-preflight request can also include the following header: // `Access-Control-Expose-Headers` if (result.AllowedExposedHeaders.Count > 0) { headers.SetCommaSeparatedValues(CorsConstants.AccessControlExposeHeaders, result.AllowedExposedHeaders.ToArray()); } } if (result.VaryByOrigin) { headers.Append(HeaderNames.Vary, "Origin"); } } private static void AddHeaderValues(IList<string> target, IList<string> headerValues) { if (headerValues == null) { return; } for (var i = 0; i < headerValues.Count; i++) { target.Add(headerValues[i]); } } private bool IsOriginAllowed(CorsPolicy policy, StringValues origin) { if (StringValues.IsNullOrEmpty(origin)) { _logger.RequestDoesNotHaveOriginHeader(); return false; } var originString = origin.ToString(); _logger.RequestHasOriginHeader(originString); if (policy.AllowAnyOrigin || policy.IsOriginAllowed(originString)) { _logger.PolicySuccess(); return true; } _logger.PolicyFailure(); _logger.OriginNotAllowed(originString); return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // Don't entity encode high chars (160 to 256) #define ENTITY_ENCODE_HIGH_ASCII_CHARS using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Text; namespace System.Net { public static class WebUtility { // some consts copied from Char / CharUnicodeInfo since we don't have friend access to those types private const char HIGH_SURROGATE_START = '\uD800'; private const char LOW_SURROGATE_START = '\uDC00'; private const char LOW_SURROGATE_END = '\uDFFF'; private const int UNICODE_PLANE00_END = 0x00FFFF; private const int UNICODE_PLANE01_START = 0x10000; private const int UNICODE_PLANE16_END = 0x10FFFF; private const int UnicodeReplacementChar = '\uFFFD'; #region HtmlEncode / HtmlDecode methods private static readonly char[] s_htmlEntityEndingChars = new char[] { ';', '&' }; public static string HtmlEncode(string value) { if (String.IsNullOrEmpty(value)) { return value; } // Don't create StringBuilder if we don't have anything to encode int index = IndexOfHtmlEncodingChars(value, 0); if (index == -1) { return value; } StringBuilder sb = StringBuilderCache.Acquire(value.Length); HtmlEncode(value, index, sb); return StringBuilderCache.GetStringAndRelease(sb); } private static unsafe void HtmlEncode(string value, int index, StringBuilder output) { Debug.Assert(output != null); Debug.Assert(0 <= index && index <= value.Length, "0 <= index && index <= value.Length"); int cch = value.Length - index; fixed (char* str = value) { char* pch = str; while (index-- > 0) { output.Append(*pch++); } for (; cch > 0; cch--, pch++) { char ch = *pch; if (ch <= '>') { switch (ch) { case '<': output.Append("&lt;"); break; case '>': output.Append("&gt;"); break; case '"': output.Append("&quot;"); break; case '\'': output.Append("&#39;"); break; case '&': output.Append("&amp;"); break; default: output.Append(ch); break; } } else { int valueToEncode = -1; // set to >= 0 if needs to be encoded #if ENTITY_ENCODE_HIGH_ASCII_CHARS if (ch >= 160 && ch < 256) { // The seemingly arbitrary 160 comes from RFC valueToEncode = ch; } else #endif // ENTITY_ENCODE_HIGH_ASCII_CHARS if (Char.IsSurrogate(ch)) { int scalarValue = GetNextUnicodeScalarValueFromUtf16Surrogate(ref pch, ref cch); if (scalarValue >= UNICODE_PLANE01_START) { valueToEncode = scalarValue; } else { // Don't encode BMP characters (like U+FFFD) since they wouldn't have // been encoded if explicitly present in the string anyway. ch = (char)scalarValue; } } if (valueToEncode >= 0) { // value needs to be encoded output.Append("&#"); output.Append(valueToEncode.ToString(CultureInfo.InvariantCulture)); output.Append(';'); } else { // write out the character directly output.Append(ch); } } } } } public static string HtmlDecode(string value) { if (String.IsNullOrEmpty(value)) { return value; } // Don't create StringBuilder if we don't have anything to encode if (!StringRequiresHtmlDecoding(value)) { return value; } StringBuilder sb = StringBuilderCache.Acquire(value.Length); HtmlDecode(value, sb); return StringBuilderCache.GetStringAndRelease(sb); } [SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "System.UInt16.TryParse(System.String,System.Globalization.NumberStyles,System.IFormatProvider,System.UInt16@)", Justification = "UInt16.TryParse guarantees that result is zero if the parse fails.")] private static void HtmlDecode(string value, StringBuilder output) { Debug.Assert(output != null); int l = value.Length; for (int i = 0; i < l; i++) { char ch = value[i]; if (ch == '&') { // We found a '&'. Now look for the next ';' or '&'. The idea is that // if we find another '&' before finding a ';', then this is not an entity, // and the next '&' might start a real entity (VSWhidbey 275184) int index = value.IndexOfAny(s_htmlEntityEndingChars, i + 1); if (index > 0 && value[index] == ';') { string entity = value.Substring(i + 1, index - i - 1); if (entity.Length > 1 && entity[0] == '#') { // The # syntax can be in decimal or hex, e.g. // &#229; --> decimal // &#xE5; --> same char in hex // See http://www.w3.org/TR/REC-html40/charset.html#entities bool parsedSuccessfully; uint parsedValue; if (entity[1] == 'x' || entity[1] == 'X') { parsedSuccessfully = UInt32.TryParse(entity.Substring(2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out parsedValue); } else { parsedSuccessfully = UInt32.TryParse(entity.Substring(1), NumberStyles.Integer, CultureInfo.InvariantCulture, out parsedValue); } if (parsedSuccessfully) { // decoded character must be U+0000 .. U+10FFFF, excluding surrogates parsedSuccessfully = ((parsedValue < HIGH_SURROGATE_START) || (LOW_SURROGATE_END < parsedValue && parsedValue <= UNICODE_PLANE16_END)); } if (parsedSuccessfully) { if (parsedValue <= UNICODE_PLANE00_END) { // single character output.Append((char)parsedValue); } else { // multi-character char leadingSurrogate, trailingSurrogate; ConvertSmpToUtf16(parsedValue, out leadingSurrogate, out trailingSurrogate); output.Append(leadingSurrogate); output.Append(trailingSurrogate); } i = index; // already looked at everything until semicolon continue; } } else { i = index; // already looked at everything until semicolon char entityChar = HtmlEntities.Lookup(entity); if (entityChar != (char)0) { ch = entityChar; } else { output.Append('&'); output.Append(entity); output.Append(';'); continue; } } } } output.Append(ch); } } private static unsafe int IndexOfHtmlEncodingChars(string s, int startPos) { Debug.Assert(0 <= startPos && startPos <= s.Length, "0 <= startPos && startPos <= s.Length"); int cch = s.Length - startPos; fixed (char* str = s) { for (char* pch = &str[startPos]; cch > 0; pch++, cch--) { char ch = *pch; if (ch <= '>') { switch (ch) { case '<': case '>': case '"': case '\'': case '&': return s.Length - cch; } } #if ENTITY_ENCODE_HIGH_ASCII_CHARS else if (ch >= 160 && ch < 256) { return s.Length - cch; } #endif // ENTITY_ENCODE_HIGH_ASCII_CHARS else if (Char.IsSurrogate(ch)) { return s.Length - cch; } } } return -1; } #endregion #region UrlEncode implementation // *** Source: alm/tfs_core/Framework/Common/UriUtility/HttpUtility.cs // This specific code was copied from above ASP.NET codebase. private static byte[] UrlEncode(byte[] bytes, int offset, int count, bool alwaysCreateNewReturnValue) { byte[] encoded = UrlEncode(bytes, offset, count); return (alwaysCreateNewReturnValue && (encoded != null) && (encoded == bytes)) ? (byte[])encoded.Clone() : encoded; } private static byte[] UrlEncode(byte[] bytes, int offset, int count) { if (!ValidateUrlEncodingParameters(bytes, offset, count)) { return null; } int cSpaces = 0; int cUnsafe = 0; // count them first for (int i = 0; i < count; i++) { char ch = (char)bytes[offset + i]; if (ch == ' ') cSpaces++; else if (!IsUrlSafeChar(ch)) cUnsafe++; } // nothing to expand? if (cSpaces == 0 && cUnsafe == 0) return bytes; // expand not 'safe' characters into %XX, spaces to +s byte[] expandedBytes = new byte[count + cUnsafe * 2]; int pos = 0; for (int i = 0; i < count; i++) { byte b = bytes[offset + i]; char ch = (char)b; if (IsUrlSafeChar(ch)) { expandedBytes[pos++] = b; } else if (ch == ' ') { expandedBytes[pos++] = (byte)'+'; } else { expandedBytes[pos++] = (byte)'%'; expandedBytes[pos++] = (byte)IntToHex((b >> 4) & 0xf); expandedBytes[pos++] = (byte)IntToHex(b & 0x0f); } } return expandedBytes; } #endregion #region UrlEncode public methods [SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings", Justification = "Already shipped public API; code moved here as part of API consolidation")] public static string UrlEncode(string value) { if (value == null) return null; byte[] bytes = Encoding.UTF8.GetBytes(value); byte[] encodedBytes = UrlEncode(bytes, 0, bytes.Length, false /* alwaysCreateNewReturnValue */); return Encoding.UTF8.GetString(encodedBytes, 0, encodedBytes.Length); } public static byte[] UrlEncodeToBytes(byte[] value, int offset, int count) { return UrlEncode(value, offset, count, true /* alwaysCreateNewReturnValue */); } #endregion #region UrlDecode implementation // *** Source: alm/tfs_core/Framework/Common/UriUtility/HttpUtility.cs // This specific code was copied from above ASP.NET codebase. // Changes done - Removed the logic to handle %Uxxxx as it is not standards compliant. private static string UrlDecodeInternal(string value, Encoding encoding) { if (value == null) { return null; } int count = value.Length; UrlDecoder helper = new UrlDecoder(count, encoding); // go through the string's chars collapsing %XX and // appending each char as char, with exception of %XX constructs // that are appended as bytes for (int pos = 0; pos < count; pos++) { char ch = value[pos]; if (ch == '+') { ch = ' '; } else if (ch == '%' && pos < count - 2) { int h1 = HexToInt(value[pos + 1]); int h2 = HexToInt(value[pos + 2]); if (h1 >= 0 && h2 >= 0) { // valid 2 hex chars byte b = (byte)((h1 << 4) | h2); pos += 2; // don't add as char helper.AddByte(b); continue; } } if ((ch & 0xFF80) == 0) helper.AddByte((byte)ch); // 7 bit have to go as bytes because of Unicode else helper.AddChar(ch); } return helper.GetString(); } private static byte[] UrlDecodeInternal(byte[] bytes, int offset, int count) { if (!ValidateUrlEncodingParameters(bytes, offset, count)) { return null; } int decodedBytesCount = 0; byte[] decodedBytes = new byte[count]; for (int i = 0; i < count; i++) { int pos = offset + i; byte b = bytes[pos]; if (b == '+') { b = (byte)' '; } else if (b == '%' && i < count - 2) { int h1 = HexToInt((char)bytes[pos + 1]); int h2 = HexToInt((char)bytes[pos + 2]); if (h1 >= 0 && h2 >= 0) { // valid 2 hex chars b = (byte)((h1 << 4) | h2); i += 2; } } decodedBytes[decodedBytesCount++] = b; } if (decodedBytesCount < decodedBytes.Length) { Array.Resize(ref decodedBytes, decodedBytesCount); } return decodedBytes; } #endregion #region UrlDecode public methods [SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings", Justification = "Already shipped public API; code moved here as part of API consolidation")] public static string UrlDecode(string encodedValue) { return UrlDecodeInternal(encodedValue, Encoding.UTF8); } public static byte[] UrlDecodeToBytes(byte[] encodedValue, int offset, int count) { return UrlDecodeInternal(encodedValue, offset, count); } #endregion #region Helper methods // similar to Char.ConvertFromUtf32, but doesn't check arguments or generate strings // input is assumed to be an SMP character private static void ConvertSmpToUtf16(uint smpChar, out char leadingSurrogate, out char trailingSurrogate) { Debug.Assert(UNICODE_PLANE01_START <= smpChar && smpChar <= UNICODE_PLANE16_END); int utf32 = (int)(smpChar - UNICODE_PLANE01_START); leadingSurrogate = (char)((utf32 / 0x400) + HIGH_SURROGATE_START); trailingSurrogate = (char)((utf32 % 0x400) + LOW_SURROGATE_START); } private static unsafe int GetNextUnicodeScalarValueFromUtf16Surrogate(ref char* pch, ref int charsRemaining) { // invariants Debug.Assert(charsRemaining >= 1); Debug.Assert(Char.IsSurrogate(*pch)); if (charsRemaining <= 1) { // not enough characters remaining to resurrect the original scalar value return UnicodeReplacementChar; } char leadingSurrogate = pch[0]; char trailingSurrogate = pch[1]; if (Char.IsSurrogatePair(leadingSurrogate, trailingSurrogate)) { // we're going to consume an extra char pch++; charsRemaining--; // below code is from Char.ConvertToUtf32, but without the checks (since we just performed them) return (((leadingSurrogate - HIGH_SURROGATE_START) * 0x400) + (trailingSurrogate - LOW_SURROGATE_START) + UNICODE_PLANE01_START); } else { // unmatched surrogate return UnicodeReplacementChar; } } private static int HexToInt(char h) { return (h >= '0' && h <= '9') ? h - '0' : (h >= 'a' && h <= 'f') ? h - 'a' + 10 : (h >= 'A' && h <= 'F') ? h - 'A' + 10 : -1; } private static char IntToHex(int n) { Debug.Assert(n < 0x10); if (n <= 9) return (char)(n + (int)'0'); else return (char)(n - 10 + (int)'A'); } // Set of safe chars, from RFC 1738.4 minus '+' private static bool IsUrlSafeChar(char ch) { if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9') return true; switch (ch) { case '-': case '_': case '.': case '!': case '*': case '(': case ')': return true; } return false; } private static bool ValidateUrlEncodingParameters(byte[] bytes, int offset, int count) { if (bytes == null && count == 0) return false; if (bytes == null) { throw new ArgumentNullException("bytes"); } if (offset < 0 || offset > bytes.Length) { throw new ArgumentOutOfRangeException("offset"); } if (count < 0 || offset + count > bytes.Length) { throw new ArgumentOutOfRangeException("count"); } return true; } private static bool StringRequiresHtmlDecoding(string s) { // this string requires html decoding if it contains '&' or a surrogate character for (int i = 0; i < s.Length; i++) { char c = s[i]; if (c == '&' || Char.IsSurrogate(c)) { return true; } } return false; } #endregion #region UrlDecoder nested class // *** Source: alm/tfs_core/Framework/Common/UriUtility/HttpUtility.cs // This specific code was copied from above ASP.NET codebase. // Internal class to facilitate URL decoding -- keeps char buffer and byte buffer, allows appending of either chars or bytes private class UrlDecoder { private int _bufferSize; // Accumulate characters in a special array private int _numChars; private char[] _charBuffer; // Accumulate bytes for decoding into characters in a special array private int _numBytes; private byte[] _byteBuffer; // Encoding to convert chars to bytes private Encoding _encoding; private void FlushBytes() { if (_numBytes > 0) { _numChars += _encoding.GetChars(_byteBuffer, 0, _numBytes, _charBuffer, _numChars); _numBytes = 0; } } internal UrlDecoder(int bufferSize, Encoding encoding) { _bufferSize = bufferSize; _encoding = encoding; _charBuffer = new char[bufferSize]; // byte buffer created on demand } internal void AddChar(char ch) { if (_numBytes > 0) FlushBytes(); _charBuffer[_numChars++] = ch; } internal void AddByte(byte b) { if (_byteBuffer == null) _byteBuffer = new byte[_bufferSize]; _byteBuffer[_numBytes++] = b; } internal String GetString() { if (_numBytes > 0) FlushBytes(); if (_numChars > 0) return new String(_charBuffer, 0, _numChars); else return String.Empty; } } #endregion #region HtmlEntities nested class // helper class for lookup of HTML encoding entities private static class HtmlEntities { // The list is from http://www.w3.org/TR/REC-html40/sgml/entities.html, except for &apos;, which // is defined in http://www.w3.org/TR/2008/REC-xml-20081126/#sec-predefined-ent. private static String[] s_entitiesList = new String[] { "\x0022-quot", "\x0026-amp", "\x0027-apos", "\x003c-lt", "\x003e-gt", "\x00a0-nbsp", "\x00a1-iexcl", "\x00a2-cent", "\x00a3-pound", "\x00a4-curren", "\x00a5-yen", "\x00a6-brvbar", "\x00a7-sect", "\x00a8-uml", "\x00a9-copy", "\x00aa-ordf", "\x00ab-laquo", "\x00ac-not", "\x00ad-shy", "\x00ae-reg", "\x00af-macr", "\x00b0-deg", "\x00b1-plusmn", "\x00b2-sup2", "\x00b3-sup3", "\x00b4-acute", "\x00b5-micro", "\x00b6-para", "\x00b7-middot", "\x00b8-cedil", "\x00b9-sup1", "\x00ba-ordm", "\x00bb-raquo", "\x00bc-frac14", "\x00bd-frac12", "\x00be-frac34", "\x00bf-iquest", "\x00c0-Agrave", "\x00c1-Aacute", "\x00c2-Acirc", "\x00c3-Atilde", "\x00c4-Auml", "\x00c5-Aring", "\x00c6-AElig", "\x00c7-Ccedil", "\x00c8-Egrave", "\x00c9-Eacute", "\x00ca-Ecirc", "\x00cb-Euml", "\x00cc-Igrave", "\x00cd-Iacute", "\x00ce-Icirc", "\x00cf-Iuml", "\x00d0-ETH", "\x00d1-Ntilde", "\x00d2-Ograve", "\x00d3-Oacute", "\x00d4-Ocirc", "\x00d5-Otilde", "\x00d6-Ouml", "\x00d7-times", "\x00d8-Oslash", "\x00d9-Ugrave", "\x00da-Uacute", "\x00db-Ucirc", "\x00dc-Uuml", "\x00dd-Yacute", "\x00de-THORN", "\x00df-szlig", "\x00e0-agrave", "\x00e1-aacute", "\x00e2-acirc", "\x00e3-atilde", "\x00e4-auml", "\x00e5-aring", "\x00e6-aelig", "\x00e7-ccedil", "\x00e8-egrave", "\x00e9-eacute", "\x00ea-ecirc", "\x00eb-euml", "\x00ec-igrave", "\x00ed-iacute", "\x00ee-icirc", "\x00ef-iuml", "\x00f0-eth", "\x00f1-ntilde", "\x00f2-ograve", "\x00f3-oacute", "\x00f4-ocirc", "\x00f5-otilde", "\x00f6-ouml", "\x00f7-divide", "\x00f8-oslash", "\x00f9-ugrave", "\x00fa-uacute", "\x00fb-ucirc", "\x00fc-uuml", "\x00fd-yacute", "\x00fe-thorn", "\x00ff-yuml", "\x0152-OElig", "\x0153-oelig", "\x0160-Scaron", "\x0161-scaron", "\x0178-Yuml", "\x0192-fnof", "\x02c6-circ", "\x02dc-tilde", "\x0391-Alpha", "\x0392-Beta", "\x0393-Gamma", "\x0394-Delta", "\x0395-Epsilon", "\x0396-Zeta", "\x0397-Eta", "\x0398-Theta", "\x0399-Iota", "\x039a-Kappa", "\x039b-Lambda", "\x039c-Mu", "\x039d-Nu", "\x039e-Xi", "\x039f-Omicron", "\x03a0-Pi", "\x03a1-Rho", "\x03a3-Sigma", "\x03a4-Tau", "\x03a5-Upsilon", "\x03a6-Phi", "\x03a7-Chi", "\x03a8-Psi", "\x03a9-Omega", "\x03b1-alpha", "\x03b2-beta", "\x03b3-gamma", "\x03b4-delta", "\x03b5-epsilon", "\x03b6-zeta", "\x03b7-eta", "\x03b8-theta", "\x03b9-iota", "\x03ba-kappa", "\x03bb-lambda", "\x03bc-mu", "\x03bd-nu", "\x03be-xi", "\x03bf-omicron", "\x03c0-pi", "\x03c1-rho", "\x03c2-sigmaf", "\x03c3-sigma", "\x03c4-tau", "\x03c5-upsilon", "\x03c6-phi", "\x03c7-chi", "\x03c8-psi", "\x03c9-omega", "\x03d1-thetasym", "\x03d2-upsih", "\x03d6-piv", "\x2002-ensp", "\x2003-emsp", "\x2009-thinsp", "\x200c-zwnj", "\x200d-zwj", "\x200e-lrm", "\x200f-rlm", "\x2013-ndash", "\x2014-mdash", "\x2018-lsquo", "\x2019-rsquo", "\x201a-sbquo", "\x201c-ldquo", "\x201d-rdquo", "\x201e-bdquo", "\x2020-dagger", "\x2021-Dagger", "\x2022-bull", "\x2026-hellip", "\x2030-permil", "\x2032-prime", "\x2033-Prime", "\x2039-lsaquo", "\x203a-rsaquo", "\x203e-oline", "\x2044-frasl", "\x20ac-euro", "\x2111-image", "\x2118-weierp", "\x211c-real", "\x2122-trade", "\x2135-alefsym", "\x2190-larr", "\x2191-uarr", "\x2192-rarr", "\x2193-darr", "\x2194-harr", "\x21b5-crarr", "\x21d0-lArr", "\x21d1-uArr", "\x21d2-rArr", "\x21d3-dArr", "\x21d4-hArr", "\x2200-forall", "\x2202-part", "\x2203-exist", "\x2205-empty", "\x2207-nabla", "\x2208-isin", "\x2209-notin", "\x220b-ni", "\x220f-prod", "\x2211-sum", "\x2212-minus", "\x2217-lowast", "\x221a-radic", "\x221d-prop", "\x221e-infin", "\x2220-ang", "\x2227-and", "\x2228-or", "\x2229-cap", "\x222a-cup", "\x222b-int", "\x2234-there4", "\x223c-sim", "\x2245-cong", "\x2248-asymp", "\x2260-ne", "\x2261-equiv", "\x2264-le", "\x2265-ge", "\x2282-sub", "\x2283-sup", "\x2284-nsub", "\x2286-sube", "\x2287-supe", "\x2295-oplus", "\x2297-otimes", "\x22a5-perp", "\x22c5-sdot", "\x2308-lceil", "\x2309-rceil", "\x230a-lfloor", "\x230b-rfloor", "\x2329-lang", "\x232a-rang", "\x25ca-loz", "\x2660-spades", "\x2663-clubs", "\x2665-hearts", "\x2666-diams", }; private static LowLevelDictionary<string, char> s_lookupTable = GenerateLookupTable(); private static LowLevelDictionary<string, char> GenerateLookupTable() { // e[0] is unicode char, e[1] is '-', e[2+] is entity string LowLevelDictionary<string, char> lookupTable = new LowLevelDictionary<string, char>(StringComparer.Ordinal); foreach (string e in s_entitiesList) { lookupTable.Add(e.Substring(2), e[0]); } return lookupTable; } public static char Lookup(string entity) { char theChar; s_lookupTable.TryGetValue(entity, out theChar); return theChar; } } #endregion } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // namespace DiscUtils.Iscsi { using System; using System.Collections.Generic; using System.Globalization; /// <summary> /// The known classes of SCSI device. /// </summary> public enum LunClass { /// <summary> /// Device is block storage (i.e. normal disk). /// </summary> BlockStorage = 0x00, /// <summary> /// Device is sequential access storage. /// </summary> TapeStorage = 0x01, /// <summary> /// Device is a printer. /// </summary> Printer = 0x02, /// <summary> /// Device is a SCSI processor. /// </summary> Processor = 0x03, /// <summary> /// Device is write-once storage. /// </summary> WriteOnceStorage = 0x04, /// <summary> /// Device is a CD/DVD drive. /// </summary> OpticalDisc = 0x05, /// <summary> /// Device is a scanner (obsolete). /// </summary> Scanner = 0x06, /// <summary> /// Device is optical memory (some optical discs). /// </summary> OpticalMemory = 0x07, /// <summary> /// Device is a media changer device. /// </summary> Jukebox = 0x08, /// <summary> /// Communications device (obsolete). /// </summary> Communications = 0x09, /// <summary> /// Device is a Storage Array (e.g. RAID). /// </summary> StorageArray = 0x0C, /// <summary> /// Device is Enclosure Services. /// </summary> EnclosureServices = 0x0D, /// <summary> /// Device is a simplified block device. /// </summary> SimplifiedDirectAccess = 0x0E, /// <summary> /// Device is an optical card reader/writer device. /// </summary> OpticalCard = 0x0F, /// <summary> /// Device is a Bridge Controller. /// </summary> BridgeController = 0x10, /// <summary> /// Device is an object-based storage device. /// </summary> ObjectBasedStorage = 0x11, /// <summary> /// Device is an Automation/Drive interface. /// </summary> AutomationDriveInterface = 0x12, /// <summary> /// Device is a Security Manager. /// </summary> SecurityManager = 0x13, /// <summary> /// Device is a well-known device, as defined by SCSI specifications. /// </summary> WellKnown = 0x1E, /// <summary> /// Unknown LUN class. /// </summary> Unknown = 0xFF } /// <summary> /// Provides information about an iSCSI LUN. /// </summary> public class LunInfo { private TargetInfo _targetInfo; private long _lun; private LunClass _deviceType; private bool _removable; private string _vendorId; private string _productId; private string _productRevision; internal LunInfo(TargetInfo targetInfo, long lun, LunClass type, bool removable, string vendor, string product, string revision) { _targetInfo = targetInfo; _lun = lun; _deviceType = type; _removable = removable; _vendorId = vendor; _productId = product; _productRevision = revision; } /// <summary> /// Gets info about the target hosting this LUN. /// </summary> public TargetInfo Target { get { return _targetInfo; } } /// <summary> /// Gets the Logical Unit Number of this device. /// </summary> public long Lun { get { return _lun; } } /// <summary> /// Gets the type (or class) of this device. /// </summary> public LunClass DeviceType { get { return _deviceType; } } /// <summary> /// Gets a value indicating whether this Lun has removable media. /// </summary> public bool Removable { get { return _removable; } } /// <summary> /// Gets the vendor id (registered name) for this device. /// </summary> public string VendorId { get { return _vendorId; } } /// <summary> /// Gets the product id (name) for this device. /// </summary> public string ProductId { get { return _productId; } } /// <summary> /// Gets the product revision for this device. /// </summary> public string ProductRevision { get { return _productRevision; } } /// <summary> /// Parses a URI referring to a LUN. /// </summary> /// <param name="uri">The URI to parse.</param> /// <returns>The LUN info.</returns> /// <remarks> /// Note the LUN info is incomplete, only as much of the information as is encoded /// into the URL is available. /// </remarks> public static LunInfo ParseUri(string uri) { return ParseUri(new Uri(uri)); } /// <summary> /// Parses a URI referring to a LUN. /// </summary> /// <param name="uri">The URI to parse.</param> /// <returns>The LUN info.</returns> /// <remarks> /// Note the LUN info is incomplete, only as much of the information as is encoded /// into the URL is available. /// </remarks> public static LunInfo ParseUri(Uri uri) { string address; int port; string targetGroupTag = string.Empty; string targetName = string.Empty; ulong lun = 0; if (uri.Scheme != "iscsi") { ThrowInvalidURI(uri.OriginalString); } address = uri.Host; port = uri.Port; if (uri.Port == -1) { port = TargetAddress.DefaultPort; } string[] uriSegments = uri.Segments; if (uriSegments.Length == 2) { targetName = uriSegments[1].Replace("/", string.Empty); } else if (uriSegments.Length == 3) { targetGroupTag = uriSegments[1].Replace("/", string.Empty); targetName = uriSegments[2].Replace("/", string.Empty); } else { ThrowInvalidURI(uri.OriginalString); } TargetInfo targetInfo = new TargetInfo(targetName, new TargetAddress[] { new TargetAddress(address, port, targetGroupTag) }); foreach (var queryElem in uri.Query.Substring(1).Split('&')) { if (queryElem.StartsWith("LUN=", StringComparison.OrdinalIgnoreCase)) { lun = ulong.Parse(queryElem.Substring(4), CultureInfo.InvariantCulture); if (lun < 256) { lun = lun << (6 * 8); } } } return new LunInfo(targetInfo, (long)lun, LunClass.Unknown, false, string.Empty, string.Empty, string.Empty); } /// <summary> /// Gets the LUN as a string. /// </summary> /// <returns>The LUN in string form.</returns> public override string ToString() { if ((((ulong)_lun) & 0xFF00000000000000) == 0) { return (_lun >> (6 * 8)).ToString(CultureInfo.InvariantCulture); } else { return _lun.ToString(CultureInfo.InvariantCulture); } } /// <summary> /// Gets the URIs corresponding to this LUN. /// </summary> /// <returns>An array of URIs as strings.</returns> /// <remarks>Multiple URIs are returned because multiple targets may serve the same LUN.</remarks> public string[] GetUris() { List<string> results = new List<string>(); foreach (var targetAddress in _targetInfo.Addresses) { results.Add(targetAddress.ToUri().ToString() + "/" + _targetInfo.Name + "?LUN=" + ToString()); } return results.ToArray(); } private static void ThrowInvalidURI(string uri) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Not a valid iSCSI URI: {0}", uri), "uri"); } } }
using UnityEngine; using System.Collections; /// <summary> /// A direction used to describe the surface of terrain. /// </summary> public enum Ferr2DT_TerrainDirection { Top = 0, Left = 1, Right = 2, Bottom = 3, None = 100 } /// <summary> /// Describes a terrain segment, and how it should be drawn. /// </summary> [System.Serializable] public class Ferr2DT_SegmentDescription { /// <summary> /// Applies only to terrain segments facing this direction. /// </summary> public Ferr2DT_TerrainDirection applyTo; /// <summary> /// Z Offset, for counteracting depth issues. /// </summary> public float zOffset; /// <summary> /// Just in case you want to adjust the height of the segment /// </summary> public float yOffset; /// <summary> /// UV coordinates for the left ending cap. /// </summary> public Rect leftCap; /// <summary> /// UV coordinates for the right ending cap. /// </summary> public Rect rightCap; /// <summary> /// A list of body UVs to randomly pick from. /// </summary> public Rect[] body; /// <summary> /// How much should the end of the path slide to make room for the caps? (Unity units) /// </summary> public float capOffset = 0f; public Ferr2DT_SegmentDescription() { body = new Rect[] { new Rect(0,0,50,50) }; applyTo = Ferr2DT_TerrainDirection.Top; } public Ferr_JSONValue ToJSON () { Ferr_JSONValue json = new Ferr_JSONValue(); json["applyTo" ] = (int)applyTo; json["zOffset" ] = zOffset; json["yOffset" ] = yOffset; json["capOffset" ] = capOffset; json["leftCap.x" ] = leftCap.x; json["leftCap.y" ] = leftCap.y; json["leftCap.xMax" ] = leftCap.xMax; json["leftCap.yMax" ] = leftCap.yMax; json["rightCap.x" ] = rightCap.x; json["rightCap.y" ] = rightCap.y; json["rightCap.xMax"] = rightCap.xMax; json["rightCap.yMax"] = rightCap.yMax; json["body"] = 0; Ferr_JSONValue bodyArr = json["body"]; for (int i = 0; i < body.Length; i++) { Ferr_JSONValue rect = new Ferr_JSONValue(); rect["x" ] = body[i].x; rect["y" ] = body[i].y; rect["xMax"] = body[i].xMax; rect["yMax"] = body[i].yMax; bodyArr[i] = rect; } return json; } public void FromJSON(Ferr_JSONValue aJSON) { Ferr_JSONValue json = new Ferr_JSONValue(); applyTo = (Ferr2DT_TerrainDirection)aJSON["applyTo", (int)Ferr2DT_TerrainDirection.Top]; zOffset = aJSON["zOffset",0f]; yOffset = aJSON["yOffset",0f]; capOffset = aJSON["capOffset",0f]; leftCap = new Rect( aJSON["leftCap.x", 0f], aJSON["leftCap.y", 0f], aJSON["leftCap.xMax", 0f], aJSON["leftCap.yMax", 0f]); rightCap = new Rect( aJSON["rightCap.x", 0f], aJSON["rightCap.y", 0f], aJSON["rightCap.xMax", 0f], aJSON["rightCap.yMax", 0f]); Ferr_JSONValue bodyArr = json["body"]; body = new Rect[bodyArr.Length]; for (int i = 0; i < body.Length; i++) { body[i] = new Rect( bodyArr[i]["x", 0 ], bodyArr[i]["y", 0 ], bodyArr[i]["xMax", 50], bodyArr[i]["yMax", 50]); } } } /// <summary> /// Describes a material that can be applied to a Ferr2DT_PathTerrain /// </summary> public class Ferr2DT_TerrainMaterial : MonoBehaviour { #region Fields /// <summary> /// The material of the interior of the terrain. /// </summary> public Material fillMaterial; /// <summary> /// The material of the edges of the terrain. /// </summary> public Material edgeMaterial; /// <summary> /// These describe all four edge options, how the top, left, right, and bottom edges should be drawn. /// </summary> [SerializeField] private Ferr2DT_SegmentDescription[] descriptors = new Ferr2DT_SegmentDescription[4]; [SerializeField] private bool isPixel = true; #endregion #region Constructor public Ferr2DT_TerrainMaterial() { for (int i = 0; i < descriptors.Length; i++) { descriptors[i] = new Ferr2DT_SegmentDescription(); } } #endregion #region Methods /// <summary> /// Creates a JSON string from this TerrainMaterial, edgeMaterial and fillMaterial are stored by name only. /// </summary> /// <returns>JSON Value object, can put it into a larger JSON object, or just ToString it.</returns> public Ferr_JSONValue ToJSON () { Ferr_JSONValue json = new Ferr_JSONValue(); json["fillMaterialName"] = fillMaterial.name; json["edgeMaterialName"] = edgeMaterial.name; json["descriptors" ] = 0; Ferr_JSONValue descArr = json["descriptors"]; for (int i = 0; i < descriptors.Length; i++) { descArr[i] = descriptors[i].ToJSON(); } return json; } /// <summary> /// Creates a TerrainMaterial from a JSON string, does -not- link edgeMaterial or fillMaterial, you'll have to do that yourself! /// </summary> /// <param name="aJSON">A JSON string, gets parsed and sent to FromJSON(Ferr_JSONValue)</param> public void FromJSON(string aJSON) { FromJSON(Ferr_JSON.Parse(aJSON)); } /// <summary> /// Creates a TerrainMaterial from a JSON object, does -not- link edgeMaterial or fillMaterial, you'll have to do that yourself! /// </summary> /// <param name="aJSON">A parsed JSON value</param> public void FromJSON(Ferr_JSONValue aJSON) { Ferr_JSONValue descArr = aJSON["descriptors"]; for (int i = 0; i < descArr.Length; i++) { descriptors[i] = new Ferr2DT_SegmentDescription(); descriptors[i].FromJSON(descArr[i]); } } /// <summary> /// Gets the edge descriptor for the given edge, defaults to the Top, if none by that type exists, or an empty one, if none are defined at all. /// </summary> /// <param name="aDirection">Direction to get.</param> /// <returns>The given direction, or the first direction, or a default, based on what actually exists.</returns> public Ferr2DT_SegmentDescription GetDescriptor(Ferr2DT_TerrainDirection aDirection) { ConvertToPercentage(); for (int i = 0; i < descriptors.Length; i++) { if (descriptors[i].applyTo == aDirection) return descriptors[i]; } if (descriptors.Length > 0) { return descriptors[0]; } return new Ferr2DT_SegmentDescription(); } /// <summary> /// Finds out if we actually have a descriptor for the given direction /// </summary> /// <param name="aDirection">Duh.</param> /// <returns>is it there, or is it not?</returns> public bool Has (Ferr2DT_TerrainDirection aDirection) { for (int i = 0; i < descriptors.Length; i++) { if (descriptors[i].applyTo == aDirection) return true; } return false; } /// <summary> /// Sets a particular direction as having a valid descriptor. Or not. That's a bool. /// </summary> /// <param name="aDirection">The direction!</param> /// <param name="aActive">To active, or not to active? That is the question!</param> public void Set (Ferr2DT_TerrainDirection aDirection, bool aActive) { if (aActive) { if (descriptors[(int)aDirection].applyTo != aDirection) { descriptors[(int)aDirection] = new Ferr2DT_SegmentDescription(); descriptors[(int)aDirection].applyTo = aDirection; } } else if (descriptors[(int)aDirection].applyTo != Ferr2DT_TerrainDirection.Top) { descriptors[(int)aDirection] = new Ferr2DT_SegmentDescription(); } } /// <summary> /// Converts our internal pixel UV coordinates to UV values Unity will recognize. /// </summary> /// <param name="aNativeRect">A UV rect, using pixels.</param> /// <returns>A UV rect using Unity coordinates.</returns> public Rect ToUV (Rect aNativeRect) { if (edgeMaterial == null) return aNativeRect; return new Rect( aNativeRect.x , (1.0f - aNativeRect.height) - aNativeRect.y, aNativeRect.width, aNativeRect.height); } /// <summary> /// Converts our internal pixel UV coordinates to UV values we can use on the screen! As 0-1. /// </summary> /// <param name="aNativeRect">A UV rect, using pixels.</param> /// <returns>A UV rect using standard UV coordinates.</returns> public Rect ToScreen(Rect aNativeRect) { if (edgeMaterial == null) return aNativeRect; return aNativeRect; } public Rect GetLCap (Ferr2DT_TerrainDirection aDirection) { return GetDescriptor(aDirection).leftCap; } public Rect GetRCap (Ferr2DT_TerrainDirection aDirection) { return GetDescriptor(aDirection).rightCap; } public Rect GetBody (Ferr2DT_TerrainDirection aDirection, int aBodyID) { return GetDescriptor(aDirection).body[aBodyID]; } public int GetBodyCount(Ferr2DT_TerrainDirection aDirection) { return GetDescriptor(aDirection).body.Length; } private void ConvertToPercentage() { if (isPixel) { for (int i = 0; i < descriptors.Length; i++) { for (int t = 0; t < descriptors[i].body.Length; t++) { descriptors[i].body[t] = ToNative(descriptors[i].body[t]); } descriptors[i].leftCap = ToNative(descriptors[i].leftCap ); descriptors[i].rightCap = ToNative(descriptors[i].rightCap); } isPixel = false; } } public Rect ToNative(Rect aPixelRect) { if (edgeMaterial == null) return aPixelRect; return new Rect( aPixelRect.x / edgeMaterial.mainTexture.width, aPixelRect.y / edgeMaterial.mainTexture.height, aPixelRect.width / edgeMaterial.mainTexture.width, aPixelRect.height / edgeMaterial.mainTexture.height); } public Rect ToPixels(Rect aNativeRect) { if (edgeMaterial == null) return aNativeRect; return new Rect( aNativeRect.x * edgeMaterial.mainTexture.width, aNativeRect.y * edgeMaterial.mainTexture.height, aNativeRect.width * edgeMaterial.mainTexture.width, aNativeRect.height * edgeMaterial.mainTexture.height); } #endregion }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Xml.Schema; using System.Xml.Xsl.Qil; using System.Xml.Xsl.Runtime; namespace System.Xml.Xsl.XPath { using T = XmlQueryTypeFactory; internal class XPathQilFactory : QilPatternFactory { public XPathQilFactory(QilFactory f, bool debug) : base(f, debug) { } // Helper methods used in addition to QilPatternFactory's ones public QilNode Error(string res, QilNode args) { return Error(InvokeFormatMessage(String(res), args)); } public QilNode Error(ISourceLineInfo lineInfo, string res, params string[] args) { return Error(String(XslLoadException.CreateMessage(lineInfo, res, args))); } public QilIterator FirstNode(QilNode n) { CheckNodeSet(n); QilIterator i = For(DocOrderDistinct(n)); return For(Filter(i, Eq(PositionOf(i), Int32(1)))); } public bool IsAnyType(QilNode n) { XmlQueryType xt = n.XmlType; bool result = !(xt.IsStrict || xt.IsNode); Debug.Assert(result == (xt.TypeCode == XmlTypeCode.Item || xt.TypeCode == XmlTypeCode.AnyAtomicType), "What else can it be?"); return result; } [Conditional("DEBUG")] public void CheckAny(QilNode n) { Debug.Assert(n != null && IsAnyType(n), "Must be of 'any' type"); } [Conditional("DEBUG")] public void CheckNode(QilNode n) { Debug.Assert(n != null && n.XmlType.IsSingleton && n.XmlType.IsNode, "Must be a singleton node"); } [Conditional("DEBUG")] public void CheckNodeSet(QilNode n) { Debug.Assert(n != null && n.XmlType.IsNode, "Must be a node-set"); } [Conditional("DEBUG")] public void CheckNodeNotRtf(QilNode n) { Debug.Assert(n != null && n.XmlType.IsSingleton && n.XmlType.IsNode && n.XmlType.IsNotRtf, "Must be a singleton node and not an Rtf"); } [Conditional("DEBUG")] public void CheckString(QilNode n) { Debug.Assert(n != null && n.XmlType.IsSubtypeOf(T.StringX), "Must be a singleton string"); } [Conditional("DEBUG")] public void CheckStringS(QilNode n) { Debug.Assert(n != null && n.XmlType.IsSubtypeOf(T.StringXS), "Must be a sequence of strings"); } [Conditional("DEBUG")] public void CheckDouble(QilNode n) { Debug.Assert(n != null && n.XmlType.IsSubtypeOf(T.DoubleX), "Must be a singleton Double"); } [Conditional("DEBUG")] public void CheckBool(QilNode n) { Debug.Assert(n != null && n.XmlType.IsSubtypeOf(T.BooleanX), "Must be a singleton Bool"); } // Return true if inferred type of the given expression is never a subtype of T.NodeS public bool CannotBeNodeSet(QilNode n) { XmlQueryType xt = n.XmlType; // Do not report compile error if n is a VarPar, whose inferred type forbids nodes (SQLBUDT 339398) return xt.IsAtomicValue && !xt.IsEmpty && !(n is QilIterator); } public QilNode SafeDocOrderDistinct(QilNode n) { XmlQueryType xt = n.XmlType; if (xt.MaybeMany) { if (xt.IsNode && xt.IsNotRtf) { // node-set return DocOrderDistinct(n); } else if (!xt.IsAtomicValue) { QilIterator i; return Loop(i = Let(n), Conditional(Gt(Length(i), Int32(1)), DocOrderDistinct(TypeAssert(i, T.NodeNotRtfS)), i ) ); } } return n; } public QilNode InvokeFormatMessage(QilNode res, QilNode args) { CheckString(res); CheckStringS(args); return XsltInvokeEarlyBound(QName("format-message"), XsltMethods.FormatMessage, T.StringX, new QilNode[] { res, args } ); } #region Comparisons public QilNode InvokeEqualityOperator(QilNodeType op, QilNode left, QilNode right) { Debug.Assert(op == QilNodeType.Eq || op == QilNodeType.Ne); double opCode; left = TypeAssert(left, T.ItemS); right = TypeAssert(right, T.ItemS); switch (op) { case QilNodeType.Eq: opCode = (double)XsltLibrary.ComparisonOperator.Eq; break; default: opCode = (double)XsltLibrary.ComparisonOperator.Ne; break; } return XsltInvokeEarlyBound(QName("EqualityOperator"), XsltMethods.EqualityOperator, T.BooleanX, new QilNode[] { Double(opCode), left, right } ); } public QilNode InvokeRelationalOperator(QilNodeType op, QilNode left, QilNode right) { Debug.Assert(op == QilNodeType.Lt || op == QilNodeType.Le || op == QilNodeType.Gt || op == QilNodeType.Ge); double opCode; left = TypeAssert(left, T.ItemS); right = TypeAssert(right, T.ItemS); switch (op) { case QilNodeType.Lt: opCode = (double)XsltLibrary.ComparisonOperator.Lt; break; case QilNodeType.Le: opCode = (double)XsltLibrary.ComparisonOperator.Le; break; case QilNodeType.Gt: opCode = (double)XsltLibrary.ComparisonOperator.Gt; break; default: opCode = (double)XsltLibrary.ComparisonOperator.Ge; break; } return XsltInvokeEarlyBound(QName("RelationalOperator"), XsltMethods.RelationalOperator, T.BooleanX, new QilNode[] { Double(opCode), left, right } ); } #endregion #region Type Conversions [Conditional("DEBUG")] private void ExpectAny(QilNode n) { Debug.Assert(IsAnyType(n), "Unexpected expression type: " + n.XmlType.ToString()); } public QilNode ConvertToType(XmlTypeCode requiredType, QilNode n) { switch (requiredType) { case XmlTypeCode.String: return ConvertToString(n); case XmlTypeCode.Double: return ConvertToNumber(n); case XmlTypeCode.Boolean: return ConvertToBoolean(n); case XmlTypeCode.Node: return EnsureNodeSet(n); case XmlTypeCode.Item: return n; default: Debug.Fail("Unexpected XmlTypeCode: " + requiredType); return null; } } // XPath spec $4.2, string() public QilNode ConvertToString(QilNode n) { switch (n.XmlType.TypeCode) { case XmlTypeCode.Boolean: return ( n.NodeType == QilNodeType.True ? (QilNode)String("true") : n.NodeType == QilNodeType.False ? (QilNode)String("false") : /*default: */ (QilNode)Conditional(n, String("true"), String("false")) ); case XmlTypeCode.Double: return (n.NodeType == QilNodeType.LiteralDouble ? (QilNode)String(XPathConvert.DoubleToString((double)(QilLiteral)n)) : (QilNode)XsltConvert(n, T.StringX) ); case XmlTypeCode.String: return n; default: if (n.XmlType.IsNode) { return XPathNodeValue(SafeDocOrderDistinct(n)); } ExpectAny(n); return XsltConvert(n, T.StringX); } } // XPath spec $4.3, boolean() public QilNode ConvertToBoolean(QilNode n) { switch (n.XmlType.TypeCode) { case XmlTypeCode.Boolean: return n; case XmlTypeCode.Double: // (x < 0 || 0 < x) == (x != 0) && !Double.IsNaN(x) QilIterator i; return (n.NodeType == QilNodeType.LiteralDouble ? Boolean((double)(QilLiteral)n < 0 || 0 < (double)(QilLiteral)n) : Loop(i = Let(n), Or(Lt(i, Double(0)), Lt(Double(0), i))) ); case XmlTypeCode.String: return (n.NodeType == QilNodeType.LiteralString ? Boolean(((string)(QilLiteral)n).Length != 0) : Ne(StrLength(n), Int32(0)) ); default: if (n.XmlType.IsNode) { return Not(IsEmpty(n)); } ExpectAny(n); return XsltConvert(n, T.BooleanX); } } // XPath spec $4.4, number() public QilNode ConvertToNumber(QilNode n) { switch (n.XmlType.TypeCode) { case XmlTypeCode.Boolean: return ( n.NodeType == QilNodeType.True ? (QilNode)Double(1) : n.NodeType == QilNodeType.False ? (QilNode)Double(0) : /*default: */ (QilNode)Conditional(n, Double(1), Double(0)) ); case XmlTypeCode.Double: return n; case XmlTypeCode.String: return XsltConvert(n, T.DoubleX); default: if (n.XmlType.IsNode) { return XsltConvert(XPathNodeValue(SafeDocOrderDistinct(n)), T.DoubleX); } ExpectAny(n); return XsltConvert(n, T.DoubleX); } } public QilNode ConvertToNode(QilNode n) { if (n.XmlType.IsNode && n.XmlType.IsNotRtf && n.XmlType.IsSingleton) { return n; } return XsltConvert(n, T.NodeNotRtf); } public QilNode ConvertToNodeSet(QilNode n) { if (n.XmlType.IsNode && n.XmlType.IsNotRtf) { return n; } return XsltConvert(n, T.NodeNotRtfS); } // Returns null if the given expression is never a node-set public QilNode TryEnsureNodeSet(QilNode n) { if (n.XmlType.IsNode && n.XmlType.IsNotRtf) { return n; } if (CannotBeNodeSet(n)) { return null; } // Ensure it is not an Rtf at runtime return InvokeEnsureNodeSet(n); } // Throws an exception if the given expression is never a node-set public QilNode EnsureNodeSet(QilNode n) { QilNode result = TryEnsureNodeSet(n); if (result == null) { throw new XPathCompileException(SR.XPath_NodeSetExpected); } return result; } public QilNode InvokeEnsureNodeSet(QilNode n) { return XsltInvokeEarlyBound(QName("ensure-node-set"), XsltMethods.EnsureNodeSet, T.NodeSDod, new QilNode[] { n } ); } #endregion #region Other XPath Functions public QilNode Id(QilNode context, QilNode id) { CheckNodeNotRtf(context); if (id.XmlType.IsSingleton) { return Deref(context, ConvertToString(id)); } QilIterator i; return Loop(i = For(id), Deref(context, ConvertToString(i))); } public QilNode InvokeStartsWith(QilNode str1, QilNode str2) { CheckString(str1); CheckString(str2); return XsltInvokeEarlyBound(QName("starts-with"), XsltMethods.StartsWith, T.BooleanX, new QilNode[] { str1, str2 } ); } public QilNode InvokeContains(QilNode str1, QilNode str2) { CheckString(str1); CheckString(str2); return XsltInvokeEarlyBound(QName("contains"), XsltMethods.Contains, T.BooleanX, new QilNode[] { str1, str2 } ); } public QilNode InvokeSubstringBefore(QilNode str1, QilNode str2) { CheckString(str1); CheckString(str2); return XsltInvokeEarlyBound(QName("substring-before"), XsltMethods.SubstringBefore, T.StringX, new QilNode[] { str1, str2 } ); } public QilNode InvokeSubstringAfter(QilNode str1, QilNode str2) { CheckString(str1); CheckString(str2); return XsltInvokeEarlyBound(QName("substring-after"), XsltMethods.SubstringAfter, T.StringX, new QilNode[] { str1, str2 } ); } public QilNode InvokeSubstring(QilNode str, QilNode start) { CheckString(str); CheckDouble(start); return XsltInvokeEarlyBound(QName("substring"), XsltMethods.Substring2, T.StringX, new QilNode[] { str, start } ); } public QilNode InvokeSubstring(QilNode str, QilNode start, QilNode length) { CheckString(str); CheckDouble(start); CheckDouble(length); return XsltInvokeEarlyBound(QName("substring"), XsltMethods.Substring3, T.StringX, new QilNode[] { str, start, length } ); } public QilNode InvokeNormalizeSpace(QilNode str) { CheckString(str); return XsltInvokeEarlyBound(QName("normalize-space"), XsltMethods.NormalizeSpace, T.StringX, new QilNode[] { str } ); } public QilNode InvokeTranslate(QilNode str1, QilNode str2, QilNode str3) { CheckString(str1); CheckString(str2); CheckString(str3); return XsltInvokeEarlyBound(QName("translate"), XsltMethods.Translate, T.StringX, new QilNode[] { str1, str2, str3 } ); } public QilNode InvokeLang(QilNode lang, QilNode context) { CheckString(lang); CheckNodeNotRtf(context); return XsltInvokeEarlyBound(QName("lang"), XsltMethods.Lang, T.BooleanX, new QilNode[] { lang, context } ); } public QilNode InvokeFloor(QilNode value) { CheckDouble(value); return XsltInvokeEarlyBound(QName("floor"), XsltMethods.Floor, T.DoubleX, new QilNode[] { value } ); } public QilNode InvokeCeiling(QilNode value) { CheckDouble(value); return XsltInvokeEarlyBound(QName("ceiling"), XsltMethods.Ceiling, T.DoubleX, new QilNode[] { value } ); } public QilNode InvokeRound(QilNode value) { CheckDouble(value); return XsltInvokeEarlyBound(QName("round"), XsltMethods.Round, T.DoubleX, new QilNode[] { value } ); } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using AIEditor.Gui; using FlatRedBall; using FlatRedBall.AI.Pathfinding; using FlatRedBall.Graphics; using FlatRedBall.Gui; using FlatRedBall.Input; using FlatRedBall.Math; using FlatRedBall.Math.Geometry; using EditorObjects; #if FRB_MDX using Microsoft.DirectX; #else using Vector3 = Microsoft.Xna.Framework.Vector3; using Keys = Microsoft.Xna.Framework.Input.Keys; #endif namespace AIEditor { #region Enums public enum EditingState { None, CreatingLink } #endregion public class EditingLogic { #region Fields private EditingState mEditingState = EditingState.None; private PositionedNode mNodeOver; private Link mLinkOver; private PositionedNode mLinkOverParent; private PositionedNode mNodeGrabbed; private List<PositionedNode> mCurrentNodes = new List<PositionedNode>(); private ReadOnlyCollection<PositionedNode> mCurrentNodesReadOnly; private PositionedNode mCurrentLinkParent; private Link mCurrentLink; private Line mNewConnectionLine; private PathDisplay mPathDisplay = new PathDisplay(); private PositionedObjectList<Text> mDistanceDisplay = new PositionedObjectList<Text>(); Text mDebugText; ReactiveHud mReactiveHud; #endregion #region Properties public ReadOnlyCollection<PositionedNode> CurrentNodes { get { return mCurrentNodesReadOnly; } } public Link CurrentLink { get { return mCurrentLink; } } public PositionedNode CurrentLinkParent { get { return mCurrentLinkParent; } } public PositionedNode NodeOver { get { return mNodeOver; } } public Link LinkOver { get { return mLinkOver; } } public PositionedNode LinkOverParent { get { return mLinkOverParent; } } #endregion #region Methods #region Constructor public EditingLogic() { mNewConnectionLine = new Line(); mCurrentNodesReadOnly = new ReadOnlyCollection<PositionedNode>(mCurrentNodes); mDebugText = TextManager.AddText(""); mReactiveHud = new ReactiveHud(); } #endregion #region Public Methods public void ClearPath() { mPathDisplay.ClearPath(); } public void CopyCurrentPositionedNodes() { foreach (PositionedNode node in mCurrentNodes) { PositionedNode newNode = EditorData.NodeNetwork.AddNode(); newNode.Position = node.Position; EditorData.NodeNetwork.Visible = true; EditorData.NodeNetwork.UpdateShapes(); } } public void SelectNode(PositionedNode nodeToSelect) { #region Finding path between two nodes if (GuiData.ToolsWindow.IsFindPathToNodeButtonPressed && mCurrentNodes.Count != 0 && nodeToSelect != null) { // The button should come back up GuiData.ToolsWindow.IsFindPathToNodeButtonPressed = false; List<PositionedNode> positionedNodes = EditorData.NodeNetwork.GetPath(mCurrentNodes[0], nodeToSelect); mPathDisplay.ShowPath(positionedNodes); if (positionedNodes.Count == 0) { GuiManager.ShowMessageBox("The two nodes are not connected by links.", "Not Connected"); } } #endregion #region else, simply selecting node else { mCurrentNodes.Clear(); if (nodeToSelect != null) { mCurrentNodes.Add(nodeToSelect); } } #endregion } void SelectLink(Link linkToSelect, PositionedNode linkParent) { mCurrentLink = linkToSelect; mCurrentLinkParent = linkParent; } public void Update() { if (GuiManager.DominantWindowActive == false) { //mDebugText.DisplayText = UndoManager.Instructions.Count.ToString(); ; Cursor cursor = GuiManager.Cursor; GuiData.Update(); PerformKeyboardShortcuts(); EditorObjects.CameraMethods.MouseCameraControl(SpriteManager.Camera); PerformCommandUIUpdate(); mReactiveHud.Activity(); #region Update the CommandDisplay if (mCurrentNodes.Count != 0) { GuiData.CommandDisplay.Visible = true; GuiData.CommandDisplay.Position = mCurrentNodes[0].Position; } else { GuiData.CommandDisplay.Visible = false; } #endregion CursorLogic(cursor); UndoManager.EndOfFrameActivity(); } } private void CursorLogic(Cursor cursor) { GetObjectsOver(); #region Create link or move objects with cursor // Don't do any logic if the cursor is over a window if (cursor.WindowOver == null && GuiData.CommandDisplay.IsCursorOverThis != true) { // mNodeOver is used in the following methods: switch (mEditingState) { case EditingState.CreatingLink: CreatingLinkUpdate(); break; case EditingState.None: CursorControlOverObjects(); break; } } #endregion } private void GetObjectsOver() { mNodeOver = GetNodeOver(); if (mNodeOver != null) { mLinkOver = null; mLinkOverParent = null; } else { GetLinkOver(ref mLinkOver, ref mLinkOverParent); } } #endregion #region Private Methods private void CursorControlOverObjects() { Cursor cursor = GuiManager.Cursor; #region Pushing selects and grabs a Node or link if (cursor.PrimaryPush) { #region Check for nodes mNodeGrabbed = mNodeOver; cursor.SetObjectRelativePosition(mNodeGrabbed); SelectNode(mNodeGrabbed); #endregion #region Check for links if (mCurrentNodes.Count == 0) { SelectLink(mLinkOver, mLinkOverParent); } #endregion } #endregion #region Holding the button down can be used to adjust node properties if (cursor.PrimaryDown) { PerformDraggingUpdate(); } #endregion #region Clicking (releasing) the mouse lets go of grabbed Polygons if (cursor.PrimaryClick) { mNodeGrabbed = null; cursor.StaticPosition = false; cursor.ObjectGrabbed = null; TextManager.RemoveText(mDistanceDisplay); } #endregion } private void CreatingLinkUpdate() { Cursor cursor = GuiManager.Cursor; if (cursor.PrimaryClick) { // The user clicked, so see if the cursor is over a PositionedNode PositionedNode nodeOver = mNodeOver; if (nodeOver != null && nodeOver != mCurrentNodes[0] && mCurrentNodes[0].IsLinkedTo(nodeOver) == false) { mCurrentNodes[0].LinkTo(nodeOver, (mCurrentNodes[0].Position - nodeOver.Position).Length() ); } } if (cursor.PrimaryDown == false) { // If the user's mouse is not down then go back to normal editing mode mNewConnectionLine.Visible = false; mEditingState = EditingState.None; return; } else { mNewConnectionLine.Visible = true; mNewConnectionLine.RelativePoint1.X = mNewConnectionLine.RelativePoint1.Y = 0; mNewConnectionLine.Position = mCurrentNodes[0].Position; mNewConnectionLine.RelativePoint2.X = cursor.WorldXAt(0) - mNewConnectionLine.Position.X; mNewConnectionLine.RelativePoint2.Y = cursor.WorldYAt(0) - mNewConnectionLine.Position.Y; } } private PositionedNode GetNodeOver() { Cursor cursor = GuiManager.Cursor; float worldX; float worldY; if (EditorData.NodeNetwork.Nodes.Count != 0) { // While GetVisibleNodeRadius lets us get the radius for any node, for now we'll just // assume that all nodes are on the same Z plane. If this changes later, move the // GetVisibleNodeRadius call down into the loop where the nodeRadius variable is used. float nodeRadius = EditorData.NodeNetwork.GetVisibleNodeRadius(SpriteManager.Camera, 0); for(int i = 0; i < EditorData.NodeNetwork.Nodes.Count; i++) { PositionedNode node = EditorData.NodeNetwork.Nodes[i]; worldX = cursor.WorldXAt(node.Z); worldY = cursor.WorldYAt(node.Z); if ((node.X - worldX) * (node.X - worldX) + (node.Y - worldY) * (node.Y - worldY) < nodeRadius*nodeRadius) { return node; } } } return null; } private void GetLinkOver(ref Link linkOver, ref PositionedNode linkOverParent) { Cursor cursor = GuiManager.Cursor; float worldX; float worldY; if (EditorData.NodeNetwork.Nodes.Count != 0) { float tolerance = 5 / SpriteManager.Camera.PixelsPerUnitAt(0); for (int i = 0; i < EditorData.NodeNetwork.Nodes.Count; i++) { PositionedNode node = EditorData.NodeNetwork.Nodes[i]; worldX = cursor.WorldXAt(node.Z); worldY = cursor.WorldYAt(node.Z); for (int linkIndex = 0; linkIndex < node.Links.Count; linkIndex++) { Segment segment = new Segment( node.Position, node.Links[linkIndex].NodeLinkingTo.Position); float distance = segment.DistanceTo(worldX, worldY); if (distance < tolerance) { linkOverParent = node; linkOver = node.Links[linkIndex]; return; } } } } linkOverParent = null; linkOver = null; } private void PerformCommandUIUpdate() { Cursor cursor = GuiManager.Cursor; if (cursor.WindowOver != null || mCurrentNodes.Count == 0) return; if (cursor.PrimaryPush) { if (GuiData.CommandDisplay.IsCursorOverCreateLinkIcon) { mEditingState = EditingState.CreatingLink; } } } private void PerformDraggingUpdate() { Cursor cursor = GuiManager.Cursor; if (mNodeGrabbed != null) { if (GuiData.ToolsWindow.IsMoveButtonPressed) { PositionedObjectMover.MouseMoveObject(mNodeGrabbed); foreach (Link link in mNodeGrabbed.Links) { link.Cost = (mNodeGrabbed.Position - link.NodeLinkingTo.Position).Length(); // Currently links are two-way, so make sure that the cost is updated both ways PositionedNode nodeLinkedTo = link.NodeLinkingTo; foreach (Link otherLink in nodeLinkedTo.Links) { if (otherLink.NodeLinkingTo == mNodeGrabbed) { otherLink.Cost = link.Cost; } } } UpdateDistanceDisplay(); EditorData.NodeNetwork.UpdateShapes(); } } } private void PerformKeyboardShortcuts() { if (InputManager.Keyboard.KeyPushedConsideringInputReceiver(Keys.Delete)) { #region Delete Nodes if (mCurrentNodes.Count != 0) { for (int i = 0; i < mCurrentNodes.Count; i++) { EditorData.NodeNetwork.Remove(mCurrentNodes[i]); } EditorData.NodeNetwork.UpdateShapes(); SelectNode(null); } #endregion #region Delete Links if (mCurrentLink != null) { PositionedNode firstNode = mCurrentLinkParent; PositionedNode otherNode = mCurrentLink.NodeLinkingTo; firstNode.BreakLinkBetween(otherNode); EditorData.NodeNetwork.UpdateShapes(); SelectLink(null, null); } #endregion } } private void UpdateDistanceDisplay() { int numberOfLinks = mNodeGrabbed.Links.Count; while (mDistanceDisplay.Count < numberOfLinks) { mDistanceDisplay.Add(TextManager.AddText("")); } for (int i = 0; i < numberOfLinks; i++) { #if FRB_MDX mDistanceDisplay[i].Position = Vector3.Scale(( mNodeGrabbed.Position + mNodeGrabbed.Links[i].NodeLinkingTo.Position ), .5f); #else mDistanceDisplay[i].Position = (mNodeGrabbed.Position + mNodeGrabbed.Links[i].NodeLinkingTo.Position) * .5f; #endif mDistanceDisplay[i].DisplayText = (mNodeGrabbed.Position - mNodeGrabbed.Links[i].NodeLinkingTo.Position).Length().ToString(); } } #endregion #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using System; using System.IO; using System.Text; using System.Xml.XPath; using System.Xml.Schema; using System.Diagnostics; using System.Collections.Generic; using System.Globalization; using System.Runtime.Versioning; namespace System.Xml { // Represents a writer that provides fast non-cached forward-only way of generating XML streams containing XML documents // that conform to the W3C Extensible Markup Language (XML) 1.0 specification and the Namespaces in XML specification. public abstract partial class XmlWriter : IDisposable { // Write methods // Writes out the XML declaration with the version "1.0". public virtual Task WriteStartDocumentAsync() { throw new NotImplementedException(); } //Writes out the XML declaration with the version "1.0" and the speficied standalone attribute. public virtual Task WriteStartDocumentAsync(bool standalone) { throw new NotImplementedException(); } //Closes any open elements or attributes and puts the writer back in the Start state. public virtual Task WriteEndDocumentAsync() { throw new NotImplementedException(); } // Writes out the DOCTYPE declaration with the specified name and optional attributes. public virtual Task WriteDocTypeAsync(string name, string pubid, string sysid, string subset) { throw new NotImplementedException(); } // Writes out the specified start tag and associates it with the given namespace and prefix. public virtual Task WriteStartElementAsync(string prefix, string localName, string ns) { throw new NotImplementedException(); } // Closes one element and pops the corresponding namespace scope. public virtual Task WriteEndElementAsync() { throw new NotImplementedException(); } // Closes one element and pops the corresponding namespace scope. Writes out a full end element tag, e.g. </element>. public virtual Task WriteFullEndElementAsync() { throw new NotImplementedException(); } // Writes out the attribute with the specified LocalName, value, and NamespaceURI. // Writes out the attribute with the specified prefix, LocalName, NamespaceURI and value. public Task WriteAttributeStringAsync(string prefix, string localName, string ns, string value) { Task task = WriteStartAttributeAsync(prefix, localName, ns); if (task.IsSuccess()) { return WriteStringAsync(value).CallTaskFuncWhenFinishAsync(thisRef => thisRef.WriteEndAttributeAsync(), this); } else { return WriteAttributeStringAsyncHelper(task, value); } } private async Task WriteAttributeStringAsyncHelper(Task task, string value) { await task.ConfigureAwait(false); await WriteStringAsync(value).ConfigureAwait(false); await WriteEndAttributeAsync().ConfigureAwait(false); } // Writes the start of an attribute. protected internal virtual Task WriteStartAttributeAsync(string prefix, string localName, string ns) { throw new NotImplementedException(); } // Closes the attribute opened by WriteStartAttribute call. protected internal virtual Task WriteEndAttributeAsync() { throw new NotImplementedException(); } // Writes out a <![CDATA[...]]>; block containing the specified text. public virtual Task WriteCDataAsync(string text) { throw new NotImplementedException(); } // Writes out a comment <!--...-->; containing the specified text. public virtual Task WriteCommentAsync(string text) { throw new NotImplementedException(); } // Writes out a processing instruction with a space between the name and text as follows: <?name text?> public virtual Task WriteProcessingInstructionAsync(string name, string text) { throw new NotImplementedException(); } // Writes out an entity reference as follows: "&"+name+";". public virtual Task WriteEntityRefAsync(string name) { throw new NotImplementedException(); } // Forces the generation of a character entity for the specified Unicode character value. public virtual Task WriteCharEntityAsync(char ch) { throw new NotImplementedException(); } // Writes out the given whitespace. public virtual Task WriteWhitespaceAsync(string ws) { throw new NotImplementedException(); } // Writes out the specified text content. public virtual Task WriteStringAsync(string text) { throw new NotImplementedException(); } // Write out the given surrogate pair as an entity reference. public virtual Task WriteSurrogateCharEntityAsync(char lowChar, char highChar) { throw new NotImplementedException(); } // Writes out the specified text content. public virtual Task WriteCharsAsync(char[] buffer, int index, int count) { throw new NotImplementedException(); } // Writes raw markup from the given character buffer. public virtual Task WriteRawAsync(char[] buffer, int index, int count) { throw new NotImplementedException(); } // Writes raw markup from the given string. public virtual Task WriteRawAsync(string data) { throw new NotImplementedException(); } // Encodes the specified binary bytes as base64 and writes out the resulting text. public virtual Task WriteBase64Async(byte[] buffer, int index, int count) { throw new NotImplementedException(); } // Encodes the specified binary bytes as binhex and writes out the resulting text. public virtual Task WriteBinHexAsync(byte[] buffer, int index, int count) { return BinHexEncoder.EncodeAsync(buffer, index, count, this); } // Flushes data that is in the internal buffers into the underlying streams/TextReader and flushes the stream/TextReader. public virtual Task FlushAsync() { throw new NotImplementedException(); } // Scalar Value Methods // Writes out the specified name, ensuring it is a valid NmToken according to the XML specification // (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name). public virtual Task WriteNmTokenAsync(string name) { if (name == null || name.Length == 0) { throw new ArgumentException(SR.Xml_EmptyName); } return WriteStringAsync(XmlConvert.VerifyNMTOKEN(name, ExceptionType.ArgumentException)); } // Writes out the specified name, ensuring it is a valid Name according to the XML specification // (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name). public virtual Task WriteNameAsync(string name) { return WriteStringAsync(XmlConvert.VerifyQName(name, ExceptionType.ArgumentException)); } // Writes out the specified namespace-qualified name by looking up the prefix that is in scope for the given namespace. public virtual async Task WriteQualifiedNameAsync(string localName, string ns) { if (ns != null && ns.Length > 0) { string prefix = LookupPrefix(ns); if (prefix == null) { throw new ArgumentException(SR.Format(SR.Xml_UndefNamespace, ns)); } await WriteStringAsync(prefix).ConfigureAwait(false); await WriteStringAsync(":").ConfigureAwait(false); } await WriteStringAsync(localName).ConfigureAwait(false); } // XmlReader Helper Methods // Writes out all the attributes found at the current position in the specified XmlReader. public virtual async Task WriteAttributesAsync(XmlReader reader, bool defattr) { if (null == reader) { throw new ArgumentNullException(nameof(reader)); } if (reader.NodeType == XmlNodeType.Element || reader.NodeType == XmlNodeType.XmlDeclaration) { if (reader.MoveToFirstAttribute()) { await WriteAttributesAsync(reader, defattr).ConfigureAwait(false); reader.MoveToElement(); } } else if (reader.NodeType != XmlNodeType.Attribute) { throw new XmlException(SR.Xml_InvalidPosition, string.Empty); } else { do { // we need to check both XmlReader.IsDefault and XmlReader.SchemaInfo.IsDefault. // If either of these is true and defattr=false, we should not write the attribute out if (defattr || !reader.IsDefaultInternal) { await WriteStartAttributeAsync(reader.Prefix, reader.LocalName, reader.NamespaceURI).ConfigureAwait(false); while (reader.ReadAttributeValue()) { if (reader.NodeType == XmlNodeType.EntityReference) { await WriteEntityRefAsync(reader.Name).ConfigureAwait(false); } else { await WriteStringAsync(reader.Value).ConfigureAwait(false); } } await WriteEndAttributeAsync().ConfigureAwait(false); } } while (reader.MoveToNextAttribute()); } } // Copies the current node from the given reader to the writer (including child nodes), and if called on an element moves the XmlReader // to the corresponding end element. public virtual Task WriteNodeAsync(XmlReader reader, bool defattr) { if (null == reader) { throw new ArgumentNullException(nameof(reader)); } if (reader.Settings != null && reader.Settings.Async) { return WriteNodeAsync_CallAsyncReader(reader, defattr); } else { return WriteNodeAsync_CallSyncReader(reader, defattr); } } // Copies the current node from the given reader to the writer (including child nodes), and if called on an element moves the XmlReader // to the corresponding end element. //use sync methods on the reader internal async Task WriteNodeAsync_CallSyncReader(XmlReader reader, bool defattr) { bool canReadChunk = reader.CanReadValueChunk; int d = reader.NodeType == XmlNodeType.None ? -1 : reader.Depth; do { switch (reader.NodeType) { case XmlNodeType.Element: await WriteStartElementAsync(reader.Prefix, reader.LocalName, reader.NamespaceURI).ConfigureAwait(false); await WriteAttributesAsync(reader, defattr).ConfigureAwait(false); if (reader.IsEmptyElement) { await WriteEndElementAsync().ConfigureAwait(false); break; } break; case XmlNodeType.Text: if (canReadChunk) { if (_writeNodeBuffer == null) { _writeNodeBuffer = new char[WriteNodeBufferSize]; } int read; while ((read = reader.ReadValueChunk(_writeNodeBuffer, 0, WriteNodeBufferSize)) > 0) { await this.WriteCharsAsync(_writeNodeBuffer, 0, read).ConfigureAwait(false); } } else { await WriteStringAsync(reader.Value).ConfigureAwait(false); } break; case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: await WriteWhitespaceAsync(reader.Value).ConfigureAwait(false); break; case XmlNodeType.CDATA: await WriteCDataAsync(reader.Value).ConfigureAwait(false); break; case XmlNodeType.EntityReference: await WriteEntityRefAsync(reader.Name).ConfigureAwait(false); break; case XmlNodeType.XmlDeclaration: case XmlNodeType.ProcessingInstruction: await WriteProcessingInstructionAsync(reader.Name, reader.Value).ConfigureAwait(false); break; case XmlNodeType.DocumentType: await WriteDocTypeAsync(reader.Name, reader.GetAttribute("PUBLIC"), reader.GetAttribute("SYSTEM"), reader.Value).ConfigureAwait(false); break; case XmlNodeType.Comment: await WriteCommentAsync(reader.Value).ConfigureAwait(false); break; case XmlNodeType.EndElement: await WriteFullEndElementAsync().ConfigureAwait(false); break; } } while (reader.Read() && (d < reader.Depth || (d == reader.Depth && reader.NodeType == XmlNodeType.EndElement))); } // Copies the current node from the given reader to the writer (including child nodes), and if called on an element moves the XmlReader // to the corresponding end element. //use async methods on the reader internal async Task WriteNodeAsync_CallAsyncReader(XmlReader reader, bool defattr) { bool canReadChunk = reader.CanReadValueChunk; int d = reader.NodeType == XmlNodeType.None ? -1 : reader.Depth; do { switch (reader.NodeType) { case XmlNodeType.Element: await WriteStartElementAsync(reader.Prefix, reader.LocalName, reader.NamespaceURI).ConfigureAwait(false); await WriteAttributesAsync(reader, defattr).ConfigureAwait(false); if (reader.IsEmptyElement) { await WriteEndElementAsync().ConfigureAwait(false); break; } break; case XmlNodeType.Text: if (canReadChunk) { if (_writeNodeBuffer == null) { _writeNodeBuffer = new char[WriteNodeBufferSize]; } int read; while ((read = await reader.ReadValueChunkAsync(_writeNodeBuffer, 0, WriteNodeBufferSize).ConfigureAwait(false)) > 0) { await this.WriteCharsAsync(_writeNodeBuffer, 0, read).ConfigureAwait(false); } } else { //reader.Value may block on Text or WhiteSpace node, use GetValueAsync await WriteStringAsync(await reader.GetValueAsync().ConfigureAwait(false)).ConfigureAwait(false); } break; case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: await WriteWhitespaceAsync(await reader.GetValueAsync().ConfigureAwait(false)).ConfigureAwait(false); break; case XmlNodeType.CDATA: await WriteCDataAsync(reader.Value).ConfigureAwait(false); break; case XmlNodeType.EntityReference: await WriteEntityRefAsync(reader.Name).ConfigureAwait(false); break; case XmlNodeType.XmlDeclaration: case XmlNodeType.ProcessingInstruction: await WriteProcessingInstructionAsync(reader.Name, reader.Value).ConfigureAwait(false); break; case XmlNodeType.DocumentType: await WriteDocTypeAsync(reader.Name, reader.GetAttribute("PUBLIC"), reader.GetAttribute("SYSTEM"), reader.Value).ConfigureAwait(false); break; case XmlNodeType.Comment: await WriteCommentAsync(reader.Value).ConfigureAwait(false); break; case XmlNodeType.EndElement: await WriteFullEndElementAsync().ConfigureAwait(false); break; } } while (await reader.ReadAsync().ConfigureAwait(false) && (d < reader.Depth || (d == reader.Depth && reader.NodeType == XmlNodeType.EndElement))); } // Copies the current node from the given XPathNavigator to the writer (including child nodes). public virtual async Task WriteNodeAsync(XPathNavigator navigator, bool defattr) { if (navigator == null) { throw new ArgumentNullException(nameof(navigator)); } int iLevel = 0; navigator = navigator.Clone(); while (true) { bool mayHaveChildren = false; XPathNodeType nodeType = navigator.NodeType; switch (nodeType) { case XPathNodeType.Element: await WriteStartElementAsync(navigator.Prefix, navigator.LocalName, navigator.NamespaceURI).ConfigureAwait(false); // Copy attributes if (navigator.MoveToFirstAttribute()) { do { IXmlSchemaInfo schemaInfo = navigator.SchemaInfo; if (defattr || (schemaInfo == null || !schemaInfo.IsDefault)) { await WriteStartAttributeAsync(navigator.Prefix, navigator.LocalName, navigator.NamespaceURI).ConfigureAwait(false); // copy string value to writer await WriteStringAsync(navigator.Value).ConfigureAwait(false); await WriteEndAttributeAsync().ConfigureAwait(false); } } while (navigator.MoveToNextAttribute()); navigator.MoveToParent(); } // Copy namespaces if (navigator.MoveToFirstNamespace(XPathNamespaceScope.Local)) { await WriteLocalNamespacesAsync(navigator).ConfigureAwait(false); navigator.MoveToParent(); } mayHaveChildren = true; break; case XPathNodeType.Attribute: // do nothing on root level attribute break; case XPathNodeType.Text: await WriteStringAsync(navigator.Value).ConfigureAwait(false); break; case XPathNodeType.SignificantWhitespace: case XPathNodeType.Whitespace: await WriteWhitespaceAsync(navigator.Value).ConfigureAwait(false); break; case XPathNodeType.Root: mayHaveChildren = true; break; case XPathNodeType.Comment: await WriteCommentAsync(navigator.Value).ConfigureAwait(false); break; case XPathNodeType.ProcessingInstruction: await WriteProcessingInstructionAsync(navigator.LocalName, navigator.Value).ConfigureAwait(false); break; case XPathNodeType.Namespace: // do nothing on root level namespace break; default: Debug.Assert(false); break; } if (mayHaveChildren) { // If children exist, move down to next level if (navigator.MoveToFirstChild()) { iLevel++; continue; } else { // EndElement if (navigator.NodeType == XPathNodeType.Element) { if (navigator.IsEmptyElement) { await WriteEndElementAsync().ConfigureAwait(false); } else { await WriteFullEndElementAsync().ConfigureAwait(false); } } } } // No children while (true) { if (iLevel == 0) { // The entire subtree has been copied return; } if (navigator.MoveToNext()) { // Found a sibling, so break to outer loop break; } // No siblings, so move up to previous level iLevel--; navigator.MoveToParent(); // EndElement if (navigator.NodeType == XPathNodeType.Element) await WriteFullEndElementAsync().ConfigureAwait(false); } } } // Element Helper Methods // Writes out an attribute with the specified name, namespace URI, and string value. public async Task WriteElementStringAsync(string prefix, String localName, String ns, String value) { await WriteStartElementAsync(prefix, localName, ns).ConfigureAwait(false); if (null != value && 0 != value.Length) { await WriteStringAsync(value).ConfigureAwait(false); } await WriteEndElementAsync().ConfigureAwait(false); } // Copy local namespaces on the navigator's current node to the raw writer. The namespaces are returned by the navigator in reversed order. // The recursive call reverses them back. private async Task WriteLocalNamespacesAsync(XPathNavigator nsNav) { string prefix = nsNav.LocalName; string ns = nsNav.Value; if (nsNav.MoveToNextNamespace(XPathNamespaceScope.Local)) { await WriteLocalNamespacesAsync(nsNav).ConfigureAwait(false); } if (prefix.Length == 0) { await WriteAttributeStringAsync(string.Empty, "xmlns", XmlReservedNs.NsXmlNs, ns).ConfigureAwait(false); } else { await WriteAttributeStringAsync("xmlns", prefix, XmlReservedNs.NsXmlNs, ns).ConfigureAwait(false); } } } }
// ********************************* // Message from Original Author: // // 2008 Jose Menendez Poo // Please give me credit if you use this code. It's all I ask. // Contact me for more info: menendezpoo@gmail.com // ********************************* // // Original project from http://ribbon.codeplex.com/ // Continue to support and maintain by http://officeribbon.codeplex.com/ using System; using System.Collections.Generic; using System.Text; using System.Drawing; using System.ComponentModel; using System.Drawing.Drawing2D; using System.Windows.Forms.RibbonHelpers; namespace System.Windows.Forms { public class RibbonOrbDropDown : RibbonPopup { #region const private const bool DefaultAutoSizeContentButtons = true; private const int DefaultContentButtonsMinWidth = 150; private const int DefaultContentRecentItemsMinWidth = 150; #endregion #region Fields internal RibbonOrbMenuItem LastPoppedMenuItem; private Rectangle designerSelectedBounds; private int glyphGap = 3; private Padding _contentMargin; private Ribbon _ribbon; private RibbonItemCollection _menuItems; private RibbonItemCollection _recentItems; private RibbonItemCollection _optionItems; private RibbonMouseSensor _sensor; private int _optionsPadding; private DateTime OpenedTime; //Steve - capture time popup was shown private string _recentItemsCaption; private int _RecentItemsCaptionLineSpacing = 8; //private GlobalHook _keyboardHook; private int _contentButtonsWidth = DefaultContentButtonsMinWidth; private bool _autoSizeContentButtons = DefaultAutoSizeContentButtons; private int _contentButtonsMinWidth = DefaultContentButtonsMinWidth; private int _contentRecentItemsMinWidth = DefaultContentRecentItemsMinWidth; #endregion #region Ctor internal RibbonOrbDropDown(Ribbon ribbon) : base() { DoubleBuffered = true; _ribbon = ribbon; _menuItems = new RibbonItemCollection(); _recentItems = new RibbonItemCollection(); _optionItems = new RibbonItemCollection(); _menuItems.SetOwner(Ribbon); _recentItems.SetOwner(Ribbon); _optionItems.SetOwner(Ribbon); _optionsPadding = 6; Size = new System.Drawing.Size(527, 447); BorderRoundness = 8; //if (!(Site != null && Site.DesignMode)) //{ // _keyboardHook = new GlobalHook(GlobalHook.HookTypes.Keyboard); // _keyboardHook.KeyUp += new KeyEventHandler(_keyboardHook_KeyUp); //} } ~RibbonOrbDropDown() { if (_sensor != null) { _sensor.Dispose(); } //if (_keyboardHook != null) //{ // _keyboardHook.Dispose(); //} } #endregion #region Props /// <summary> /// Gets all items involved in the dropdown /// </summary> internal List<RibbonItem> AllItems { get { List<RibbonItem> lst = new List<RibbonItem>(); lst.AddRange(MenuItems); lst.AddRange(RecentItems); lst.AddRange(OptionItems); return lst; } } /// <summary> /// Gets the margin of the content bounds /// </summary> [Browsable(false)] public Padding ContentMargin { get { if (_contentMargin.Size.IsEmpty) { _contentMargin = new Padding(6, 17, 6, 29); } return _contentMargin; } } /// <summary> /// Gets the bounds of the content (where menu buttons are) /// </summary> [Browsable(false)] public Rectangle ContentBounds { get { return Rectangle.FromLTRB(ContentMargin.Left, ContentMargin.Top, ClientRectangle.Right - ContentMargin.Right, ClientRectangle.Bottom - ContentMargin.Bottom); } } /// <summary> /// Gets the bounds of the content part that contains the buttons on the left /// </summary> [Browsable(false)] public Rectangle ContentButtonsBounds { get { Rectangle r = ContentBounds; r.Width = _contentButtonsWidth; if (Ribbon.RightToLeft == RightToLeft.Yes) r.X = ContentBounds.Right - _contentButtonsWidth; return r; } } /// <summary> /// Gets or sets the minimum width for the content buttons. /// </summary> [DefaultValue(DefaultContentButtonsMinWidth)] public int ContentButtonsMinWidth { get { return _contentButtonsMinWidth; } set { _contentButtonsMinWidth = value; } } /// <summary> /// Gets the bounds fo the content part that contains the recent-item list /// </summary> [Browsable(false)] public Rectangle ContentRecentItemsBounds { get { Rectangle r = ContentBounds; r.Width -= _contentButtonsWidth; //Steve - Recent Items Caption r.Height -= ContentRecentItemsCaptionBounds.Height; r.Y += ContentRecentItemsCaptionBounds.Height; if (Ribbon.RightToLeft == RightToLeft.No) r.X += _contentButtonsWidth; return r; } } /// <summary> /// Gets the bounds of the caption area on the content part of the recent-item list /// </summary> [Browsable(false)] public Rectangle ContentRecentItemsCaptionBounds { get { if (RecentItemsCaption != null) { //Lets measure the height of the text so we take into account the font and its size SizeF cs; using (Graphics g = this.CreateGraphics()) { cs = g.MeasureString(RecentItemsCaption, Ribbon.RibbonTabFont); } Rectangle r = ContentBounds; r.Width -= _contentButtonsWidth; r.Height = Convert.ToInt32(cs.Height) + Ribbon.ItemMargin.Top + Ribbon.ItemMargin.Bottom; //padding r.Height += _RecentItemsCaptionLineSpacing; //Spacing for the divider line if (Ribbon.RightToLeft == RightToLeft.No) r.X += _contentButtonsWidth; return r; } else return Rectangle.Empty; } } /// <summary> /// Gets the bounds of the caption area on the content part of the recent-item list /// </summary> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int RecentItemsCaptionLineSpacing { get { return _RecentItemsCaptionLineSpacing; } } /// <summary> /// Gets or sets the minimum width for the recent items. /// </summary> [DefaultValue(DefaultContentRecentItemsMinWidth)] public int ContentRecentItemsMinWidth { get { return _contentRecentItemsMinWidth; } set { _contentRecentItemsMinWidth = value; } } /// <summary> /// Gets if currently on design mode /// </summary> private bool RibbonInDesignMode { get { return RibbonDesigner.Current != null; } } /// <summary> /// Gets the collection of items shown in the menu area /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public RibbonItemCollection MenuItems { get { return _menuItems; } } /// <summary> /// Gets the collection of items shown in the options area (bottom) /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public RibbonItemCollection OptionItems { get { return _optionItems; } } [DefaultValue(6)] [Description("Spacing between option buttons (those on the bottom)")] public int OptionItemsPadding { get { return _optionsPadding; } set { _optionsPadding = value; } } /// <summary> /// Gets the collection of items shown in the recent items area /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public RibbonItemCollection RecentItems { get { return _recentItems; } } /// <summary> /// Gets or Sets the caption for the Recent Items area /// </summary> [DefaultValue(null)] public string RecentItemsCaption { get { return _recentItemsCaption; } set { _recentItemsCaption = value; Invalidate(); } } /// <summary> /// Gets the ribbon that owns this dropdown /// </summary> [Browsable(false)] public Ribbon Ribbon { get { return _ribbon; } } /// <summary> /// Gets the sensor of the dropdown /// </summary> [Browsable(false)] public RibbonMouseSensor Sensor { get { return _sensor; } } /// <summary> /// Gets the bounds of the glyph /// </summary> internal Rectangle ButtonsGlyphBounds { get { Size s = new Size(50, 18); Rectangle rf = ContentButtonsBounds; Rectangle r = new Rectangle(rf.Left + (rf.Width - s.Width * 2) / 2, rf.Top + glyphGap, s.Width, s.Height); if (MenuItems.Count > 0) { r.Y = MenuItems[MenuItems.Count - 1].Bounds.Bottom + glyphGap; } return r; } } /// <summary> /// Gets the bounds of the glyph /// </summary> internal Rectangle ButtonsSeparatorGlyphBounds { get { Size s = new Size(18, 18); Rectangle r = ButtonsGlyphBounds; r.X = r.Right + glyphGap; return r; } } /// <summary> /// Gets the bounds of the recent items add glyph /// </summary> internal Rectangle RecentGlyphBounds { get { Size s = new Size(50, 18); Rectangle rf = ContentRecentItemsBounds; Rectangle r = new Rectangle(rf.Left + glyphGap, rf.Top + glyphGap, s.Width, s.Height); if (RecentItems.Count > 0) { r.Y = RecentItems[RecentItems.Count - 1].Bounds.Bottom + glyphGap; } return r; } } /// <summary> /// Gets the bounds of the option items add glyph /// </summary> internal Rectangle OptionGlyphBounds { get { Size s = new Size(50, 18); Rectangle rf = ContentBounds; Rectangle r = new Rectangle(rf.Right - s.Width, rf.Bottom + glyphGap, s.Width, s.Height); if (OptionItems.Count > 0) { r.X = OptionItems[OptionItems.Count - 1].Bounds.Left - s.Width - glyphGap; } return r; } } [DefaultValue(DefaultAutoSizeContentButtons)] public bool AutoSizeContentButtons { get { return _autoSizeContentButtons; } set { _autoSizeContentButtons = value; } } #endregion #region Methods internal void HandleDesignerItemRemoved(RibbonItem item) { if (MenuItems.Contains(item)) { MenuItems.Remove(item); } else if (RecentItems.Contains(item)) { RecentItems.Remove(item); } else if (OptionItems.Contains(item)) { OptionItems.Remove(item); } OnRegionsChanged(); } /// <summary> /// Gets the height that a separator should be on the DropDown /// </summary> /// <param name="s"></param> /// <returns></returns> private int SeparatorHeight(RibbonSeparator s) { if (!string.IsNullOrEmpty(s.Text)) { return 20; } else { return 3; } } /// <summary> /// Updates the regions and bounds of items /// </summary> private void UpdateRegions() { int curtop = 0; int curright = 0; int menuItemHeight = 44; int recentHeight = 22; int mbuttons = 1; //margin int mrecent = 1; //margin int buttonsHeight = 0; int recentsHeight = 0; if (AutoSizeContentButtons) { #region important to do the item max width check before the ContentBounds and other stuff is used (internal Property stuff) int itemMaxWidth = 0; using (Graphics g = CreateGraphics()) { foreach (RibbonItem item in MenuItems) { int width = item.MeasureSize(this, new RibbonElementMeasureSizeEventArgs(g, RibbonElementSizeMode.DropDown)).Width; if (width > itemMaxWidth) itemMaxWidth = width; } } itemMaxWidth = Math.Min(itemMaxWidth, ContentBounds.Width - ContentRecentItemsMinWidth); itemMaxWidth = Math.Max(itemMaxWidth, ContentButtonsMinWidth); _contentButtonsWidth = itemMaxWidth; #endregion } Rectangle rcontent = ContentBounds; Rectangle rbuttons = ContentButtonsBounds; Rectangle rrecent = ContentRecentItemsBounds; foreach (RibbonItem item in AllItems) { item.SetSizeMode(RibbonElementSizeMode.DropDown); item.SetCanvas(this); } #region Menu Items curtop = rcontent.Top + 1; foreach (RibbonItem item in MenuItems) { Rectangle ritem = new Rectangle(rbuttons.Left + mbuttons, curtop, rbuttons.Width - mbuttons * 2, menuItemHeight); if (item is RibbonSeparator) ritem.Height = SeparatorHeight(item as RibbonSeparator); item.SetBounds(ritem); curtop += ritem.Height; } buttonsHeight = curtop - rcontent.Top + 1; #endregion #region Recent List //curtop = rbuttons.Top; //Steve - for recent documents curtop = rrecent.Top; //Steve - for recent documents foreach (RibbonItem item in RecentItems) { Rectangle ritem = new Rectangle(rrecent.Left + mrecent, curtop, rrecent.Width - mrecent * 2, recentHeight); if (item is RibbonSeparator) ritem.Height = SeparatorHeight(item as RibbonSeparator); item.SetBounds(ritem); curtop += ritem.Height; } recentsHeight = curtop - rbuttons.Top; #endregion #region Set size int actualHeight = Math.Max(buttonsHeight, recentsHeight); if (RibbonDesigner.Current != null) { actualHeight += ButtonsGlyphBounds.Height + glyphGap * 2; } Height = actualHeight + ContentMargin.Vertical; rcontent = ContentBounds; #endregion #region Option buttons curright = ClientSize.Width - ContentMargin.Right; using (Graphics g = CreateGraphics()) { foreach (RibbonItem item in OptionItems) { Size s = item.MeasureSize(this, new RibbonElementMeasureSizeEventArgs(g, RibbonElementSizeMode.DropDown)); curtop = rcontent.Bottom + (ContentMargin.Bottom - s.Height) / 2; item.SetBounds(new Rectangle(new Point(curright - s.Width, curtop), s)); curright = item.Bounds.Left - OptionItemsPadding; } } #endregion } /// <summary> /// Refreshes the sensor /// </summary> private void UpdateSensor() { if (_sensor != null) { _sensor.Dispose(); } _sensor = new RibbonMouseSensor(this, Ribbon, AllItems); } /// <summary> /// Updates all areas and bounds of items /// </summary> internal void OnRegionsChanged() { UpdateRegions(); UpdateSensor(); UpdateDesignerSelectedBounds(); Invalidate(); } /// <summary> /// Selects the specified item on the designer /// </summary> /// <param name="item"></param> internal void SelectOnDesigner(RibbonItem item) { if (RibbonDesigner.Current != null) { RibbonDesigner.Current.SelectedElement = item; UpdateDesignerSelectedBounds(); Invalidate(); } } /// <summary> /// Updates the selection bounds on the designer /// </summary> internal void UpdateDesignerSelectedBounds() { designerSelectedBounds = Rectangle.Empty; if (RibbonInDesignMode) { RibbonItem item = RibbonDesigner.Current.SelectedElement as RibbonItem; if (item != null && AllItems.Contains(item)) { designerSelectedBounds = item.Bounds; } } } protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); if (RibbonInDesignMode) { #region DesignMode clicks if (ContentBounds.Contains(e.Location)) { if (ContentButtonsBounds.Contains(e.Location)) { foreach (RibbonItem item in MenuItems) { if (item.Bounds.Contains(e.Location)) { SelectOnDesigner(item); break; } } } else if (ContentRecentItemsBounds.Contains(e.Location)) { foreach (RibbonItem item in RecentItems) { if (item.Bounds.Contains(e.Location)) { SelectOnDesigner(item); break; } } } } if (ButtonsGlyphBounds.Contains(e.Location)) { RibbonDesigner.Current.CreteOrbMenuItem(typeof(RibbonOrbMenuItem)); } else if (ButtonsSeparatorGlyphBounds.Contains(e.Location)) { RibbonDesigner.Current.CreteOrbMenuItem(typeof(RibbonSeparator)); } else if (RecentGlyphBounds.Contains(e.Location)) { RibbonDesigner.Current.CreteOrbRecentItem(typeof(RibbonOrbRecentItem)); } else if (OptionGlyphBounds.Contains(e.Location)) { RibbonDesigner.Current.CreteOrbOptionItem(typeof(RibbonOrbOptionButton)); } else { foreach (RibbonItem item in OptionItems) { if (item.Bounds.Contains(e.Location)) { SelectOnDesigner(item); break; } } } #endregion } } protected override void OnOpening(System.ComponentModel.CancelEventArgs e) { base.OnOpening(e); UpdateRegions(); } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); Ribbon.Renderer.OnRenderOrbDropDownBackground( new RibbonOrbDropDownEventArgs(Ribbon, this, e.Graphics, e.ClipRectangle)); foreach (RibbonItem item in AllItems) { item.OnPaint(this, new RibbonElementPaintEventArgs(e.ClipRectangle, e.Graphics, RibbonElementSizeMode.DropDown)); } if (RibbonInDesignMode) { using (SolidBrush b = new SolidBrush(Color.FromArgb(50, Color.Blue))) { e.Graphics.FillRectangle(b, ButtonsGlyphBounds); e.Graphics.FillRectangle(b, RecentGlyphBounds); e.Graphics.FillRectangle(b, OptionGlyphBounds); e.Graphics.FillRectangle(b, ButtonsSeparatorGlyphBounds); } using (StringFormat sf = new StringFormat()) { sf.Alignment = StringAlignment.Center; sf.LineAlignment = StringAlignment.Center; sf.Trimming = StringTrimming.None; e.Graphics.DrawString("+", Font, Brushes.White, ButtonsGlyphBounds, sf); e.Graphics.DrawString("+", Font, Brushes.White, RecentGlyphBounds, sf); e.Graphics.DrawString("+", Font, Brushes.White, OptionGlyphBounds, sf); e.Graphics.DrawString("---", Font, Brushes.White, ButtonsSeparatorGlyphBounds, sf); } using (Pen p = new Pen(Color.Black)) { p.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot; e.Graphics.DrawRectangle(p, designerSelectedBounds); } //e.Graphics.DrawString("Press ESC to Hide", Font, Brushes.Black, Width - 100f, 2f); } } protected override void OnClosed(EventArgs e) { Ribbon.OrbPressed = false; Ribbon.OrbSelected = false; LastPoppedMenuItem = null; foreach (RibbonItem item in AllItems) { item.SetSelected(false); item.SetPressed(false); } base.OnClosed(e); } protected override void OnShowed(EventArgs e) { base.OnShowed(e); OpenedTime = DateTime.Now; UpdateSensor(); } protected override void OnMouseClick(MouseEventArgs e) { if (Ribbon.RectangleToScreen(Ribbon.OrbBounds).Contains(PointToScreen(e.Location))) { Ribbon.OnOrbClicked(EventArgs.Empty); //Steve - if click time is within the double click time after the drop down was shown, then this is a double click if (DateTime.Compare(DateTime.Now, OpenedTime.AddMilliseconds(SystemInformation.DoubleClickTime)) < 0) Ribbon.OnOrbDoubleClicked(EventArgs.Empty); } base.OnMouseClick(e); } protected override void OnMouseDoubleClick(MouseEventArgs e) { base.OnMouseDoubleClick(e); if (Ribbon.RectangleToScreen(Ribbon.OrbBounds).Contains(PointToScreen(e.Location))) { Ribbon.OnOrbDoubleClicked(EventArgs.Empty); } } private void _keyboardHook_KeyUp(object sender, KeyEventArgs e) { //base.OnKeyUp(e); if (e.KeyCode == Keys.Down) { RibbonItem NextItem = null; RibbonItem SelectedItem = null; foreach (RibbonItem itm in MenuItems) { if (itm.Selected) { SelectedItem = itm; break; } } if (SelectedItem != null) { //get the next item in the chain int Index = MenuItems.IndexOf(SelectedItem); NextItem = GetNextSelectableMenuItem(Index + 1); } else { //nothing found so lets search through the recent buttons foreach (RibbonItem itm in RecentItems) { if (itm.Selected) { SelectedItem = itm; itm.SetSelected(false); itm.RedrawItem(); break; } } if (SelectedItem != null) { //get the next item in the chain int Index = RecentItems.IndexOf(SelectedItem); NextItem = GetNextSelectableRecentItem(Index + 1); } else { //nothing found so lets search through the option buttons foreach (RibbonItem itm in OptionItems) { if (itm.Selected) { SelectedItem = itm; itm.SetSelected(false); itm.RedrawItem(); break; } } if (SelectedItem != null) { //get the next item in the chain int Index = OptionItems.IndexOf(SelectedItem); NextItem = GetNextSelectableOptionItem(Index + 1); } } } //last check to make sure we found a selected item if (SelectedItem == null) { //we should have the right item by now so lets select it NextItem = GetNextSelectableMenuItem(0); if (NextItem != null) { NextItem.SetSelected(true); NextItem.RedrawItem(); } } else { SelectedItem.SetSelected(false); SelectedItem.RedrawItem(); NextItem.SetSelected(true); NextItem.RedrawItem(); } //_sensor.SelectedItem = NextItem; //_sensor.HittedItem = NextItem; } else if (e.KeyCode == Keys.Up) { } } private RibbonItem GetNextSelectableMenuItem(int StartIndex) { for (int idx = StartIndex; idx < MenuItems.Count; idx++) { RibbonButton btn = MenuItems[idx] as RibbonButton; if (btn != null) return btn; } //nothing found so lets move on to the recent items RibbonItem NextItem = GetNextSelectableRecentItem(0); if (NextItem == null) { //nothing found so lets try the option items NextItem = GetNextSelectableOptionItem(0); if (NextItem == null) { //nothing again so go back to the top of the menu items NextItem = GetNextSelectableMenuItem(0); } } return NextItem; } private RibbonItem GetNextSelectableRecentItem(int StartIndex) { for (int idx = StartIndex; idx < RecentItems.Count; idx++) { RibbonButton btn = RecentItems[idx] as RibbonButton; if (btn != null) return btn; } //nothing found so lets move on to the option items RibbonItem NextItem = GetNextSelectableOptionItem(0); if (NextItem == null) { //nothing found so lets try the menu items NextItem = GetNextSelectableMenuItem(0); if (NextItem == null) { //nothing again so go back to the top of the recent items NextItem = GetNextSelectableRecentItem(0); } } return NextItem; } private RibbonItem GetNextSelectableOptionItem(int StartIndex) { for (int idx = StartIndex; idx < OptionItems.Count; idx++) { RibbonButton btn = OptionItems[idx] as RibbonButton; if (btn != null) return btn; } //nothing found so lets move on to the menu items RibbonItem NextItem = GetNextSelectableMenuItem(0); if (NextItem == null) { //nothing found so lets try the recent items NextItem = GetNextSelectableRecentItem(0); if (NextItem == null) { //nothing again so go back to the top of the option items NextItem = GetNextSelectableOptionItem(0); } } return NextItem; } #endregion } }
/* * AssemblyName.cs - Implementation of the * "System.Reflection.AssemblyName" class. * * Copyright (C) 2001, 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Reflection { #if !ECMA_COMPAT using System; using System.IO; using System.Text; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Configuration.Assemblies; using System.Security.Cryptography; public sealed class AssemblyName : ICloneable #if CONFIG_SERIALIZATION , ISerializable, IDeserializationCallback #endif { // Internal state. private String codeBase; private CultureInfo culture; private AssemblyNameFlags flags; private String name; private AssemblyHashAlgorithm hashAlg; private StrongNameKeyPair keyPair; private Version version; private AssemblyVersionCompatibility versionCompat; private byte[] publicKey; private byte[] publicKeyToken; #if CONFIG_SERIALIZATION private SerializationInfo info; #endif // Constructor. public AssemblyName() { versionCompat = AssemblyVersionCompatibility.SameMachine; } #if CONFIG_SERIALIZATION internal AssemblyName(SerializationInfo info, StreamingContext context) { this.info = info; } #endif private AssemblyName(AssemblyName other) { codeBase = other.codeBase; culture = other.culture; flags = other.flags; name = other.name; hashAlg = other.hashAlg; keyPair = other.keyPair; version = (version == null ? null : (Version)(other.version.Clone())); versionCompat = other.versionCompat; publicKey = (other.publicKey == null ? null : (byte[])(other.publicKey.Clone())); publicKeyToken = (other.publicKeyToken == null ? null : (byte[])(other.publicKeyToken.Clone())); } // Fill assembly name information from a file. Returns a load error code. [MethodImpl(MethodImplOptions.InternalCall)] extern private static int FillAssemblyNameFromFile (AssemblyName nameInfo, String assemblyFile, Assembly caller); // Get the assembly name for a specific file. public static AssemblyName GetAssemblyName(String assemblyFile) { if(assemblyFile == null) { throw new ArgumentNullException("assemblyFile"); } assemblyFile = Path.GetFullPath(assemblyFile); AssemblyName nameInfo = new AssemblyName(); if(assemblyFile[0] == '/' || assemblyFile[0] == '\\') { nameInfo.CodeBase = "file://" + assemblyFile.Replace('\\', '/'); } else { nameInfo.CodeBase = "file:///" + assemblyFile.Replace('\\', '/'); } int error = FillAssemblyNameFromFile (nameInfo, assemblyFile, Assembly.GetCallingAssembly()); if(error != Assembly.LoadError_OK) { Assembly.ThrowLoadError(assemblyFile, error); } return nameInfo; } // Get or set the code base for the assembly name. public String CodeBase { get { return codeBase; } set { codeBase = value; } } // Get or set the culture associated with the assembly name. public CultureInfo CultureInfo { get { return culture; } set { culture = value; } } // Get the escaped code base for the assembly name. public String EscapedCodeBase { get { if(codeBase == null) { return null; } StringBuilder builder = new StringBuilder(); foreach(char ch in codeBase) { if(ch == ' ' || ch == '%') { builder.Append(String.Format("%{0:x2}", (int)ch)); } else { builder.Append(ch); } } return builder.ToString(); } } // Get or set the assembly name flags. public AssemblyNameFlags Flags { get { return flags; } set { flags = value; } } // Get the full name of the assembly. public String FullName { get { if(name == null) { return null; } StringBuilder builder = new StringBuilder(); builder.Append(name); builder.Append(", Version="); if(version != null) { builder.Append(version.ToString()); } else { builder.Append("0.0.0.0"); } builder.Append(", Culture="); if(culture != null && culture.LCID != 0x007F) { builder.Append(culture.Name); } else { builder.Append("neutral"); } byte[] token = GetPublicKeyToken(); builder.Append(", PublicKeyToken="); if(token != null) { foreach(byte b in token) { builder.Append(String.Format("{0:x2}", (int)b)); } } else { builder.Append("null"); } return builder.ToString(); } } // Get or set the hash algorithm for this assembly name. public AssemblyHashAlgorithm HashAlgorithm { get { return hashAlg; } set { hashAlg = value; } } // Get or set the key pair for this assembly name. public StrongNameKeyPair KeyPair { get { return keyPair; } set { keyPair = value; } } // Get or set the simple name of the assembly name. public String Name { get { return name; } set { name = value; } } // Get or set the version information of the assembly name. public Version Version { get { return version; } set { version = value; } } // Get or set the version compatibility value for the assembly name. public AssemblyVersionCompatibility VersionCompatibility { get { return versionCompat; } set { versionCompat = value; } } // Clone this object. public Object Clone() { return new AssemblyName(this); } // Get the public key for the assembly's originator. public byte[] GetPublicKey() { return publicKey; } // Set the public key for the assembly's originator. public void SetPublicKey(byte[] publicKey) { this.publicKey = publicKey; this.flags |= AssemblyNameFlags.PublicKey; } // Get the public key token for the assembly's originator. public byte[] GetPublicKeyToken() { #if CONFIG_CRYPTO if(publicKeyToken == null && publicKey != null) { // The public key token is the reverse of the last // eight bytes of the SHA1 hash of the public key. SHA1CryptoServiceProvider sha1; sha1 = new SHA1CryptoServiceProvider(); byte[] hash = sha1.ComputeHash(publicKey); ((IDisposable)sha1).Dispose(); publicKeyToken = new byte [8]; int posn; for(posn = 0; posn < 8; ++posn) { publicKeyToken[posn] = hash[hash.Length - 1 - posn]; } } #endif return publicKeyToken; } // Set the public key token for the assembly's originator. public void SetPublicKeyToken(byte[] publicKeyToken) { this.publicKeyToken = publicKeyToken; } // Convert this assembly name into a string. public override String ToString() { String name = FullName; if(name != null) { return name; } return base.ToString(); } // Set the culture by name. internal void SetCultureByName(String name) { if(name == null || name.Length == 0 || name == "iv") { culture = null; } else { try { culture = new CultureInfo(name); } catch(Exception) { // The culture name was probably not understood. culture = null; } } } // Set the version information by number. internal void SetVersion(int major, int minor, int build, int revision) { version = new Version(major, minor, build, revision); } static internal AssemblyName Parse(String assemblyName) { AssemblyName retval = new AssemblyName(); if(assemblyName.IndexOf(",") == -1) { retval.Name = assemblyName; } else { // TODO : Parse the rest of the information // as well. Version maybe important . retval.Name = assemblyName.Substring(0, assemblyName.IndexOf(",")); } return retval; } #if CONFIG_SERIALIZATION // Get the serialization data for this object. public void GetObjectData(SerializationInfo info, StreamingContext context) { if(info == null) { throw new ArgumentNullException("info"); } info.AddValue("_Name", name); info.AddValue("_PublicKey", publicKey, typeof(byte[])); info.AddValue("_PublicKeyToken", publicKeyToken, typeof(byte[])); if(culture == null) { info.AddValue("_CultureInfo", -1); } else { info.AddValue("_CultureInfo", culture.LCID); } info.AddValue("_CodeBase", codeBase); info.AddValue("_Version", version, typeof(Version)); info.AddValue("_HashAlgorithm", hashAlg, typeof(AssemblyHashAlgorithm)); info.AddValue("_StrongNameKeyPair", keyPair, typeof(StrongNameKeyPair)); info.AddValue("_VersionCompatibility", versionCompat, typeof(AssemblyVersionCompatibility)); info.AddValue("_Flags", flags, typeof(AssemblyNameFlags)); } // Handle a deserialization callback on this object. public void OnDeserialization(Object sender) { if(info == null) { return; } name = info.GetString("_Name"); publicKey = (byte[])(info.GetValue ("_PublicKey", typeof(byte[]))); publicKeyToken = (byte[])(info.GetValue ("_PublicKeyToken", typeof(byte[]))); int cultureID = info.GetInt32("_CultureInfo"); if(cultureID != -1) { culture = new CultureInfo(cultureID); } else { culture = null; } codeBase = info.GetString("_CodeBase"); version = (Version)(info.GetValue("_Version", typeof(Version))); hashAlg = (AssemblyHashAlgorithm)(info.GetValue ("_HashAlgorithm", typeof(AssemblyHashAlgorithm))); keyPair = (StrongNameKeyPair)(info.GetValue ("_StrongNameKeyPair", typeof(StrongNameKeyPair))); versionCompat = (AssemblyVersionCompatibility)(info.GetValue ("_VersionCompatibility", typeof(AssemblyVersionCompatibility))); flags = (AssemblyNameFlags)(info.GetValue ("_Flags", typeof(AssemblyNameFlags))); } #endif // CONFIG_SERIALIZATION }; // class AssemblyName #endif // !ECMA_COMPAT }; // namespace System.Reflection
using System; using System.Diagnostics; using System.Text; using u32 = System.UInt32; namespace System.Data.SQLite { public partial class Sqlite3 { /* ** 2004 April 13 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains routines used to translate between UTF-8, ** UTF-16, UTF-16BE, and UTF-16LE. ** ** Notes on UTF-8: ** ** Byte-0 Byte-1 Byte-2 Byte-3 Value ** 0xxxxxxx 00000000 00000000 0xxxxxxx ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx ** ** ** Notes on UTF-16: (with wwww+1==uuuuu) ** ** Word-0 Word-1 Value ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx ** ** ** BOM or Byte Order Mark: ** 0xff 0xfe little-endian utf-16 follows ** 0xfe 0xff big-endian utf-16 follows ** ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 ** ************************************************************************* */ //#include "sqliteInt.h" //#include <assert.h> //#include "vdbeInt.h" #if !SQLITE_AMALGAMATION /* ** The following constant value is used by the SQLITE_BIGENDIAN and ** SQLITE_LITTLEENDIAN macros. */ //const int sqlite3one = 1; #endif //* SQLITE_AMALGAMATION */ /* ** This lookup table is used to help decode the first byte of ** a multi-byte UTF8 character. */ static byte[] sqlite3Utf8Trans1 = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00, }; //#define WRITE_UTF8(zOut, c) { \ // if( c<0x00080 ){ \ // *zOut++ = (u8)(c&0xFF); \ // } \ // else if( c<0x00800 ){ \ // *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \ // *zOut++ = 0x80 + (u8)(c & 0x3F); \ // } \ // else if( c<0x10000 ){ \ // *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \ // *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \ // *zOut++ = 0x80 + (u8)(c & 0x3F); \ // }else{ \ // *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \ // *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \ // *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \ // *zOut++ = 0x80 + (u8)(c & 0x3F); \ // } \ //} //#define WRITE_UTF16LE(zOut, c) { \ // if( c<=0xFFFF ){ \ // *zOut++ = (u8)(c&0x00FF); \ // *zOut++ = (u8)((c>>8)&0x00FF); \ // }else{ \ // *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \ // *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \ // *zOut++ = (u8)(c&0x00FF); \ // *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \ // } \ //} //#define WRITE_UTF16BE(zOut, c) { \ // if( c<=0xFFFF ){ \ // *zOut++ = (u8)((c>>8)&0x00FF); \ // *zOut++ = (u8)(c&0x00FF); \ // }else{ \ // *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \ // *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \ // *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \ // *zOut++ = (u8)(c&0x00FF); \ // } \ //} //#define READ_UTF16LE(zIn, TERM, c){ \ // c = (*zIn++); \ // c += ((*zIn++)<<8); \ // if( c>=0xD800 && c<0xE000 && TERM ){ \ // int c2 = (*zIn++); \ // c2 += ((*zIn++)<<8); \ // c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \ // } \ //} //#define READ_UTF16BE(zIn, TERM, c){ \ // c = ((*zIn++)<<8); \ // c += (*zIn++); \ // if( c>=0xD800 && c<0xE000 && TERM ){ \ // int c2 = ((*zIn++)<<8); \ // c2 += (*zIn++); \ // c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \ // } \ //} /* ** Translate a single UTF-8 character. Return the unicode value. ** ** During translation, assume that the byte that zTerm points ** is a 0x00. ** ** Write a pointer to the next unread byte back into pzNext. ** ** Notes On Invalid UTF-8: ** ** * This routine never allows a 7-bit character (0x00 through 0x7f) to ** be encoded as a multi-byte character. Any multi-byte character that ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd. ** ** * This routine never allows a UTF16 surrogate value to be encoded. ** If a multi-byte character attempts to encode a value between ** 0xd800 and 0xe000 then it is rendered as 0xfffd. ** ** * Bytes in the range of 0x80 through 0xbf which occur as the first ** byte of a character are interpreted as single-byte characters ** and rendered as themselves even though they are technically ** invalid characters. ** ** * This routine accepts an infinite number of different UTF8 encodings ** for unicode values 0x80 and greater. It do not change over-length ** encodings to 0xfffd as some systems recommend. */ //#define READ_UTF8(zIn, zTerm, c) \ // c = *(zIn++); \ // if( c>=0xc0 ){ \ // c = sqlite3Utf8Trans1[c-0xc0]; \ // while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \ // c = (c<<6) + (0x3f & *(zIn++)); \ // } \ // if( c<0x80 \ // || (c&0xFFFFF800)==0xD800 \ // || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \ // } static u32 sqlite3Utf8Read( string zIn, /* First byte of UTF-8 character */ ref string pzNext /* Write first byte past UTF-8 char here */ ) { //unsigned int c; /* Same as READ_UTF8() above but without the zTerm parameter. ** For this routine, we assume the UTF8 string is always zero-terminated. */ if (String.IsNullOrEmpty(zIn)) return 0; //c = *( zIn++ ); //if ( c >= 0xc0 ) //{ // c = sqlite3Utf8Trans1[c - 0xc0]; // while ( ( *zIn & 0xc0 ) == 0x80 ) // { // c = ( c << 6 ) + ( 0x3f & *( zIn++ ) ); // } // if ( c < 0x80 // || ( c & 0xFFFFF800 ) == 0xD800 // || ( c & 0xFFFFFFFE ) == 0xFFFE ) { c = 0xFFFD; } //} //*pzNext = zIn; int zIndex = 0; u32 c = zIn[zIndex++]; if (c >= 0xc0) { //if ( c > 0xff ) c = 0; //else { //c = sqlite3Utf8Trans1[c - 0xc0]; while (zIndex != zIn.Length && (zIn[zIndex] & 0xc0) == 0x80) { c = (u32)((c << 6) + (0x3f & zIn[zIndex++])); } if (c < 0x80 || (c & 0xFFFFF800) == 0xD800 || (c & 0xFFFFFFFE) == 0xFFFE) { c = 0xFFFD; } } } pzNext = zIn.Substring(zIndex); return c; } /* ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate(). */ /* #define TRANSLATE_TRACE 1 */ #if !SQLITE_OMIT_UTF16 /* ** This routine transforms the internal text encoding used by pMem to ** desiredEnc. It is an error if the string is already of the desired ** encoding, or if pMem does not contain a string value. */ static int sqlite3VdbeMemTranslate(Mem pMem, int desiredEnc){ int len; /* Maximum length of output string in bytes */ Debugger.Break (); // TODO - //unsigned char *zOut; /* Output buffer */ //unsigned char *zIn; /* Input iterator */ //unsigned char *zTerm; /* End of input */ //unsigned char *z; /* Output iterator */ //unsigned int c; Debug.Assert( pMem.db==null || sqlite3_mutex_held(pMem.db.mutex) ); Debug.Assert( (pMem.flags&MEM_Str )!=0); Debug.Assert( pMem.enc!=desiredEnc ); Debug.Assert( pMem.enc!=0 ); Debug.Assert( pMem.n>=0 ); #if TRANSLATE_TRACE && SQLITE_DEBUG { char zBuf[100]; sqlite3VdbeMemPrettyPrint(pMem, zBuf); fprintf(stderr, "INPUT: %s\n", zBuf); } #endif /* If the translation is between UTF-16 little and big endian, then ** all that is required is to swap the byte order. This case is handled ** differently from the others. */ Debugger.Break (); // TODO - //if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){ // u8 temp; // int rc; // rc = sqlite3VdbeMemMakeWriteable(pMem); // if( rc!=SQLITE_OK ){ // Debug.Assert( rc==SQLITE_NOMEM ); // return SQLITE_NOMEM; // } // zIn = (u8*)pMem.z; // zTerm = &zIn[pMem->n&~1]; // while( zIn<zTerm ){ // temp = *zIn; // *zIn = *(zIn+1); // zIn++; // *zIn++ = temp; // } // pMem->enc = desiredEnc; // goto translate_out; //} /* Set len to the maximum number of bytes required in the output buffer. */ if( desiredEnc==SQLITE_UTF8 ){ /* When converting from UTF-16, the maximum growth results from ** translating a 2-byte character to a 4-byte UTF-8 character. ** A single byte is required for the output string ** nul-terminator. */ pMem->n &= ~1; len = pMem.n * 2 + 1; }else{ /* When converting from UTF-8 to UTF-16 the maximum growth is caused ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16 ** character. Two bytes are required in the output buffer for the ** nul-terminator. */ len = pMem.n * 2 + 2; } /* Set zIn to point at the start of the input buffer and zTerm to point 1 ** byte past the end. ** ** Variable zOut is set to point at the output buffer, space obtained ** from sqlite3Malloc(). */ Debugger.Break (); // TODO - //zIn = (u8*)pMem.z; //zTerm = &zIn[pMem->n]; //zOut = sqlite3DbMallocRaw(pMem->db, len); //if( !zOut ){ // return SQLITE_NOMEM; //} //z = zOut; //if( pMem->enc==SQLITE_UTF8 ){ // if( desiredEnc==SQLITE_UTF16LE ){ // /* UTF-8 -> UTF-16 Little-endian */ // while( zIn<zTerm ){ ///* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */ //READ_UTF8(zIn, zTerm, c); // WRITE_UTF16LE(z, c); // } // }else{ // Debug.Assert( desiredEnc==SQLITE_UTF16BE ); // /* UTF-8 -> UTF-16 Big-endian */ // while( zIn<zTerm ){ ///* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */ //READ_UTF8(zIn, zTerm, c); // WRITE_UTF16BE(z, c); // } // } // pMem->n = (int)(z - zOut); // *z++ = 0; //}else{ // Debug.Assert( desiredEnc==SQLITE_UTF8 ); // if( pMem->enc==SQLITE_UTF16LE ){ // /* UTF-16 Little-endian -> UTF-8 */ // while( zIn<zTerm ){ // READ_UTF16LE(zIn, zIn<zTerm, c); // WRITE_UTF8(z, c); // } // }else{ // /* UTF-16 Big-endian -> UTF-8 */ // while( zIn<zTerm ){ // READ_UTF16BE(zIn, zIn<zTerm, c); // WRITE_UTF8(z, c); // } // } // pMem->n = (int)(z - zOut); //} //*z = 0; //Debug.Assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len ); //sqlite3VdbeMemRelease(pMem); //pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem); //pMem->enc = desiredEnc; //pMem->flags |= (MEM_Term|MEM_Dyn); //pMem.z = (char*)zOut; //pMem.zMalloc = pMem.z; translate_out: #if TRANSLATE_TRACE && SQLITE_DEBUG { char zBuf[100]; sqlite3VdbeMemPrettyPrint(pMem, zBuf); fprintf(stderr, "OUTPUT: %s\n", zBuf); } #endif return SQLITE_OK; } /* ** This routine checks for a byte-order mark at the beginning of the ** UTF-16 string stored in pMem. If one is present, it is removed and ** the encoding of the Mem adjusted. This routine does not do any ** byte-swapping, it just sets Mem.enc appropriately. ** ** The allocation (static, dynamic etc.) and encoding of the Mem may be ** changed by this function. */ static int sqlite3VdbeMemHandleBom(Mem pMem){ int rc = SQLITE_OK; int bom = 0; byte[] b01 = new byte[2]; Encoding.Unicode.GetBytes( pMem.z, 0, 1,b01,0 ); assert( pMem->n>=0 ); if( pMem->n>1 ){ // u8 b1 = *(u8 *)pMem.z; // u8 b2 = *(((u8 *)pMem.z) + 1); if( b01[0]==0xFE && b01[1]==0xFF ){// if( b1==0xFE && b2==0xFF ){ bom = SQLITE_UTF16BE; } if( b01[0]==0xFF && b01[1]==0xFE ){ // if( b1==0xFF && b2==0xFE ){ bom = SQLITE_UTF16LE; } } if( bom!=0 ){ rc = sqlite3VdbeMemMakeWriteable(pMem); if( rc==SQLITE_OK ){ pMem.n -= 2; Debugger.Break (); // TODO - //memmove(pMem.z, pMem.z[2], pMem.n); //pMem.z[pMem.n] = '\0'; //pMem.z[pMem.n+1] = '\0'; pMem.flags |= MEM_Term; pMem.enc = bom; } } return rc; } #endif // * SQLITE_OMIT_UTF16 */ /* ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero, ** return the number of unicode characters in pZ up to (but not including) ** the first 0x00 byte. If nByte is not less than zero, return the ** number of unicode characters in the first nByte of pZ (or up to ** the first 0x00, whichever comes first). */ static int sqlite3Utf8CharLen(string zIn, int nByte) { //int r = 0; //string z = zIn; if (zIn.Length == 0) return 0; int zInLength = zIn.Length; int zTerm = (nByte >= 0 && nByte <= zInLength) ? nByte : zInLength; //Debug.Assert( z<=zTerm ); //for ( int i = 0 ; i < zTerm ; i++ ) //while( *z!=0 && z<zTerm ){ //{ // SQLITE_SKIP_UTF8( ref z);// SQLITE_SKIP_UTF8(z); // r++; //} //return r; if (zTerm == zInLength) return zInLength - (zIn[zTerm - 1] == 0 ? 1 : 0); else return nByte; } /* This test function is not currently used by the automated test-suite. ** Hence it is only available in debug builds. */ #if SQLITE_TEST && SQLITE_DEBUG /* ** Translate UTF-8 to UTF-8. ** ** This has the effect of making sure that the string is well-formed ** UTF-8. Miscoded characters are removed. ** ** The translation is done in-place and aborted if the output ** overruns the input. */ static int sqlite3Utf8To8(byte[] zIn){ //byte[] zOut = zIn; //byte[] zStart = zIn; //u32 c; // while( zIn[0] && zOut<=zIn ){ // c = sqlite3Utf8Read(zIn, (const u8**)&zIn); // if( c!=0xfffd ){ // WRITE_UTF8(zOut, c); // } //} //zOut = 0; //return (int)(zOut - zStart); try { string z1 = Encoding.UTF8.GetString( zIn, 0, zIn.Length ); byte[] zOut = Encoding.UTF8.GetBytes( z1 ); //if ( zOut.Length != zIn.Length ) // return 0; //else { Array.Copy( zOut, 0, zIn, 0,zIn.Length ); return zIn.Length;} } catch ( EncoderFallbackException e ) { return 0; } } #endif #if !SQLITE_OMIT_UTF16 /* ** Convert a UTF-16 string in the native encoding into a UTF-8 string. ** Memory to hold the UTF-8 string is obtained from sqlite3Malloc and must ** be freed by the calling function. ** ** NULL is returned if there is an allocation error. */ static string sqlite3Utf16to8(sqlite3 db, string z, int nByte, u8 enc){ Debugger.Break (); // TODO - Mem m = Pool.Allocate_Mem(); // memset(&m, 0, sizeof(m)); // m.db = db; // sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC); // sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8); // if( db.mallocFailed !=0{ // sqlite3VdbeMemRelease(&m); // m.z = 0; // } // Debug.Assert( (m.flags & MEM_Term)!=0 || db.mallocFailed !=0); // Debug.Assert( (m.flags & MEM_Str)!=0 || db.mallocFailed !=0); assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed ); assert( m.z || db->mallocFailed ); return m.z; } /* ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter ** enc. A pointer to the new string is returned, and the value of *pnOut ** is set to the length of the returned string in bytes. The call should ** arrange to call sqlite3DbFree() on the returned pointer when it is ** no longer required. ** ** If a malloc failure occurs, NULL is returned and the db.mallocFailed ** flag set. */ #if SQLITE_ENABLE_STAT2 char *sqlite3Utf8to16(sqlite3 db, u8 enc, char *z, int n, int *pnOut){ Mem m; memset(&m, 0, sizeof(m)); m.db = db; sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC); if( sqlite3VdbeMemTranslate(&m, enc) ){ assert( db->mallocFailed ); return 0; } assert( m.z==m.zMalloc ); *pnOut = m.n; return m.z; } #endif /* ** zIn is a UTF-16 encoded unicode string at least nChar characters long. ** Return the number of bytes in the first nChar unicode characters ** in pZ. nChar must be non-negative. */ int sqlite3Utf16ByteLen(const void *zIn, int nChar){ int c; unsigned char const *z = zIn; int n = 0; if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){ while( n<nChar ){ READ_UTF16BE(z, 1, c); n++; } }else{ while( n<nChar ){ READ_UTF16LE(z, 1, c); n++; } } return (int)(z-(unsigned char const *)zIn); } #if SQLITE_TEST /* ** This routine is called from the TCL test function "translate_selftest". ** It checks that the primitives for serializing and deserializing ** characters in each encoding are inverses of each other. */ /* ** This routine is called from the TCL test function "translate_selftest". ** It checks that the primitives for serializing and deserializing ** characters in each encoding are inverses of each other. */ void sqlite3UtfSelfTest(void){ unsigned int i, t; unsigned char zBuf[20]; unsigned char *z; int n; unsigned int c; for(i=0; i<0x00110000; i++){ z = zBuf; WRITE_UTF8(z, i); n = (int)(z-zBuf); assert( n>0 && n<=4 ); z[0] = 0; z = zBuf; c = sqlite3Utf8Read(z, (const u8**)&z); t = i; if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD; if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD; assert( c==t ); assert( (z-zBuf)==n ); } for(i=0; i<0x00110000; i++){ if( i>=0xD800 && i<0xE000 ) continue; z = zBuf; WRITE_UTF16LE(z, i); n = (int)(z-zBuf); assert( n>0 && n<=4 ); z[0] = 0; z = zBuf; READ_UTF16LE(z, 1, c); assert( c==i ); assert( (z-zBuf)==n ); } for(i=0; i<0x00110000; i++){ if( i>=0xD800 && i<0xE000 ) continue; z = zBuf; WRITE_UTF16BE(z, i); n = (int)(z-zBuf); assert( n>0 && n<=4 ); z[0] = 0; z = zBuf; READ_UTF16BE(z, 1, c); assert( c==i ); assert( (z-zBuf)==n ); } } #endif // * SQLITE_TEST */ #endif // * SQLITE_OMIT_UTF16 */ } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Xml; using System.Xml.Linq; using System.Xml.Schema; using System.Xml.Serialization; using MathNet.Numerics.LinearAlgebra; using MathNet.Spatial.Units; namespace MathNet.Spatial.Euclidean { [Serializable] public struct Point2D : IXmlSerializable, IEquatable<Point2D>, IFormattable { /// <summary> /// Using public fields cos: http://blogs.msdn.com/b/ricom/archive/2006/08/31/performance-quiz-11-ten-questions-on-value-based-programming.aspx /// </summary> public readonly double X; /// <summary> /// Using public fields cos: http://blogs.msdn.com/b/ricom/archive/2006/08/31/performance-quiz-11-ten-questions-on-value-based-programming.aspx /// </summary> public readonly double Y; public Point2D(double x, double y) { this.X = x; this.Y = y; } /// <summary> /// Creates a point r from origin rotated a counterclockwise from X-Axis /// </summary> /// <param name="r"></param> /// <param name="a"></param> public Point2D(double r, Angle a) : this(r*Math.Cos(a.Radians), r*Math.Sin(a.Radians)) { } public Point2D(IEnumerable<double> data) : this(data.ToArray()) { } public Point2D(double[] data) : this(data[0], data[1]) { if (data.Length != 2) { throw new ArgumentException("data.Length != 2!"); } } public static Point2D Origin { get { return new Point2D(0, 0); } } public static Point2D Parse(string value) { var doubles = Parser.ParseItem2D(value); return new Point2D(doubles); } public static Point2D ReadFrom(XmlReader reader) { var v = new Point2D(); v.ReadXml(reader); return v; } public static Point2D Centroid(IEnumerable<Point2D> points) { return Centroid(points.ToArray()); } public static Point2D Centroid(params Point2D[] points) { return new Point2D( points.Average(point => point.X), points.Average(point => point.Y)); } public static Point2D MidPoint(Point2D point1, Point2D point2) { return Centroid(point1, point2); } public static Point2D operator +(Point2D point, Vector2D vector) { return new Point2D(point.X + vector.X, point.Y + vector.Y); } public static Point3D operator +(Point2D point, Vector3D vector) { return new Point3D(point.X + vector.X, point.Y + vector.Y, vector.Z); } public static Point2D operator -(Point2D point, Vector2D vector) { return new Point2D(point.X - vector.X, point.Y - vector.Y); } public static Point3D operator -(Point2D point, Vector3D vector) { return new Point3D(point.X - vector.X, point.Y - vector.Y, -1*vector.Z); } public static Vector2D operator -(Point2D lhs, Point2D rhs) { return new Vector2D(lhs.X - rhs.X, lhs.Y - rhs.Y); } public static bool operator ==(Point2D left, Point2D right) { return left.Equals(right); } public static bool operator !=(Point2D left, Point2D right) { return !left.Equals(right); } public Point2D TransformBy(Matrix<double> m) { var transformed = m.Multiply(this.ToVector()); return new Point2D(transformed); } public override string ToString() { return this.ToString(null, CultureInfo.InvariantCulture); } public string ToString(IFormatProvider provider) { return this.ToString(null, provider); } public string ToString(string format, IFormatProvider provider = null) { var numberFormatInfo = provider != null ? NumberFormatInfo.GetInstance(provider) : CultureInfo.InvariantCulture.NumberFormat; string separator = numberFormatInfo.NumberDecimalSeparator == "," ? ";" : ","; return string.Format("({0}{1} {2})", this.X.ToString(format, numberFormatInfo), separator, this.Y.ToString(format, numberFormatInfo)); } public bool Equals(Point2D other) { // ReSharper disable CompareOfFloatsByEqualityOperator return this.X == other.X && this.Y == other.Y; // ReSharper restore CompareOfFloatsByEqualityOperator } public bool Equals(Point2D other, double tolerance) { if (tolerance < 0) { throw new ArgumentException("epsilon < 0"); } return Math.Abs(other.X - this.X) < tolerance && Math.Abs(other.Y - this.Y) < tolerance; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } return obj is Point2D && this.Equals((Point2D)obj); } public override int GetHashCode() { unchecked { return (this.X.GetHashCode()*397) ^ this.Y.GetHashCode(); } } /// <summary> /// This method is reserved and should not be used. When implementing the IXmlSerializable interface, you should return null (Nothing in Visual Basic) from this method, and instead, if specifying a custom schema is required, apply the <see cref="T:System.Xml.Serialization.XmlSchemaProviderAttribute"/> to the class. /// </summary> /// <returns> /// An <see cref="T:System.Xml.Schema.XmlSchema"/> that describes the XML representation of the object that is produced by the <see cref="M:System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)"/> method and consumed by the <see cref="M:System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)"/> method. /// </returns> public XmlSchema GetSchema() { return null; } /// <summary> /// Generates an object from its XML representation. /// Handles both attribute and element style /// </summary> /// <param name="reader">The <see cref="T:System.Xml.XmlReader"/> stream from which the object is deserialized. </param> public void ReadXml(XmlReader reader) { reader.MoveToContent(); var e = (XElement)XNode.ReadFrom(reader); // Hacking set readonly fields here, can't think of a cleaner workaround XmlExt.SetReadonlyField(ref this, x => x.X, XmlConvert.ToDouble(e.ReadAttributeOrElementOrDefault("X"))); XmlExt.SetReadonlyField(ref this, x => x.Y, XmlConvert.ToDouble(e.ReadAttributeOrElementOrDefault("Y"))); } /// <summary> /// Converts an object into its XML representation. /// </summary> /// <param name="writer">The <see cref="T:System.Xml.XmlWriter"/> stream to which the object is serialized. </param> public void WriteXml(XmlWriter writer) { writer.WriteAttribute("X", this.X); writer.WriteAttribute("Y", this.Y); } public Vector2D VectorTo(Point2D otherPoint) { return otherPoint - this; } public double DistanceTo(Point2D otherPoint) { var vector = this.VectorTo(otherPoint); return vector.Length; } public Vector2D ToVector2D() { return new Vector2D(this.X, this.Y); } /// <summary> /// return new Point3D(X, Y, 0); /// </summary> /// <returns>return new Point3D(X, Y, 0);</returns> public Point3D ToPoint3D() { return new Point3D(this.X, this.Y, 0); } /// <summary> /// /// </summary> /// <param name="cs"></param> /// <returns>return cs.Transform(this.ToPoint3D());</returns> public Point3D TransformBy(CoordinateSystem cs) { return cs.Transform(this.ToPoint3D()); } /// <summary> /// Create a new Point2D from a Math.NET Numerics vector of length 2. /// </summary> public static Point2D OfVector(Vector<double> vector) { if (vector.Count != 2) { throw new ArgumentException("The vector length must be 2 in order to convert it to a Point2D"); } return new Point2D(vector.At(0), vector.At(1)); } /// <summary> /// Convert to a Math.NET Numerics dense vector of length 2. /// </summary> public Vector<double> ToVector() { return Vector<double>.Build.Dense(new[] { X, Y }); } } }
using System; using System.Collections; using System.Collections.Generic; using NUnit.Framework; using NFluent; namespace FileHelpers.Tests.CommonTests { [TestFixture] public class ArrayFields { [Test] public void ArrayFields1() { var res = FileTest.Good.ArrayFields .ReadWithEngine<ArrayType1>(); SimpleComparer(res); } [Test] public void ArrayFields2() { var res = FileTest.Good.ArrayFields .ReadWithEngine<ArrayType3>(); SimpleComparer2(res); } [Test] public void ArrayFieldsString() { var res = FileTest.Good.ArrayFields .ReadWithEngine<ArrayTypeStrings>(); SimpleComparerStrings(res); } private static void SimpleComparer2(ArrayType3[] res) { Assert.AreEqual(3, res.Length); Assert.AreEqual("58745", res[0].CustomerID); Assert.AreEqual("13", res[0].BuyedArts[0]); Assert.AreEqual("+8", res[0].BuyedArts[1]); Assert.AreEqual("+3", res[0].BuyedArts[2]); Assert.AreEqual("-7", res[0].BuyedArts[3]); Assert.AreEqual(20, res[0].BuyedArts.Length); Assert.AreEqual("31245", res[1].CustomerID); Assert.AreEqual("6", res[1].BuyedArts[0]); Assert.AreEqual(17, res[1].BuyedArts.Length); Assert.AreEqual(" 1245", res[2].CustomerID); Assert.AreEqual(0, res[2].BuyedArts.Length); } private static void SimpleComparer(ArrayType1[] res) { Assert.AreEqual(3, res.Length); Assert.AreEqual(58745, res[0].CustomerID); Assert.AreEqual(13, res[0].BuyedArts[0]); Assert.AreEqual(8, res[0].BuyedArts[1]); Assert.AreEqual(3, res[0].BuyedArts[2]); Assert.AreEqual(-7, res[0].BuyedArts[3]); Assert.AreEqual(20, res[0].BuyedArts.Length); Assert.AreEqual(31245, res[1].CustomerID); Assert.AreEqual(6, res[1].BuyedArts[0]); Assert.AreEqual(17, res[1].BuyedArts.Length); Assert.AreEqual(1245, res[2].CustomerID); Assert.AreEqual(0, res[2].BuyedArts.Length); } [Test] public void ArrayFieldsDelimited() { var res = FileTest.Good.ArrayFieldsDelimited .ReadWithEngine<ArrayTypeDelimited>(); Assert.AreEqual(10, res.Length); } private static void SimpleComparerStrings(ArrayTypeStrings[] res) { Assert.AreEqual(3, res.Length); Assert.AreEqual(58745, res[0].CustomerID); Assert.AreEqual("13", res[0].BuyedArts[0]); Assert.AreEqual("+8", res[0].BuyedArts[1]); Assert.AreEqual("+3", res[0].BuyedArts[2]); Assert.AreEqual("-7", res[0].BuyedArts[3]); Assert.AreEqual(20, res[0].BuyedArts.Length); Assert.AreEqual(31245, res[1].CustomerID); Assert.AreEqual("6", res[1].BuyedArts[0]); Assert.AreEqual(17, res[1].BuyedArts.Length); Assert.AreEqual(1245, res[2].CustomerID); Assert.AreEqual(0, res[2].BuyedArts.Length); } [Test] public void ArrayFieldsRW() { var engine = new FileHelperEngine<ArrayType1>(); var res = engine.ReadFile(FileTest.Good.ArrayFields.Path); SimpleComparer(res); res = engine.ReadString(engine.WriteString(res)); SimpleComparer(res); } /// <summary> /// TODO: Implement layout engine to handle this ArrayFieldsComplex test case. /// Test a class containing an array of other objects /// Objects are delimitted and finite so in theory should be parsable. /// </summary> [Test] [Ignore("Class containing an array in turn containing many fields is not yet supported")] public void ArrayFieldsComplex() { var engine = new FileHelperEngine<ArrayComplexType>(); engine.ReadString(""); } [Test] public void ArrayFieldsBad01() { Assert.Throws<BadUsageException>( () => new FileHelperEngine<ArrayTypeBad1>()); } [Test] public void ArrayFieldsBad02() { Assert.Throws<BadUsageException>( () => new FileHelperEngine<ArrayTypeBad2>()); } [Test] public void ArrayFieldsBad03() { Assert.Throws<BadUsageException>( () => new FileHelperEngine<ArrayTypeBad3>()); } [Test] public void ArrayFieldsBad04() { Assert.Throws<BadUsageException>( () => new FileHelperEngine<ArrayTypeBad4>()); } [Test] public void ArrayFieldsBad05() { Assert.Throws<BadUsageException>( () => new FileHelperEngine<ArrayTypeBad5>()); } [Test] public void ArrayFieldsBad06() { Assert.Throws<BadUsageException>( () => new FileHelperEngine<ArrayTypeBad6>()); } [Test] public void ArrayFieldsBad10() { var engine = new FileHelperEngine<ArrayType2>(); engine.ErrorManager.ErrorMode = ErrorMode.SaveAndContinue; var res = engine.ReadFile(FileTest.Good.ArrayFields2.Path); Assert.AreEqual(0, res.Length); Assert.AreEqual(2, engine.ErrorManager.ErrorCount); Assert.AreEqual( "Line: 1 Column: 33 Field: BuyedArts. The array has only 4 values, less than the minimum length of 5", engine.ErrorManager.Errors[0].ExceptionInfo.Message); Assert.AreEqual( "Line: 2 Column: 40 Field: BuyedArts. The array has more values than the maximum length of 5", engine.ErrorManager.Errors[1].ExceptionInfo.Message); } [Test] public void ArrayWriteMinErrorNull() { Assert.Throws<InvalidOperationException>( () => { var engine = new DelimitedFileEngine<ArrayModel2To4>(); engine.WriteString(new[] { new ArrayModel2To4() { Id = 1, Name = "name1", Weighting = null } }); }); } [Test] public void ArrayWriteMinError0() { Assert.Throws<InvalidOperationException>( () => { var engine = new DelimitedFileEngine<ArrayModel2To4>(); engine.WriteString(new[] { new ArrayModel2To4() { Id = 1, Name = "name1", Weighting = new float[] {} } }); }); } [Test] public void ArrayWriteMinError1() { Assert.Throws<InvalidOperationException>( () => { var engine = new DelimitedFileEngine<ArrayModel2To4>(); engine.WriteString(new[] { new ArrayModel2To4() { Id = 1, Name = "name1", Weighting = new float[] {10.2f} } }); }); } [Test] public void ArrayWriteMaxError5() { Assert.Throws<InvalidOperationException>( () => { var engine = new DelimitedFileEngine<ArrayModel2To4>(); var res = engine.WriteString(new[] { new ArrayModel2To4() { Id = 1, Name = "name1", Weighting = new float[] {10.2f, 1, 2, 3, 4} } }); }); } [Test] public void ArrayWriteFloatFieldsNull() { var dataToExport = new List<ArrayModel1>(); dataToExport.Add(new ArrayModel1() { Id = 1, Name = "name1", Weighting = null }); var engine = new DelimitedFileEngine<ArrayModel1>(); var res = engine.WriteString(dataToExport); Assert.AreEqual("1,name1," + Environment.NewLine, res); var vals = engine.ReadString(res); Check.That(vals.Length).IsEqualTo(1); Check.That(vals[0].Weighting.Length).IsEqualTo(0); } [Test] public void ArrayReadFieldsNull() { var info = "1,name1,10.2,,30.5"; var engine = new DelimitedFileEngine<ArrayModel1>(); var res = engine.ReadString(info); Check.That(res.Length).IsEqualTo(1); Check.That(res[0].Weighting.Length).IsEqualTo(3); Check.That(res[0].Weighting[1]).IsEqualTo(-5f); } [Test] public void ArrayReadFieldsNullAndNullable() { var info = "1,name1,10.2,,30.5"; var engine = new DelimitedFileEngine<ArrayModelNullable>(); var res = engine.ReadString(info); Check.That(res.Length).IsEqualTo(1); Check.That(res[0].Weighting.Length).IsEqualTo(3); Check.That(res[0].Weighting[1]).IsEqualTo(null); } [Test] public void ArrayWriteFloatFields0() { var dataToExport = new List<ArrayModel1>(); dataToExport.Add(new ArrayModel1() { Id = 1, Name = "name1", Weighting = new float[] {} }); var engine = new DelimitedFileEngine<ArrayModel1>(); var res = engine.WriteString(dataToExport); Assert.AreEqual("1,name1," + Environment.NewLine, res); var vals = engine.ReadString(res); Check.That(vals.Length).IsEqualTo(1); Check.That(vals[0].Weighting.Length).IsEqualTo(0); } [Test] public void ArrayWriteFloatFieldsNullable() { var dataToExport = new List<ArrayModelNullable>(); dataToExport.Add(new ArrayModelNullable() { Id = 1, Name = "name1", Weighting = new float?[] {} }); var engine = new DelimitedFileEngine<ArrayModelNullable>(); var res = engine.WriteString(dataToExport); Assert.AreEqual("1,name1," + Environment.NewLine, res); var vals = engine.ReadString(res); Check.That(vals.Length).IsEqualTo(1); Check.That(vals[0].Weighting.Length).IsEqualTo(0); } [Test] public void ArrayWriteFloatFields1() { var dataToExport = new List<ArrayModel1>(); dataToExport.Add(new ArrayModel1() { Id = 1, Name = "name1", Weighting = new float[] {10.2f} }); var engine = new DelimitedFileEngine<ArrayModel1>(); var res = engine.WriteString(dataToExport); Assert.AreEqual("1,name1,10.2" + Environment.NewLine, res); } [Test] public void ArrayWriteFloatFields2() { var dataToExport = new List<ArrayModel1>(); dataToExport.Add(new ArrayModel1() { Id = 1, Name = "name1", Weighting = new float[] {10.2f, 30.5f} }); var engine = new DelimitedFileEngine<ArrayModel1>(); var res = engine.WriteString(dataToExport); Assert.AreEqual("1,name1,10.2,30.5" + Environment.NewLine, res); } [Test] public void ArrayWriteFloatFields3() { var dataToExport = new List<ArrayModel1>(); dataToExport.Add(new ArrayModel1() { Id = 1, Name = "name1", Weighting = new float[] {10.2f, 30.5f, 11f} }); var engine = new DelimitedFileEngine<ArrayModel1>(); var res = engine.WriteString(dataToExport); Assert.AreEqual("1,name1,10.2,30.5,11" + Environment.NewLine, res); } [DelimitedRecord(",")] public class ArrayModel1 { public int Id; public string Name; [FieldNullValue(-5f)] [FieldArrayLength(0, 15)] public float[] Weighting; } [DelimitedRecord(",")] public class ArrayModelNullable { public int Id; public string Name; [FieldArrayLength(0, 15)] public float?[] Weighting; } [DelimitedRecord(",")] public class ArrayModel2To4 { public int Id; public string Name; [FieldArrayLength(2, 4)] public float[] Weighting; } [FixedLengthRecord(FixedMode.ExactLength)] public class ArrayType1 { [FieldFixedLength(5)] public int CustomerID; [FieldFixedLength(7)] public int[] BuyedArts; } [FixedLengthRecord(FixedMode.ExactLength)] public class ArrayTypeStrings { [FieldFixedLength(5)] public int CustomerID; [FieldFixedLength(7)] [FieldTrim(TrimMode.Both)] public string[] BuyedArts; } [FixedLengthRecord(FixedMode.ExactLength)] public class ArrayType2 { [FieldFixedLength(5)] public int CustomerID; [FieldFixedLength(7)] [FieldArrayLength(5)] public int[] BuyedArts; } [FixedLengthRecord(FixedMode.ExactLength)] public class ArrayType3 { [FieldFixedLength(5)] public string CustomerID; [FieldFixedLength(7)] [FieldTrim(TrimMode.Both)] public string[] BuyedArts; } [DelimitedRecord("|")] public class ArrayTypeBad1 { [FieldArrayLength(2, 30)] public int CustomerID; } [DelimitedRecord("|")] public class ArrayTypeBad2 { public int[][] JaggedArray; } [DelimitedRecord("|")] public class ArrayTypeBad3 { public int[,] TableArray; } [DelimitedRecord("|")] public class ArrayTypeBad4 { [FieldArrayLength(20, 10)] public int[] ArrayField; } [DelimitedRecord("|")] public class ArrayTypeBad5 { public int[] Customers; public int CustomerID; } [DelimitedRecord("|")] public class ArrayTypeBad6 { [FieldArrayLength(20, 10)] public int[] ArrayField; public int CustomerID; } } [DelimitedRecord("\t")] public class ArrayTypeDelimited { public string[] Values; } public class ArrayComplexSubClass { public string A; public string B; public DateTime C; } [DelimitedRecord("\t")] public class ArrayComplexType { public string someOtherInfo; public string maybeAnotherThing; [FieldArrayLength(10)] public ArrayComplexSubClass[] internalClasses; } }
// // System.Web.HttpApplication // // Authors: // Patrik Torstensson (ptorsten@hotmail.com) // Tim Coleman (tim@timcoleman.com) // Gonzalo Paniagua Javier (gonzalo@ximian.com) // // (c) Copyright 2002-2003 Ximian, Inc. (http://www.ximian.com) // (c) Copyright 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. // using System; using System.Collections; using System.ComponentModel; using System.Globalization; using System.IO; using System.Threading; using System.Security.Principal; using System.Runtime.Remoting.Messaging; using System.Web.UI; using System.Web.Configuration; using System.Web.SessionState; namespace System.Web { [ToolboxItem(false)] public class HttpApplication : IHttpAsyncHandler, IHttpHandler, IComponent, IDisposable { #region Event Handlers // Async event holders AsyncEvents _acquireRequestStateAsync; AsyncEvents _authenticateRequestAsync; AsyncEvents _endRequestAsync; AsyncEvents _beginRequestAsync; AsyncEvents _authorizeRequestAsync; AsyncEvents _updateRequestCacheAsync; AsyncEvents _resolveRequestCacheAsync; AsyncEvents _releaseRequestStateAsync; AsyncEvents _preRequestHandlerExecuteAsync; AsyncEvents _postRequestHandlerExecuteAsync; // ID objects used to indentify the event static object AcquireRequestStateId = new Object (); static object AuthenticateRequestId = new Object (); static object DefaultAuthenticationId = new Object (); static object EndRequestId = new Object (); static object DisposedId = new Object (); static object BeginRequestId = new Object (); static object AuthorizeRequestId = new Object (); static object UpdateRequestCacheId = new Object (); static object ResolveRequestCacheId = new Object (); static object ReleaseRequestStateId = new Object (); static object PreSendRequestContentId = new Object (); static object PreSendRequestHeadersId = new Object (); static object PreRequestHandlerExecuteId = new Object (); static object PostRequestHandlerExecuteId = new Object (); static object ErrorId = new Object (); #if NET_2_0 AsyncEvents _postAcquireRequestStateAsync; AsyncEvents _postAuthenticateRequestAsync; AsyncEvents _postAuthorizeRequestAsync; AsyncEvents _postMapRequestHandlerAsync; AsyncEvents _postReleaseRequestStateAsync; AsyncEvents _postResolveRequestCacheAsync; AsyncEvents _postUpdateRequestCacheAsync; AsyncEvents _preAcquireRequestStateAsync; AsyncEvents _preAuthenticateRequestAsync; AsyncEvents _preAuthorizeRequestAsync; AsyncEvents _preMapRequestHandlerAsync; AsyncEvents _preReleaseRequestStateAsync; AsyncEvents _preResolveRequestCacheAsync; AsyncEvents _preUpdateRequestCacheAsync; static object PostAcquireRequestStateId = new Object (); static object PostAuthenticateRequestId = new Object (); static object PostAuthorizeRequestId = new Object (); static object PostMapRequestHandlerId = new Object (); static object PostReleaseRequestStateId = new Object (); static object PostResolveRequestCacheId = new Object (); static object PostUpdateRequestCacheId = new Object (); static object PreAcquireRequestStateId = new Object (); static object PreAuthenticateRequestId = new Object (); static object PreAuthorizeRequestId = new Object (); static object PreMapRequestHandlerId = new Object (); static object PreReleaseRequestStateId = new Object (); static object PreResolveRequestCacheId = new Object (); static object PreUpdateRequestCacheId = new Object (); #endif // List of events private EventHandlerList _Events; public event EventHandler AcquireRequestState { add { Events.AddHandler (AcquireRequestStateId, value); } remove { Events.RemoveHandler (AcquireRequestStateId, value); } } public event EventHandler AuthenticateRequest { add { Events.AddHandler (AuthenticateRequestId, value); } remove { Events.RemoveHandler (AuthenticateRequestId, value); } } public event EventHandler AuthorizeRequest { add { Events.AddHandler (AuthorizeRequestId, value); } remove { Events.RemoveHandler (AuthorizeRequestId, value); } } public event EventHandler BeginRequest { add { Events.AddHandler (BeginRequestId, value); } remove { Events.RemoveHandler (BeginRequestId, value); } } public event EventHandler Disposed { add { Events.AddHandler (DisposedId, value); } remove { Events.RemoveHandler (DisposedId, value); } } public event EventHandler EndRequest { add { Events.AddHandler (EndRequestId, value); } remove { Events.RemoveHandler (EndRequestId, value); } } public event EventHandler Error { add { Events.AddHandler (ErrorId, value); } remove { Events.RemoveHandler (ErrorId, value); } } public event EventHandler PostRequestHandlerExecute { add { Events.AddHandler (PostRequestHandlerExecuteId, value); } remove { Events.RemoveHandler (PostRequestHandlerExecuteId, value); } } public event EventHandler PreRequestHandlerExecute { add { Events.AddHandler (PreRequestHandlerExecuteId, value); } remove { Events.RemoveHandler (PreRequestHandlerExecuteId, value); } } public event EventHandler PreSendRequestContent { add { Events.AddHandler (PreSendRequestContentId, value); } remove { Events.RemoveHandler (PreSendRequestContentId, value); } } public event EventHandler ReleaseRequestState { add { Events.AddHandler (ReleaseRequestStateId, value); } remove { Events.RemoveHandler (ReleaseRequestStateId, value); } } public event EventHandler ResolveRequestCache { add { Events.AddHandler (ResolveRequestCacheId, value); } remove { Events.RemoveHandler (ResolveRequestCacheId, value); } } public event EventHandler UpdateRequestCache { add { Events.AddHandler (UpdateRequestCacheId, value); } remove { Events.RemoveHandler (UpdateRequestCacheId, value); } } public event EventHandler PreSendRequestHeaders { add { Events.AddHandler (PreSendRequestHeadersId, value); } remove { Events.RemoveHandler (PreSendRequestHeadersId, value); } } internal event EventHandler DefaultAuthentication { add { Events.AddHandler (DefaultAuthenticationId, value); } remove { Events.RemoveHandler (DefaultAuthenticationId, value); } } public void AddOnAcquireRequestStateAsync (BeginEventHandler beg, EndEventHandler end) { if (null == _acquireRequestStateAsync) _acquireRequestStateAsync = new AsyncEvents (); _acquireRequestStateAsync.Add (beg, end); } public void AddOnAuthenticateRequestAsync(BeginEventHandler beg, EndEventHandler end) { if (null == _authenticateRequestAsync) _authenticateRequestAsync = new AsyncEvents (); _authenticateRequestAsync.Add (beg, end); } public void AddOnAuthorizeRequestAsync (BeginEventHandler beg, EndEventHandler end) { if (null == _authorizeRequestAsync) _authorizeRequestAsync = new AsyncEvents (); _authorizeRequestAsync.Add (beg, end); } public void AddOnBeginRequestAsync (BeginEventHandler beg, EndEventHandler end) { if (null == _beginRequestAsync) _beginRequestAsync = new AsyncEvents (); _beginRequestAsync.Add (beg, end); } public void AddOnEndRequestAsync (BeginEventHandler beg, EndEventHandler end) { if (null == _endRequestAsync) _endRequestAsync = new AsyncEvents (); _endRequestAsync.Add (beg, end); } public void AddOnPostRequestHandlerExecuteAsync (BeginEventHandler beg, EndEventHandler end) { if (null == _postRequestHandlerExecuteAsync) _postRequestHandlerExecuteAsync = new AsyncEvents (); _postRequestHandlerExecuteAsync.Add (beg, end); } public void AddOnPreRequestHandlerExecuteAsync (BeginEventHandler beg, EndEventHandler end) { if (null == _preRequestHandlerExecuteAsync) _preRequestHandlerExecuteAsync = new AsyncEvents (); _preRequestHandlerExecuteAsync.Add (beg, end); } public void AddOnReleaseRequestStateAsync (BeginEventHandler beg, EndEventHandler end) { if (null == _releaseRequestStateAsync) _releaseRequestStateAsync = new AsyncEvents (); _releaseRequestStateAsync.Add (beg, end); } public void AddOnResolveRequestCacheAsync (BeginEventHandler beg, EndEventHandler end) { if (null == _resolveRequestCacheAsync) _resolveRequestCacheAsync = new AsyncEvents (); _resolveRequestCacheAsync.Add (beg, end); } public void AddOnUpdateRequestCacheAsync (BeginEventHandler beg, EndEventHandler end) { if (null == _updateRequestCacheAsync) _updateRequestCacheAsync = new AsyncEvents (); _updateRequestCacheAsync.Add (beg, end); } #if NET_2_0 public event EventHandler PostAcquireRequestState { add { Events.AddHandler (PostAcquireRequestStateId, value); } remove { Events.RemoveHandler (PostAcquireRequestStateId, value); } } public event EventHandler PostAuthenticateRequest { add { Events.AddHandler (PostAuthenticateRequestId, value); } remove { Events.RemoveHandler (PostAuthenticateRequestId, value); } } public event EventHandler PostAuthorizeRequest { add { Events.AddHandler (PostAuthorizeRequestId, value); } remove { Events.RemoveHandler (PostAuthorizeRequestId, value); } } public event EventHandler PostMapRequestHandler { add { Events.AddHandler (PostMapRequestHandlerId, value); } remove { Events.RemoveHandler (PostMapRequestHandlerId, value); } } public event EventHandler PostReleaseRequestState { add { Events.AddHandler (PostReleaseRequestStateId, value); } remove { Events.RemoveHandler (PostReleaseRequestStateId, value); } } public event EventHandler PostResolveRequestCache { add { Events.AddHandler (PostResolveRequestCacheId, value); } remove { Events.RemoveHandler (PostResolveRequestCacheId, value); } } public event EventHandler PostUpdateRequestCache { add { Events.AddHandler (PostUpdateRequestCacheId, value); } remove { Events.RemoveHandler (PostUpdateRequestCacheId, value); } } public void AddOnAcquireRequestStateAsync (BeginEventHandler beg, EndEventHandler end, object state) { if (null == _acquireRequestStateAsync) _acquireRequestStateAsync = new AsyncEvents (); _acquireRequestStateAsync.Add (beg, end, state); } public void AddOnAuthenticateRequestAsync(BeginEventHandler beg, EndEventHandler end, object state) { if (null == _authenticateRequestAsync) _authenticateRequestAsync = new AsyncEvents (); _authenticateRequestAsync.Add (beg, end, state); } public void AddOnAuthorizeRequestAsync (BeginEventHandler beg, EndEventHandler end, object state) { if (null == _authorizeRequestAsync) _authorizeRequestAsync = new AsyncEvents (); _authorizeRequestAsync.Add (beg, end, state); } public void AddOnBeginRequestAsync (BeginEventHandler beg, EndEventHandler end, object state) { if (null == _beginRequestAsync) _beginRequestAsync = new AsyncEvents (); _beginRequestAsync.Add (beg, end, state); } public void AddOnEndRequestAsync (BeginEventHandler beg, EndEventHandler end, object state) { if (null == _endRequestAsync) _endRequestAsync = new AsyncEvents (); _endRequestAsync.Add (beg, end, state); } public void AddOnPostAcquireRequestStateAsync (BeginEventHandler beg, EndEventHandler end) { AddOnPostAcquireRequestStateAsync (beg, end, null); } public void AddOnPostAcquireRequestStateAsync (BeginEventHandler beg, EndEventHandler end, object state) { if (null == _postAcquireRequestStateAsync) _postAcquireRequestStateAsync = new AsyncEvents (); _postAcquireRequestStateAsync.Add (beg, end, state); } public void AddOnPostAuthenticateRequestAsync (BeginEventHandler beg, EndEventHandler end) { AddOnPostAuthenticateRequestAsync (beg, end, null); } public void AddOnPostAuthenticateRequestAsync (BeginEventHandler beg, EndEventHandler end, object state) { if (null == _postAuthenticateRequestAsync) _postAuthenticateRequestAsync = new AsyncEvents (); _postAuthenticateRequestAsync.Add (beg, end, state); } public void AddOnPostAuthorizeRequestAsync (BeginEventHandler beg, EndEventHandler end) { AddOnPostAuthorizeRequestAsync (beg, end, null); } public void AddOnPostAuthorizeRequestAsync (BeginEventHandler beg, EndEventHandler end, object state) { if (null == _postAuthorizeRequestAsync) _postAuthorizeRequestAsync = new AsyncEvents (); _postAuthorizeRequestAsync.Add (beg, end, state); } public void AddOnPostMapRequestHandlerAsync (BeginEventHandler beg, EndEventHandler end) { AddOnPostMapRequestHandlerAsync (beg, end, null); } public void AddOnPostMapRequestHandlerAsync (BeginEventHandler beg, EndEventHandler end, object state) { if (null == _postMapRequestHandlerAsync) _postMapRequestHandlerAsync = new AsyncEvents (); _postMapRequestHandlerAsync.Add (beg, end, state); } public void AddOnPostReleaseRequestStateAsync (BeginEventHandler beg, EndEventHandler end) { AddOnPostReleaseRequestStateAsync (beg, end, null); } public void AddOnPostReleaseRequestStateAsync (BeginEventHandler beg, EndEventHandler end, object state) { if (null == _postReleaseRequestStateAsync) _postReleaseRequestStateAsync = new AsyncEvents (); _postReleaseRequestStateAsync.Add (beg, end, state); } public void AddOnPostRequestHandlerExecuteAsync (BeginEventHandler beg, EndEventHandler end, object state) { if (null == _postRequestHandlerExecuteAsync) _postRequestHandlerExecuteAsync = new AsyncEvents (); _postRequestHandlerExecuteAsync.Add (beg, end, state); } public void AddOnPostResolveRequestCacheAsync (BeginEventHandler beg, EndEventHandler end) { AddOnPostResolveRequestCacheAsync (beg, end, null); } public void AddOnPostResolveRequestCacheAsync (BeginEventHandler beg, EndEventHandler end, object state) { if (null == _postResolveRequestCacheAsync) _postResolveRequestCacheAsync = new AsyncEvents (); _postResolveRequestCacheAsync.Add (beg, end, state); } public void AddOnPostUpdateRequestCacheAsync (BeginEventHandler beg, EndEventHandler end) { AddOnPostUpdateRequestCacheAsync (beg, end, null); } public void AddOnPostUpdateRequestCacheAsync (BeginEventHandler beg, EndEventHandler end, object state) { if (null == _postUpdateRequestCacheAsync) _postUpdateRequestCacheAsync = new AsyncEvents (); _postUpdateRequestCacheAsync.Add (beg, end, state); } public void AddOnPreAcquireRequestStateAsync (BeginEventHandler beg, EndEventHandler end) { AddOnPreAcquireRequestStateAsync (beg, end, null); } public void AddOnPreAcquireRequestStateAsync (BeginEventHandler beg, EndEventHandler end, object state) { if (null == _preAcquireRequestStateAsync) _preAcquireRequestStateAsync = new AsyncEvents (); _preAcquireRequestStateAsync.Add (beg, end, state); } public void AddOnPreAuthenticateRequestAsync (BeginEventHandler beg, EndEventHandler end) { AddOnPreAuthenticateRequestAsync (beg, end, null); } public void AddOnPreAuthenticateRequestAsync (BeginEventHandler beg, EndEventHandler end, object state) { if (null == _preAuthenticateRequestAsync) _preAuthenticateRequestAsync = new AsyncEvents (); _preAuthenticateRequestAsync.Add (beg, end, state); } public void AddOnPreAuthorizeRequestAsync (BeginEventHandler beg, EndEventHandler end) { AddOnPreAuthorizeRequestAsync (beg, end, null); } public void AddOnPreAuthorizeRequestAsync (BeginEventHandler beg, EndEventHandler end, object state) { if (null == _preAuthorizeRequestAsync) _preAuthorizeRequestAsync = new AsyncEvents (); _preAuthorizeRequestAsync.Add (beg, end, state); } public void AddOnPreMapRequestHandlerAsync (BeginEventHandler beg, EndEventHandler end) { AddOnPreMapRequestHandlerAsync (beg, end, null); } public void AddOnPreMapRequestHandlerAsync (BeginEventHandler beg, EndEventHandler end, object state) { if (null == _preMapRequestHandlerAsync) _preMapRequestHandlerAsync = new AsyncEvents (); _preMapRequestHandlerAsync.Add (beg, end, state); } public void AddOnPreReleaseRequestStateAsync (BeginEventHandler beg, EndEventHandler end) { AddOnPreReleaseRequestStateAsync (beg, end, null); } public void AddOnPreReleaseRequestStateAsync (BeginEventHandler beg, EndEventHandler end, object state) { if (null == _preReleaseRequestStateAsync) _preReleaseRequestStateAsync = new AsyncEvents (); _preReleaseRequestStateAsync.Add (beg, end, state); } public void AddOnPreRequestHandlerExecuteAsync (BeginEventHandler beg, EndEventHandler end, object state) { if (null == _preRequestHandlerExecuteAsync) _preRequestHandlerExecuteAsync = new AsyncEvents (); _preRequestHandlerExecuteAsync.Add (beg, end, state); } public void AddOnPreResolveRequestCacheAsync (BeginEventHandler beg, EndEventHandler end) { AddOnPreResolveRequestCacheAsync (beg, end, null); } public void AddOnPreResolveRequestCacheAsync (BeginEventHandler beg, EndEventHandler end, object state) { if (null == _preResolveRequestCacheAsync) _preResolveRequestCacheAsync = new AsyncEvents (); _preResolveRequestCacheAsync.Add (beg, end, state); } public void AddOnPreUpdateRequestCacheAsync (BeginEventHandler beg, EndEventHandler end) { AddOnPreUpdateRequestCacheAsync (beg, end, null); } public void AddOnPreUpdateRequestCacheAsync (BeginEventHandler beg, EndEventHandler end, object state) { if (null == _preUpdateRequestCacheAsync) _preUpdateRequestCacheAsync = new AsyncEvents (); _preUpdateRequestCacheAsync.Add (beg, end, state); } public void AddOnReleaseRequestStateAsync (BeginEventHandler beg, EndEventHandler end, object state) { if (null == _releaseRequestStateAsync) _releaseRequestStateAsync = new AsyncEvents (); _releaseRequestStateAsync.Add (beg, end, state); } public void AddOnResolveRequestCacheAsync (BeginEventHandler beg, EndEventHandler end, object state) { if (null == _resolveRequestCacheAsync) _resolveRequestCacheAsync = new AsyncEvents (); _resolveRequestCacheAsync.Add (beg, end, state); } public void AddOnUpdateRequestCacheAsync (BeginEventHandler beg, EndEventHandler end, object state) { if (null == _updateRequestCacheAsync) _updateRequestCacheAsync = new AsyncEvents (); _updateRequestCacheAsync.Add (beg, end, state); } #endif #endregion #region Recycle Helper class HandlerFactory { public IHttpHandler Handler; public IHttpHandlerFactory Factory; public HandlerFactory (IHttpHandler handler, IHttpHandlerFactory factory) { this.Handler = handler; this.Factory = factory; } } #endregion #region State Machine interface IStateHandler { void Execute(); bool CompletedSynchronously { get; } bool PossibleToTimeout { get; } } class EventState : IStateHandler { HttpApplication _app; EventHandler _event; public EventState (HttpApplication app, EventHandler evt) { _app = app; _event = evt; } public void Execute () { if (null != _event) _event (_app, EventArgs.Empty); } public bool CompletedSynchronously { get { return true; } } public bool PossibleToTimeout { get { return true; } } } class AsyncEventState : IStateHandler { HttpApplication _app; BeginEventHandler _begin; EndEventHandler _end; AsyncCallback _callback; bool _async; object _state; public AsyncEventState (HttpApplication app, BeginEventHandler begin, EndEventHandler end, object state) { _async = false; _app = app; _begin = begin; _end = end; _callback = new AsyncCallback (OnAsyncReady); } public void Execute () { _async = true; IAsyncResult ar = _begin (_app, EventArgs.Empty, _callback, _state); if (ar.CompletedSynchronously) { _async = false; _end (ar); } } public bool CompletedSynchronously { get { return !_async; } } public bool PossibleToTimeout { get { // We can't cancel a async event return false; } } private void OnAsyncReady (IAsyncResult ar) { if (ar.CompletedSynchronously) return; Exception error = null; try { // Invoke end handler _end(ar); } catch (Exception exc) { // Flow this error to the next state (handle during state execution) error = exc; } _app._state.ExecuteNextAsync (error); } } class AsyncEvents { ArrayList _events; class EventRecord { public EventRecord(BeginEventHandler beg, EndEventHandler end, object state) { Begin = beg; End = end; State = state; } public BeginEventHandler Begin; public EndEventHandler End; public object State; } public AsyncEvents () { _events = new ArrayList (); } public void Add (BeginEventHandler begin, EndEventHandler end) { _events.Add (new EventRecord (begin, end, null)); } public void Add (BeginEventHandler begin, EndEventHandler end, object state) { _events.Add (new EventRecord (begin, end, state)); } public void GetAsStates (HttpApplication app, ArrayList states) { foreach (object obj in _events) states.Add (new AsyncEventState (app, ((EventRecord) obj).Begin, ((EventRecord) obj).End, ((EventRecord) obj).State)); } } class ExecuteHandlerState : IStateHandler { HttpApplication _app; AsyncCallback _callback; IHttpAsyncHandler _handler; bool _async; public ExecuteHandlerState (HttpApplication app) { _app = app; _callback = new AsyncCallback (OnAsyncReady); } private void OnAsyncReady (IAsyncResult ar) { if (ar.CompletedSynchronously) return; Exception error = null; try { // Invoke end handler _handler.EndProcessRequest(ar); } catch (Exception exc) { // Flow this error to the next state (handle during state execution) error = exc; } _handler = null; _app._state.ExecuteNextAsync (error); } public void Execute () { IHttpHandler handler = _app.Context.Handler; if (handler == null) return; // Check if we can execute async if (handler is IHttpAsyncHandler) { _async = true; _handler = (IHttpAsyncHandler) handler; IAsyncResult ar = _handler.BeginProcessRequest (_app.Context, _callback, null); if (ar.CompletedSynchronously) { _async = false; _handler = null; ((IHttpAsyncHandler) handler).EndProcessRequest (ar); } } else { _async = false; // Sync handler handler.ProcessRequest (_app.Context); } } public bool CompletedSynchronously { get { return !_async; } } public bool PossibleToTimeout { get { if (_app.Context.Handler is IHttpAsyncHandler) return false; return true; } } } class CreateHandlerState : IStateHandler { HttpApplication _app; public CreateHandlerState (HttpApplication app) { _app = app; } public void Execute () { _app.Context.Handler = _app.CreateHttpHandler ( _app.Context, _app.Request.RequestType, _app.Request.FilePath, _app.Request.PhysicalPath); } public bool CompletedSynchronously { get { return true; } } public bool PossibleToTimeout { get { return false; } } } class FilterHandlerState : IStateHandler { HttpApplication _app; public FilterHandlerState (HttpApplication app) { _app = app; } public void Execute () { _app.Context.Response.DoFilter (true); } public bool CompletedSynchronously { get { return true; } } public bool PossibleToTimeout { get { return true; } } } class StateMachine { HttpApplication _app; WaitCallback _asynchandler; IStateHandler [] _handlers; int _currentStateIdx; int _endStateIdx; int _endRequestStateIdx; int _countSteps; int _countSyncSteps; // Helper to create the states for a normal event private void GetAsStates (object Event, ArrayList states) { // Get list of clients for the sync events Delegate evnt = _app.Events [Event]; if (evnt == null) return; System.Delegate [] clients = evnt.GetInvocationList(); foreach (Delegate client in clients) states.Add (new EventState (_app, (EventHandler) client)); } internal StateMachine (HttpApplication app) { _app = app; } internal void Init () { _asynchandler = new WaitCallback (OnAsyncCallback); // Create a arraylist of states to execute ArrayList states = new ArrayList (); // BeginRequest if (null != _app._beginRequestAsync) _app._beginRequestAsync.GetAsStates (_app, states); GetAsStates (HttpApplication.BeginRequestId, states); #if NET_2_0 // PreAuthenticateRequest if (null != _app._preAuthenticateRequestAsync) _app._preAuthenticateRequestAsync.GetAsStates (_app, states); GetAsStates (HttpApplication.PreAuthenticateRequestId, states); #endif // AuthenticateRequest if (null != _app._authenticateRequestAsync) _app._authenticateRequestAsync.GetAsStates (_app, states); GetAsStates (HttpApplication.AuthenticateRequestId, states); // DefaultAuthentication EventHandler defaultAuthHandler = (EventHandler) _app.Events [HttpApplication.DefaultAuthenticationId]; states.Add (new EventState (_app, defaultAuthHandler)); #if NET_2_0 // PostAuthenticateRequest if (null != _app._postAuthenticateRequestAsync) _app._postAuthenticateRequestAsync.GetAsStates (_app, states); GetAsStates (HttpApplication.PostAuthenticateRequestId, states); // PreAuthorizeRequest if (null != _app._preAuthorizeRequestAsync) _app._preAuthorizeRequestAsync.GetAsStates (_app, states); GetAsStates (HttpApplication.PreAuthorizeRequestId, states); #endif // AuthorizeRequest if (null != _app._authorizeRequestAsync) _app._authorizeRequestAsync.GetAsStates (_app, states); GetAsStates (HttpApplication.AuthorizeRequestId, states); #if NET_2_0 // PostAuthorizeRequest if (null != _app._postAuthorizeRequestAsync) _app._postAuthorizeRequestAsync.GetAsStates (_app, states); GetAsStates (HttpApplication.PostAuthorizeRequestId, states); // PreResolveRequestCache if (null != _app._preResolveRequestCacheAsync) _app._preResolveRequestCacheAsync.GetAsStates (_app, states); GetAsStates (HttpApplication.PreResolveRequestCacheId, states); #endif // ResolveRequestCache if (null != _app._resolveRequestCacheAsync) _app._resolveRequestCacheAsync.GetAsStates (_app, states); GetAsStates (HttpApplication.ResolveRequestCacheId, states); #if NET_2_0 // PostResolveRequestCache if (null != _app._postResolveRequestCacheAsync) _app._postResolveRequestCacheAsync.GetAsStates (_app, states); GetAsStates (HttpApplication.PostResolveRequestCacheId, states); // PreMapRequestHandler if (null != _app._preMapRequestHandlerAsync) _app._preMapRequestHandlerAsync.GetAsStates (_app, states); GetAsStates (HttpApplication.PreMapRequestHandlerId, states); #endif // [A handler (a page corresponding to the request URL) is created at this point.] states.Add (new CreateHandlerState (_app)); #if NET_2_0 // PostMapRequestHandler if (null != _app._postMapRequestHandlerAsync) _app._postMapRequestHandlerAsync.GetAsStates (_app, states); GetAsStates (HttpApplication.PostMapRequestHandlerId, states); // PreAcquireRequestState if (null != _app._preAcquireRequestStateAsync) _app._preAcquireRequestStateAsync.GetAsStates (_app, states); GetAsStates (HttpApplication.PreAcquireRequestStateId, states); #endif // AcquireRequestState if (null != _app._acquireRequestStateAsync) _app._acquireRequestStateAsync.GetAsStates (_app, states); GetAsStates (HttpApplication.AcquireRequestStateId, states); #if NET_2_0 // PostAcquireRequestState if (null != _app._postAcquireRequestStateAsync) _app._postAcquireRequestStateAsync.GetAsStates (_app, states); GetAsStates (HttpApplication.PostAcquireRequestStateId, states); #endif // PreRequestHandlerExecute if (null != _app._preRequestHandlerExecuteAsync) _app._preRequestHandlerExecuteAsync.GetAsStates (_app, states); GetAsStates (HttpApplication.PreRequestHandlerExecuteId, states); // [The handler is executed.] states.Add (new ExecuteHandlerState (_app)); // PostRequestHandlerExecute if (null != _app._postRequestHandlerExecuteAsync) _app._postRequestHandlerExecuteAsync.GetAsStates (_app, states); GetAsStates (HttpApplication.PostRequestHandlerExecuteId, states); #if NET_2_0 // PreReleaseRequestState if (null != _app._preReleaseRequestStateAsync) _app._preReleaseRequestStateAsync.GetAsStates (_app, states); GetAsStates (HttpApplication.PreReleaseRequestStateId, states); #endif // ReleaseRequestState if (null != _app._releaseRequestStateAsync) _app._releaseRequestStateAsync.GetAsStates (_app, states); GetAsStates (HttpApplication.ReleaseRequestStateId, states); #if NET_2_0 // PostReleaseRequestState if (null != _app._postReleaseRequestStateAsync) _app._postReleaseRequestStateAsync.GetAsStates (_app, states); GetAsStates (HttpApplication.PostReleaseRequestStateId, states); #endif // [Response filters, if any, filter the output.] states.Add (new FilterHandlerState (_app)); #if NET_2_0 // PreUpdateRequestCache if (null != _app._preUpdateRequestCacheAsync) _app._preUpdateRequestCacheAsync.GetAsStates (_app, states); GetAsStates (HttpApplication.PreUpdateRequestCacheId, states); #endif // UpdateRequestCache if (null != _app._updateRequestCacheAsync) _app._updateRequestCacheAsync.GetAsStates (_app, states); GetAsStates (HttpApplication.UpdateRequestCacheId, states); #if NET_2_0 // PostUpdateRequestCache if (null != _app._postUpdateRequestCacheAsync) _app._postUpdateRequestCacheAsync.GetAsStates (_app, states); GetAsStates (HttpApplication.PostUpdateRequestCacheId, states); #endif // EndRequest _endRequestStateIdx = states.Count; if (null != _app._endRequestAsync) _app._endRequestAsync.GetAsStates (_app, states); GetAsStates (HttpApplication.EndRequestId, states); // Make list ready to execute _handlers = new IStateHandler [states.Count]; states.CopyTo (_handlers); } internal void Reset () { _countSyncSteps = 0; _countSteps = 0; _currentStateIdx = -1; _endStateIdx = _handlers.Length - 1; } internal void Start () { Reset (); #if !TARGET_J2EE ExecuteNextAsync (null); #else ExecuteNext(null); #endif } internal void ExecuteNextAsync (Exception lasterror) { if (!Thread.CurrentThread.IsThreadPoolThread) ThreadPool.QueueUserWorkItem (_asynchandler, lasterror); else ExecuteNext (lasterror); } internal void ExecuteNext (Exception lasterror) { bool ready_sync = false; IStateHandler handler; lock (_app) { _app.OnStateExecuteEnter (); try { do { if (null != lasterror) { _app.HandleError (lasterror); lasterror = null; } // Check if request flow is to be stopped if ((_app.GetLastError () != null || _app._CompleteRequest) && _currentStateIdx < _endRequestStateIdx) { _currentStateIdx = _endRequestStateIdx; // MS does not filter on error _app._Context.Response.DoFilter (false); } else if (_currentStateIdx < _endStateIdx) { // Get next state handler _currentStateIdx++; } if (_currentStateIdx >= _handlers.Length) { _currentStateIdx = _endStateIdx; break; } handler = _handlers [_currentStateIdx]; _countSteps++; lasterror = ExecuteState (handler, ref ready_sync); if (ready_sync) _countSyncSteps++; } while (_currentStateIdx < _endStateIdx); if (null != lasterror) _app.HandleError (lasterror); } finally { _app.OnStateExecuteLeave (); } } // Finish the request off.. if (lasterror != null || _currentStateIdx == _endStateIdx) { _app._asyncWebResult.Complete ((_countSyncSteps == _countSteps), null, null); _app.Context.Handler = null; _app.Context.ApplicationInstance = null; _app.RecycleHandlers (); _app._asyncWebResult = null; HttpApplicationFactory.RecycleInstance (_app); } } private void OnAsyncCallback (object obj) { ExecuteNext ((Exception) obj); } #if TARGET_J2EE private Exception HandleJavaException(Exception obj) { Exception lasterror = null; if (obj is System.Reflection.TargetInvocationException ) { lasterror = obj.InnerException; #if DEBUG if (lasterror is java.lang.reflect.InvocationTargetException) { Console.WriteLine("Got java.lang.reflect.InvocationTargetException caused by"); java.lang.reflect.InvocationTargetException e1 = (java.lang.reflect.InvocationTargetException)lasterror; Console.WriteLine("{0},{1}", e1.getTargetException().GetType(), e1.getTargetException().Message); Console.WriteLine(e1.getTargetException().StackTrace); } else #endif if (lasterror is vmw.@internal.j2ee.StopExecutionException) { lasterror = null; _app.CompleteRequest (); } #if DEBUG else { Console.WriteLine("Error 1!!! {0}:{1}", lasterror.GetType(), lasterror.Message); Console.WriteLine(lasterror.StackTrace); } #endif } return lasterror; } #endif private Exception ExecuteState (IStateHandler state, ref bool readysync) { Exception lasterror = null; try { if (state.PossibleToTimeout) { _app.Context.BeginTimeoutPossible (); } try { state.Execute (); } finally { if (state.PossibleToTimeout) { _app.Context.EndTimeoutPossible (); } } #if TARGET_J2EE //Catch case of aborting by timeout if (_app.Context.TimedOut) { _app.CompleteRequest (); return null; } #endif if (state.PossibleToTimeout) { // Async Execute _app.Context.TryWaitForTimeout (); } readysync = state.CompletedSynchronously; #if TARGET_J2EE // Finishing execution for End without error }catch (vmw.@internal.j2ee.StopExecutionException){ lasterror = null; _app.CompleteRequest (); #endif } catch (ThreadAbortException obj) { object o = obj.ExceptionState; Type type = (o != null) ? o.GetType () : null; if (type == typeof (StepTimeout)) { Thread.ResetAbort (); lasterror = new HttpException ("The request timed out."); _app.CompleteRequest (); } else if (type == typeof (StepCompleteRequest)) { Thread.ResetAbort (); _app.CompleteRequest (); } } catch (Exception obj) { #if TARGET_J2EE lasterror = HandleJavaException(obj); #else lasterror = obj; #endif } return lasterror; } } #endregion #region Fields StateMachine _state; bool _CompleteRequest; HttpContext _Context; Exception _lastError; HttpContext _savedContext; IPrincipal _savedUser; HttpAsyncResult _asyncWebResult; ISite _Site; HttpModuleCollection _ModuleCollection; HttpSessionState _Session; HttpApplicationState _appState; string assemblyLocation; ArrayList _recycleHandlers; bool _InPreRequestResponseMode; CultureInfo appCulture; CultureInfo appUICulture; CultureInfo prevAppCulture; CultureInfo prevAppUICulture; #endregion #region Constructor #if TARGET_J2EE public HttpApplication () { } #else public HttpApplication () { assemblyLocation = GetType ().Assembly.Location; } #endif #endregion #region Methods internal IHttpHandler CreateHttpHandler (HttpContext context, string type, string file, string path) { HandlerFactoryConfiguration handler = HttpContext.GetAppConfig ("system.web/httpHandlers") as HandlerFactoryConfiguration; if (handler == null) throw new HttpException ("Cannot get system.web/httpHandlers handler."); object result = handler.FindHandler (type, file).GetInstance (); if (result is IHttpHandler) return (IHttpHandler) result; if (result is IHttpHandlerFactory) { IHttpHandlerFactory factory = (IHttpHandlerFactory) result; try { IHttpHandler ret = factory.GetHandler (context, type, file, path); if (null != ret) { if (null == _recycleHandlers) _recycleHandlers = new ArrayList(); _recycleHandlers.Add (new HandlerFactory (ret, factory)); } return ret; } catch (DirectoryNotFoundException) { throw new HttpException (404, "Cannot find '" + file + "'."); } catch (FileNotFoundException fnf) { string fname = fnf.FileName; if (fname != null && fname != "") { file = Path.GetFileName (fname); } throw new HttpException (404, "Cannot find '" + file + "'."); } } throw new HttpException ("Handler not found"); } internal void RecycleHandlers () { if (null == _recycleHandlers || _recycleHandlers.Count == 0) return; foreach (HandlerFactory item in _recycleHandlers) item.Factory.ReleaseHandler (item.Handler); _recycleHandlers.Clear (); } internal void InitModules () { ModulesConfiguration modules; modules = (ModulesConfiguration) HttpContext.GetAppConfig ("system.web/httpModules"); if (null == modules) throw new HttpException ( HttpRuntime.FormatResourceString ("missing_modules_config")); _ModuleCollection = modules.CreateCollection (); if (_ModuleCollection == null) return; int pos, count; count = _ModuleCollection.Count; for (pos = 0; pos != count; pos++) ((IHttpModule) _ModuleCollection.Get (pos)).Init (this); } internal void InitCulture () { GlobalizationConfiguration cfg = GlobalizationConfiguration.GetInstance (null); if (cfg != null) { appCulture = cfg.Culture; appUICulture = cfg.UICulture; } } void SaveThreadCulture () { Thread th = Thread.CurrentThread; if (appCulture != null) { prevAppCulture = th.CurrentCulture; th.CurrentCulture = appCulture; } if (appUICulture != null) { prevAppUICulture = th.CurrentUICulture; th.CurrentUICulture = appUICulture; } } void RestoreThreadCulture () { Thread th = Thread.CurrentThread; if (prevAppCulture != null) { th.CurrentCulture = prevAppCulture; prevAppCulture = null; } if (prevAppUICulture != null) { th.CurrentUICulture = prevAppUICulture; prevAppUICulture = null; } } internal void OnStateExecuteEnter () { InitCulture (); SaveThreadCulture (); _savedContext = HttpContext.Context; HttpContext.Context = _Context; HttpRuntime.TimeoutManager.Add (_Context); SetPrincipal (_Context.User); } internal void OnStateExecuteLeave () { RestoreThreadCulture (); HttpRuntime.TimeoutManager.Remove (_Context); HttpContext.Context = _savedContext; RestorePrincipal (); } #if TARGET_J2EE internal void SetPrincipal (IPrincipal principal) { } internal void RestorePrincipal () { } #else internal void SetPrincipal (IPrincipal principal) { // Don't overwrite _savedUser if called from inside a step if (_savedUser == null) _savedUser = Thread.CurrentPrincipal; Thread.CurrentPrincipal = principal; } internal void RestorePrincipal () { if (_savedUser == null) return; Thread.CurrentPrincipal = _savedUser; _savedUser = null; } #endif internal void ClearError () { _lastError = null; } internal Exception GetLastError () { if (_Context == null) return _lastError; return _Context.Error; } internal void HandleError (Exception obj) { EventHandler handler; bool fire = true; if (null != _Context) { if (null != _Context.Error) fire = false; _Context.AddError (obj); } else { if (null != _lastError) fire = false; _lastError = obj; } if (!fire) return; // Fire OnError event here handler = (EventHandler) Events [HttpApplication.ErrorId]; if (null != handler) { try { handler (this, EventArgs.Empty); } catch (Exception excp) { if (null != _Context) _Context.AddError (excp); } } } internal void Startup (HttpContext context, HttpApplicationState state) { _Context = context; _appState = state; _state = new StateMachine (this); // Initialize all IHttpModule(s) InitModules (); HttpApplicationFactory.AttachEvents (this); InitCulture (); // Initialize custom application _InPreRequestResponseMode = true; try { Init (); } catch (Exception obj) { HandleError (obj); } _InPreRequestResponseMode = false; _state.Init (); } internal void Cleanup () { try { Dispose (); } catch (Exception obj) { HandleError (obj); } if (null != _ModuleCollection) { int pos; int count = _ModuleCollection.Count; for (pos = 0; pos != count; pos++) ((IHttpModule) _ModuleCollection.Get (pos)).Dispose (); _ModuleCollection = null; } _state = null; } public void CompleteRequest () { _CompleteRequest = true; } public virtual void Dispose () { _Site = null; EventHandler disposed = (EventHandler) Events [HttpApplication.DisposedId]; if (null != disposed) disposed (this, EventArgs.Empty); } public virtual void Init () { } public virtual string GetVaryByCustomString (HttpContext context, string custom) { if (custom.ToLower () == "browser") return context.Request.Browser.Type; return null; } IAsyncResult IHttpAsyncHandler.BeginProcessRequest (HttpContext context, AsyncCallback cb, object extraData) { _Context = context; _Context.ApplicationInstance = this; _CompleteRequest = false; _asyncWebResult = new HttpAsyncResult (cb, extraData); _state.Start (); return _asyncWebResult; } void IHttpAsyncHandler.EndProcessRequest (IAsyncResult result) { HttpAsyncResult ar = (HttpAsyncResult) result; if (null != ar.Error) throw ar.Error; } void IHttpHandler.ProcessRequest (HttpContext context) { throw new NotSupportedException (HttpRuntime.FormatResourceString("sync_not_supported")); } bool IHttpHandler.IsReusable { get { return true; } } #endregion #region Properties internal string AssemblyLocation { get { return assemblyLocation; } } [Browsable (false)] [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)] public HttpApplicationState Application { get { return _appState; } } [Browsable (false)] [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)] public HttpContext Context { get { return _Context; } } protected EventHandlerList Events { get { if (null == _Events) _Events = new EventHandlerList (); return _Events; } } [Browsable (false)] [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)] public HttpModuleCollection Modules { get { if (null == _ModuleCollection) _ModuleCollection = new HttpModuleCollection (); return _ModuleCollection; } } [Browsable (false)] [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)] public HttpRequest Request { get { if (null != _Context && (!_InPreRequestResponseMode)) return _Context.Request; throw new HttpException ("Can't get request object"); } } [Browsable (false)] [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)] public HttpResponse Response { get { if (null != _Context && (!_InPreRequestResponseMode)) return _Context.Response; throw new HttpException ("Can't get response object"); } } [Browsable (false)] [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)] public HttpServerUtility Server { get { if (null != _Context) return _Context.Server; return new HttpServerUtility (this); } } [Browsable (false)] [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)] public HttpSessionState Session { #if TARGET_J2EE get { if (null != _Context && null != _Context.Session) return _Context.Session; throw new HttpException ("Failed to get session object"); } #else get { if (null != _Session) return _Session; if (null != _Context && null != _Context.Session) return _Context.Session; throw new HttpException ("Failed to get session object"); } #endif } [Browsable (false)] [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)] public IPrincipal User { get { return _Context.User; } } [Browsable (false)] [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)] public ISite Site { get { return _Site; } set { _Site = value; } } #endregion Properties } // Used in HttpResponse.End () class StepCompleteRequest { } }
// <copyright file="FirefoxDriver.cs" company="WebDriver Committers"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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. // </copyright> using System; using System.Collections.Generic; using System.IO; using OpenQA.Selenium.Remote; namespace OpenQA.Selenium.Firefox { /// <summary> /// Provides a way to access Firefox to run tests. /// </summary> /// <remarks> /// When the FirefoxDriver object has been instantiated the browser will load. The test can then navigate to the URL under test and /// start your test. /// <para> /// In the case of the FirefoxDriver, you can specify a named profile to be used, or you can let the /// driver create a temporary, anonymous profile. A custom extension allowing the driver to communicate /// to the browser will be installed into the profile. /// </para> /// </remarks> /// <example> /// <code> /// [TestFixture] /// public class Testing /// { /// private IWebDriver driver; /// <para></para> /// [SetUp] /// public void SetUp() /// { /// driver = new FirefoxDriver(); /// } /// <para></para> /// [Test] /// public void TestGoogle() /// { /// driver.Navigate().GoToUrl("http://www.google.co.uk"); /// /* /// * Rest of the test /// */ /// } /// <para></para> /// [TearDown] /// public void TearDown() /// { /// driver.Quit(); /// } /// } /// </code> /// </example> public class FirefoxDriver : RemoteWebDriver { private const string SetContextCommand = "setContext"; private const string InstallAddOnCommand = "installAddOn"; private const string UninstallAddOnCommand = "uninstallAddOn"; /// <summary> /// Initializes a new instance of the <see cref="FirefoxDriver"/> class. /// </summary> public FirefoxDriver() : this(new FirefoxOptions()) { } /// <summary> /// Initializes a new instance of the <see cref="FirefoxDriver"/> class using the specified options. Uses the Mozilla-provided Marionette driver implementation. /// </summary> /// <param name="options">The <see cref="FirefoxOptions"/> to be used with the Firefox driver.</param> public FirefoxDriver(FirefoxOptions options) : this(CreateService(options), options, RemoteWebDriver.DefaultCommandTimeout) { } /// <summary> /// Initializes a new instance of the <see cref="FirefoxDriver"/> class using the specified driver service. Uses the Mozilla-provided Marionette driver implementation. /// </summary> /// <param name="service">The <see cref="FirefoxDriverService"/> used to initialize the driver.</param> public FirefoxDriver(FirefoxDriverService service) : this(service, new FirefoxOptions(), RemoteWebDriver.DefaultCommandTimeout) { } /// <summary> /// Initializes a new instance of the <see cref="FirefoxDriver"/> class using the specified path /// to the directory containing geckodriver.exe. /// </summary> /// <param name="geckoDriverDirectory">The full path to the directory containing geckodriver.exe.</param> public FirefoxDriver(string geckoDriverDirectory) : this(geckoDriverDirectory, new FirefoxOptions()) { } /// <summary> /// Initializes a new instance of the <see cref="FirefoxDriver"/> class using the specified path /// to the directory containing geckodriver.exe and options. /// </summary> /// <param name="geckoDriverDirectory">The full path to the directory containing geckodriver.exe.</param> /// <param name="options">The <see cref="FirefoxOptions"/> to be used with the Firefox driver.</param> public FirefoxDriver(string geckoDriverDirectory, FirefoxOptions options) : this(geckoDriverDirectory, options, RemoteWebDriver.DefaultCommandTimeout) { } /// <summary> /// Initializes a new instance of the <see cref="FirefoxDriver"/> class using the specified path /// to the directory containing geckodriver.exe, options, and command timeout. /// </summary> /// <param name="geckoDriverDirectory">The full path to the directory containing geckodriver.exe.</param> /// <param name="options">The <see cref="FirefoxOptions"/> to be used with the Firefox driver.</param> /// <param name="commandTimeout">The maximum amount of time to wait for each command.</param> public FirefoxDriver(string geckoDriverDirectory, FirefoxOptions options, TimeSpan commandTimeout) : this(FirefoxDriverService.CreateDefaultService(geckoDriverDirectory), options, commandTimeout) { } /// <summary> /// Initializes a new instance of the <see cref="FirefoxDriver"/> class using the specified options, driver service, and timeout. Uses the Mozilla-provided Marionette driver implementation. /// </summary> /// <param name="service">The <see cref="FirefoxDriverService"/> to use.</param> /// <param name="options">The <see cref="FirefoxOptions"/> to be used with the Firefox driver.</param> public FirefoxDriver(FirefoxDriverService service, FirefoxOptions options) : this(service, options, RemoteWebDriver.DefaultCommandTimeout) { } /// <summary> /// Initializes a new instance of the <see cref="FirefoxDriver"/> class using the specified options, driver service, and timeout. Uses the Mozilla-provided Marionette driver implementation. /// </summary> /// <param name="service">The <see cref="FirefoxDriverService"/> to use.</param> /// <param name="options">The <see cref="FirefoxOptions"/> to be used with the Firefox driver.</param> /// <param name="commandTimeout">The maximum amount of time to wait for each command.</param> public FirefoxDriver(FirefoxDriverService service, FirefoxOptions options, TimeSpan commandTimeout) : base(new DriverServiceCommandExecutor(service, commandTimeout), ConvertOptionsToCapabilities(options)) { // Add the custom commands unique to Firefox this.AddCustomFirefoxCommand(SetContextCommand, CommandInfo.PostCommand, "/session/{sessionId}/moz/context"); this.AddCustomFirefoxCommand(InstallAddOnCommand, CommandInfo.PostCommand, "/session/{sessionId}/moz/addon/install"); this.AddCustomFirefoxCommand(UninstallAddOnCommand, CommandInfo.PostCommand, "/session/{sessionId}/moz/addon/uninstall"); } /// <summary> /// Gets or sets the <see cref="IFileDetector"/> responsible for detecting /// sequences of keystrokes representing file paths and names. /// </summary> /// <remarks>The Firefox driver does not allow a file detector to be set, /// as the server component of the Firefox driver only allows uploads from /// the local computer environment. Attempting to set this property has no /// effect, but does not throw an exception. If you are attempting to run /// the Firefox driver remotely, use <see cref="RemoteWebDriver"/> in /// conjunction with a standalone WebDriver server.</remarks> public override IFileDetector FileDetector { get { return base.FileDetector; } set { } } /// <summary> /// Sets the command context used when issuing commands to geckodriver. /// </summary> /// <param name="context">The <see cref="FirefoxCommandContext"/> value to which to set the context.</param> public void SetContext(FirefoxCommandContext context) { string contextValue = context.ToString().ToLowerInvariant(); Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters["context"] = contextValue; Response response = this.Execute(SetContextCommand, parameters); } /// <summary> /// Installs a Firefox add-on from a file, typically a .xpi file. /// </summary> /// <param name="addOnFileToInstall">Full path and file name of the add-on to install.</param> public void InstallAddOnFromFile(string addOnFileToInstall) { if (string.IsNullOrEmpty(addOnFileToInstall)) { throw new ArgumentNullException("addOnFileToInstall", "Add-on file name must not be null or the empty string"); } if (!File.Exists(addOnFileToInstall)) { throw new ArgumentException("File " + addOnFileToInstall + " does not exist", "addOnFileToInstall"); } // Implementation note: There is a version of the install add-on // command that can be used with a file name directly, by passing // a "path" property in the parameters object of the command. If // delegating to the "use the base64-encoded blob" version causes // issues, we can change this method to use the file name directly // instead. byte[] addOnBytes = File.ReadAllBytes(addOnFileToInstall); string base64AddOn = Convert.ToBase64String(addOnBytes); this.InstallAddOn(base64AddOn); } /// <summary> /// Installs a Firefox add-on. /// </summary> /// <param name="base64EncodedAddOn">The base64-encoded string representation of the add-on binary.</param> public void InstallAddOn(string base64EncodedAddOn) { if (string.IsNullOrEmpty(base64EncodedAddOn)) { throw new ArgumentNullException("base64EncodedAddOn", "Base64 encoded add-on must not be null or the empty string"); } Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters["addon"] = base64EncodedAddOn; this.Execute(InstallAddOnCommand, parameters); } /// <summary> /// Uninstalls a Firefox add-on. /// </summary> /// <param name="addOnId">The ID of the add-on to uninstall.</param> public void UninstallAddOn(string addOnId) { if (string.IsNullOrEmpty(addOnId)) { throw new ArgumentNullException("addOnId", "Base64 encoded add-on must not be null or the empty string"); } Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters["id"] = addOnId; this.Execute(UninstallAddOnCommand, parameters); } /// <summary> /// In derived classes, the <see cref="PrepareEnvironment"/> method prepares the environment for test execution. /// </summary> protected virtual void PrepareEnvironment() { // Does nothing, but provides a hook for subclasses to do "stuff" } private static ICapabilities ConvertOptionsToCapabilities(FirefoxOptions options) { if (options == null) { throw new ArgumentNullException("options", "options must not be null"); } return options.ToCapabilities(); } private static FirefoxDriverService CreateService(FirefoxOptions options) { return FirefoxDriverService.CreateDefaultService(); } private void AddCustomFirefoxCommand(string commandName, string method, string resourcePath) { CommandInfo commandInfoToAdd = new CommandInfo(method, resourcePath); this.CommandExecutor.CommandInfoRepository.TryAddCommand(commandName, commandInfoToAdd); } } }
#region Copyright (c) 2016 Atif Aziz. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion namespace WebLinq.Modules { #region Imports using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Data; using System.Linq; using System.Net.Http; using System.Reactive.Linq; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using System.Xml.Linq; using Html; using Mannex.Collections.Generic; using Sys; using Xsv; using Unit = System.Reactive.Unit; using HttpClient = HttpClient; using LoadOption = System.Xml.Linq.LoadOptions; #endregion public static class UriModule { public static Uri FormatUri(FormattableString formattableString) => formattableString == null ? throw new ArgumentNullException(nameof(formattableString)) : new Uri((FormatStringParser.Parse(formattableString.Format, (s, i, len) => s.HasWhiteSpace(i, len), delegate { return false; }) .Any(hws => hws) ? FormattableStringFactory.Create( string.Join(string.Empty, FormatStringParser.Parse(formattableString.Format, (s, i, len) => Regex.Replace(s.Substring(i, len), @"\s+", string.Empty), (s, i, len) => s.Substring(i, len))), formattableString.GetArguments()) : formattableString).ToString(UriFormatProvider.InvariantCulture)); } public static class HttpModule { public static IHttpClient Http => HttpClient.Default; public static IObservable<HttpFetch<ParsedHtml>> Html(this IHttpObservable query) => query.Html(HtmlParser.Default); public static IHttpObservable Submit(this IHttpObservable query, string formSelector, NameValueCollection data) => Submit(query, formSelector, null, null, data); public static IHttpObservable Submit(this IHttpObservable query, int formIndex, NameValueCollection data) => Submit(query, null, formIndex, null, data); public static IHttpObservable SubmitTo(this IHttpObservable query, Uri url, string formSelector, NameValueCollection data) => Submit(query, formSelector, null, url, data); public static IHttpObservable SubmitTo(this IHttpObservable query, Uri url, int formIndex, NameValueCollection data) => Submit(query, null, formIndex, url, data); static IHttpObservable Submit(IHttpObservable query, string formSelector, int? formIndex, Uri url, NameValueCollection data) => HttpObservable.Return( from html in query.Html() select HttpQuery.Submit(html.Client, html.Content, formSelector, formIndex, url, data)); public static IHttpObservable Submit(this IHttpObservable query, string formSelector, ISubmissionData<Unit> data) => Submit(query, formSelector, null, null, data); public static IHttpObservable Submit(this IHttpObservable query, int formIndex, ISubmissionData<Unit> data) => Submit(query, null, formIndex, null, data); public static IHttpObservable SubmitTo(this IHttpObservable query, Uri url, string formSelector, ISubmissionData<Unit> data) => Submit(query, formSelector, null, url, data); public static IHttpObservable SubmitTo(this IHttpObservable query, Uri url, int formIndex, ISubmissionData<Unit> data) => Submit(query, null, formIndex, url, data); static IHttpObservable Submit(IHttpObservable query, string formSelector, int? formIndex, Uri url, ISubmissionData<Unit> data) => query.Html().Submit(formSelector, formIndex, url, data); public static IObservable<HttpFetch<string>> Links(this IHttpObservable query) => query.Links(null); public static IObservable<HttpFetch<T>> Links<T>(this IHttpObservable query, Func<string, HtmlObject, T> selector) => Links(query, null, selector); public static IObservable<HttpFetch<string>> Links(this IHttpObservable query, Uri baseUrl) => Links(query, baseUrl, (href, _) => href); public static IObservable<HttpFetch<T>> Links<T>(this IHttpObservable query, Uri baseUrl, Func<string, HtmlObject, T> selector) => query.Html().Links(baseUrl, selector); public static IObservable<HttpFetch<HtmlObject>> Tables(this IHttpObservable query) => query.Html().Tables(); public static IObservable<HttpFetch<DataTable>> FormsAsDataTable(this IHttpObservable query) => query.Html().FormsAsDataTable(); public static IObservable<HttpFetch<HtmlForm>> Forms(this IHttpObservable query) => query.Html().Forms(); public static IObservable<HttpFetch<HttpContent>> Crawl(Uri url) => Crawl(url, int.MaxValue); public static IObservable<HttpFetch<HttpContent>> Crawl(Uri url, int depth) => Crawl(url, depth, _ => true); public static IObservable<HttpFetch<HttpContent>> Crawl(Uri url, Func<Uri, bool> followPredicate) => Crawl(url, int.MaxValue, followPredicate); public static IObservable<HttpFetch<HttpContent>> Crawl(Uri url, int depth, Func<Uri, bool> followPredicate) => CrawlImpl(url, depth, followPredicate).ToObservable(); static IEnumerable<HttpFetch<HttpContent>> CrawlImpl(Uri rootUrl, int depth, Func<Uri, bool> followPredicate) { var linkSet = new HashSet<Uri> { rootUrl }; var queue = new Queue<KeyValuePair<int, Uri>>(); queue.Enqueue(0.AsKeyTo(rootUrl)); while (queue.Count > 0) { var dequeued = queue.Dequeue(); var url = dequeued.Value; var level = dequeued.Key; // TODO retry intermittent errors? var fetch = Http.Get(url) .SkipErroneousFetch() .Buffer() .SingleOrDefaultAsync() .GetAwaiter() .GetResult(); if (fetch == null) continue; yield return fetch; if (level >= depth) continue; // If content is HTML then sniff links and add them to the // queue assuming they are from the same domain and pass the // user-supplied condition to follow. var contentMediaType = fetch.Content.Headers.ContentType?.MediaType; if (!"text/html".Equals(contentMediaType, StringComparison.OrdinalIgnoreCase)) continue; var lq = from e in HttpObservable.Return(_ => Observable.Return(fetch)).Links().Content() select Uri.TryCreate(e, UriKind.Absolute, out url) ? url : null into e where e != null && (e.Scheme == Uri.UriSchemeHttp || e.Scheme == Uri.UriSchemeHttps) && !linkSet.Contains(e) && rootUrl.Host.Equals(e.Host, StringComparison.OrdinalIgnoreCase) && followPredicate(e) select e; foreach (var e in lq.ToEnumerable()) { if (linkSet.Add(e)) queue.Enqueue((level + 1).AsKeyTo(e)); } } } } public static class HtmlModule { public static IHtmlParser HtmlParser => Html.HtmlParser.Default; public static ParsedHtml ParseHtml(string html) => ParseHtml(html, null); public static ParsedHtml ParseHtml(string html, Uri baseUrl) => HtmlParser.Parse(html, baseUrl); public static IEnumerable<string> Links(string html) => Links(html, null, (href, _) => href); public static IEnumerable<T> Links<T>(string html, Func<string, HtmlObject, T> selector) => Links(html, null, selector); public static IEnumerable<string> Links(string html, Uri baseUrl) => Links(html, baseUrl, (href, _) => href); public static IEnumerable<T> Links<T>(string html, Uri baseUrl, Func<string, HtmlObject, T> selector) => ParseHtml(html, baseUrl).Links(selector); public static IEnumerable<HtmlObject> Tables(string html) => ParseHtml(html).Tables(); } public static class XsvModule { public static IObservable<DataTable> CsvToDataTable(string text, params DataColumn[] columns) => XsvToDataTable(text, ",", true, columns); public static IObservable<DataTable> XsvToDataTable(string text, string delimiter, bool quoted, params DataColumn[] columns) => XsvQuery.XsvToDataTable(text, delimiter, quoted, columns); } public static class XmlModule { public static XDocument ParseXml(string xml) => XDocument.Parse(xml, LoadOptions.None); public static XDocument ParseXml(string xml, LoadOption options) => XDocument.Parse(xml, options); } public static class SpawnModule { public static ISpawnObservable<string> Spawn(string path, ProgramArguments args) => Spawner.Default.Spawn(path, args, output => output, null); public static ISpawnObservable<KeyValuePair<T, string>> Spawn<T>(string path, ProgramArguments args, T stdoutKey, T stderrKey) => Spawner.Default.Spawn(path, args, stdoutKey, stderrKey); public static ISpawnObservable<T> Spawn<T>(string path, ProgramArguments args, Func<string, T> stdoutSelector, Func<string, T> stderrSelector) => Spawner.Default.Spawn(path, args, stdoutSelector, stderrSelector); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /* * This files defines the following types: * - _IOCompletionCallback * - OverlappedData * - Overlapped */ /*============================================================================= ** ** ** ** Purpose: Class for converting information to and from the native ** overlapped structure used in asynchronous file i/o ** ** =============================================================================*/ using System.Runtime; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Runtime.ConstrainedExecution; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Collections.Concurrent; namespace System.Threading { #region class _IOCompletionCallback internal class _IOCompletionCallback { private IOCompletionCallback _ioCompletionCallback; private ExecutionContext _executionContext; private uint _errorCode; // Error code private uint _numBytes; // No. of bytes transferred private unsafe NativeOverlapped* _pOVERLAP; internal _IOCompletionCallback(IOCompletionCallback ioCompletionCallback) { _ioCompletionCallback = ioCompletionCallback; _executionContext = ExecutionContext.Capture(); } private static ContextCallback s_ccb = new ContextCallback(IOCompletionCallback_Context); private static unsafe void IOCompletionCallback_Context(Object state) { _IOCompletionCallback helper = (_IOCompletionCallback)state; Debug.Assert(helper != null, "_IOCompletionCallback cannot be null"); helper._ioCompletionCallback(helper._errorCode, helper._numBytes, helper._pOVERLAP); } internal static unsafe void PerformIOCompletionCallback(uint errorCode, uint numBytes, NativeOverlapped* pOVERLAP) { Overlapped overlapped; _IOCompletionCallback helper; do { overlapped = OverlappedData.GetOverlappedFromNative(pOVERLAP).m_overlapped; helper = overlapped.iocbHelper; if (helper == null || helper._executionContext == null || helper._executionContext == ExecutionContext.Default) { // We got here because of UnsafePack (or) Pack with EC flow supressed IOCompletionCallback callback = overlapped.UserCallback; callback(errorCode, numBytes, pOVERLAP); } else { // We got here because of Pack helper._errorCode = errorCode; helper._numBytes = numBytes; helper._pOVERLAP = pOVERLAP; ExecutionContext.Run(helper._executionContext, s_ccb, helper); } //Quickly check the VM again, to see if a packet has arrived. //OverlappedData.CheckVMForIOPacket(out pOVERLAP, out errorCode, out numBytes); pOVERLAP = null; } while (pOVERLAP != null); } } #endregion class _IOCompletionCallback #region class OverlappedData internal sealed class OverlappedData { // The offset of m_nativeOverlapped field from m_pEEType private static int s_nativeOverlappedOffset; internal IAsyncResult m_asyncResult; internal IOCompletionCallback m_iocb; internal _IOCompletionCallback m_iocbHelper; internal Overlapped m_overlapped; private Object m_userObject; private IntPtr m_pinSelf; private GCHandle[] m_pinnedData; internal NativeOverlapped m_nativeOverlapped; // Adding an empty default ctor for annotation purposes internal OverlappedData() { } ~OverlappedData() { if (m_pinnedData != null) { for (int i = 0; i < m_pinnedData.Length; i++) { if (m_pinnedData[i].IsAllocated) { m_pinnedData[i].Free(); } } } } internal void ReInitialize() { m_asyncResult = null; m_iocb = null; m_iocbHelper = null; m_overlapped = null; m_userObject = null; Debug.Assert(m_pinSelf.IsNull(), "OverlappedData has not been freed: m_pinSelf"); m_pinSelf = IntPtr.Zero; // Reuse m_pinnedData array m_nativeOverlapped = default(NativeOverlapped); } internal unsafe NativeOverlapped* Pack(IOCompletionCallback iocb, Object userData) { if (!m_pinSelf.IsNull()) { throw new InvalidOperationException(SR.InvalidOperation_Overlapped_Pack); } m_iocb = iocb; m_iocbHelper = (iocb != null) ? new _IOCompletionCallback(iocb) : null; m_userObject = userData; return AllocateNativeOverlapped(); } internal unsafe NativeOverlapped* UnsafePack(IOCompletionCallback iocb, Object userData) { if (!m_pinSelf.IsNull()) { throw new InvalidOperationException(SR.InvalidOperation_Overlapped_Pack); } m_iocb = iocb; m_iocbHelper = null; m_userObject = userData; return AllocateNativeOverlapped(); } internal IntPtr UserHandle { get { return m_nativeOverlapped.EventHandle; } set { m_nativeOverlapped.EventHandle = value; } } private unsafe NativeOverlapped* AllocateNativeOverlapped() { if (m_userObject != null) { if (m_userObject.GetType() == typeof(Object[])) { Object[] objArray = (Object[])m_userObject; if (m_pinnedData == null || m_pinnedData.Length < objArray.Length) Array.Resize(ref m_pinnedData, objArray.Length); for (int i = 0; i < objArray.Length; i++) { if (!m_pinnedData[i].IsAllocated) m_pinnedData[i] = GCHandle.Alloc(objArray[i], GCHandleType.Pinned); else m_pinnedData[i].Target = objArray[i]; } } else { if (m_pinnedData == null || m_pinnedData.Length < 1) m_pinnedData = new GCHandle[1]; if (!m_pinnedData[0].IsAllocated) m_pinnedData[0] = GCHandle.Alloc(m_userObject, GCHandleType.Pinned); else m_pinnedData[0].Target = m_userObject; } } m_pinSelf = RuntimeImports.RhHandleAlloc(this, GCHandleType.Pinned); fixed (NativeOverlapped* pNativeOverlapped = &m_nativeOverlapped) { return pNativeOverlapped; } } internal static unsafe void FreeNativeOverlapped(NativeOverlapped* nativeOverlappedPtr) { OverlappedData overlappedData = OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr); overlappedData.FreeNativeOverlapped(); } private void FreeNativeOverlapped() { IntPtr pinSelf = m_pinSelf; if (!pinSelf.IsNull()) { if (Interlocked.CompareExchange(ref m_pinSelf, IntPtr.Zero, pinSelf) == pinSelf) { if (m_pinnedData != null) { for (int i = 0; i < m_pinnedData.Length; i++) { if (m_pinnedData[i].IsAllocated && (m_pinnedData[i].Target != null)) { m_pinnedData[i].Target = null; } } } RuntimeImports.RhHandleFree(pinSelf); } } } internal static unsafe OverlappedData GetOverlappedFromNative(NativeOverlapped* nativeOverlappedPtr) { if (s_nativeOverlappedOffset == 0) { CalculateNativeOverlappedOffset(); } void* pOverlappedData = (byte*)nativeOverlappedPtr - s_nativeOverlappedOffset; return Unsafe.Read<OverlappedData>(&pOverlappedData); } private static unsafe void CalculateNativeOverlappedOffset() { OverlappedData overlappedData = new OverlappedData(); fixed (IntPtr* pEETypePtr = &overlappedData.m_pEEType) fixed (NativeOverlapped* pNativeOverlapped = &overlappedData.m_nativeOverlapped) { s_nativeOverlappedOffset = (int)((byte*)pNativeOverlapped - (byte*)pEETypePtr); } } } #endregion class OverlappedData #region class Overlapped public class Overlapped { private static PinnableBufferCache s_overlappedDataCache = new PinnableBufferCache("System.Threading.OverlappedData", () => new OverlappedData()); private OverlappedData m_overlappedData; public Overlapped() { m_overlappedData = (OverlappedData)s_overlappedDataCache.Allocate(); m_overlappedData.m_overlapped = this; } public Overlapped(int offsetLo, int offsetHi, IntPtr hEvent, IAsyncResult ar) { m_overlappedData = (OverlappedData)s_overlappedDataCache.Allocate(); m_overlappedData.m_overlapped = this; m_overlappedData.m_nativeOverlapped.OffsetLow = offsetLo; m_overlappedData.m_nativeOverlapped.OffsetHigh = offsetHi; m_overlappedData.UserHandle = hEvent; m_overlappedData.m_asyncResult = ar; } [Obsolete("This constructor is not 64-bit compatible. Use the constructor that takes an IntPtr for the event handle. http://go.microsoft.com/fwlink/?linkid=14202")] public Overlapped(int offsetLo, int offsetHi, int hEvent, IAsyncResult ar) : this(offsetLo, offsetHi, new IntPtr(hEvent), ar) { } public IAsyncResult AsyncResult { get { return m_overlappedData.m_asyncResult; } set { m_overlappedData.m_asyncResult = value; } } public int OffsetLow { get { return m_overlappedData.m_nativeOverlapped.OffsetLow; } set { m_overlappedData.m_nativeOverlapped.OffsetLow = value; } } public int OffsetHigh { get { return m_overlappedData.m_nativeOverlapped.OffsetHigh; } set { m_overlappedData.m_nativeOverlapped.OffsetHigh = value; } } [Obsolete("This property is not 64-bit compatible. Use EventHandleIntPtr instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int EventHandle { get { return m_overlappedData.UserHandle.ToInt32(); } set { m_overlappedData.UserHandle = new IntPtr(value); } } public IntPtr EventHandleIntPtr { get { return m_overlappedData.UserHandle; } set { m_overlappedData.UserHandle = value; } } internal _IOCompletionCallback iocbHelper { get { return m_overlappedData.m_iocbHelper; } } internal IOCompletionCallback UserCallback { get { return m_overlappedData.m_iocb; } } /*==================================================================== * Packs a managed overlapped class into native Overlapped struct. * Roots the iocb and stores it in the ReservedCOR field of native Overlapped * Pins the native Overlapped struct and returns the pinned index. ====================================================================*/ [Obsolete("This method is not safe. Use Pack (iocb, userData) instead. http://go.microsoft.com/fwlink/?linkid=14202")] [CLSCompliant(false)] public unsafe NativeOverlapped* Pack(IOCompletionCallback iocb) { return Pack(iocb, null); } [CLSCompliant(false)] public unsafe NativeOverlapped* Pack(IOCompletionCallback iocb, Object userData) { return m_overlappedData.Pack(iocb, userData); } [Obsolete("This method is not safe. Use UnsafePack (iocb, userData) instead. http://go.microsoft.com/fwlink/?linkid=14202")] [CLSCompliant(false)] public unsafe NativeOverlapped* UnsafePack(IOCompletionCallback iocb) { return UnsafePack(iocb, null); } [CLSCompliant(false)] public unsafe NativeOverlapped* UnsafePack(IOCompletionCallback iocb, Object userData) { return m_overlappedData.UnsafePack(iocb, userData); } /*==================================================================== * Unpacks an unmanaged native Overlapped struct. * Unpins the native Overlapped struct ====================================================================*/ [CLSCompliant(false)] public static unsafe Overlapped Unpack(NativeOverlapped* nativeOverlappedPtr) { if (nativeOverlappedPtr == null) throw new ArgumentNullException(nameof(nativeOverlappedPtr)); Contract.EndContractBlock(); Overlapped overlapped = OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr).m_overlapped; return overlapped; } [CLSCompliant(false)] public static unsafe void Free(NativeOverlapped* nativeOverlappedPtr) { if (nativeOverlappedPtr == null) throw new ArgumentNullException(nameof(nativeOverlappedPtr)); Contract.EndContractBlock(); Overlapped overlapped = OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr).m_overlapped; OverlappedData.FreeNativeOverlapped(nativeOverlappedPtr); OverlappedData overlappedData = overlapped.m_overlappedData; overlapped.m_overlappedData = null; overlappedData.ReInitialize(); s_overlappedDataCache.Free(overlappedData); } } #endregion class Overlapped } // namespace
// Copyright 2014 The Rector & Visitors of the University of Virginia // // 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 Xamarin.Forms; using Newtonsoft.Json; using Sensus.UI.UiProperties; using System.Collections.Generic; using System.Linq; namespace Sensus.UI.Inputs { public class SliderWithOptionsInput : Input, IVariableDefiningInput { public const string EFFECT_RESOLUTION_EFFECT_NAME = "HideSliderEffect"; public const string EFFECT_RESOLUTION_NAME = EFFECT_RESOLUTION_GROUP_NAME + "." + EFFECT_RESOLUTION_EFFECT_NAME; private readonly Effect _effect = Effect.Resolve(EFFECT_RESOLUTION_NAME); private string _tipText; private Slider _slider; private double _incrementalValue; private bool _incrementalValueHasChanged; private Label _sliderLabel; private ButtonGridView _grid; private string _definedVariable; private object _value; /// <summary> /// A short tip that explains how to pick an item from the dialog window. /// </summary> /// <value>The tip text.</value> [EntryStringUiProperty("Tip Text:", true, 9, false)] public string TipText { get { return _tipText; } set { _tipText = value?.Trim(); } } /// <summary> /// Minimum value available on the slider. /// </summary> /// <value>The minimum.</value> [EntryDoubleUiProperty(null, true, 10, true)] public double Minimum { get; set; } /// <summary> /// Maximum value available on the slider. /// </summary> /// <value>The maximum.</value> [EntryDoubleUiProperty(null, true, 11, true)] public double Maximum { get; set; } /// <summary> /// How much the slider's value should change between points. /// </summary> /// <value>The increment.</value> [EntryDoubleUiProperty(null, true, 12, true)] public double Increment { get; set; } /// <summary> /// Label to display at the left end of the slider range. /// </summary> /// <value>The left label.</value> [EntryStringUiProperty("Left Label:", true, 13, false)] public string LeftLabel { get; set; } /// <summary> /// Label to display at the right end of the slider range. /// </summary> /// <value>The left label.</value> [EntryStringUiProperty("Right Label:", true, 14, false)] public string RightLabel { get; set; } /// <summary> /// Whether or not the slider's current value should be displayed. /// </summary> /// <value><c>true</c> to display slider value; otherwise, <c>false</c>.</value> [OnOffUiProperty("Display Slider Value:", true, 15)] public bool DisplaySliderValue { get; set; } /// <summary> /// Whether or not to display the minimum and maximum values of the slider. /// </summary> /// <value><c>true</c> to display the minimum and maximum; otherwise, <c>false</c>.</value> [OnOffUiProperty("Display Min and Max:", true, 16)] public bool DisplayMinMax { get; set; } [EditableListUiProperty("Other Options:", true, 17, true)] public List<string> OtherOptions { get; set; } public bool AutoSizeOptionButtons { get; set; } /// <summary> /// The name of the variable in <see cref="Protocol.VariableValueUiProperty"/> that this input should /// define the value for. For example, if you wanted this input to supply the value for a variable /// named `study-name`, then set this field to `study-name` and the user's selection will be used as /// the value for this variable. /// </summary> /// <value>The defined variable.</value> [EntryStringUiProperty("Define Variable:", true, 2, false)] public string DefinedVariable { get { return _definedVariable; } set { _definedVariable = value?.Trim(); } } public override object Value { get { // the slider can be untouched but still have a value associated with it (i.e., the position of the slider). if the slider // is not a required input, then this value would be returned, which is not what we want since the user never interacted with the // input. so, additionally keep track of whether the value has actually changed, indicating that the user has touched the control. return _value; // _slider == null || !_incrementalValueHasChanged ? null : (object)_incrementalValue; } } [JsonIgnore] public override bool Enabled { get { return _slider.IsEnabled; } set { _slider.IsEnabled = value; if (_grid != null) { _grid.IsEnabled = value; } } } public override string DefaultName { get { return "Slider (with options)"; } } public SliderWithOptionsInput() { Construct(1, 10); } public SliderWithOptionsInput(string labelText, double minimum, double maximum) : base(labelText) { Construct(minimum, maximum); } public SliderWithOptionsInput(string labelText, string name, double minimum, double maximum) : base(labelText, name) { Construct(minimum, maximum); } private void Construct(double minimum, double maximum) { _tipText = "Please tap the range below to select a value"; Minimum = minimum; Maximum = maximum; Increment = (Maximum - Minimum + 1) / 10; LeftLabel = null; RightLabel = null; DisplaySliderValue = true; DisplayMinMax = true; } public override View GetView(int index) { if (base.GetView(index) == null) { _slider = new Slider { HorizontalOptions = LayoutOptions.FillAndExpand, // need to set the min and max to extremes to allow them to be reset below to arbitrary values Minimum = double.MinValue, Maximum = double.MaxValue // set the style ID on the view so that we can retrieve it when UI testing #if UI_TESTING , StyleId = Name #endif }; Label sliderValueLabel = new Label() { FontSize = 20, HorizontalOptions = LayoutOptions.CenterAndExpand, HorizontalTextAlignment = TextAlignment.Center, IsVisible = false }; Label optionsLabel = new Label { HorizontalOptions = LayoutOptions.CenterAndExpand, FontSize = 18, Text = "More choices ...", TextColor = (Color)Application.Current.Resources["LessDimmedColor"], TextDecorations = TextDecorations.Underline, }; TapGestureRecognizer gesture = new TapGestureRecognizer() { NumberOfTapsRequired = 1 }; gesture.Tapped += (s, e) => { if (_slider.Effects.Contains(_effect) == false) { _slider.Effects.Add(_effect); } sliderValueLabel.IsVisible = false; optionsLabel.IsVisible = false; _grid.IsVisible = true; }; optionsLabel.GestureRecognizers.Add(gesture); _incrementalValue = double.NaN; // need this to ensure that the initial value selected by the user registers as a change. _incrementalValueHasChanged = false; _sliderLabel = CreateLabel(index); if (!string.IsNullOrWhiteSpace(_tipText)) { _sliderLabel.Text += " (" + _tipText + ")"; } _slider.Minimum = Minimum; _slider.Maximum = Maximum; // set the initial value to the minimum so that the slider bar progress fill does not reflect an // initial value of zero. the thumb has been hidden, but the fill will be rendered according to this // value. this is needed with a slider range that has a negative minimum. _slider.Value = Minimum; _slider.ValueChanged += (sender, e) => { double newIncrementalValue = GetIncrementalValue(e.NewValue); if (newIncrementalValue != _incrementalValue) { _incrementalValue = newIncrementalValue; _incrementalValueHasChanged = true; _value = _incrementalValue; _slider.Value = _incrementalValue; Complete = true; _slider.Effects.Remove(_effect); foreach (ButtonWithValue gridButton in _grid.Buttons) { gridButton.Style = null; } optionsLabel.IsVisible = true; _grid.IsVisible = false; sliderValueLabel.IsVisible = DisplaySliderValue; sliderValueLabel.Text = _incrementalValue.ToString(); } }; // we use the effects framework to hide the slider's initial position from the user, in order to avoid biasing the user away from or toward the initial position. _slider.Effects.Add(_effect); _grid = new ButtonGridView(1, (s, e) => { ButtonWithValue button = (ButtonWithValue)s; _value = button.Value; Complete = true; foreach (ButtonWithValue gridButton in _grid.Buttons) { gridButton.Style = null; } button.Style = (Style)Application.Current.Resources["SelectedButton"]; }) { AutoSize = AutoSizeOptionButtons, IsVisible = false }; StackLayout optionsLayout = new StackLayout { HorizontalOptions = LayoutOptions.FillAndExpand, Orientation = StackOrientation.Vertical, IsVisible = OtherOptions.Any(), Children = { optionsLabel, _grid } }; foreach (string buttonValue in OtherOptions) { ButtonWithValue button = _grid.AddButton(buttonValue, buttonValue); button.StyleClass = new List<string>(); } _grid.Arrange(); base.SetView(new StackLayout { Orientation = StackOrientation.Vertical, VerticalOptions = LayoutOptions.Start, Children = { _sliderLabel, new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.FillAndExpand, Children = { new Label { Text = DisplayMinMax ? _slider.Minimum.ToString() : " ", // we used to set the label invisible, but this doesn't leave enough vertical space above/below the slider. adding a blank space does the trick. FontSize = 20, HorizontalOptions = LayoutOptions.Fill }, _slider, new Label { Text = DisplayMinMax ? _slider.Maximum.ToString() : " ", // we used to set the label invisible, but this doesn't leave enough vertical space above/below the slider. adding a blank space does the trick. FontSize = 20, HorizontalOptions = LayoutOptions.Fill } } }, sliderValueLabel, new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.FillAndExpand, Children = { new Label { Text = LeftLabel, FontSize = 15, HorizontalOptions = LayoutOptions.FillAndExpand }, new Label { Text = RightLabel, FontSize = 15, HorizontalOptions = LayoutOptions.End } }, IsVisible = !string.IsNullOrWhiteSpace(LeftLabel) || !string.IsNullOrWhiteSpace(RightLabel) }, optionsLayout } }); } else { if (Enabled) { // if the view was already initialized and is enabled, just update the label since the index might have changed. string tipText = _incrementalValueHasChanged ? "" : " " + _tipText; _sliderLabel.Text = GetLabelText(index) + (DisplaySliderValue && _incrementalValueHasChanged ? " " + _incrementalValue.ToString() : "") + tipText; } else { // if the view was already initialized but is not enabled and has never been interacted with, there should be no tip text since the user can't do anything with the slider. if (!_incrementalValueHasChanged) { _slider.Value = Minimum; _sliderLabel.Text = GetLabelText(index) + " No value selected."; } } } return base.GetView(index); } private double GetIncrementalValue(double value) { return Math.Round(value / Increment) * Increment; } public override string ToString() { return base.ToString() + " -- " + Minimum + " to " + Maximum; } } }
/* Copyright (c) 2005-2006 Tomas Matousek. The use and distribution terms for this software are contained in the file named License.txt, which can be found in the root of the Phalanger distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice from this software. */ #nullable enable using System; using System.Globalization; using System.Collections; using System.Collections.Generic; using System.Linq; using System.ComponentModel; using System.Runtime.InteropServices; using System.Diagnostics; using Pchp.Core; using System.Xml; using Pchp.Core.Utilities; using System.Text.RegularExpressions; namespace Pchp.Library.DateTime { /// <summary> /// Provides timezone information for PHP functions. /// </summary> [PhpExtension(PhpExtensionAttribute.KnownExtensionNames.Date)] public static class PhpTimeZone { private const string EnvVariableName = "TZ"; [DebuggerDisplay("{PhpName} - {Info}")] private struct TimeZoneInfoItem { /// <summary> /// Comparer of <see cref="TimeZoneInfoItem"/>, comparing its <see cref="TimeZoneInfoItem.PhpName"/>. /// </summary> public class Comparer : IComparer<TimeZoneInfoItem> { public int Compare(TimeZoneInfoItem x, TimeZoneInfoItem y) { return StringComparer.OrdinalIgnoreCase.Compare(x.PhpName, y.PhpName); } } /// <summary> /// PHP time zone name. /// </summary> public readonly string PhpName; /// <summary> /// Actual <see cref="TimeZoneInfo"/> from .NET. /// </summary> public readonly TimeZoneInfo Info; /// <summary> /// Abbreviation. If more than one, separated with comma. /// </summary> public readonly string Abbreviation; /// <summary> /// Not listed item used only as an alias for another time zone. /// </summary> public readonly bool IsAlias; /// <summary> /// Gets value indicating the given abbreviation can be used for this timezone. /// </summary> public bool HasAbbreviation(string abbr) { if (!string.IsNullOrEmpty(abbr) && Abbreviation != null) { // Abbreviation.Split(new[] { ',' }).Contains(abbr, StringComparer.OrdinalIgnoreCase); int index = 0; while ((index = Abbreviation.IndexOf(abbr, index, StringComparison.OrdinalIgnoreCase)) >= 0) { int end = index + abbr.Length; if (index == 0 || Abbreviation[index - 1] == ',') { if (end == Abbreviation.Length || Abbreviation[end] == ',') { return true; } } // index++; } } return false; } internal TimeZoneInfoItem(string/*!*/phpName, TimeZoneInfo/*!*/info, string abbreviation, bool isAlias) { // TODO: alter the ID with php-like name //if (!phpName.Equals(info.Id, StringComparison.OrdinalIgnoreCase)) //{ // info = TimeZoneInfo.CreateCustomTimeZone(phpName, info.BaseUtcOffset, info.DisplayName, info.StandardName, info.DaylightName, info.GetAdjustmentRules()); //} // this.PhpName = phpName; this.Info = info; this.Abbreviation = abbreviation; this.IsAlias = isAlias; } } #region timezones /// <summary> /// PHP time zone database. /// </summary> private readonly static Lazy<TimeZoneInfoItem[]>/*!!*/s_lazyTimeZones = new Lazy<TimeZoneInfoItem[]>( InitializeTimeZones, System.Threading.LazyThreadSafetyMode.ExecutionAndPublication); private static TimeZoneInfoItem[]/*!!*/InitializeTimeZones() { // read list of initial timezones var sortedTZ = new SortedSet<TimeZoneInfoItem>(ReadTimeZones(), new TimeZoneInfoItem.Comparer()); // add additional time zones: sortedTZ.Add(new TimeZoneInfoItem("UTC", TimeZoneInfo.Utc, "utc", false)); sortedTZ.Add(new TimeZoneInfoItem("Etc/UTC", TimeZoneInfo.Utc, "utc", true)); sortedTZ.Add(new TimeZoneInfoItem("Etc/GMT-0", TimeZoneInfo.Utc, "gmt", true)); sortedTZ.Add(new TimeZoneInfoItem("GMT", TimeZoneInfo.Utc, "gmt", true)); sortedTZ.Add(new TimeZoneInfoItem("GMT0", TimeZoneInfo.Utc, "gmt", true)); sortedTZ.Add(new TimeZoneInfoItem("UCT", TimeZoneInfo.Utc, "utc", true)); sortedTZ.Add(new TimeZoneInfoItem("Universal", TimeZoneInfo.Utc, "utc", true)); sortedTZ.Add(new TimeZoneInfoItem("Zulu", TimeZoneInfo.Utc, "utc", true)); //sortedTZ.Add(new TimeZoneInfoItem("MET", sortedTZ.First(t => t.PhpName == "Europe/Rome").Info, null, true)); //sortedTZ.Add(new TimeZoneInfoItem("WET", sortedTZ.First(t => t.PhpName == "Europe/Berlin").Info, null, true)); //{ "PRC" //{ "ROC" //{ "ROK" // W-SU = //{ "Poland" //{ "Portugal" //{ "PRC" //{ "ROC" //{ "ROK" //{ "Singapore" = Asia/Singapore //{ "Turkey" // return sortedTZ.ToArray(); } static bool IsAlias(string id) { // whether to not display such tz within timezone_identifiers_list() var isphpname = id.IndexOf('/') >= 0 || id.IndexOf("GMT", StringComparison.Ordinal) >= 0 && id.IndexOf(' ') < 0; return !isphpname; } static Dictionary<string, string> LoadAbbreviations() { var abbrs = new Dictionary<string, string>(512); // timezone_id => abbrs using (var abbrsstream = new System.IO.StreamReader(typeof(PhpTimeZone).Assembly.GetManifestResourceStream("Pchp.Library.Resources.abbreviations.txt"))) { string line; while ((line = abbrsstream.ReadLine()) != null) { if (string.IsNullOrEmpty(line) || line[0] == '#') continue; var idx = line.IndexOf(' '); if (idx > 0) { // abbreviation[space]timezone_id var abbr = line.Remove(idx); // abbreviation var tz = line.Substring(idx + 1); // timezone_id if (abbrs.TryGetValue(tz, out var oldabbr)) { // more abbrs for a single tz if (oldabbr.IndexOf(abbr) >= 0) continue; // the list contains duplicities .. abbr = oldabbr + "," + abbr; } abbrs[tz] = abbr; } } } return abbrs; } static IEnumerable<string[]> LoadKnownTimeZones() { // collect php time zone names and match them with Windows TZ IDs: using (var xml = XmlReader.Create(new System.IO.StreamReader(typeof(PhpTimeZone).Assembly.GetManifestResourceStream("Pchp.Library.Resources.WindowsTZ.xml")))) { while (xml.Read()) { switch (xml.NodeType) { case XmlNodeType.Element: if (xml.Name == "mapZone") { // <mapZone other="Dateline Standard Time" type="Etc/GMT+12"/> var winId = xml.GetAttribute("other"); var phpIds = xml.GetAttribute("type"); if (string.IsNullOrEmpty(phpIds)) { yield return new[] { winId }; } else if (phpIds.IndexOf(' ') < 0) { yield return new[] { winId, phpIds }; } else { var list = new List<string>(4) { winId }; list.AddRange(phpIds.Split(' ')); yield return list.ToArray(); } } break; } } } // other time zones: yield return new[] { "US/Alaska", "Alaskan Standard Time" }; //yield return new[] { "US/Aleutian", (???) }; yield return new[] { "US/Arizona", "US Mountain Standard Time" }; yield return new[] { "US/Central", "Central Standard Time" }; yield return new[] { "East-Indiana", "US Eastern Standard Time" }; yield return new[] { "Eastern", "Eastern Standard Time" }; yield return new[] { "US/Hawaii", "Hawaiian Standard Time" }; // "US/Indiana-Starke" // "US/Michigan" yield return new[] { "US/Mountain", "Mountain Standard Time" }; yield return new[] { "US/Pacific", "Pacific Standard Time" }; yield return new[] { "US/Pacific-New", "Pacific Standard Time" }; yield return new[] { "US/Samoa", "Samoa Standard Time" }; } static IEnumerable<TimeZoneInfoItem>/*!!*/ReadTimeZones() { // map of time zones: var tzdict = TimeZoneInfo .GetSystemTimeZones() .ToDictionary(tz => tz.Id, StringComparer.OrdinalIgnoreCase); // add aliases and knonwn time zones from bundled XML: foreach (var names in LoadKnownTimeZones()) { for (int i = 0; i < names.Length; i++) { if (tzdict.TryGetValue(names[i], out var tz) && tz != null) { // update the map of known time zones: foreach (var n in names) { tzdict[n] = tz; } break; } } } // prepare abbreviations var abbrs = LoadAbbreviations(); // yield return all discovered time zones: foreach (var pair in tzdict) { abbrs.TryGetValue(pair.Key, out var abbreviation); yield return new TimeZoneInfoItem(pair.Key, pair.Value, abbreviation, IsAlias(pair.Key)); } } #endregion /// <summary> /// Gets the current time zone for PHP date-time library functions. Associated with the current context. /// </summary> /// <remarks>It returns the time zone set by date_default_timezone_set PHP function. /// If no time zone was set, the time zone is determined in following order: /// 1. the time zone set in configuration /// 2. the time zone of the current system /// 3. default UTC time zone</remarks> internal static TimeZoneInfo GetCurrentTimeZone(Context ctx) { return DateConfiguration.GetConfiguration(ctx).TimeZoneInfo; } internal static void SetCurrentTimeZone(Context ctx, TimeZoneInfo value) { DateConfiguration.GetConfiguration(ctx).TimeZoneInfo = value; } internal static bool SetCurrentTimeZone(Context ctx, string zoneName) { var zone = GetTimeZone(zoneName); if (zone != null) { SetCurrentTimeZone(ctx, zone); return true; } else { PhpException.Throw(PhpError.Notice, Resources.LibResources.unknown_timezone, zoneName); return false; } } /// <summary> /// Finds out the time zone in the way how PHP does. /// </summary> internal static TimeZoneInfo DetermineDefaultTimeZone(/*out Func<TimeZoneInfo, bool> changedFunc*/) { TimeZoneInfo result; //// check environment variable: //string env_tz = System.Environment.GetEnvironmentVariable(EnvVariableName); //if (!string.IsNullOrEmpty(env_tz)) //{ // result = GetTimeZone(env_tz); // if (result != null) // { // // recheck the timezone only if the environment variable changes // changedFunc = (timezone) => !String.Equals(timezone.StandardName, System.Environment.GetEnvironmentVariable(EnvVariableName), StringComparison.OrdinalIgnoreCase); // // return the timezone set in environment // return result; // } // PhpException.Throw(PhpError.Notice, LibResources.GetString("unknown_timezone_env", env_tz)); //} //// check configuration: //LibraryConfiguration config = LibraryConfiguration.Local; //if (config.Date.TimeZone != null) //{ // // recheck the timezone only if the local configuration changes, ignore the environment variable from this point at all // changedFunc = (timezone) => LibraryConfiguration.Local.Date.TimeZone != timezone; // return config.Date.TimeZone; //} // convert current system time zone to PHP zone, // or use UTC time zone by default result = SystemToPhpTimeZone(TimeZoneInfo.Local) ?? TimeZoneInfo.Utc; //PhpException.Throw(PhpError.Strict, LibResources.GetString("using_implicit_timezone", result.Id)); // recheck the timezone when the TimeZone in local configuration is set //changedFunc = (timezone) => false;//LibraryConfiguration.Local.Date.TimeZone != null; return result; } ///// <summary> ///// Gets/sets/resets legacy configuration setting "date.timezone". ///// </summary> //internal static object GsrTimeZone(LibraryConfiguration/*!*/ local, LibraryConfiguration/*!*/ @default, object value, IniAction action) //{ // string result = (local.Date.TimeZone != null) ? local.Date.TimeZone.StandardName : null; // switch (action) // { // case IniAction.Set: // { // string name = Core.Convert.ObjectToString(value); // TimeZoneInfo zone = GetTimeZone(name); // if (zone == null) // { // PhpException.Throw(PhpError.Warning, LibResources.GetString("unknown_timezone", name)); // } // else // { // local.Date.TimeZone = zone; // } // break; // } // case IniAction.Restore: // local.Date.TimeZone = @default.Date.TimeZone; // break; // } // return result; //} /// <summary> /// Gets an instance of <see cref="TimeZone"/> corresponding to specified PHP name for time zone. /// </summary> /// <param name="phpName">PHP time zone name.</param> /// <returns>The time zone or a <B>null</B> reference.</returns> internal static TimeZoneInfo? GetTimeZone(string/*!*/ phpName) { if (string.IsNullOrEmpty(phpName)) { return null; } // simple binary search (not the Array.BinarySearch) var timezones = PhpTimeZone.s_lazyTimeZones.Value; int a = 0, b = timezones.Length - 1; while (a <= b) { int x = (a + b) >> 1; int comparison = StringComparer.OrdinalIgnoreCase.Compare(timezones[x].PhpName, phpName); if (comparison == 0) return timezones[x].Info; if (comparison < 0) a = x + 1; else //if (comparison > 0) b = x - 1; } // try custom offset or a known abbreviation: var dt = new DateInfo(); var _ = 0; if (dt.SetTimeZone(phpName, ref _)) { // +00:00 // -00:00 // abbr return dt.ResolveTimeZone(); } // return null; } /// <summary> /// Tries to match given <paramref name="systemTimeZone"/> to our fixed <see cref="s_timezones"/>. /// </summary> static TimeZoneInfo? SystemToPhpTimeZone(TimeZoneInfo systemTimeZone) { if (systemTimeZone == null) return null; var tzns = s_lazyTimeZones.Value; for (int i = 0; i < tzns.Length; i++) { var tz = tzns[i].Info; if (tz != null && tz.DisplayName.Equals(systemTimeZone.DisplayName, StringComparison.OrdinalIgnoreCase)) // TODO: && tz.HasSameRules(systemTimeZone)) return tz; } return null; } #region date_default_timezone_get, date_default_timezone_set public static bool date_default_timezone_set(Context ctx, string zoneName) { return SetCurrentTimeZone(ctx, zoneName); } public static string date_default_timezone_get(Context ctx) { // TODO: this is not PHP name return GetCurrentTimeZone(ctx).Id; } #endregion #region date_timezone_get, date_timezone_set /// <summary> /// Alias to <see cref="DateTimeInterface.getTimezone"/>. /// </summary> public static DateTimeZone date_timezone_get(DateTimeInterface dt) => dt.getTimezone(); /// <summary> /// Alias to <see cref="DateTime.setTimezone(DateTimeZone)"/>. /// </summary> public static DateTime date_timezone_set(DateTime dt, DateTimeZone timezone) => dt.setTimezone(timezone); #endregion #region timezone_identifiers_list, timezone_version_get, timezone_abbreviations_list, timezone_name_from_abbr static readonly Dictionary<string, int> s_what = new Dictionary<string, int>(10, StringComparer.OrdinalIgnoreCase) { {"africa", DateTimeZone.AFRICA}, {"america", DateTimeZone.AMERICA}, {"antarctica", DateTimeZone.ANTARCTICA}, {"artic", DateTimeZone.ARCTIC}, {"asia", DateTimeZone.ASIA}, {"atlantic", DateTimeZone.ATLANTIC}, {"australia", DateTimeZone.AUSTRALIA}, {"europe", DateTimeZone.EUROPE}, {"indian", DateTimeZone.INDIAN}, {"pacific", DateTimeZone.PACIFIC}, {"etc", DateTimeZone.UTC}, }; /// <summary> /// Gets zone constant. /// </summary> static int GuessWhat(TimeZoneInfoItem tz) { int slash = tz.PhpName.IndexOf('/'); if (slash > 0) { s_what.TryGetValue(tz.PhpName.Remove(slash), out int code); return code; } else { return 0; } } /// <summary> /// Returns a numerically indexed array containing all defined timezone identifiers. /// </summary> public static PhpArray timezone_identifiers_list(int what = DateTimeZone.ALL, string? country = null) { if ((what & DateTimeZone.PER_COUNTRY) == DateTimeZone.PER_COUNTRY || !string.IsNullOrEmpty(country)) { throw new NotImplementedException(); } var timezones = PhpTimeZone.s_lazyTimeZones.Value; // copy names to PHP array: var array = new PhpArray(timezones.Length); for (int i = 0; i < timezones.Length; i++) { if (timezones[i].IsAlias) { continue; } if (what == DateTimeZone.ALL || what == DateTimeZone.ALL_WITH_BC || (what & GuessWhat(timezones[i])) != 0) { array.Add(timezones[i].PhpName); } } // return array; } /// <summary> /// Gets the version of used the time zone database. /// </summary> public static string timezone_version_get() { //try //{ // using (var reg = Microsoft.Win32.Registry.LocalMachine.CreateSubKey(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones")) // return reg.GetValue("TzVersion", 0).ToString() + ".system"; //} //catch { } // no windows update installed return "0.system"; } /// <summary> /// Returns associative array containing dst, offset and the timezone name. /// Alias to <see cref="DateTimeZone.listAbbreviations"/>. /// </summary> public static PhpArray timezone_abbreviations_list() { var timezones = PhpTimeZone.s_lazyTimeZones.Value; var result = new PhpArray(); // for (int i = 0; i < timezones.Length; i++) { var tz = timezones[i]; var abbrs = tz.Abbreviation; if (abbrs != null) { foreach (var abbr in abbrs.Split(new[] { ',' })) { if (!result.TryGetValue(abbr, out var tzs)) tzs = new PhpArray(); tzs.Array.Add(new PhpArray(3) { {"dst", tz.Info.SupportsDaylightSavingTime }, {"offset", (long)tz.Info.BaseUtcOffset.TotalSeconds }, {"timezone_id", tz.PhpName }, }); result[abbr] = tzs; } } } // return result; } /// <summary> /// Returns the timezone name from abbreviation. /// </summary> [return: CastToFalse] public static string? timezone_name_from_abbr(string abbr, int gmtOffset = -1, int isdst = -1) { var timezones = PhpTimeZone.s_lazyTimeZones.Value; string? result = null; // candidate if (string.IsNullOrEmpty(abbr) && gmtOffset == -1) { // not specified return null; // FALSE } // for (int i = 0; i < timezones.Length; i++) { var tz = timezones[i]; if (tz.IsAlias) { continue; } // if {abbr} is specified => {abbrs} must contain it, otherwise do not check this timezone var matchesabbr = tz.HasAbbreviation(abbr); // offset is ignored if (gmtOffset == -1) { if (matchesabbr) { result = tz.PhpName; break; } continue; } // resolve dst delta (if needed) TimeSpan dstdelta; if (isdst >= 0) // dst taken into account { dstdelta = tz.Info.SupportsDaylightSavingTime ? tz.Info.GetAdjustmentRules().Select(r => r.DaylightDelta).FirstOrDefault(r => r.Ticks != 0) : default; if (dstdelta.Ticks == 0) { continue; } } else { dstdelta = default; } // offset must match var matchesoffset = (tz.Info.BaseUtcOffset + dstdelta).TotalSeconds == gmtOffset; if (matchesoffset) { if (matchesabbr || string.IsNullOrEmpty(abbr)) return tz.PhpName; // offset matches but not the abbreviation // in case nothing else is found use this as the result result ??= tz.PhpName; } } // return result; } #endregion #region timezone_open, timezone_offset_get /// <summary> /// Alias of new <see cref="DateTimeZone"/> /// </summary> [return: CastToFalse] public static DateTimeZone? timezone_open(string timezone) { var tz = GetTimeZone(timezone); if (tz != null) { return new DateTimeZone(tz); } return null; // FALSE } /// <summary> /// Alias of <see cref="DateTimeZone.getOffset"/> /// </summary> [return: CastToFalse] public static int timezone_offset_get(DateTimeZone timezone, Library.DateTime.DateTime datetime) { return (timezone != null) ? timezone.getOffset(datetime) : -1; } [return: CastToFalse] public static PhpArray? timezone_transitions_get(DateTimeZone timezone, int timestamp_begin = 0, int timestamp_end = 0) { return timezone?.getTransitions(timestamp_begin, timestamp_end); } #endregion #region timezone_location_get /// <summary> /// Returns location information for a timezone. /// </summary> [return: CastToFalse] public static PhpArray timezone_location_get(DateTimeZone @object) => @object.getLocation(); #endregion /// <summary> /// Alias to <see cref="DateTimeZone.getName"/> /// </summary> public static string timezone_name_get(DateTimeZone @object) => @object.getName(); } }
using System; using System.Buffers.Text; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Text; namespace Orleans.Runtime { [Serializable] public class UniqueKey : IComparable<UniqueKey>, IEquatable<UniqueKey> { private const ulong TYPE_CODE_DATA_MASK = 0xFFFFFFFF; // Lowest 4 bytes private static readonly char[] KeyExtSeparationChar = {'+'}; /// <summary> /// Type id values encoded into UniqueKeys /// </summary> public enum Category : byte { None = 0, SystemTarget = 1, SystemGrain = 2, Grain = 3, Client = 4, KeyExtGrain = 6, // 7 was GeoClient KeyExtSystemTarget = 8, } public UInt64 N0 { get; private set; } public UInt64 N1 { get; private set; } public UInt64 TypeCodeData { get; private set; } public string KeyExt { get; private set; } [NonSerialized] private uint uniformHashCache; public int BaseTypeCode { get { return (int)(TypeCodeData & TYPE_CODE_DATA_MASK); } } public Category IdCategory { get { return GetCategory(TypeCodeData); } } public bool IsLongKey { get { return N0 == 0; } } public bool IsSystemTargetKey => IsSystemTarget(IdCategory); private static bool IsSystemTarget(Category category) => category == Category.SystemTarget || category == Category.KeyExtSystemTarget; public bool HasKeyExt => IsKeyExt(IdCategory); private static bool IsKeyExt(Category category) => category == Category.KeyExtGrain || category == Category.KeyExtSystemTarget; internal static readonly UniqueKey Empty = new UniqueKey { N0 = 0, N1 = 0, TypeCodeData = 0, KeyExt = null }; internal static UniqueKey Parse(ReadOnlySpan<char> input) { var trimmed = input.Trim().ToString(); // first, for convenience we attempt to parse the string using GUID syntax. this is needed by unit // tests but i don't know if it's needed for production. Guid guid; if (Guid.TryParse(trimmed, out guid)) return NewKey(guid); else { var fields = trimmed.Split(KeyExtSeparationChar, 2); var n0 = ulong.Parse(fields[0].Substring(0, 16), NumberStyles.HexNumber); var n1 = ulong.Parse(fields[0].Substring(16, 16), NumberStyles.HexNumber); var typeCodeData = ulong.Parse(fields[0].Substring(32, 16), NumberStyles.HexNumber); string keyExt = null; switch (fields.Length) { default: throw new InvalidDataException("UniqueKey hex strings cannot contain more than one + separator."); case 1: break; case 2: if (fields[1] != "null") { keyExt = fields[1]; } break; } return NewKey(n0, n1, typeCodeData, keyExt); } } internal static UniqueKey NewKey(ulong n0, ulong n1, Category category, long typeData, string keyExt) { if (!IsKeyExt(category) && keyExt != null) throw new ArgumentException("Only key extended grains can specify a non-null key extension."); var typeCodeData = ((ulong)category << 56) + ((ulong)typeData & 0x00FFFFFFFFFFFFFF); return NewKey(n0, n1, typeCodeData, keyExt); } internal static UniqueKey NewKey(long longKey, Category category = Category.None, long typeData = 0, string keyExt = null) { ThrowIfIsSystemTargetKey(category); var n1 = unchecked((ulong)longKey); return NewKey(0, n1, category, typeData, keyExt); } public static UniqueKey NewKey() { return NewKey(Guid.NewGuid()); } internal static UniqueKey NewKey(Guid guid, Category category = Category.None, long typeData = 0, string keyExt = null) { ThrowIfIsSystemTargetKey(category); var guidBytes = guid.ToByteArray(); var n0 = BitConverter.ToUInt64(guidBytes, 0); var n1 = BitConverter.ToUInt64(guidBytes, 8); return NewKey(n0, n1, category, typeData, keyExt); } public static UniqueKey NewSystemTargetKey(Guid guid, long typeData) { var guidBytes = guid.ToByteArray(); var n0 = BitConverter.ToUInt64(guidBytes, 0); var n1 = BitConverter.ToUInt64(guidBytes, 8); return NewKey(n0, n1, Category.SystemTarget, typeData, null); } public static UniqueKey NewSystemTargetKey(short systemId) { ulong n1 = unchecked((ulong)systemId); return NewKey(0, n1, Category.SystemTarget, 0, null); } public static UniqueKey NewGrainServiceKey(short key, long typeData) { ulong n1 = unchecked((ulong)key); return NewKey(0, n1, Category.SystemTarget, typeData, null); } public static UniqueKey NewGrainServiceKey(string key, long typeData) { return NewKey(0, 0, Category.KeyExtSystemTarget, typeData, key); } internal static UniqueKey NewKey(ulong n0, ulong n1, ulong typeCodeData, string keyExt) { ValidateKeyExt(keyExt, typeCodeData); return new UniqueKey { N0 = n0, N1 = n1, TypeCodeData = typeCodeData, KeyExt = keyExt }; } private void ThrowIfIsNotLong() { if (!IsLongKey) throw new InvalidOperationException("this key cannot be interpreted as a long value"); } private static void ThrowIfIsSystemTargetKey(Category category) { if (IsSystemTarget(category)) throw new ArgumentException( "This overload of NewKey cannot be used to construct an instance of UniqueKey containing a SystemTarget id."); } private void ThrowIfHasKeyExt(string methodName) { if (HasKeyExt) throw new InvalidOperationException( string.Format( "This overload of {0} cannot be used if the grain uses the primary key extension feature.", methodName)); } public long PrimaryKeyToLong(out string extendedKey) { ThrowIfIsNotLong(); extendedKey = this.KeyExt; return unchecked((long)N1); } public long PrimaryKeyToLong() { ThrowIfHasKeyExt("UniqueKey.PrimaryKeyToLong"); string unused; return PrimaryKeyToLong(out unused); } public Guid PrimaryKeyToGuid(out string extendedKey) { extendedKey = this.KeyExt; return ConvertToGuid(); } public Guid PrimaryKeyToGuid() { ThrowIfHasKeyExt("UniqueKey.PrimaryKeyToGuid"); string unused; return PrimaryKeyToGuid(out unused); } public override bool Equals(object o) { return o is UniqueKey && Equals((UniqueKey)o); } // We really want Equals to be as fast as possible, as a minimum cost, as close to native as possible. // No function calls, no boxing, inline. public bool Equals(UniqueKey other) { return N0 == other.N0 && N1 == other.N1 && TypeCodeData == other.TypeCodeData && (!HasKeyExt || KeyExt == other.KeyExt); } // We really want CompareTo to be as fast as possible, as a minimum cost, as close to native as possible. // No function calls, no boxing, inline. public int CompareTo(UniqueKey other) { return TypeCodeData < other.TypeCodeData ? -1 : TypeCodeData > other.TypeCodeData ? 1 : N0 < other.N0 ? -1 : N0 > other.N0 ? 1 : N1 < other.N1 ? -1 : N1 > other.N1 ? 1 : !HasKeyExt || KeyExt == null ? 0 : String.Compare(KeyExt, other.KeyExt, StringComparison.Ordinal); } public override int GetHashCode() { return unchecked((int)GetUniformHashCode()); } internal uint GetUniformHashCode() { // Disabling this ReSharper warning; hashCache is a logically read-only variable, so accessing them in GetHashCode is safe. // ReSharper disable NonReadonlyFieldInGetHashCode if (uniformHashCache == 0) { uint n; if (HasKeyExt && KeyExt != null) { n = JenkinsHash.ComputeHash(this.ToByteArray()); } else { n = JenkinsHash.ComputeHash(TypeCodeData, N0, N1); } // Unchecked is required because the Jenkins hash is an unsigned 32-bit integer, // which we need to convert to a signed 32-bit integer. uniformHashCache = n; } return uniformHashCache; // ReSharper restore NonReadonlyFieldInGetHashCode } /// <summary> /// If KeyExt not exists, returns following structure /// |8 bytes|8 bytes|8 bytes|4 bytes| - total 28 bytes. /// If KeyExt exists, adds additional KeyExt bytes length /// </summary> /// <returns></returns> internal ReadOnlySpan<byte> ToByteArray() { var extBytes = this.KeyExt != null ? Encoding.UTF8.GetBytes(KeyExt) : null; var extBytesLength = extBytes?.Length ?? 0; var sizeWithoutExtBytes = sizeof(ulong) * 3 + sizeof(int); var spanBytes = new byte[sizeWithoutExtBytes + extBytesLength].AsSpan(); var offset = 0; var ulongBytes = MemoryMarshal.Cast<byte, ulong>(spanBytes.Slice(offset, sizeof(ulong) * 3)); ulongBytes[0] = this.N0; ulongBytes[1] = this.N1; ulongBytes[2] = this.TypeCodeData; offset += sizeof(ulong) * 3; // Copy KeyExt if (extBytes != null) { MemoryMarshal.Cast<byte, int>(spanBytes.Slice(offset, sizeof(int)))[0] = extBytesLength; offset += sizeof(int); extBytes.CopyTo(spanBytes.Slice(offset, extBytesLength)); } else { MemoryMarshal.Cast<byte, int>(spanBytes.Slice(offset, sizeof(int)))[0] = -1; } return spanBytes; } private Guid ConvertToGuid() { return new Guid((UInt32)(N0 & 0xffffffff), (UInt16)(N0 >> 32), (UInt16)(N0 >> 48), (byte)N1, (byte)(N1 >> 8), (byte)(N1 >> 16), (byte)(N1 >> 24), (byte)(N1 >> 32), (byte)(N1 >> 40), (byte)(N1 >> 48), (byte)(N1 >> 56)); } public override string ToString() { return ToHexString(); } internal string ToHexString() { var s = new StringBuilder(); s.AppendFormat("{0:x16}{1:x16}{2:x16}", N0, N1, TypeCodeData); if (!HasKeyExt) return s.ToString(); s.Append("+"); s.Append(KeyExt ?? "null"); return s.ToString(); } private static void ValidateKeyExt(string keyExt, UInt64 typeCodeData) { Category category = GetCategory(typeCodeData); if (category == Category.KeyExtGrain || category == Category.KeyExtSystemTarget) { if (string.IsNullOrWhiteSpace(keyExt)) { if (null == keyExt) { throw new ArgumentNullException("keyExt"); } else { throw new ArgumentException("Extended key is empty or white space.", "keyExt"); } } } } internal static Category GetCategory(UInt64 typeCodeData) { return (Category)((typeCodeData >> 56) & 0xFF); } } }
// Copyright (C) 2014 dot42 // // Original filename: Org.Apache.Http.Client.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. #pragma warning disable 1717 namespace Org.Apache.Http.Client { /// <summary> /// <para>Interface for an HTTP client. HTTP clients encapsulate a smorgasbord of objects required to execute HTTP requests while handling cookies, authentication, connection management, and other features. Thread safety of HTTP clients depends on the implementation and configuration of the specific client.</para><para><para></para><para></para><title>Revision:</title><para>676020 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/HttpClient /// </java-name> [Dot42.DexImport("org/apache/http/client/HttpClient", AccessFlags = 1537)] public partial interface IHttpClient /* scope: __dot42__ */ { /// <summary> /// <para>Obtains the parameters for this client. These parameters will become defaults for all requests being executed with this client, and for the parameters of dependent objects in this client.</para><para></para> /// </summary> /// <returns> /// <para>the default parameters </para> /// </returns> /// <java-name> /// getParams /// </java-name> [Dot42.DexImport("getParams", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)] global::Org.Apache.Http.Params.IHttpParams GetParams() /* MethodBuilder.Create */ ; /// <summary> /// <para>Obtains the connection manager used by this client.</para><para></para> /// </summary> /// <returns> /// <para>the connection manager </para> /// </returns> /// <java-name> /// getConnectionManager /// </java-name> [Dot42.DexImport("getConnectionManager", "()Lorg/apache/http/conn/ClientConnectionManager;", AccessFlags = 1025)] global::Org.Apache.Http.Conn.IClientConnectionManager GetConnectionManager() /* MethodBuilder.Create */ ; /// <summary> /// <para>Executes a request using the default context.</para><para></para> /// </summary> /// <returns> /// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para> /// </returns> /// <java-name> /// execute /// </java-name> [Dot42.DexImport("execute", "(Lorg/apache/http/client/methods/HttpUriRequest;)Lorg/apache/http/HttpResponse;", AccessFlags = 1025)] global::Org.Apache.Http.IHttpResponse Execute(global::Org.Apache.Http.Client.Methods.IHttpUriRequest request) /* MethodBuilder.Create */ ; /// <summary> /// <para>Executes a request using the given context. The route to the target will be determined by the HTTP client.</para><para></para> /// </summary> /// <returns> /// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para> /// </returns> /// <java-name> /// execute /// </java-name> [Dot42.DexImport("execute", "(Lorg/apache/http/client/methods/HttpUriRequest;Lorg/apache/http/protocol/HttpCon" + "text;)Lorg/apache/http/HttpResponse;", AccessFlags = 1025)] global::Org.Apache.Http.IHttpResponse Execute(global::Org.Apache.Http.Client.Methods.IHttpUriRequest request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; /// <summary> /// <para>Executes a request using the given context. The route to the target will be determined by the HTTP client.</para><para></para> /// </summary> /// <returns> /// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para> /// </returns> /// <java-name> /// execute /// </java-name> [Dot42.DexImport("execute", "(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;)Lorg/apache/http/HttpRes" + "ponse;", AccessFlags = 1025)] global::Org.Apache.Http.IHttpResponse Execute(global::Org.Apache.Http.HttpHost request, global::Org.Apache.Http.IHttpRequest context) /* MethodBuilder.Create */ ; /// <summary> /// <para>Executes a request to the target using the given context.</para><para></para> /// </summary> /// <returns> /// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para> /// </returns> /// <java-name> /// execute /// </java-name> [Dot42.DexImport("execute", "(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lorg/apache/http/protocol" + "/HttpContext;)Lorg/apache/http/HttpResponse;", AccessFlags = 1025)] global::Org.Apache.Http.IHttpResponse Execute(global::Org.Apache.Http.HttpHost target, global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; /// <summary> /// <para>Executes a request using the given context. The route to the target will be determined by the HTTP client.</para><para></para> /// </summary> /// <returns> /// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para> /// </returns> /// <java-name> /// execute /// </java-name> [Dot42.DexImport("execute", "(Lorg/apache/http/client/methods/HttpUriRequest;Lorg/apache/http/client/ResponseH" + "andler;)Ljava/lang/Object;", AccessFlags = 1025, Signature = "<T:Ljava/lang/Object;>(Lorg/apache/http/client/methods/HttpUriRequest;Lorg/apache" + "/http/client/ResponseHandler<+TT;>;)TT;")] T Execute<T>(global::Org.Apache.Http.Client.Methods.IHttpUriRequest request, global::Org.Apache.Http.Client.IResponseHandler<T> context) /* MethodBuilder.Create */ ; /// <summary> /// <para>Executes a request to the target using the given context.</para><para></para> /// </summary> /// <returns> /// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para> /// </returns> /// <java-name> /// execute /// </java-name> [Dot42.DexImport("execute", "(Lorg/apache/http/client/methods/HttpUriRequest;Lorg/apache/http/client/ResponseH" + "andler;Lorg/apache/http/protocol/HttpContext;)Ljava/lang/Object;", AccessFlags = 1025, Signature = "<T:Ljava/lang/Object;>(Lorg/apache/http/client/methods/HttpUriRequest;Lorg/apache" + "/http/client/ResponseHandler<+TT;>;Lorg/apache/http/protocol/HttpContext;)TT;")] T Execute<T>(global::Org.Apache.Http.Client.Methods.IHttpUriRequest target, global::Org.Apache.Http.Client.IResponseHandler<T> request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; /// <summary> /// <para>Executes a request to the target using the given context.</para><para></para> /// </summary> /// <returns> /// <para>the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client. </para> /// </returns> /// <java-name> /// execute /// </java-name> [Dot42.DexImport("execute", "(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lorg/apache/http/client/R" + "esponseHandler;)Ljava/lang/Object;", AccessFlags = 1025, Signature = "<T:Ljava/lang/Object;>(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lor" + "g/apache/http/client/ResponseHandler<+TT;>;)TT;")] T Execute<T>(global::Org.Apache.Http.HttpHost target, global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Client.IResponseHandler<T> context) /* MethodBuilder.Create */ ; /// <summary> /// <para>Executes a request to the target using the given context and processes the response using the given response handler.</para><para></para> /// </summary> /// <returns> /// <para>the response object as generated by the response handler. </para> /// </returns> /// <java-name> /// execute /// </java-name> [Dot42.DexImport("execute", "(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lorg/apache/http/client/R" + "esponseHandler;Lorg/apache/http/protocol/HttpContext;)Ljava/lang/Object;", AccessFlags = 1025, Signature = "<T:Ljava/lang/Object;>(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lor" + "g/apache/http/client/ResponseHandler<+TT;>;Lorg/apache/http/protocol/HttpContext" + ";)TT;")] T Execute<T>(global::Org.Apache.Http.HttpHost target, global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Client.IResponseHandler<T> responseHandler, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; } /// <summary> /// <para>A client-side request director. The director decides which steps are necessary to execute a request. It establishes connections and optionally processes redirects and authentication challenges. The director may therefore generate and send a sequence of requests in order to execute one initial request.</para><para><br></br><b>Note:</b> It is most likely that implementations of this interface will allocate connections, and return responses that depend on those connections for reading the response entity. Such connections MUST be released, but that is out of the scope of a request director.</para><para><para></para><para></para><title>Revision:</title><para>676020 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/RequestDirector /// </java-name> [Dot42.DexImport("org/apache/http/client/RequestDirector", AccessFlags = 1537)] public partial interface IRequestDirector /* scope: __dot42__ */ { /// <summary> /// <para>Executes a request. <br></br><b>Note:</b> For the time being, a new director is instantiated for each request. This is the same behavior as for <code>HttpMethodDirector</code> in HttpClient 3.</para><para></para> /// </summary> /// <returns> /// <para>the final response to the request. This is never an intermediate response with status code 1xx.</para> /// </returns> /// <java-name> /// execute /// </java-name> [Dot42.DexImport("execute", "(Lorg/apache/http/HttpHost;Lorg/apache/http/HttpRequest;Lorg/apache/http/protocol" + "/HttpContext;)Lorg/apache/http/HttpResponse;", AccessFlags = 1025)] global::Org.Apache.Http.IHttpResponse Execute(global::Org.Apache.Http.HttpHost target, global::Org.Apache.Http.IHttpRequest request, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; } /// <summary> /// <para>Signals failure to retry the request due to non-repeatable request entity.</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/NonRepeatableRequestException /// </java-name> [Dot42.DexImport("org/apache/http/client/NonRepeatableRequestException", AccessFlags = 33)] public partial class NonRepeatableRequestException : global::Org.Apache.Http.ProtocolException /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new NonRepeatableEntityException with a <code>null</code> detail message. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public NonRepeatableRequestException() /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates a new NonRepeatableEntityException with the specified detail message.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public NonRepeatableRequestException(string message) /* MethodBuilder.Create */ { } } /// <summary> /// <para>A handler for determining if the given execution context is user specific or not. The token object returned by this handler is expected to uniquely identify the current user if the context is user specific or to be <code>null</code> if the context does not contain any resources or details specific to the current user. </para><para>The user token will be used to ensure that user specific resouces will not shared with or reused by other users.</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/UserTokenHandler /// </java-name> [Dot42.DexImport("org/apache/http/client/UserTokenHandler", AccessFlags = 1537)] public partial interface IUserTokenHandler /* scope: __dot42__ */ { /// <summary> /// <para>The token object returned by this method is expected to uniquely identify the current user if the context is user specific or to be <code>null</code> if it is not.</para><para></para> /// </summary> /// <returns> /// <para>user token that uniquely identifies the user or <code>null&lt;/null&gt; if the context is not user specific. </code></para> /// </returns> /// <java-name> /// getUserToken /// </java-name> [Dot42.DexImport("getUserToken", "(Lorg/apache/http/protocol/HttpContext;)Ljava/lang/Object;", AccessFlags = 1025)] object GetUserToken(global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; } /// <summary> /// <para>Handler that encapsulates the process of generating a response object from a HttpResponse.</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/ResponseHandler /// </java-name> [Dot42.DexImport("org/apache/http/client/ResponseHandler", AccessFlags = 1537, Signature = "<T:Ljava/lang/Object;>Ljava/lang/Object;")] public partial interface IResponseHandler<T> /* scope: __dot42__ */ { /// <summary> /// <para>Processes an HttpResponse and returns some value corresponding to that response.</para><para></para> /// </summary> /// <returns> /// <para>A value determined by the response</para> /// </returns> /// <java-name> /// handleResponse /// </java-name> [Dot42.DexImport("handleResponse", "(Lorg/apache/http/HttpResponse;)Ljava/lang/Object;", AccessFlags = 1025, Signature = "(Lorg/apache/http/HttpResponse;)TT;")] T HandleResponse(global::Org.Apache.Http.IHttpResponse response) /* MethodBuilder.Create */ ; } /// <summary> /// <para>Signals violation of HTTP specification caused by an invalid redirect</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/RedirectException /// </java-name> [Dot42.DexImport("org/apache/http/client/RedirectException", AccessFlags = 33)] public partial class RedirectException : global::Org.Apache.Http.ProtocolException /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new RedirectException with a <code>null</code> detail message. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public RedirectException() /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates a new RedirectException with the specified detail message.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public RedirectException(string message) /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates a new RedirectException with the specified detail message and cause.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/Throwable;)V", AccessFlags = 1)] public RedirectException(string message, global::System.Exception cause) /* MethodBuilder.Create */ { } } /// <summary> /// <para>A handler for determining if an HTTP request should be redirected to a new location in response to an HTTP response received from the target server.</para><para>Classes implementing this interface must synchronize access to shared data as methods of this interfrace may be executed from multiple threads </para><para><para> </para></para> /// </summary> /// <java-name> /// org/apache/http/client/RedirectHandler /// </java-name> [Dot42.DexImport("org/apache/http/client/RedirectHandler", AccessFlags = 1537)] public partial interface IRedirectHandler /* scope: __dot42__ */ { /// <summary> /// <para>Determines if a request should be redirected to a new location given the response from the target server.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if the request should be redirected, <code>false</code> otherwise </para> /// </returns> /// <java-name> /// isRedirectRequested /// </java-name> [Dot42.DexImport("isRedirectRequested", "(Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpContext;)Z", AccessFlags = 1025)] bool IsRedirectRequested(global::Org.Apache.Http.IHttpResponse response, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; /// <summary> /// <para>Determines the location request is expected to be redirected to given the response from the target server and the current request execution context.</para><para></para> /// </summary> /// <returns> /// <para>redirect URI </para> /// </returns> /// <java-name> /// getLocationURI /// </java-name> [Dot42.DexImport("getLocationURI", "(Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpContext;)Ljava/net/U" + "RI;", AccessFlags = 1025)] global::System.Uri GetLocationURI(global::Org.Apache.Http.IHttpResponse response, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; } /// <summary> /// <para>Signals a circular redirect</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/CircularRedirectException /// </java-name> [Dot42.DexImport("org/apache/http/client/CircularRedirectException", AccessFlags = 33)] public partial class CircularRedirectException : global::Org.Apache.Http.Client.RedirectException /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new CircularRedirectException with a <code>null</code> detail message. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public CircularRedirectException() /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates a new CircularRedirectException with the specified detail message.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public CircularRedirectException(string message) /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates a new CircularRedirectException with the specified detail message and cause.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/Throwable;)V", AccessFlags = 1)] public CircularRedirectException(string message, global::System.Exception cause) /* MethodBuilder.Create */ { } } /// <summary> /// <para>A handler for determining if an HttpRequest should be retried after a recoverable exception during execution.</para><para>Classes implementing this interface must synchronize access to shared data as methods of this interfrace may be executed from multiple threads </para><para><para>Michael Becke </para><simplesectsep></simplesectsep><para> </para></para> /// </summary> /// <java-name> /// org/apache/http/client/HttpRequestRetryHandler /// </java-name> [Dot42.DexImport("org/apache/http/client/HttpRequestRetryHandler", AccessFlags = 1537)] public partial interface IHttpRequestRetryHandler /* scope: __dot42__ */ { /// <summary> /// <para>Determines if a method should be retried after an IOException occurs during execution.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if the method should be retried, <code>false</code> otherwise </para> /// </returns> /// <java-name> /// retryRequest /// </java-name> [Dot42.DexImport("retryRequest", "(Ljava/io/IOException;ILorg/apache/http/protocol/HttpContext;)Z", AccessFlags = 1025)] bool RetryRequest(global::System.IO.IOException exception, int executionCount, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; } /// <summary> /// <para>Signals a non 2xx HTTP response. </para> /// </summary> /// <java-name> /// org/apache/http/client/HttpResponseException /// </java-name> [Dot42.DexImport("org/apache/http/client/HttpResponseException", AccessFlags = 33)] public partial class HttpResponseException : global::Org.Apache.Http.Client.ClientProtocolException /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(ILjava/lang/String;)V", AccessFlags = 1)] public HttpResponseException(int statusCode, string s) /* MethodBuilder.Create */ { } /// <java-name> /// getStatusCode /// </java-name> [Dot42.DexImport("getStatusCode", "()I", AccessFlags = 1)] public virtual int GetStatusCode() /* MethodBuilder.Create */ { return default(int); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal HttpResponseException() /* TypeBuilder.AddDefaultConstructor */ { } /// <java-name> /// getStatusCode /// </java-name> public int StatusCode { [Dot42.DexImport("getStatusCode", "()I", AccessFlags = 1)] get{ return GetStatusCode(); } } } /// <summary> /// <para>Abstract credentials provider.</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/CredentialsProvider /// </java-name> [Dot42.DexImport("org/apache/http/client/CredentialsProvider", AccessFlags = 1537)] public partial interface ICredentialsProvider /* scope: __dot42__ */ { /// <summary> /// <para>Sets the credentials for the given authentication scope. Any previous credentials for the given scope will be overwritten.</para><para><para>getCredentials(AuthScope) </para></para> /// </summary> /// <java-name> /// setCredentials /// </java-name> [Dot42.DexImport("setCredentials", "(Lorg/apache/http/auth/AuthScope;Lorg/apache/http/auth/Credentials;)V", AccessFlags = 1025)] void SetCredentials(global::Org.Apache.Http.Auth.AuthScope authscope, global::Org.Apache.Http.Auth.ICredentials credentials) /* MethodBuilder.Create */ ; /// <summary> /// <para>Get the credentials for the given authentication scope.</para><para><para>setCredentials(AuthScope, Credentials) </para></para> /// </summary> /// <returns> /// <para>the credentials</para> /// </returns> /// <java-name> /// getCredentials /// </java-name> [Dot42.DexImport("getCredentials", "(Lorg/apache/http/auth/AuthScope;)Lorg/apache/http/auth/Credentials;", AccessFlags = 1025)] global::Org.Apache.Http.Auth.ICredentials GetCredentials(global::Org.Apache.Http.Auth.AuthScope authscope) /* MethodBuilder.Create */ ; /// <summary> /// <para>Clears all credentials. </para> /// </summary> /// <java-name> /// clear /// </java-name> [Dot42.DexImport("clear", "()V", AccessFlags = 1025)] void Clear() /* MethodBuilder.Create */ ; } /// <summary> /// <para>Abstract cookie store.</para><para><para></para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/client/CookieStore /// </java-name> [Dot42.DexImport("org/apache/http/client/CookieStore", AccessFlags = 1537)] public partial interface ICookieStore /* scope: __dot42__ */ { /// <summary> /// <para>Adds an HTTP cookie, replacing any existing equivalent cookies. If the given cookie has already expired it will not be added, but existing values will still be removed.</para><para></para> /// </summary> /// <java-name> /// addCookie /// </java-name> [Dot42.DexImport("addCookie", "(Lorg/apache/http/cookie/Cookie;)V", AccessFlags = 1025)] void AddCookie(global::Org.Apache.Http.Cookie.ICookie cookie) /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns all cookies contained in this store.</para><para></para> /// </summary> /// <returns> /// <para>all cookies </para> /// </returns> /// <java-name> /// getCookies /// </java-name> [Dot42.DexImport("getCookies", "()Ljava/util/List;", AccessFlags = 1025, Signature = "()Ljava/util/List<Lorg/apache/http/cookie/Cookie;>;")] global::Java.Util.IList<global::Org.Apache.Http.Cookie.ICookie> GetCookies() /* MethodBuilder.Create */ ; /// <summary> /// <para>Removes all of cookies in this store that have expired by the specified date.</para><para></para> /// </summary> /// <returns> /// <para>true if any cookies were purged. </para> /// </returns> /// <java-name> /// clearExpired /// </java-name> [Dot42.DexImport("clearExpired", "(Ljava/util/Date;)Z", AccessFlags = 1025)] bool ClearExpired(global::Java.Util.Date date) /* MethodBuilder.Create */ ; /// <summary> /// <para>Clears all cookies. </para> /// </summary> /// <java-name> /// clear /// </java-name> [Dot42.DexImport("clear", "()V", AccessFlags = 1025)] void Clear() /* MethodBuilder.Create */ ; } /// <summary> /// <para>Signals an error in the HTTP protocol. </para> /// </summary> /// <java-name> /// org/apache/http/client/ClientProtocolException /// </java-name> [Dot42.DexImport("org/apache/http/client/ClientProtocolException", AccessFlags = 33)] public partial class ClientProtocolException : global::System.IO.IOException /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public ClientProtocolException() /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public ClientProtocolException(string @string) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/Throwable;)V", AccessFlags = 1)] public ClientProtocolException(global::System.Exception exception) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/Throwable;)V", AccessFlags = 1)] public ClientProtocolException(string message, global::System.Exception cause) /* MethodBuilder.Create */ { } } /// <summary> /// <para><para> </para></para> /// </summary> /// <java-name> /// org/apache/http/client/AuthenticationHandler /// </java-name> [Dot42.DexImport("org/apache/http/client/AuthenticationHandler", AccessFlags = 1537)] public partial interface IAuthenticationHandler /* scope: __dot42__ */ { /// <java-name> /// isAuthenticationRequested /// </java-name> [Dot42.DexImport("isAuthenticationRequested", "(Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpContext;)Z", AccessFlags = 1025)] bool IsAuthenticationRequested(global::Org.Apache.Http.IHttpResponse response, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; /// <java-name> /// getChallenges /// </java-name> [Dot42.DexImport("getChallenges", "(Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpContext;)Ljava/util/" + "Map;", AccessFlags = 1025, Signature = "(Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpContext;)Ljava/util/" + "Map<Ljava/lang/String;Lorg/apache/http/Header;>;")] global::Java.Util.IMap<string, global::Org.Apache.Http.IHeader> GetChallenges(global::Org.Apache.Http.IHttpResponse response, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; /// <java-name> /// selectScheme /// </java-name> [Dot42.DexImport("selectScheme", "(Ljava/util/Map;Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpConte" + "xt;)Lorg/apache/http/auth/AuthScheme;", AccessFlags = 1025, Signature = "(Ljava/util/Map<Ljava/lang/String;Lorg/apache/http/Header;>;Lorg/apache/http/Http" + "Response;Lorg/apache/http/protocol/HttpContext;)Lorg/apache/http/auth/AuthScheme" + ";")] global::Org.Apache.Http.Auth.IAuthScheme SelectScheme(global::Java.Util.IMap<string, global::Org.Apache.Http.IHeader> challenges, global::Org.Apache.Http.IHttpResponse response, global::Org.Apache.Http.Protocol.IHttpContext context) /* MethodBuilder.Create */ ; } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; namespace Microsoft.Protocols.TestTools.StackSdk.FileAccessService { /// <summary> /// An authenticated context that is established between am SMB 2.0 /// Protocol client and an SMB 2.0 Protocol server over an SMB 2.0 /// Protocol connection for a specific security principal. There /// could be multiple active sessions over a single SMB 2.0 Protocol /// connection. The SessionId field distinguishes the various sessions. /// </summary> public class Session { #region fields private int globalIndex; private ulong sessionId; private int connectionId; private uint state; private byte[] securityContext; private byte[] sessionKey; private bool shouldSign; /// <summary> /// all opens of a session. /// </summary> protected Collection<Open> openTable; /// <summary> /// all tree connects of a session. /// </summary> protected Collection<TreeConnect> treeConnectTable; #endregion #region properties /// <summary> /// A global integer index in the Global Table of Context. It is be global unique. The value is 1 /// for the first instance, and it always increases by 1 when a new instance is created. /// </summary> public int GlobalIndex { get { return this.globalIndex; } set { this.globalIndex = value; } } /// <summary> /// A numeric value that uniquely identifies the session within the scope of the transport /// connection over which the session was established. This value, transformed into a 64-bit /// number, is typically sent to clients as the SessionId in the SMB2 header. /// </summary> public ulong SessionId { get { return this.sessionId; } set { this.sessionId = value; } } /// <summary> /// The connection on which this session was established (see also sections 3.3.5.5.1 and 3.3.4.4). /// </summary> public int ConnectionId { get { return this.connectionId; } set { this.connectionId = value; } } /// <summary> /// The current activity state of this session. This value MUST be either InProgress, Valid, /// or Expired. /// </summary> public uint State { get { return this.state; } set { this.state = value; } } /// <summary> /// The security context of the user that authenticated this session. This value MUST be in a form /// that allows for evaluating security descriptors within the server, as well as being passed to /// the underlying object store to handle security evaluation that may happen there. /// </summary> public byte[] SecurityContext { get { return this.securityContext; } set { this.securityContext = value; } } /// <summary> /// The 16-byte cryptographic key for this authenticated context. /// </summary> public byte[] SessionKey { get { return this.sessionKey; } set { this.sessionKey = value; } } /// <summary> /// The 16-byte cryptographic key for this authenticated context which is used in SMB only. /// </summary> public byte[] SessionKey4Smb { get { return FileServiceUtils.ProtectSessionKey(this.sessionKey); } } /// <summary> /// A Boolean that, if set, indicates that this session MUST sign communication if signing is enabled /// on this connection. /// </summary> public bool ShouldSign { get { return this.shouldSign; } set { this.shouldSign = value; } } #endregion #region constructor /// <summary> /// Constructor. /// </summary> public Session() { this.GlobalIndex = 0; this.SessionId = 0; this.ConnectionId = 0; this.State = 0; this.SecurityContext = new byte[0]; this.SessionKey = new byte[16]; this.ShouldSign = false; this.openTable = new Collection<Open>(); this.treeConnectTable = new Collection<TreeConnect>(); } /// <summary> /// Constructor. /// </summary> /// <param name="connectionId">the connection identity of the session.</param> /// <param name="sessionId">the session identity of the session.</param> public Session(int connectionId, ulong sessionId) { this.GlobalIndex = 0; this.SessionId = sessionId; this.ConnectionId = connectionId; this.State = 0; this.SecurityContext = new byte[0]; this.SessionKey = new byte[16]; this.ShouldSign = false; this.openTable = new Collection<Open>(); this.treeConnectTable = new Collection<TreeConnect>(); } /// <summary> /// Deep copy constructor. /// </summary> public Session(Session session) { if (session != null) { this.GlobalIndex = session.GlobalIndex; this.SessionId = session.SessionId; this.ConnectionId = session.ConnectionId; this.State = session.State; this.SecurityContext = new byte[session.SecurityContext.Length]; Array.Copy(session.SecurityContext, this.SecurityContext, session.SecurityContext.Length); this.SessionKey = new byte[session.SessionKey.Length]; Array.Copy(session.SessionKey, this.SessionKey, session.SessionKey.Length); this.ShouldSign = session.ShouldSign; this.openTable = new Collection<Open>(); foreach (Open open in session.openTable) { this.openTable.Add(new Open(open)); } this.treeConnectTable = new Collection<TreeConnect>(); foreach (TreeConnect treeConnect in session.treeConnectTable) { this.treeConnectTable.Add(new TreeConnect(treeConnect)); } } else { this.GlobalIndex = 0; this.SessionId = 0; this.ConnectionId = 0; this.State = 0; this.SecurityContext = new byte[0]; this.SessionKey = new byte[16]; this.ShouldSign = false; this.openTable = new Collection<Open>(); this.treeConnectTable = new Collection<TreeConnect>(); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Buffers; using System.Diagnostics; using System.IO; using System.IO.Pipelines; using System.Net.Http.HPack; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Connections; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2.FlowControl; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure; using Microsoft.Extensions.Primitives; using Microsoft.Net.Http.Headers; using HttpMethods = Microsoft.AspNetCore.Http.HttpMethods; namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2 { internal abstract partial class Http2Stream : HttpProtocol, IThreadPoolWorkItem, IDisposable, IPooledStream { private Http2StreamContext _context = default!; private Http2OutputProducer _http2Output = default!; private StreamInputFlowControl _inputFlowControl = default!; private StreamOutputFlowControl _outputFlowControl = default!; private Http2MessageBody? _messageBody; private bool _decrementCalled; public Pipe RequestBodyPipe { get; private set; } = default!; internal long DrainExpirationTicks { get; set; } private StreamCompletionFlags _completionState; private readonly object _completionLock = new object(); public void Initialize(Http2StreamContext context) { base.Initialize(context); _decrementCalled = false; _completionState = StreamCompletionFlags.None; InputRemaining = null; RequestBodyStarted = false; DrainExpirationTicks = 0; _context = context; // First time the stream is used we need to create flow control, producer and pipes. // When a stream is reused these types will be reset and reused. if (_inputFlowControl == null) { _inputFlowControl = new StreamInputFlowControl( this, context.FrameWriter, context.ConnectionInputFlowControl, context.ServerPeerSettings.InitialWindowSize, context.ServerPeerSettings.InitialWindowSize / 2); _outputFlowControl = new StreamOutputFlowControl( context.ConnectionOutputFlowControl, context.ClientPeerSettings.InitialWindowSize); _http2Output = new Http2OutputProducer(this, context, _outputFlowControl); RequestBodyPipe = CreateRequestBodyPipe(); Output = _http2Output; } else { _inputFlowControl.Reset(); _outputFlowControl.Reset(context.ClientPeerSettings.InitialWindowSize); _http2Output.StreamReset(); RequestBodyPipe.Reset(); } } public void InitializeWithExistingContext(int streamId) { _context.StreamId = streamId; Initialize(_context); } public int StreamId => _context.StreamId; public long? InputRemaining { get; internal set; } public bool RequestBodyStarted { get; private set; } public bool EndStreamReceived => (_completionState & StreamCompletionFlags.EndStreamReceived) == StreamCompletionFlags.EndStreamReceived; private bool IsAborted => (_completionState & StreamCompletionFlags.Aborted) == StreamCompletionFlags.Aborted; internal bool RstStreamReceived => (_completionState & StreamCompletionFlags.RstStreamReceived) == StreamCompletionFlags.RstStreamReceived; public bool ReceivedEmptyRequestBody { get { lock (_completionLock) { return EndStreamReceived && !RequestBodyStarted; } } } // We only want to reuse a stream that was not aborted and has completely finished writing. // This ensures Http2OutputProducer.ProcessDataWrites is in the correct state to be reused. // CanReuse must be evaluated on the main frame-processing looping after the stream is removed // from the connection's active streams collection. This is required because a RST_STREAM // frame could arrive after the END_STREAM flag is received. Only once the stream is removed // from the connection's active stream collection can no longer be reset, and is safe to // evaluate for pooling. public bool CanReuse => !_connectionAborted && HasResponseCompleted; protected override void OnReset() { _keepAlive = true; _connectionAborted = false; _userTrailers = null; // Reset Http2 Features _currentIHttpMinRequestBodyDataRateFeature = this; _currentIHttp2StreamIdFeature = this; _currentIHttpResponseTrailersFeature = this; _currentIHttpResetFeature = this; _currentIPersistentStateFeature = this; } protected override void OnRequestProcessingEnded() { CompleteStream(errored: false); } public void CompleteStream(bool errored) { try { // https://tools.ietf.org/html/rfc7540#section-8.1 // If the app finished without reading the request body tell the client not to finish sending it. if (!EndStreamReceived && !RstStreamReceived) { if (!errored) { Log.RequestBodyNotEntirelyRead(ConnectionIdFeature, TraceIdentifier); } var (oldState, newState) = ApplyCompletionFlag(StreamCompletionFlags.Aborted); if (oldState != newState) { Debug.Assert(_decrementCalled); // If there was an error starting the stream then we don't want to write RST_STREAM here. // The connection will handle writing RST_STREAM with the correct error code. if (!errored) { // Don't block on IO. This never faults. _ = _http2Output.WriteRstStreamAsync(Http2ErrorCode.NO_ERROR).Preserve(); } RequestBodyPipe.Writer.Complete(); } } _http2Output.Complete(); RequestBodyPipe.Reader.Complete(); // The app can no longer read any more of the request body, so return any bytes that weren't read to the // connection's flow-control window. _inputFlowControl.Abort(); } finally { _context.StreamLifetimeHandler.OnStreamCompleted(this); } } protected override string CreateRequestId() => StringUtilities.ConcatAsHexSuffix(ConnectionId, ':', (uint)StreamId); protected override MessageBody CreateMessageBody() { if (ReceivedEmptyRequestBody) { return MessageBody.ZeroContentLengthClose; } if (_messageBody != null) { _messageBody.Reset(); } else { _messageBody = new Http2MessageBody(this); } return _messageBody; } // Compare to Http1Connection.OnStartLine protected override bool TryParseRequest(ReadResult result, out bool endConnection) { // We don't need any of the parameters because we don't implement BeginRead to actually // do the reading from a pipeline, nor do we use endConnection to report connection-level errors. endConnection = !TryValidatePseudoHeaders(); return true; } private bool TryValidatePseudoHeaders() { // The initial pseudo header validation takes place in Http2Connection.ValidateHeader and StartStream // They make sure the right fields are at least present (except for Connect requests) exactly once. _httpVersion = Http.HttpVersion.Http2; // Method could already have been set from :method static table index if (Method == HttpMethod.None && !TryValidateMethod()) { return false; } if (!TryValidateAuthorityAndHost(out var hostText)) { return false; } // CONNECT - :scheme and :path must be excluded if (Method == HttpMethod.Connect) { if (!String.IsNullOrEmpty(HttpRequestHeaders.HeaderScheme) || !String.IsNullOrEmpty(HttpRequestHeaders.HeaderPath)) { ResetAndAbort(new ConnectionAbortedException(CoreStrings.Http2ErrorConnectMustNotSendSchemeOrPath), Http2ErrorCode.PROTOCOL_ERROR); return false; } RawTarget = hostText; return true; } // :scheme https://tools.ietf.org/html/rfc7540#section-8.1.2.3 // ":scheme" is not restricted to "http" and "https" schemed URIs. A // proxy or gateway can translate requests for non - HTTP schemes, // enabling the use of HTTP to interact with non - HTTP services. // A common example is TLS termination. var headerScheme = HttpRequestHeaders.HeaderScheme.ToString(); HttpRequestHeaders.HeaderScheme = default; // Suppress pseduo headers from the public headers collection. if (!ReferenceEquals(headerScheme, Scheme) && !string.Equals(headerScheme, Scheme, StringComparison.OrdinalIgnoreCase)) { if (!ServerOptions.AllowAlternateSchemes || !Uri.CheckSchemeName(headerScheme)) { ResetAndAbort(new ConnectionAbortedException( CoreStrings.FormatHttp2StreamErrorSchemeMismatch(headerScheme, Scheme)), Http2ErrorCode.PROTOCOL_ERROR); return false; } Scheme = headerScheme; } // :path (and query) - Required // Must start with / except may be * for OPTIONS var path = HttpRequestHeaders.HeaderPath.ToString(); HttpRequestHeaders.HeaderPath = default; // Suppress pseduo headers from the public headers collection. RawTarget = path; // OPTIONS - https://tools.ietf.org/html/rfc7540#section-8.1.2.3 // This pseudo-header field MUST NOT be empty for "http" or "https" // URIs; "http" or "https" URIs that do not contain a path component // MUST include a value of '/'. The exception to this rule is an // OPTIONS request for an "http" or "https" URI that does not include // a path component; these MUST include a ":path" pseudo-header field // with a value of '*'. if (Method == HttpMethod.Options && path.Length == 1 && path[0] == '*') { // * is stored in RawTarget only since HttpRequest expects Path to be empty or start with a /. Path = string.Empty; QueryString = string.Empty; return true; } // Approximate MaxRequestLineSize by totaling the required pseudo header field lengths. var requestLineLength = _methodText!.Length + Scheme!.Length + hostText.Length + path.Length; if (requestLineLength > ServerOptions.Limits.MaxRequestLineSize) { ResetAndAbort(new ConnectionAbortedException(CoreStrings.BadRequest_RequestLineTooLong), Http2ErrorCode.PROTOCOL_ERROR); return false; } var queryIndex = path.IndexOf('?'); QueryString = queryIndex == -1 ? string.Empty : path.Substring(queryIndex); var pathSegment = queryIndex == -1 ? path.AsSpan() : path.AsSpan(0, queryIndex); return TryValidatePath(pathSegment); } private bool TryValidateMethod() { // :method _methodText = HttpRequestHeaders.HeaderMethod.ToString(); HttpRequestHeaders.HeaderMethod = default; // Suppress pseduo headers from the public headers collection. Method = HttpUtilities.GetKnownMethod(_methodText); if (Method == HttpMethod.None) { ResetAndAbort(new ConnectionAbortedException(CoreStrings.FormatHttp2ErrorMethodInvalid(_methodText)), Http2ErrorCode.PROTOCOL_ERROR); return false; } if (Method == HttpMethod.Custom) { if (HttpCharacters.IndexOfInvalidTokenChar(_methodText) >= 0) { ResetAndAbort(new ConnectionAbortedException(CoreStrings.FormatHttp2ErrorMethodInvalid(_methodText)), Http2ErrorCode.PROTOCOL_ERROR); return false; } } return true; } private bool TryValidateAuthorityAndHost(out string hostText) { // :authority (optional) // Prefer this over Host var authority = HttpRequestHeaders.HeaderAuthority; HttpRequestHeaders.HeaderAuthority = default; // Suppress pseduo headers from the public headers collection. var host = HttpRequestHeaders.HeaderHost; if (!StringValues.IsNullOrEmpty(authority)) { // https://tools.ietf.org/html/rfc7540#section-8.1.2.3 // Clients that generate HTTP/2 requests directly SHOULD use the ":authority" // pseudo - header field instead of the Host header field. // An intermediary that converts an HTTP/2 request to HTTP/1.1 MUST // create a Host header field if one is not present in a request by // copying the value of the ":authority" pseudo - header field. // We take this one step further, we don't want mismatched :authority // and Host headers, replace Host if :authority is defined. The application // will operate on the Host header. HttpRequestHeaders.HeaderHost = authority; host = authority; } // https://tools.ietf.org/html/rfc7230#section-5.4 // A server MUST respond with a 400 (Bad Request) status code to any // HTTP/1.1 request message that lacks a Host header field and to any // request message that contains more than one Host header field or a // Host header field with an invalid field-value. hostText = host.ToString(); if (host.Count > 1 || !HttpUtilities.IsHostHeaderValid(hostText)) { // RST replaces 400 ResetAndAbort(new ConnectionAbortedException(CoreStrings.FormatBadRequest_InvalidHostHeader_Detail(hostText)), Http2ErrorCode.PROTOCOL_ERROR); return false; } return true; } [SkipLocalsInit] private bool TryValidatePath(ReadOnlySpan<char> pathSegment) { // Must start with a leading slash if (pathSegment.IsEmpty || pathSegment[0] != '/') { ResetAndAbort(new ConnectionAbortedException(CoreStrings.FormatHttp2StreamErrorPathInvalid(RawTarget)), Http2ErrorCode.PROTOCOL_ERROR); return false; } var pathEncoded = pathSegment.Contains('%'); // Compare with Http1Connection.OnOriginFormTarget // URIs are always encoded/escaped to ASCII https://tools.ietf.org/html/rfc3986#page-11 // Multibyte Internationalized Resource Identifiers (IRIs) are first converted to utf8; // then encoded/escaped to ASCII https://www.ietf.org/rfc/rfc3987.txt "Mapping of IRIs to URIs" try { const int MaxPathBufferStackAllocSize = 256; // The decoder operates only on raw bytes Span<byte> pathBuffer = pathSegment.Length <= MaxPathBufferStackAllocSize // A constant size plus slice generates better code // https://github.com/dotnet/aspnetcore/pull/19273#discussion_r383159929 ? stackalloc byte[MaxPathBufferStackAllocSize].Slice(0, pathSegment.Length) // TODO - Consider pool here for less than 4096 // https://github.com/dotnet/aspnetcore/pull/19273#discussion_r383604184 : new byte[pathSegment.Length]; for (var i = 0; i < pathSegment.Length; i++) { var ch = pathSegment[i]; // The header parser should already be checking this Debug.Assert(32 < ch && ch < 127); pathBuffer[i] = (byte)ch; } Path = PathNormalizer.DecodePath(pathBuffer, pathEncoded, RawTarget!, QueryString!.Length); return true; } catch (InvalidOperationException) { ResetAndAbort(new ConnectionAbortedException(CoreStrings.FormatHttp2StreamErrorPathInvalid(RawTarget)), Http2ErrorCode.PROTOCOL_ERROR); return false; } } public Task OnDataAsync(Http2Frame dataFrame, in ReadOnlySequence<byte> payload) { // Since padding isn't buffered, immediately count padding bytes as read for flow control purposes. if (dataFrame.DataHasPadding) { // Add 1 byte for the padding length prefix. OnDataRead(dataFrame.DataPadLength + 1); } var dataPayload = payload.Slice(0, dataFrame.DataPayloadLength); // minus padding var endStream = dataFrame.DataEndStream; if (dataPayload.Length > 0) { lock (_completionLock) { RequestBodyStarted = true; if (endStream) { // No need to send any more window updates for this stream now that we've received all the data. // Call before flushing the request body pipe, because that might induce a window update. _inputFlowControl.StopWindowUpdates(); } _inputFlowControl.Advance((int)dataPayload.Length); // This check happens after flow control so that when we throw and abort, the byte count is returned to the connection // level accounting. if (InputRemaining.HasValue) { // https://tools.ietf.org/html/rfc7540#section-8.1.2.6 if (dataPayload.Length > InputRemaining.Value) { throw new Http2StreamErrorException(StreamId, CoreStrings.Http2StreamErrorMoreDataThanLength, Http2ErrorCode.PROTOCOL_ERROR); } InputRemaining -= dataPayload.Length; } // Ignore data frames for aborted streams, but only after counting them for purposes of connection level flow control. if (!IsAborted) { dataPayload.CopyTo(RequestBodyPipe.Writer); // If the stream is completed go ahead and call RequestBodyPipe.Writer.Complete(). // Data will still be available to the reader. if (!endStream) { var flushTask = RequestBodyPipe.Writer.FlushAsync(); // It shouldn't be possible for the RequestBodyPipe to fill up an return an incomplete task if // _inputFlowControl.Advance() didn't throw. Debug.Assert(flushTask.IsCompletedSuccessfully); // If it's a IValueTaskSource backed ValueTask, // inform it its result has been read so it can reset flushTask.GetAwaiter().GetResult(); } } } } if (endStream) { OnEndStreamReceived(); } return Task.CompletedTask; } public void OnEndStreamReceived() { ApplyCompletionFlag(StreamCompletionFlags.EndStreamReceived); if (InputRemaining.HasValue) { // https://tools.ietf.org/html/rfc7540#section-8.1.2.6 if (InputRemaining.Value != 0) { throw new Http2StreamErrorException(StreamId, CoreStrings.Http2StreamErrorLessDataThanLength, Http2ErrorCode.PROTOCOL_ERROR); } } OnTrailersComplete(); RequestBodyPipe.Writer.Complete(); _inputFlowControl.StopWindowUpdates(); } public void OnDataRead(int bytesRead) { _inputFlowControl.UpdateWindows(bytesRead); } public bool TryUpdateOutputWindow(int bytes) { return _context.FrameWriter.TryUpdateStreamWindow(_outputFlowControl, bytes); } public void AbortRstStreamReceived() { // Client sent a reset stream frame, decrement total count. DecrementActiveClientStreamCount(); ApplyCompletionFlag(StreamCompletionFlags.RstStreamReceived); Abort(new IOException(CoreStrings.HttpStreamResetByClient)); } public void Abort(IOException abortReason) { var (oldState, newState) = ApplyCompletionFlag(StreamCompletionFlags.Aborted); if (oldState == newState) { return; } AbortCore(abortReason); } protected override void OnErrorAfterResponseStarted() { // We can no longer change the response, send a Reset instead. var abortReason = new ConnectionAbortedException(CoreStrings.Http2StreamErrorAfterHeaders); ResetAndAbort(abortReason, Http2ErrorCode.INTERNAL_ERROR); } protected override void ApplicationAbort() => ApplicationAbort(new ConnectionAbortedException(CoreStrings.ConnectionAbortedByApplication), Http2ErrorCode.INTERNAL_ERROR); private void ApplicationAbort(ConnectionAbortedException abortReason, Http2ErrorCode error) { ResetAndAbort(abortReason, error); } internal void ResetAndAbort(ConnectionAbortedException abortReason, Http2ErrorCode error) { // Future incoming frames will drain for a default grace period to avoid destabilizing the connection. var (oldState, newState) = ApplyCompletionFlag(StreamCompletionFlags.Aborted); if (oldState == newState) { return; } Log.Http2StreamResetAbort(TraceIdentifier, error, abortReason); DecrementActiveClientStreamCount(); // Don't block on IO. This never faults. _ = _http2Output.WriteRstStreamAsync(error).Preserve(); AbortCore(abortReason); } private void AbortCore(Exception abortReason) { // Call _http2Output.Stop() prior to poisoning the request body stream or pipe to // ensure that an app that completes early due to the abort doesn't result in header frames being sent. _http2Output.Stop(); CancelRequestAbortedToken(); // Unblock the request body. PoisonBody(abortReason); RequestBodyPipe.Writer.Complete(abortReason); _inputFlowControl.Abort(); } public void DecrementActiveClientStreamCount() { // Decrement can be called twice, via calling CompleteAsync and then Abort on the HttpContext. // Only decrement once total. lock (_completionLock) { if (_decrementCalled) { return; } _decrementCalled = true; } _context.StreamLifetimeHandler.DecrementActiveClientStreamCount(); } private Pipe CreateRequestBodyPipe() => new Pipe(new PipeOptions ( pool: _context.MemoryPool, readerScheduler: ServiceContext.Scheduler, writerScheduler: PipeScheduler.Inline, // Never pause within the window range. Flow control will prevent more data from being added. // See the assert in OnDataAsync. pauseWriterThreshold: _context.ServerPeerSettings.InitialWindowSize + 1, resumeWriterThreshold: _context.ServerPeerSettings.InitialWindowSize + 1, useSynchronizationContext: false, minimumSegmentSize: _context.MemoryPool.GetMinimumSegmentSize() )); private (StreamCompletionFlags OldState, StreamCompletionFlags NewState) ApplyCompletionFlag(StreamCompletionFlags completionState) { lock (_completionLock) { var oldCompletionState = _completionState; _completionState |= completionState; return (oldCompletionState, _completionState); } } /// <summary> /// Used to kick off the request processing loop by derived classes. /// </summary> public abstract void Execute(); public void Dispose() { _http2Output.Dispose(); } [Flags] private enum StreamCompletionFlags { None = 0, RstStreamReceived = 1, EndStreamReceived = 2, Aborted = 4, } public override void OnHeader(int index, bool indexedValue, ReadOnlySpan<byte> name, ReadOnlySpan<byte> value) { base.OnHeader(index, indexedValue, name, value); if (indexedValue) { // Special case setting headers when the value is indexed for performance. switch (index) { case H2StaticTable.MethodGet: HttpRequestHeaders.HeaderMethod = HttpMethods.Get; Method = HttpMethod.Get; _methodText = HttpMethods.Get; return; case H2StaticTable.MethodPost: HttpRequestHeaders.HeaderMethod = HttpMethods.Post; Method = HttpMethod.Post; _methodText = HttpMethods.Post; return; case H2StaticTable.SchemeHttp: HttpRequestHeaders.HeaderScheme = SchemeHttp; return; case H2StaticTable.SchemeHttps: HttpRequestHeaders.HeaderScheme = SchemeHttps; return; } } // HPack append will return false if the index is not a known request header. // For example, someone could send the index of "Server" (a response header) in the request. // If that happens then fallback to using Append with the name bytes. if (!HttpRequestHeaders.TryHPackAppend(index, value)) { AppendHeader(name, value); } } [MethodImpl(MethodImplOptions.NoInlining)] private void AppendHeader(ReadOnlySpan<byte> name, ReadOnlySpan<byte> value) { HttpRequestHeaders.Append(name, value, checkForNewlineChars : true); } void IPooledStream.DisposeCore() { Dispose(); } long IPooledStream.PoolExpirationTicks => DrainExpirationTicks; } }
// 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.Diagnostics; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronPython.Compiler; namespace IronPython.Runtime { /// <summary> /// Captures and flows the state of executing code from the generated /// Python code into the IronPython runtime. /// </summary> [DebuggerTypeProxy(typeof(CodeContext.DebugProxy)), DebuggerDisplay("ModuleName = {ModuleName}")] public sealed class CodeContext { private readonly ModuleContext/*!*/ _modContext; private readonly PythonDictionary/*!*/ _dict; /// <summary> /// Creates a new CodeContext which is backed by the specified Python dictionary. /// </summary> public CodeContext(PythonDictionary/*!*/ dict, ModuleContext/*!*/ moduleContext) { ContractUtils.RequiresNotNull(dict, "dict"); ContractUtils.RequiresNotNull(moduleContext, "moduleContext"); _dict = dict; _modContext = moduleContext; } #region Public APIs /// <summary> /// Gets the module state for top-level code. /// </summary> public ModuleContext ModuleContext { get { return _modContext; } } /// <summary> /// Gets the DLR scope object that corresponds to the global variables of this context. /// </summary> public Scope GlobalScope { get { return _modContext.GlobalScope; } } /// <summary> /// Gets the PythonContext which created the CodeContext. /// </summary> public PythonContext LanguageContext { get { return _modContext.Context; } } #endregion #region Internal Helpers /// <summary> /// Gets the dictionary for the global variables from the ModuleContext. /// </summary> internal PythonDictionary GlobalDict { get { return _modContext.Globals; } } /// <summary> /// True if this global context should display CLR members on shared types (for example .ToString on int/bool/etc...) /// /// False if these attributes should be hidden. /// </summary> internal bool ShowCls { get { return ModuleContext.ShowCls; } set { ModuleContext.ShowCls = value; } } /// <summary> /// Attempts to lookup the provided name in this scope or any outer scope. /// </summary> internal bool TryLookupName(string name, out object value) { string strName = name; if (_dict.TryGetValue(strName, out value)) { return true; } return _modContext.Globals.TryGetValue(strName, out value); } /// <summary> /// Looks up a global variable. If the variable is not defined in the /// global scope then built-ins is consulted. /// </summary> internal bool TryLookupBuiltin(string name, out object value) { object builtins; if (!GlobalDict.TryGetValue("__builtins__", out builtins)) { value = null; return false; } if (builtins is PythonModule builtinsScope && builtinsScope.__dict__.TryGetValue(name, out value)) { return true; } if (builtins is PythonDictionary dict && dict.TryGetValue(name, out value)) { return true; } value = null; return false; } /// <summary> /// Gets the dictionary used for storage of local variables. /// </summary> internal PythonDictionary Dict { get { return _dict; } } /// <summary> /// Attempts to lookup the variable in the local scope. /// </summary> internal bool TryGetVariable(string name, out object value) { return Dict.TryGetValue(name, out value); } /// <summary> /// Removes a variable from the local scope. /// </summary> internal bool TryRemoveVariable(string name) { return Dict.Remove(name); } /// <summary> /// Sets a variable in the local scope. /// </summary> internal void SetVariable(string name, object value) { Dict.Add(name, value); } /// <summary> /// Gets a variable from the global scope. /// </summary> internal bool TryGetGlobalVariable(string name, out object res) { return GlobalDict.TryGetValue(name, out res); } /// <summary> /// Sets a variable in the global scope. /// </summary> internal void SetGlobalVariable(string name, object value) { GlobalDict.Add(name, value); } /// <summary> /// Removes a variable from the global scope. /// </summary> internal bool TryRemoveGlobalVariable(string name) { return GlobalDict.Remove(name); } internal PythonGlobal/*!*/[] GetGlobalArray() { return ((GlobalDictionaryStorage)_dict._storage).Data; } internal bool IsTopLevel { get { return Dict != ModuleContext.Globals; } } /// <summary> /// Returns the dictionary associated with __builtins__ if one is /// set or null if it's not available. If __builtins__ is a module /// the module's dictionary is returned. /// </summary> internal PythonDictionary GetBuiltinsDict() { object builtins; if (GlobalDict._storage.TryGetBuiltins(out builtins)) { if (builtins is PythonModule builtinsScope) { return builtinsScope.__dict__; } return builtins as PythonDictionary; } return null; } internal PythonModule Module { get { return _modContext.Module; } } internal string ModuleName { get { return Module.GetName(); } } internal class DebugProxy { private readonly CodeContext _context; public DebugProxy(CodeContext context) { _context = context; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public PythonModule Members { get { return _context.Module; } } } #endregion } }
namespace XenAdmin.TabPages { partial class GeneralTabPage { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { licenseStatus.Dispose(); 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() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(GeneralTabPage)); this.buttonProperties = new System.Windows.Forms.Button(); this.panel1 = new System.Windows.Forms.Panel(); this.panel3 = new System.Windows.Forms.Panel(); this.linkLabelExpand = new System.Windows.Forms.LinkLabel(); this.linkLabelCollapse = new System.Windows.Forms.LinkLabel(); this.panel2 = new XenAdmin.Controls.PanelNoFocusScroll(); this.panelStorageLinkSystemCapabilities = new System.Windows.Forms.Panel(); this.pdSectionStorageLinkSystemCapabilities = new XenAdmin.Controls.PDSection(); this.panelMultipathBoot = new System.Windows.Forms.Panel(); this.pdSectionMultipathBoot = new XenAdmin.Controls.PDSection(); this.panelStorageLink = new System.Windows.Forms.Panel(); this.pdStorageLink = new XenAdmin.Controls.PDSection(); this.panelUpdates = new System.Windows.Forms.Panel(); this.pdSectionUpdates = new XenAdmin.Controls.PDSection(); this.panelMemoryAndVCPUs = new System.Windows.Forms.Panel(); this.pdSectionVCPUs = new XenAdmin.Controls.PDSection(); this.panelMultipathing = new System.Windows.Forms.Panel(); this.pdSectionMultipathing = new XenAdmin.Controls.PDSection(); this.panelStatus = new System.Windows.Forms.Panel(); this.pdSectionStatus = new XenAdmin.Controls.PDSection(); this.panelHighAvailability = new System.Windows.Forms.Panel(); this.pdSectionHighAvailability = new XenAdmin.Controls.PDSection(); this.panelBootOptions = new System.Windows.Forms.Panel(); this.pdSectionBootOptions = new XenAdmin.Controls.PDSection(); this.panelCPU = new System.Windows.Forms.Panel(); this.pdSectionCPU = new XenAdmin.Controls.PDSection(); this.panelLicense = new System.Windows.Forms.Panel(); this.pdSectionLicense = new XenAdmin.Controls.PDSection(); this.panelVersion = new System.Windows.Forms.Panel(); this.pdSectionVersion = new XenAdmin.Controls.PDSection(); this.panelMemory = new System.Windows.Forms.Panel(); this.pdSectionMemory = new XenAdmin.Controls.PDSection(); this.panelManagementInterfaces = new System.Windows.Forms.Panel(); this.pdSectionManagementInterfaces = new XenAdmin.Controls.PDSection(); this.panelCustomFields = new System.Windows.Forms.Panel(); this.pdSectionCustomFields = new XenAdmin.Controls.PDSection(); this.panelGeneral = new System.Windows.Forms.Panel(); this.pdSectionGeneral = new XenAdmin.Controls.PDSection(); this.pageContainerPanel.SuspendLayout(); this.panel1.SuspendLayout(); this.panel3.SuspendLayout(); this.panel2.SuspendLayout(); this.panelStorageLinkSystemCapabilities.SuspendLayout(); this.panelMultipathBoot.SuspendLayout(); this.panelStorageLink.SuspendLayout(); this.panelUpdates.SuspendLayout(); this.panelMemoryAndVCPUs.SuspendLayout(); this.panelMultipathing.SuspendLayout(); this.panelStatus.SuspendLayout(); this.panelHighAvailability.SuspendLayout(); this.panelBootOptions.SuspendLayout(); this.panelCPU.SuspendLayout(); this.panelLicense.SuspendLayout(); this.panelVersion.SuspendLayout(); this.panelMemory.SuspendLayout(); this.panelManagementInterfaces.SuspendLayout(); this.panelCustomFields.SuspendLayout(); this.panelGeneral.SuspendLayout(); this.SuspendLayout(); // // pageContainerPanel // this.pageContainerPanel.Controls.Add(this.panel2); this.pageContainerPanel.Controls.Add(this.panel1); resources.ApplyResources(this.pageContainerPanel, "pageContainerPanel"); // // buttonProperties // resources.ApplyResources(this.buttonProperties, "buttonProperties"); this.buttonProperties.Name = "buttonProperties"; this.buttonProperties.UseVisualStyleBackColor = true; this.buttonProperties.Click += new System.EventHandler(this.EditButton_Click); // // panel1 // this.panel1.Controls.Add(this.panel3); resources.ApplyResources(this.panel1, "panel1"); this.panel1.Name = "panel1"; // // panel3 // this.panel3.Controls.Add(this.buttonProperties); this.panel3.Controls.Add(this.linkLabelExpand); this.panel3.Controls.Add(this.linkLabelCollapse); resources.ApplyResources(this.panel3, "panel3"); this.panel3.Name = "panel3"; // // linkLabelExpand // resources.ApplyResources(this.linkLabelExpand, "linkLabelExpand"); this.linkLabelExpand.Name = "linkLabelExpand"; this.linkLabelExpand.TabStop = true; this.linkLabelExpand.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabelExpand_LinkClicked); // // linkLabelCollapse // resources.ApplyResources(this.linkLabelCollapse, "linkLabelCollapse"); this.linkLabelCollapse.Name = "linkLabelCollapse"; this.linkLabelCollapse.TabStop = true; this.linkLabelCollapse.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabelCollapse_LinkClicked); // // panel2 // resources.ApplyResources(this.panel2, "panel2"); this.panel2.Controls.Add(this.panelStorageLinkSystemCapabilities); this.panel2.Controls.Add(this.panelMultipathBoot); this.panel2.Controls.Add(this.panelStorageLink); this.panel2.Controls.Add(this.panelUpdates); this.panel2.Controls.Add(this.panelMemoryAndVCPUs); this.panel2.Controls.Add(this.panelMultipathing); this.panel2.Controls.Add(this.panelStatus); this.panel2.Controls.Add(this.panelHighAvailability); this.panel2.Controls.Add(this.panelBootOptions); this.panel2.Controls.Add(this.panelCPU); this.panel2.Controls.Add(this.panelLicense); this.panel2.Controls.Add(this.panelVersion); this.panel2.Controls.Add(this.panelMemory); this.panel2.Controls.Add(this.panelManagementInterfaces); this.panel2.Controls.Add(this.panelCustomFields); this.panel2.Controls.Add(this.panelGeneral); this.panel2.Name = "panel2"; // // panelStorageLinkSystemCapabilities // resources.ApplyResources(this.panelStorageLinkSystemCapabilities, "panelStorageLinkSystemCapabilities"); this.panelStorageLinkSystemCapabilities.Controls.Add(this.pdSectionStorageLinkSystemCapabilities); this.panelStorageLinkSystemCapabilities.Name = "panelStorageLinkSystemCapabilities"; // // pdSectionStorageLinkSystemCapabilities // this.pdSectionStorageLinkSystemCapabilities.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdSectionStorageLinkSystemCapabilities, "pdSectionStorageLinkSystemCapabilities"); this.pdSectionStorageLinkSystemCapabilities.Name = "pdSectionStorageLinkSystemCapabilities"; this.pdSectionStorageLinkSystemCapabilities.ShowCellToolTips = false; // // panelMultipathBoot // resources.ApplyResources(this.panelMultipathBoot, "panelMultipathBoot"); this.panelMultipathBoot.Controls.Add(this.pdSectionMultipathBoot); this.panelMultipathBoot.Name = "panelMultipathBoot"; // // pdSectionMultipathBoot // this.pdSectionMultipathBoot.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdSectionMultipathBoot, "pdSectionMultipathBoot"); this.pdSectionMultipathBoot.Name = "pdSectionMultipathBoot"; this.pdSectionMultipathBoot.ShowCellToolTips = false; // // panelStorageLink // resources.ApplyResources(this.panelStorageLink, "panelStorageLink"); this.panelStorageLink.Controls.Add(this.pdStorageLink); this.panelStorageLink.Name = "panelStorageLink"; // // pdStorageLink // this.pdStorageLink.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdStorageLink, "pdStorageLink"); this.pdStorageLink.Name = "pdStorageLink"; this.pdStorageLink.ShowCellToolTips = false; this.pdStorageLink.ExpandedChanged += new System.Action<XenAdmin.Controls.PDSection>(this.s_ExpandedEventHandler); // // panelUpdates // resources.ApplyResources(this.panelUpdates, "panelUpdates"); this.panelUpdates.Controls.Add(this.pdSectionUpdates); this.panelUpdates.Name = "panelUpdates"; // // pdSectionUpdates // this.pdSectionUpdates.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdSectionUpdates, "pdSectionUpdates"); this.pdSectionUpdates.Name = "pdSectionUpdates"; this.pdSectionUpdates.ShowCellToolTips = false; this.pdSectionUpdates.ExpandedChanged += new System.Action<XenAdmin.Controls.PDSection>(this.s_ExpandedEventHandler); // // panelMemoryAndVCPUs // resources.ApplyResources(this.panelMemoryAndVCPUs, "panelMemoryAndVCPUs"); this.panelMemoryAndVCPUs.Controls.Add(this.pdSectionVCPUs); this.panelMemoryAndVCPUs.Name = "panelMemoryAndVCPUs"; // // pdSectionVCPUs // this.pdSectionVCPUs.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdSectionVCPUs, "pdSectionVCPUs"); this.pdSectionVCPUs.Name = "pdSectionVCPUs"; this.pdSectionVCPUs.ShowCellToolTips = false; this.pdSectionVCPUs.ExpandedChanged += new System.Action<XenAdmin.Controls.PDSection>(this.s_ExpandedEventHandler); // // panelMultipathing // resources.ApplyResources(this.panelMultipathing, "panelMultipathing"); this.panelMultipathing.Controls.Add(this.pdSectionMultipathing); this.panelMultipathing.Name = "panelMultipathing"; // // pdSectionMultipathing // this.pdSectionMultipathing.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdSectionMultipathing, "pdSectionMultipathing"); this.pdSectionMultipathing.Name = "pdSectionMultipathing"; this.pdSectionMultipathing.ShowCellToolTips = false; this.pdSectionMultipathing.ExpandedChanged += new System.Action<XenAdmin.Controls.PDSection>(this.s_ExpandedEventHandler); // // panelStatus // resources.ApplyResources(this.panelStatus, "panelStatus"); this.panelStatus.Controls.Add(this.pdSectionStatus); this.panelStatus.Name = "panelStatus"; // // pdSectionStatus // this.pdSectionStatus.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdSectionStatus, "pdSectionStatus"); this.pdSectionStatus.Name = "pdSectionStatus"; this.pdSectionStatus.ShowCellToolTips = false; this.pdSectionStatus.ExpandedChanged += new System.Action<XenAdmin.Controls.PDSection>(this.s_ExpandedEventHandler); // // panelHighAvailability // resources.ApplyResources(this.panelHighAvailability, "panelHighAvailability"); this.panelHighAvailability.Controls.Add(this.pdSectionHighAvailability); this.panelHighAvailability.Name = "panelHighAvailability"; // // pdSectionHighAvailability // this.pdSectionHighAvailability.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdSectionHighAvailability, "pdSectionHighAvailability"); this.pdSectionHighAvailability.Name = "pdSectionHighAvailability"; this.pdSectionHighAvailability.ShowCellToolTips = false; this.pdSectionHighAvailability.ExpandedChanged += new System.Action<XenAdmin.Controls.PDSection>(this.s_ExpandedEventHandler); // // panelBootOptions // resources.ApplyResources(this.panelBootOptions, "panelBootOptions"); this.panelBootOptions.Controls.Add(this.pdSectionBootOptions); this.panelBootOptions.Name = "panelBootOptions"; // // pdSectionBootOptions // this.pdSectionBootOptions.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdSectionBootOptions, "pdSectionBootOptions"); this.pdSectionBootOptions.Name = "pdSectionBootOptions"; this.pdSectionBootOptions.ShowCellToolTips = false; this.pdSectionBootOptions.ExpandedChanged += new System.Action<XenAdmin.Controls.PDSection>(this.s_ExpandedEventHandler); // // panelCPU // resources.ApplyResources(this.panelCPU, "panelCPU"); this.panelCPU.Controls.Add(this.pdSectionCPU); this.panelCPU.Name = "panelCPU"; // // pdSectionCPU // this.pdSectionCPU.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdSectionCPU, "pdSectionCPU"); this.pdSectionCPU.Name = "pdSectionCPU"; this.pdSectionCPU.ShowCellToolTips = false; this.pdSectionCPU.ExpandedChanged += new System.Action<XenAdmin.Controls.PDSection>(this.s_ExpandedEventHandler); // // panelLicense // resources.ApplyResources(this.panelLicense, "panelLicense"); this.panelLicense.Controls.Add(this.pdSectionLicense); this.panelLicense.Name = "panelLicense"; // // pdSectionLicense // this.pdSectionLicense.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdSectionLicense, "pdSectionLicense"); this.pdSectionLicense.Name = "pdSectionLicense"; this.pdSectionLicense.ShowCellToolTips = false; this.pdSectionLicense.ExpandedChanged += new System.Action<XenAdmin.Controls.PDSection>(this.s_ExpandedEventHandler); // // panelVersion // resources.ApplyResources(this.panelVersion, "panelVersion"); this.panelVersion.Controls.Add(this.pdSectionVersion); this.panelVersion.Name = "panelVersion"; // // pdSectionVersion // this.pdSectionVersion.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdSectionVersion, "pdSectionVersion"); this.pdSectionVersion.Name = "pdSectionVersion"; this.pdSectionVersion.ShowCellToolTips = false; this.pdSectionVersion.ExpandedChanged += new System.Action<XenAdmin.Controls.PDSection>(this.s_ExpandedEventHandler); // // panelMemory // resources.ApplyResources(this.panelMemory, "panelMemory"); this.panelMemory.Controls.Add(this.pdSectionMemory); this.panelMemory.Name = "panelMemory"; // // pdSectionMemory // this.pdSectionMemory.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdSectionMemory, "pdSectionMemory"); this.pdSectionMemory.Name = "pdSectionMemory"; this.pdSectionMemory.ShowCellToolTips = false; this.pdSectionMemory.ExpandedChanged += new System.Action<XenAdmin.Controls.PDSection>(this.s_ExpandedEventHandler); // // panelManagementInterfaces // resources.ApplyResources(this.panelManagementInterfaces, "panelManagementInterfaces"); this.panelManagementInterfaces.Controls.Add(this.pdSectionManagementInterfaces); this.panelManagementInterfaces.Name = "panelManagementInterfaces"; // // pdSectionManagementInterfaces // this.pdSectionManagementInterfaces.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdSectionManagementInterfaces, "pdSectionManagementInterfaces"); this.pdSectionManagementInterfaces.Name = "pdSectionManagementInterfaces"; this.pdSectionManagementInterfaces.ShowCellToolTips = false; this.pdSectionManagementInterfaces.ExpandedChanged += new System.Action<XenAdmin.Controls.PDSection>(this.s_ExpandedEventHandler); // // panelCustomFields // resources.ApplyResources(this.panelCustomFields, "panelCustomFields"); this.panelCustomFields.Controls.Add(this.pdSectionCustomFields); this.panelCustomFields.Name = "panelCustomFields"; // // pdSectionCustomFields // this.pdSectionCustomFields.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdSectionCustomFields, "pdSectionCustomFields"); this.pdSectionCustomFields.Name = "pdSectionCustomFields"; this.pdSectionCustomFields.ShowCellToolTips = true; this.pdSectionCustomFields.ExpandedChanged += new System.Action<XenAdmin.Controls.PDSection>(this.s_ExpandedEventHandler); // // panelGeneral // resources.ApplyResources(this.panelGeneral, "panelGeneral"); this.panelGeneral.Controls.Add(this.pdSectionGeneral); this.panelGeneral.Name = "panelGeneral"; // // pdSectionGeneral // this.pdSectionGeneral.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdSectionGeneral, "pdSectionGeneral"); this.pdSectionGeneral.Name = "pdSectionGeneral"; this.pdSectionGeneral.ShowCellToolTips = false; this.pdSectionGeneral.ExpandedChanged += new System.Action<XenAdmin.Controls.PDSection>(this.s_ExpandedEventHandler); // // GeneralTabPage // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.DoubleBuffered = true; this.Name = "GeneralTabPage"; this.pageContainerPanel.ResumeLayout(false); this.panel1.ResumeLayout(false); this.panel3.ResumeLayout(false); this.panel3.PerformLayout(); this.panel2.ResumeLayout(false); this.panel2.PerformLayout(); this.panelStorageLinkSystemCapabilities.ResumeLayout(false); this.panelMultipathBoot.ResumeLayout(false); this.panelStorageLink.ResumeLayout(false); this.panelUpdates.ResumeLayout(false); this.panelMemoryAndVCPUs.ResumeLayout(false); this.panelMultipathing.ResumeLayout(false); this.panelStatus.ResumeLayout(false); this.panelHighAvailability.ResumeLayout(false); this.panelBootOptions.ResumeLayout(false); this.panelCPU.ResumeLayout(false); this.panelLicense.ResumeLayout(false); this.panelVersion.ResumeLayout(false); this.panelMemory.ResumeLayout(false); this.panelManagementInterfaces.ResumeLayout(false); this.panelCustomFields.ResumeLayout(false); this.panelGeneral.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button buttonProperties; private System.Windows.Forms.Panel panel1; private XenAdmin.Controls.PanelNoFocusScroll panel2; private System.Windows.Forms.Panel panelGeneral; private XenAdmin.Controls.PDSection pdSectionGeneral; private System.Windows.Forms.Panel panelMemoryAndVCPUs; private XenAdmin.Controls.PDSection pdSectionVCPUs; private System.Windows.Forms.Panel panelBootOptions; private XenAdmin.Controls.PDSection pdSectionBootOptions; private System.Windows.Forms.Panel panelMultipathing; private XenAdmin.Controls.PDSection pdSectionMultipathing; private System.Windows.Forms.Panel panelStatus; private XenAdmin.Controls.PDSection pdSectionStatus; private System.Windows.Forms.Panel panelHighAvailability; private XenAdmin.Controls.PDSection pdSectionHighAvailability; private System.Windows.Forms.Panel panelCustomFields; private XenAdmin.Controls.PDSection pdSectionCustomFields; private System.Windows.Forms.Panel panelManagementInterfaces; private XenAdmin.Controls.PDSection pdSectionManagementInterfaces; private System.Windows.Forms.Panel panelCPU; private XenAdmin.Controls.PDSection pdSectionCPU; private System.Windows.Forms.Panel panelVersion; private XenAdmin.Controls.PDSection pdSectionVersion; private System.Windows.Forms.Panel panelLicense; private XenAdmin.Controls.PDSection pdSectionLicense; private System.Windows.Forms.Panel panelMemory; private XenAdmin.Controls.PDSection pdSectionMemory; private System.Windows.Forms.Panel panelUpdates; private XenAdmin.Controls.PDSection pdSectionUpdates; private System.Windows.Forms.LinkLabel linkLabelExpand; private System.Windows.Forms.LinkLabel linkLabelCollapse; private System.Windows.Forms.Panel panel3; private System.Windows.Forms.Panel panelStorageLink; private XenAdmin.Controls.PDSection pdStorageLink; private System.Windows.Forms.Panel panelMultipathBoot; private XenAdmin.Controls.PDSection pdSectionMultipathBoot; private System.Windows.Forms.Panel panelStorageLinkSystemCapabilities; private XenAdmin.Controls.PDSection pdSectionStorageLinkSystemCapabilities; } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; using ASC.Collections; using ASC.Common.Data.Sql; using ASC.Common.Data.Sql.Expressions; using ASC.Core; using ASC.Core.Tenants; using ASC.CRM.Core.Entities; using ASC.Files.Core; using ASC.Web.CRM.Core.Search; using ASC.Web.Files.Api; using OrderBy = ASC.CRM.Core.Entities.OrderBy; namespace ASC.CRM.Core.Dao { public class CachedCasesDao : CasesDao { private readonly HttpRequestDictionary<Cases> _casesCache = new HttpRequestDictionary<Cases>("crm_cases"); public CachedCasesDao(int tenantID) : base(tenantID) { } public override Cases GetByID(int caseID) { return _casesCache.Get(caseID.ToString(CultureInfo.InvariantCulture), () => GetByIDBase(caseID)); } private Cases GetByIDBase(int caseID) { return base.GetByID(caseID); } public override void UpdateCases(Cases cases) { if (cases != null && cases.ID > 0) ResetCache(cases.ID); base.UpdateCases(cases); } public override Cases DeleteCases(int casesID) { ResetCache(casesID); return base.DeleteCases(casesID); } private void ResetCache(int taskID) { _casesCache.Reset(taskID.ToString(CultureInfo.InvariantCulture)); } } public class CasesDao : AbstractDao { public CasesDao(int tenantID) : base(tenantID) { } public void AddMember(int caseID, int memberID) { SetRelative(memberID, EntityType.Case, caseID); } public Dictionary<int, int[]> GetMembers(int[] caseID) { return GetRelativeToEntity(null, EntityType.Case, caseID); } public int[] GetMembers(int caseID) { return GetRelativeToEntity(null, EntityType.Case, caseID); } public void SetMembers(int caseID, int[] memberID) { SetRelative(memberID, EntityType.Case, caseID); } public void RemoveMember(int caseID, int memberID) { RemoveRelative(memberID, EntityType.Case, caseID); } public virtual int[] SaveCasesList(List<Cases> items) { using (var tx = Db.BeginTransaction()) { var result = items.Select(item => CreateCasesInDb(item.Title)).ToArray(); tx.Commit(); // Delete relative keys _cache.Remove(new Regex(TenantID.ToString(CultureInfo.InvariantCulture) + "cases.*")); return result; } } public Cases CloseCases(int caseID) { if (caseID <= 0) throw new ArgumentException(); var cases = GetByID(caseID); if (cases == null) return null; CRMSecurity.DemandAccessTo(cases); Db.ExecuteNonQuery( Update("crm_case") .Set("is_closed", true) .Where("id", caseID) ); cases.IsClosed = true; return cases; } public Cases ReOpenCases(int caseID) { if (caseID <= 0) throw new ArgumentException(); var cases = GetByID(caseID); if (cases == null) return null; CRMSecurity.DemandAccessTo(cases); Db.ExecuteNonQuery( Update("crm_case") .Set("is_closed", false) .Where("id", caseID) ); cases.IsClosed = false; return cases; } public int CreateCases(String title) { var result = CreateCasesInDb(title); // Delete relative keys _cache.Remove(new Regex(TenantID.ToString(CultureInfo.InvariantCulture) + "invoice.*")); return result; } private int CreateCasesInDb(String title) { return Db.ExecuteScalar<int>( Insert("crm_case") .InColumnValue("id", 0) .InColumnValue("title", title) .InColumnValue("is_closed", false) .InColumnValue("create_on", TenantUtil.DateTimeToUtc(TenantUtil.DateTimeNow())) .InColumnValue("create_by", SecurityContext.CurrentAccount.ID) .InColumnValue("last_modifed_on", TenantUtil.DateTimeToUtc(TenantUtil.DateTimeNow())) .InColumnValue("last_modifed_by", SecurityContext.CurrentAccount.ID) .Identity(1, 0, true)); } public virtual void UpdateCases(Cases cases) { CRMSecurity.DemandEdit(cases); // Delete relative keys _cache.Remove(new Regex(TenantID.ToString(CultureInfo.InvariantCulture) + "invoice.*")); Db.ExecuteNonQuery( Update("crm_case") .Set("title", cases.Title) .Set("is_closed", cases.IsClosed) .Set("last_modifed_on", TenantUtil.DateTimeToUtc(TenantUtil.DateTimeNow())) .Set("last_modifed_by", SecurityContext.CurrentAccount.ID) .Where("id", cases.ID) ); } public virtual Cases DeleteCases(int casesID) { if (casesID <= 0) return null; var cases = GetByID(casesID); if (cases == null) return null; CRMSecurity.DemandDelete(cases); // Delete relative keys _cache.Remove(new Regex(TenantID.ToString(CultureInfo.InvariantCulture) + "invoice.*")); DeleteBatchCases(new[] { casesID }); return cases; } public virtual List<Cases> DeleteBatchCases(List<Cases> caseses) { caseses = caseses.FindAll(CRMSecurity.CanDelete).ToList(); if (!caseses.Any()) return caseses; // Delete relative keys _cache.Remove(new Regex(TenantID.ToString(CultureInfo.InvariantCulture) + "invoice.*")); DeleteBatchCasesExecute(caseses); return caseses; } public virtual List<Cases> DeleteBatchCases(int[] casesID) { if (casesID == null || !casesID.Any()) return null; var cases = GetCases(casesID).FindAll(CRMSecurity.CanDelete).ToList(); if (!cases.Any()) return cases; // Delete relative keys _cache.Remove(new Regex(TenantID.ToString(CultureInfo.InvariantCulture) + "invoice.*")); DeleteBatchCasesExecute(cases); return cases; } private void DeleteBatchCasesExecute(List<Cases> caseses) { var casesID = caseses.Select(x => x.ID).ToArray(); using (var tagdao = FilesIntegration.GetTagDao()) { var tagNames = Db.ExecuteList(Query("crm_relationship_event").Select("id") .Where(Exp.Eq("have_files", true) & Exp.In("entity_id", casesID) & Exp.Eq("entity_type", (int)EntityType.Case))) .Select(row => String.Format("RelationshipEvent_{0}", row[0])).ToArray(); var filesIDs = tagdao.GetTags(tagNames, TagType.System).Where(t => t.EntryType == FileEntryType.File).Select(t => t.EntryId).ToArray(); using (var tx = Db.BeginTransaction(true)) { Db.ExecuteNonQuery(Delete("crm_field_value").Where(Exp.In("entity_id", casesID) & Exp.Eq("entity_type", (int)EntityType.Case))); Db.ExecuteNonQuery(Delete("crm_relationship_event").Where(Exp.In("entity_id", casesID) & Exp.Eq("entity_type", (int)EntityType.Case))); Db.ExecuteNonQuery(Delete("crm_task").Where(Exp.In("entity_id", casesID) & Exp.Eq("entity_type", (int)EntityType.Case))); Db.ExecuteNonQuery(new SqlDelete("crm_entity_tag").Where(Exp.In("entity_id", casesID) & Exp.Eq("entity_type", (int)EntityType.Case))); Db.ExecuteNonQuery(Delete("crm_case").Where(Exp.In("id", casesID))); tx.Commit(); } caseses.ForEach(item => CoreContext.AuthorizationManager.RemoveAllAces(item)); if (0 < tagNames.Length) { using (var filedao = FilesIntegration.GetFileDao()) { foreach (var filesID in filesIDs) { filedao.DeleteFile(filesID); } } } } //todo: remove indexes } public List<Cases> GetAllCases() { return GetCases(String.Empty, 0, null, null, 0, 0, new OrderBy(SortedByType.Title, true)); } public int GetCasesCount() { return GetCasesCount(String.Empty, 0, null, null); } public int GetCasesCount( String searchText, int contactID, bool? isClosed, IEnumerable<String> tags) { var cacheKey = TenantID.ToString(CultureInfo.InvariantCulture) + "cases" + SecurityContext.CurrentAccount.ID.ToString() + searchText + contactID; if (tags != null) cacheKey += String.Join("", tags.ToArray()); if (isClosed.HasValue) cacheKey += isClosed.Value; var fromCache = _cache.Get<string>(cacheKey); if (fromCache != null) return Convert.ToInt32(fromCache); var withParams = !(String.IsNullOrEmpty(searchText) && contactID <= 0 && isClosed == null && (tags == null || !tags.Any())); var exceptIDs = CRMSecurity.GetPrivateItems(typeof(Cases)).ToList(); int result; if (withParams) { var whereConditional = WhereConditional(exceptIDs, searchText, contactID, isClosed, tags); result = whereConditional != null ? Db.ExecuteScalar<int>(Query("crm_case").Where(whereConditional).SelectCount()) : 0; } else { var countWithoutPrivate = Db.ExecuteScalar<int>(Query("crm_case").SelectCount()); var privateCount = exceptIDs.Count; if (privateCount > countWithoutPrivate) { _log.ErrorFormat(@"Private cases count more than all cases. Tenant: {0}. CurrentAccount: {1}", TenantID, SecurityContext.CurrentAccount.ID); privateCount = 0; } result = countWithoutPrivate - privateCount; } if (result > 0) { _cache.Insert(cacheKey, result, TimeSpan.FromSeconds(30)); } return result; } private Exp WhereConditional( ICollection<int> exceptIDs, String searchText, int contactID, bool? isClosed, IEnumerable<String> tags) { var conditions = new List<Exp>(); var ids = new List<int>(); if (!String.IsNullOrEmpty(searchText)) { searchText = searchText.Trim(); var keywords = searchText.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .ToArray(); if (keywords.Length > 0) { if (!BundleSearch.TrySelectCase(searchText, out ids)) { conditions.Add(BuildLike(new[] { "title" }, keywords)); } else if (!ids.Any()) { return null; } } } if (contactID > 0) { var sqlQuery = new SqlQuery("crm_entity_contact") .Select("entity_id") .Where(Exp.Eq("contact_id", contactID) & Exp.Eq("entity_type", (int)EntityType.Case)); if (ids.Count > 0) sqlQuery.Where(Exp.In("entity_id", ids)); ids = Db.ExecuteList(sqlQuery).Select(item => Convert.ToInt32(item[0])).ToList(); if (ids.Count == 0) return null; } if (isClosed.HasValue) conditions.Add(Exp.Eq("is_closed", isClosed)); if (tags != null && tags.Any()) { ids = SearchByTags(EntityType.Case, ids.ToArray(), tags); if (ids.Count == 0) return null; } if (ids.Count > 0) { if (exceptIDs.Count > 0) { ids = ids.Except(exceptIDs).ToList(); if (ids.Count == 0) return null; } conditions.Add(Exp.In("id", ids)); } else if (exceptIDs.Count > 0) { conditions.Add(!Exp.In("id", exceptIDs.ToArray())); } if (conditions.Count == 0) return null; return conditions.Count == 1 ? conditions[0] : conditions.Aggregate((i, j) => i & j); } public List<Cases> GetCases(IEnumerable<int> casesID) { if (casesID == null || !casesID.Any()) return new List<Cases>(); var sqlQuery = GetCasesSqlQuery(Exp.In("id", casesID.ToArray())); return Db.ExecuteList(sqlQuery).ConvertAll(ToCases).FindAll(CRMSecurity.CanAccessTo); } public List<Cases> GetCases( String searchText, int contactID, bool? isClosed, IEnumerable<String> tags, int from, int count, OrderBy orderBy) { var sqlQuery = GetCasesSqlQuery(null); var withParams = !(String.IsNullOrEmpty(searchText) && contactID <= 0 && isClosed == null && (tags == null || !tags.Any())); var whereConditional = WhereConditional(CRMSecurity.GetPrivateItems(typeof(Cases)).ToList(), searchText, contactID, isClosed, tags); if (withParams && whereConditional == null) return new List<Cases>(); sqlQuery.Where(whereConditional); if (0 < from && from < int.MaxValue) sqlQuery.SetFirstResult(from); if (0 < count && count < int.MaxValue) sqlQuery.SetMaxResults(count); sqlQuery.OrderBy("is_closed", true); if (orderBy != null && Enum.IsDefined(typeof(SortedByType), orderBy.SortedBy)) switch ((SortedByType)orderBy.SortedBy) { case SortedByType.Title: sqlQuery.OrderBy("title", orderBy.IsAsc); break; case SortedByType.CreateBy: sqlQuery.OrderBy("create_by", orderBy.IsAsc); break; case SortedByType.DateAndTime: sqlQuery.OrderBy("create_on", orderBy.IsAsc); break; } return Db.ExecuteList(sqlQuery).ConvertAll(ToCases); } public List<Cases> GetCasesByPrefix(String prefix, int from, int count) { if (count == 0) throw new ArgumentException(); prefix = prefix.Trim(); var keywords = prefix.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToArray(); var q = GetCasesSqlQuery(null); if (keywords.Length == 1) { q.Where(Exp.Like("title", keywords[0])); } else { foreach (var k in keywords) { q.Where(Exp.Like("title", k)); } } if (0 < from && from < int.MaxValue) q.SetFirstResult(from); if (0 < count && count < int.MaxValue) q.SetMaxResults(count); var sqlResult = Db.ExecuteList(q).ConvertAll(row => ToCases(row)).FindAll(CRMSecurity.CanAccessTo); return sqlResult.OrderBy(cases => cases.Title).ToList(); } public virtual List<Cases> GetByID(int[] ids) { return Db.ExecuteList(GetCasesSqlQuery(Exp.In("id", ids))).ConvertAll(ToCases); } public virtual Cases GetByID(int id) { if (id <= 0) return null; var cases = GetByID(new[] { id }); return cases.Count == 0 ? null : cases[0]; } #region Private Methods private static Cases ToCases(object[] row) { return new Cases { ID = Convert.ToInt32(row[0]), Title = Convert.ToString(row[1]), CreateBy = ToGuid(row[2]), CreateOn = TenantUtil.DateTimeFromUtc(DateTime.Parse(row[3].ToString())), IsClosed = Convert.ToBoolean(row[4]) }; } private SqlQuery GetCasesSqlQuery(Exp where) { var sqlQuery = Query("crm_case") .Select("id", "title", "create_by", "create_on", "is_closed"); if (where != null) { sqlQuery.Where(where); } return sqlQuery; } #endregion public void ReassignCasesResponsible(Guid fromUserId, Guid toUserId) { var cases = GetAllCases(); foreach (var item in cases) { var responsibles = CRMSecurity.GetAccessSubjectGuidsTo(item); if (!responsibles.Any()) continue; responsibles.Remove(fromUserId); responsibles.Add(toUserId); CRMSecurity.SetAccessTo(item, responsibles.Distinct().ToList()); } } } }
// 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.Runtime.InteropServices; using System.Threading; using System.Text; #pragma warning disable SA1121 // we don't want to simplify built-ins here as we're using aliasing using CFStringRef = System.IntPtr; using FSEventStreamRef = System.IntPtr; using size_t = System.IntPtr; using FSEventStreamEventId = System.UInt64; using FSEventStreamEventFlags = Interop.EventStream.FSEventStreamEventFlags; using CFRunLoopRef = System.IntPtr; using Microsoft.Win32.SafeHandles; namespace System.IO { public partial class FileSystemWatcher { /// <summary>Called when FileSystemWatcher is finalized.</summary> private void FinalizeDispose() { // Make sure we cleanup StopRaisingEvents(); } private void StartRaisingEvents() { // If we're called when "Initializing" is true, set enabled to true if (IsSuspended()) { _enabled = true; return; } // Don't start another instance if one is already runnings if (_cancellation != null) { return; } try { CancellationTokenSource cancellation = new CancellationTokenSource(); RunningInstance instance = new RunningInstance(this, _directory, _includeSubdirectories, TranslateFlags(_notifyFilters), cancellation.Token); _enabled = true; _cancellation = cancellation; instance.Start(); } catch { _enabled = false; _cancellation = null; throw; } } private void StopRaisingEvents() { _enabled = false; if (IsSuspended()) return; CancellationTokenSource token = _cancellation; if (token != null) { _cancellation = null; token.Cancel(); } } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- private CancellationTokenSource _cancellation; private static FSEventStreamEventFlags TranslateFlags(NotifyFilters flagsToTranslate) { FSEventStreamEventFlags flags = 0; // Always re-create the filter flags when start is called since they could have changed if ((flagsToTranslate & (NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Size)) != 0) { flags = FSEventStreamEventFlags.kFSEventStreamEventFlagItemInodeMetaMod | FSEventStreamEventFlags.kFSEventStreamEventFlagItemFinderInfoMod | FSEventStreamEventFlags.kFSEventStreamEventFlagItemModified | FSEventStreamEventFlags.kFSEventStreamEventFlagItemChangeOwner; } if ((flagsToTranslate & NotifyFilters.Security) != 0) { flags |= FSEventStreamEventFlags.kFSEventStreamEventFlagItemChangeOwner | FSEventStreamEventFlags.kFSEventStreamEventFlagItemXattrMod; } if ((flagsToTranslate & NotifyFilters.DirectoryName) != 0) { flags |= FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsDir | FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsSymlink | FSEventStreamEventFlags.kFSEventStreamEventFlagItemCreated | FSEventStreamEventFlags.kFSEventStreamEventFlagItemRemoved | FSEventStreamEventFlags.kFSEventStreamEventFlagItemRenamed; } if ((flagsToTranslate & NotifyFilters.FileName) != 0) { flags |= FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsFile | FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsSymlink | FSEventStreamEventFlags.kFSEventStreamEventFlagItemCreated | FSEventStreamEventFlags.kFSEventStreamEventFlagItemRemoved | FSEventStreamEventFlags.kFSEventStreamEventFlagItemRenamed; } return flags; } private sealed class RunningInstance { // Flags used to create the event stream private const Interop.EventStream.FSEventStreamCreateFlags EventStreamFlags = (Interop.EventStream.FSEventStreamCreateFlags.kFSEventStreamCreateFlagFileEvents | Interop.EventStream.FSEventStreamCreateFlags.kFSEventStreamCreateFlagNoDefer | Interop.EventStream.FSEventStreamCreateFlags.kFSEventStreamCreateFlagWatchRoot); // Weak reference to the associated watcher. A weak reference is used so that the FileSystemWatcher may be collected and finalized, // causing an active operation to be torn down. private readonly WeakReference<FileSystemWatcher> _weakWatcher; // The user can input relative paths, which can muck with our path comparisons. Save off the // actual full path so we can use it for comparing private string _fullDirectory; // Boolean if we allow events from nested folders private bool _includeChildren; // The bitmask of events that we want to send to the user private FSEventStreamEventFlags _filterFlags; // The EventStream to listen for events on private SafeEventStreamHandle _eventStream; // Callback delegate for the EventStream events private Interop.EventStream.FSEventStreamCallback _callback; // Token to monitor for cancellation requests, upon which processing is stopped and all // state is cleaned up. private readonly CancellationToken _cancellationToken; // Calling RunLoopStop multiple times SegFaults so protect the call to it private bool _stopping; private ExecutionContext _context; internal RunningInstance( FileSystemWatcher watcher, string directory, bool includeChildren, FSEventStreamEventFlags filter, CancellationToken cancelToken) { Debug.Assert(string.IsNullOrEmpty(directory) == false); Debug.Assert(!cancelToken.IsCancellationRequested); _weakWatcher = new WeakReference<FileSystemWatcher>(watcher); _fullDirectory = System.IO.Path.GetFullPath(directory); _includeChildren = includeChildren; _filterFlags = filter; _cancellationToken = cancelToken; _cancellationToken.UnsafeRegister(obj => ((RunningInstance)obj).CancellationCallback(), this); _stopping = false; } private static class StaticWatcherRunLoopManager { // A reference to the RunLoop that we can use to start or stop a Watcher private static CFRunLoopRef s_watcherRunLoop = IntPtr.Zero; private static int s_scheduledStreamsCount = 0; private static readonly object s_lockObject = new object(); public static void ScheduleEventStream(SafeEventStreamHandle eventStream) { lock (s_lockObject) { if (s_watcherRunLoop != IntPtr.Zero) { // Schedule the EventStream to run on the thread's RunLoop s_scheduledStreamsCount++; Interop.EventStream.FSEventStreamScheduleWithRunLoop(eventStream, s_watcherRunLoop, Interop.RunLoop.kCFRunLoopDefaultMode); return; } Debug.Assert(s_scheduledStreamsCount == 0); s_scheduledStreamsCount = 1; var runLoopStarted = new ManualResetEventSlim(); new Thread(WatchForFileSystemEventsThreadStart) { IsBackground = true }.Start(new object[] { runLoopStarted, eventStream }); runLoopStarted.Wait(); } } public static void UnscheduleFromRunLoop(SafeEventStreamHandle eventStream) { Debug.Assert(s_watcherRunLoop != IntPtr.Zero); lock (s_lockObject) { if (s_watcherRunLoop != IntPtr.Zero) { // Always unschedule the RunLoop before cleaning up Interop.EventStream.FSEventStreamUnscheduleFromRunLoop(eventStream, s_watcherRunLoop, Interop.RunLoop.kCFRunLoopDefaultMode); s_scheduledStreamsCount--; if (s_scheduledStreamsCount == 0) { // Stop the FS event message pump Interop.RunLoop.CFRunLoopStop(s_watcherRunLoop); s_watcherRunLoop = IntPtr.Zero; } } } } private static void WatchForFileSystemEventsThreadStart(object args) { var inputArgs = (object[])args; var runLoopStarted = (ManualResetEventSlim)inputArgs[0]; var _eventStream = (SafeEventStreamHandle)inputArgs[1]; // Get this thread's RunLoop IntPtr runLoop = Interop.RunLoop.CFRunLoopGetCurrent(); s_watcherRunLoop = runLoop; Debug.Assert(s_watcherRunLoop != IntPtr.Zero); // Retain the RunLoop so that it doesn't get moved or cleaned up before we're done with it. IntPtr retainResult = Interop.CoreFoundation.CFRetain(runLoop); Debug.Assert(retainResult == runLoop, "CFRetain is supposed to return the input value"); // Schedule the EventStream to run on the thread's RunLoop Interop.EventStream.FSEventStreamScheduleWithRunLoop(_eventStream, runLoop, Interop.RunLoop.kCFRunLoopDefaultMode); runLoopStarted.Set(); try { // Start the OS X RunLoop (a blocking call) that will pump file system changes into the callback function Interop.RunLoop.CFRunLoopRun(); } finally { lock (s_lockObject) { Interop.CoreFoundation.CFRelease(runLoop); } } } } private void CancellationCallback() { if (!_stopping && _eventStream != null) { _stopping = true; try { // When we get here, we've requested to stop so cleanup the EventStream and unschedule from the RunLoop Interop.EventStream.FSEventStreamStop(_eventStream); } finally { StaticWatcherRunLoopManager.UnscheduleFromRunLoop(_eventStream); } } } internal unsafe void Start() { // Make sure _fullPath doesn't contain a link or alias // since the OS will give back the actual, non link'd or alias'd paths _fullDirectory = Interop.Sys.RealPath(_fullDirectory); if (_fullDirectory == null) { throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), _fullDirectory, true); } Debug.Assert(string.IsNullOrEmpty(_fullDirectory) == false, "Watch directory is null or empty"); // Normalize the _fullDirectory path to have a trailing slash if (_fullDirectory[_fullDirectory.Length - 1] != '/') { _fullDirectory += "/"; } // Get the path to watch and verify we created the CFStringRef SafeCreateHandle path = Interop.CoreFoundation.CFStringCreateWithCString(_fullDirectory); if (path.IsInvalid) { throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), _fullDirectory, true); } // Take the CFStringRef and put it into an array to pass to the EventStream SafeCreateHandle arrPaths = Interop.CoreFoundation.CFArrayCreate(new CFStringRef[1] { path.DangerousGetHandle() }, (UIntPtr)1); if (arrPaths.IsInvalid) { path.Dispose(); throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), _fullDirectory, true); } // Create the callback for the EventStream if it wasn't previously created for this instance. if (_callback == null) { _callback = new Interop.EventStream.FSEventStreamCallback(FileSystemEventCallback); } _context = ExecutionContext.Capture(); // Make sure the OS file buffer(s) are fully flushed so we don't get events from cached I/O Interop.Sys.Sync(); // Create the event stream for the path and tell the stream to watch for file system events. _eventStream = Interop.EventStream.FSEventStreamCreate( _callback, arrPaths, Interop.EventStream.kFSEventStreamEventIdSinceNow, 0.0f, EventStreamFlags); if (_eventStream.IsInvalid) { arrPaths.Dispose(); path.Dispose(); throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), _fullDirectory, true); } StaticWatcherRunLoopManager.ScheduleEventStream(_eventStream); bool started = Interop.EventStream.FSEventStreamStart(_eventStream); if (!started) { // Try to get the Watcher to raise the error event; if we can't do that, just silently exit since the watcher is gone anyway FileSystemWatcher watcher; if (_weakWatcher.TryGetTarget(out watcher)) { // An error occurred while trying to start the run loop so fail out watcher.OnError(new ErrorEventArgs(new IOException(SR.EventStream_FailedToStart, Marshal.GetLastWin32Error()))); } } } private unsafe void FileSystemEventCallback( FSEventStreamRef streamRef, IntPtr clientCallBackInfo, size_t numEvents, byte** eventPaths, FSEventStreamEventFlags* eventFlags, FSEventStreamEventId* eventIds) { // Try to get the actual watcher from our weak reference. We maintain a weak reference most of the time // so as to avoid a rooted cycle that would prevent our processing loop from ever ending // if the watcher is dropped by the user without being disposed. If we can't get the watcher, // there's nothing more to do (we can't raise events), so bail. FileSystemWatcher watcher; if (!_weakWatcher.TryGetTarget(out watcher)) { CancellationCallback(); return; } ExecutionContext context = _context; if (context is null) { // Flow suppressed, just run here ProcessEvents(numEvents.ToInt32(), eventPaths, eventFlags, eventIds, watcher); } else { ExecutionContext.Run( context, (object o) => ((RunningInstance)o).ProcessEvents(numEvents.ToInt32(), eventPaths, eventFlags, eventIds, watcher), this); } } private unsafe void ProcessEvents(int numEvents, byte** eventPaths, FSEventStreamEventFlags* eventFlags, FSEventStreamEventId* eventIds, FileSystemWatcher watcher) { // Since renames come in pairs, when we find the first we need to search for the next one. Once we find it, we'll add it to this // list so when the for-loop comes across it, we'll skip it since it's already been processed as part of the original of the pair. List<FSEventStreamEventId> handledRenameEvents = null; Memory<char>[] events = new Memory<char>[numEvents]; ParseEvents(); for (int i = 0; i < numEvents; i++) { ReadOnlySpan<char> path = events[i].Span; Debug.Assert(path[path.Length - 1] != '/', "Trailing slashes on events is not supported"); // Match Windows and don't notify us about changes to the Root folder if (_fullDirectory.Length >= path.Length && path.Equals(_fullDirectory.AsSpan(0, path.Length), StringComparison.OrdinalIgnoreCase)) { continue; } WatcherChangeTypes eventType = 0; // First, we should check if this event should kick off a re-scan since we can't really rely on anything after this point if that is true if (ShouldRescanOccur(eventFlags[i])) { watcher.OnError(new ErrorEventArgs(new IOException(SR.FSW_BufferOverflow, (int)eventFlags[i]))); break; } else if ((handledRenameEvents != null) && (handledRenameEvents.Contains(eventIds[i]))) { // If this event is the second in a rename pair then skip it continue; } else if (CheckIfPathIsNested(path) && ((eventType = FilterEvents(eventFlags[i])) != 0)) { // The base FileSystemWatcher does a match check against the relative path before combining with // the root dir; however, null is special cased to signify the root dir, so check if we should use that. ReadOnlySpan<char> relativePath = ReadOnlySpan<char>.Empty; if (path.Length > _fullDirectory.Length && path.StartsWith(_fullDirectory, StringComparison.OrdinalIgnoreCase)) { // Remove the root directory to get the relative path relativePath = path.Slice(_fullDirectory.Length); } // Raise a notification for the event if (((eventType & WatcherChangeTypes.Changed) > 0)) { watcher.NotifyFileSystemEventArgs(WatcherChangeTypes.Changed, relativePath); } if (((eventType & WatcherChangeTypes.Created) > 0)) { watcher.NotifyFileSystemEventArgs(WatcherChangeTypes.Created, relativePath); } if (((eventType & WatcherChangeTypes.Deleted) > 0)) { watcher.NotifyFileSystemEventArgs(WatcherChangeTypes.Deleted, relativePath); } if (((eventType & WatcherChangeTypes.Renamed) > 0)) { // Find the rename that is paired to this rename, which should be the next rename in the list int pairedId = FindRenameChangePairedChange(i, eventFlags, numEvents); if (pairedId == int.MinValue) { // Getting here means we have a rename without a pair, meaning it should be a create for the // move from unwatched folder to watcher folder scenario or a move from the watcher folder out. // Check if the item exists on disk to check which it is // Don't send a new notification if we already sent one for this event. if (DoesItemExist(path, IsFlagSet(eventFlags[i], FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsFile))) { if ((eventType & WatcherChangeTypes.Created) == 0) { watcher.NotifyFileSystemEventArgs(WatcherChangeTypes.Created, relativePath); } } else if ((eventType & WatcherChangeTypes.Deleted) == 0) { watcher.NotifyFileSystemEventArgs(WatcherChangeTypes.Deleted, relativePath); } } else { // Remove the base directory prefix and add the paired event to the list of // events to skip and notify the user of the rename ReadOnlySpan<char> newPathRelativeName = events[pairedId].Span; if (newPathRelativeName.Length >= _fullDirectory.Length && newPathRelativeName.StartsWith(_fullDirectory, StringComparison.OrdinalIgnoreCase)) { newPathRelativeName = newPathRelativeName.Slice(_fullDirectory.Length); } watcher.NotifyRenameEventArgs(WatcherChangeTypes.Renamed, newPathRelativeName, relativePath); // Create a new list, if necessary, and add the event if (handledRenameEvents == null) { handledRenameEvents = new List<FSEventStreamEventId>(); } handledRenameEvents.Add(eventIds[pairedId]); } } } ArraySegment<char> underlyingArray; if (MemoryMarshal.TryGetArray(events[i], out underlyingArray)) ArrayPool<char>.Shared.Return(underlyingArray.Array); } this._context = ExecutionContext.Capture(); void ParseEvents() { for (int i = 0; i < events.Length; i++) { int byteCount = 0; Debug.Assert(eventPaths[i] != null); byte* temp = eventPaths[i]; // Finds the position of null character. while (*temp != 0) { temp++; byteCount++; } Debug.Assert(byteCount > 0, "Empty events are not supported"); events[i] = new Memory<char>(ArrayPool<char>.Shared.Rent(Encoding.UTF8.GetMaxCharCount(byteCount))); int charCount; // Converting an array of bytes to UTF-8 char array charCount = Encoding.UTF8.GetChars(new ReadOnlySpan<byte>(eventPaths[i], byteCount), events[i].Span); events[i] = events[i].Slice(0, charCount); } } } /// <summary> /// Compares the given event flags to the filter flags and returns which event (if any) corresponds /// to those flags. /// </summary> private WatcherChangeTypes FilterEvents(FSEventStreamEventFlags eventFlags) { const FSEventStreamEventFlags changedFlags = FSEventStreamEventFlags.kFSEventStreamEventFlagItemInodeMetaMod | FSEventStreamEventFlags.kFSEventStreamEventFlagItemFinderInfoMod | FSEventStreamEventFlags.kFSEventStreamEventFlagItemModified | FSEventStreamEventFlags.kFSEventStreamEventFlagItemChangeOwner | FSEventStreamEventFlags.kFSEventStreamEventFlagItemXattrMod; WatcherChangeTypes eventType = 0; // If any of the Changed flags are set in both Filter and Event then a Changed event has occurred. if (((_filterFlags & changedFlags) & (eventFlags & changedFlags)) > 0) { eventType |= WatcherChangeTypes.Changed; } // Notify created/deleted/renamed events if they pass through the filters bool allowDirs = (_filterFlags & FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsDir) > 0; bool allowFiles = (_filterFlags & FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsFile) > 0; bool isDir = (eventFlags & FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsDir) > 0; bool isFile = (eventFlags & FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsFile) > 0; bool eventIsCorrectType = (isDir && allowDirs) || (isFile && allowFiles); bool eventIsLink = (eventFlags & (FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsHardlink | FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsSymlink | FSEventStreamEventFlags.kFSEventStreamEventFlagItemIsLastHardlink)) > 0; if (eventIsCorrectType || ((allowDirs || allowFiles) && (eventIsLink))) { // Notify Created/Deleted/Renamed events. if (IsFlagSet(eventFlags, FSEventStreamEventFlags.kFSEventStreamEventFlagItemRenamed)) { eventType |= WatcherChangeTypes.Renamed; } if (IsFlagSet(eventFlags, FSEventStreamEventFlags.kFSEventStreamEventFlagItemCreated)) { eventType |= WatcherChangeTypes.Created; } if (IsFlagSet(eventFlags, FSEventStreamEventFlags.kFSEventStreamEventFlagItemRemoved)) { eventType |= WatcherChangeTypes.Deleted; } } return eventType; } private bool ShouldRescanOccur(FSEventStreamEventFlags flags) { // Check if any bit is set that signals that the caller should rescan return (IsFlagSet(flags, FSEventStreamEventFlags.kFSEventStreamEventFlagMustScanSubDirs) || IsFlagSet(flags, FSEventStreamEventFlags.kFSEventStreamEventFlagUserDropped) || IsFlagSet(flags, FSEventStreamEventFlags.kFSEventStreamEventFlagKernelDropped) || IsFlagSet(flags, FSEventStreamEventFlags.kFSEventStreamEventFlagRootChanged) || IsFlagSet(flags, FSEventStreamEventFlags.kFSEventStreamEventFlagMount) || IsFlagSet(flags, FSEventStreamEventFlags.kFSEventStreamEventFlagUnmount)); } private bool CheckIfPathIsNested(ReadOnlySpan<char> eventPath) { // If we shouldn't include subdirectories, check if this path's parent is the watch directory // Check if the parent is the root. If so, then we'll continue processing based on the name. // If it isn't, then this will be set to false and we'll skip the name processing since it's irrelevant. return _includeChildren || _fullDirectory.AsSpan().StartsWith(System.IO.Path.GetDirectoryName(eventPath), StringComparison.OrdinalIgnoreCase); } private unsafe int FindRenameChangePairedChange( int currentIndex, FSEventStreamEventFlags* eventFlags, int numEvents) { // Start at one past the current index and try to find the next Rename item, which should be the old path. for (int i = currentIndex + 1; i < numEvents; i++) { if (IsFlagSet(eventFlags[i], FSEventStreamEventFlags.kFSEventStreamEventFlagItemRenamed)) { // We found match, stop looking return i; } } return int.MinValue; } private static bool IsFlagSet(FSEventStreamEventFlags flags, FSEventStreamEventFlags value) { return (value & flags) == value; } private static bool DoesItemExist(ReadOnlySpan<char> path, bool isFile) { if (path.IsEmpty || path.Length == 0) return false; if (!isFile) return FileSystem.DirectoryExists(path); return PathInternal.IsDirectorySeparator(path[path.Length - 1]) ? false : FileSystem.FileExists(path); } } } }
<?cs include:"doctype.cs" ?> <?cs include:"macros.cs" ?> <html<?cs if:devsite ?> devsite<?cs /if ?>> <?cs if:sdk.redirect ?> <head> <title>Redirecting...</title> <meta http-equiv="refresh" content="0;url=<?cs var:toroot ?>sdk/<?cs if:sdk.redirect.path ?><?cs var:sdk.redirect.path ?><?cs else ?>index.html<?cs /if ?>"> </head> <?cs else ?> <?cs include:"head_tag.cs" ?> <?cs /if ?> <body class="gc-documentation <?cs if:(guide||develop||training||reference||tools||sdk) ?>develop<?cs elif:design ?>design<?cs elif:distribute ?>distribute<?cs /if ?>" itemscope itemtype="http://schema.org/CreativeWork"> <a name="top"></a> <?cs include:"header.cs" ?> <div <?cs if:fullpage ?><?cs else ?>class="col-13" id="doc-col"<?cs /if ?> > <?cs if:sdk.redirect ?> <div class="g-unit"> <div id="jd-content"> <p>Redirecting to <a href="<?cs var:toroot ?>sdk/<?cs if:sdk.redirect.path ?><?cs var:sdk.redirect.path ?><?cs else ?>index.html<?cs /if ?>"><?cs if:sdk.redirect.path ?><?cs var:sdk.redirect.path ?><?cs else ?>Download the SDK<?cs /if ?> </a> ...</p> <?cs else ?> <?cs # else, if NOT redirect ... # # # The following is for SDK/NDK pages # # ?> <?cs if:header.hide ?><?cs else ?> <h1 itemprop="name"><?cs var:page.title ?></h1> <?cs /if ?> <div id="jd-content" itemprop="description"> <?cs if:sdk.not_latest_version ?> <div class="special"> <p><strong>This is NOT the current Android SDK release.</strong></p> <p><a href="/sdk/index.html">Download the current Android SDK</a></p> </div> <?cs /if ?> <?cs if:ndk ?> <?cs # # # # # # # # the following is for the NDK # # (nested in if/else redirect) # # # # ?> <table class="download" id="download-table"> <tr> <th>Platform</th> <th>Package</th> <th style="white-space:nowrap">Size (Bytes)</th> <th>SHA1 Checksum</th> </tr> <tr> <td>Windows 32-bit</td> <td> <a onClick="return onDownload(this)" href="http://dl.google.com/android/repository/<?cs var:ndk.win32_download ?>"><?cs var:ndk.win32_download ?></a> </td> <td><?cs var:ndk.win32_bytes ?></td> <td><?cs var:ndk.win32_checksum ?></td> </tr> <!-- <tr> <td> <a onClick="return onDownload(this)" href="http://dl.google.com/android/repository/<?cs var:ndk.win32.legacy_download ?>"><?cs var:ndk.win32.legacy_download ?></a> </td> <td><?cs var:ndk.win32.legacy_bytes ?></td> <td><?cs var:ndk.win32.legacy_checksum ?></td> </tr> --> <tr> <td>Windows 64-bit</td> <td> <a onClick="return onDownload(this)" href="http://dl.google.com/android/repository/<?cs var:ndk.win64_download ?>"><?cs var:ndk.win64_download ?></a> </td> <td><?cs var:ndk.win64_bytes ?></td> <td><?cs var:ndk.win64_checksum ?></td> </tr> <!-- <tr> <td> <a onClick="return onDownload(this)" href="http://dl.google.com/android/repository/<?cs var:ndk.win64.legacy_download ?>"><?cs var:ndk.win64.legacy_download ?></a> </td> <td><?cs var:ndk.win64.legacy_bytes ?></td> <td><?cs var:ndk.win64.legacy_checksum ?></td> </tr> --> <tr> <td>Mac OS X 32-bit</td> <td> <a onClick="return onDownload(this)" href="http://dl.google.com/android/repository/<?cs var:ndk.mac32_download ?>"><?cs var:ndk.mac32_download ?></a> </td> <td><?cs var:ndk.mac32_bytes ?></td> <td><?cs var:ndk.mac32_checksum ?></td> </tr> <!-- <tr> <td> <a onClick="return onDownload(this)" href="http://dl.google.com/android/repository/<?cs var:ndk.mac32.legacy_download ?>"><?cs var:ndk.mac32.legacy_download ?></a> </td> <td><?cs var:ndk.mac32.legacy_bytes ?></td> <td><?cs var:ndk.mac32.legacy_checksum ?></td> </tr> --> <td>Mac OS X 64-bit</td> <td> <a onClick="return onDownload(this)" href="http://dl.google.com/android/repository/<?cs var:ndk.mac64_download ?>"><?cs var:ndk.mac64_download ?></a> </td> <td><?cs var:ndk.mac64_bytes ?></td> <td><?cs var:ndk.mac64_checksum ?></td> </tr> <!-- <tr> <td> <a onClick="return onDownload(this)" href="http://dl.google.com/android/repository/<?cs var:ndk.mac64.legacy_download ?>"><?cs var:ndk.mac64.legacy_download ?></a> </td> <td><?cs var:ndk.mac64.legacy_bytes ?></td> <td><?cs var:ndk.mac64.legacy_checksum ?></td> </tr> --> <!-- <tr> <td> <a onClick="return onDownload(this)" href="http://dl.google.com/android/repository/<?cs var:ndk.linux32.legacy_download ?>"><?cs var:ndk.linux32.legacy_download ?></a> </td> <td><?cs var:ndk.linux32.legacy_bytes ?></td> <td><?cs var:ndk.linux32.legacy_checksum ?></td> </tr> --> <tr> <td>Linux 64-bit (x86)</td> <td> <a onClick="return onDownload(this)" href="http://dl.google.com/android/repository/<?cs var:ndk.linux64_download ?>"><?cs var:ndk.linux64_download ?></a> </td> <td><?cs var:ndk.linux64_bytes ?></td> <td><?cs var:ndk.linux64_checksum ?></td> </tr> <!-- <tr> <td> <a onClick="return onDownload(this)" href="http://dl.google.com/android/repository/<?cs var:ndk.linux64.legacy_download ?>"><?cs var:ndk.linux64.legacy_download ?></a> </td> <td><?cs var:ndk.linux64.legacy_bytes ?></td> <td><?cs var:ndk.linux64.legacy_checksum ?></td> </tr> --> </table> <?cs ######## HERE IS THE JD DOC CONTENT ######### ?> <?cs call:tag_list(root.descr) ?> <script> function onDownload(link) { $("#downloadForRealz").html("Download " + $(link).text()); $("#downloadForRealz").attr('href',$(link).attr('href')); $("#tos").fadeIn('slow'); location.hash = "download"; return false; } function onAgreeChecked() { if ($("input#agree").is(":checked")) { $("a#downloadForRealz").removeClass('disabled'); } else { $("a#downloadForRealz").addClass('disabled'); } } function onDownloadNdkForRealz(link) { if ($("input#agree").is(':checked')) { $("#tos").fadeOut('slow'); $('html, body').animate({ scrollTop: $("#Installing").offset().top }, 800, function() { $("#Installing").click(); }); return true; } else { $("label#agreeLabel").parent().stop().animate({color: "#258AAF"}, 200, function() {$("label#agreeLabel").parent().stop().animate({color: "#222"}, 200)} ); return false; } } $(window).hashchange( function(){ if (location.hash == "") { location.reload(); } }); </script> <?cs else ?> <?cs # end if NDK ... # # # # # # # the following is for the SDK # # (nested in if/else redirect and if/else NDK) # # # # ?> <?cs if:android.whichdoc == "online" ?> <?cs ######## HERE IS THE JD DOC CONTENT FOR ONLINE ######### ?> <?cs call:tag_list(root.descr) ?> <div class="pax col-13 online" style="margin:0;"> <h3>SDK Tools Only</h3> <p>If you prefer to use a different IDE or run the tools from the command line or with build scripts, you can instead download the stand-alone Android SDK Tools. These packages provide the basic SDK tools for app development, without an IDE. Also see the <a href="<?cs var:toroot ?>tools/sdk/tools-notes.html">SDK tools release notes</a>.</p> <table class="download"> <tr> <th>Platform</th> <th>Package</th> <th>Size</th> <th>SHA-1 Checksum</th> </tr> <tr> <td rowspan="2">Windows</td> <td> <a onclick="return onDownload(this)" id="win-tools" href="http://dl.google.com/android/<?cs var:sdk.win_installer ?>"><?cs var:sdk.win_installer ?></a> (Recommended) </td> <td><?cs var:sdk.win_installer_bytes ?> bytes</td> <td><?cs var:sdk.win_installer_checksum ?></td> </tr> <tr> <!-- blank TD from Windows rowspan --> <td> <a onclick="return onDownload(this)" href="http://dl.google.com/android/<?cs var:sdk.win_download ?>"><?cs var:sdk.win_download ?></a> </td> <td><?cs var:sdk.win_bytes ?> bytes</td> <td><?cs var:sdk.win_checksum ?></td> </tr> <tr> <td><nobr>Mac OS X</nobr></td> <td> <a onclick="return onDownload(this)" id="mac-tools" href="http://dl.google.com/android/<?cs var:sdk.mac_download ?>"><?cs var:sdk.mac_download ?></a> </td> <td><?cs var:sdk.mac_bytes ?> bytes</td> <td><?cs var:sdk.mac_checksum ?></td> </tr> <tr> <td>Linux</td> <td> <a onclick="return onDownload(this)" id="linux-tools" href="http://dl.google.com/android/<?cs var:sdk.linux_download ?>"><?cs var:sdk.linux_download ?></a> </td> <td><?cs var:sdk.linux_bytes ?> bytes</td> <td><?cs var:sdk.linux_checksum ?></td> </tr> </table> <h3>All Android Studio Packages</h3> <p>Select a specific Android Studio package for your platform. Also see the <a href="<?cs var:toroot ?>tools/revisions/studio.html">Android Studio release notes</a>.</p> <table class="download"> <tr> <th>Platform</th> <th>Package</th> <th>Size</th> <th>SHA-1 Checksum</th> </tr> <tr> <td rowspan="3">Windows</td> <td> <a onclick="return onDownload(this)" id="win-bundle" href="https://dl.google.com/dl/android/studio/install/<?cs var:studio.version ?>/<?cs var:studio.win_bundle_exe_download ?>" ><?cs var:studio.win_bundle_exe_download ?></a><br>(Recommended) </td> <td><?cs var:studio.win_bundle_exe_bytes ?> bytes</td> <td><?cs var:studio.win_bundle_exe_checksum ?></td> </tr> <tr> <!-- blank TD from Windows rowspan --> <td> <a onclick="return onDownload(this)" href="https://dl.google.com/dl/android/studio/install/<?cs var:studio.version ?>/<?cs var:studio.win_notools_exe_download ?>" ><?cs var:studio.win_notools_exe_download ?></a><br>(No SDK tools included) </td> <td><?cs var:studio.win_notools_exe_bytes ?> bytes</td> <td><?cs var:studio.win_notools_exe_checksum ?></td> </tr> <tr> <!-- blank TD from Windows rowspan --> <td> <a onclick="return onDownload(this)" href="https://dl.google.com/dl/android/studio/ide-zips/<?cs var:studio.version ?>/<?cs var:studio.win_bundle_download ?>" ><?cs var:studio.win_bundle_download ?></a> </td> <td><?cs var:studio.win_bundle_bytes ?> bytes</td> <td><?cs var:studio.win_bundle_checksum ?></td> </tr> <tr> <td><nobr>Mac OS X</nobr></td> <td> <a onclick="return onDownload(this)" id="mac-bundle" href="https://dl.google.com/dl/android/studio/install/<?cs var:studio.version ?>/<?cs var:studio.mac_bundle_download ?>" ><?cs var:studio.mac_bundle_download ?></a> </td> <td><?cs var:studio.mac_bundle_bytes ?> bytes</td> <td><?cs var:studio.mac_bundle_checksum ?></td> </tr> <tr> <td>Linux</td> <td> <a onclick="return onDownload(this)" id="linux-bundle" href="https://dl.google.com/dl/android/studio/ide-zips/<?cs var:studio.version ?>/<?cs var:studio.linux_bundle_download ?>" ><?cs var:studio.linux_bundle_download ?></a> </td> <td><?cs var:studio.linux_bundle_bytes ?> bytes</td> <td><?cs var:studio.linux_bundle_checksum ?></td> </tr> </table> </div><!-- end pax --> </div><!-- end col-13 for lower-half content --> <script> if (location.hash == "#Requirements") { $('.reqs').show(); } else if (location.hash == "#ExistingIDE") { $('.ide').show(); } var os; var bundlename; var $toolslink; if (navigator.appVersion.indexOf("Mobile")!=-1) { // Do nothing for any "mobile" user agent } else if (navigator.appVersion.indexOf("Win")!=-1) { os = "Windows"; bundlename = '#win-bundle'; $toolslink = $('#win-tools'); } else if (navigator.appVersion.indexOf("Mac")!=-1) { os = "Mac"; bundlename = '#mac-bundle'; $toolslink = $('#mac-tools'); } else if (navigator.appVersion.indexOf("Linux")!=-1 && navigator.appVersion.indexOf("Android")==-1) { os = "Linux"; bundlename = '#linux-bundle'; $toolslink = $('#linux-tools'); } if (os != undefined) { $('#not-supported').hide(); /* set up primary Android Studio download button */ $('.download-bundle-button').append(" <br/><span class='small'>for " + os + "</span>"); $('.download-bundle-button').click(function() {return onDownload(this,true,true);}).attr('href', bundlename); } function onDownload(link, button, bundle) { /* set text for download button */ if (button) { $("#downloadForRealz").html($(link).text()); } else { $("#downloadForRealz").html("Download " + $(link).text()); } $("#downloadForRealz").attr('bundle', bundle); $("a#downloadForRealz").attr("name", $(link).attr('href')); $("#tos").show(); $("#landing").hide(); location.hash = "top"; return false; } function onAgreeChecked() { /* verify that the TOS is agreed */ if ($("input#agree").is(":checked")) { /* if downloading the bundle */ if ($("#downloadForRealz").attr('bundle')) { /* construct the name of the link we want */ linkId = $("a#downloadForRealz").attr("name"); /* set the real url for download */ $("a#downloadForRealz").attr("href", $(linkId).attr("href")); } else { $("a#downloadForRealz").attr("href", $("a#downloadForRealz").attr("name")); } /* reveal the download button */ $("a#downloadForRealz").removeClass('disabled'); } else { $("a#downloadForRealz").addClass('disabled'); } } function onDownloadForRealz(link) { if ($("input#agree").is(':checked')) { location.hash = ""; location.hash = "top"; $("div.sdk-terms").slideUp(); $("h1#tos-header").text('Now downloading...'); $(".sdk-terms-intro").text('You\'ll be redirected to the install instructions in a moment.'); $("#sdk-terms-form").fadeOut('slow', function() { setTimeout(function() { if ($("#downloadForRealz").attr('bundle') == 'true') { // User downloaded the studio Bundle window.location = "/sdk/installing/index.html?pkg=studio"; } else { // User downloaded the SDK Tools window.location = "/sdk/installing/index.html?pkg=tools"; } }, 3000); }); ga('send', 'event', 'SDK', 'IDE and Tools', $("#downloadForRealz").html()); return true; } else { $("label#agreeLabel").parent().stop().animate({color: "#258AAF"}, 200, function() {$("label#agreeLabel").parent().stop().animate({color: "#222"}, 200)} ); return false; } } $(window).hashchange( function(){ if (location.hash == "") { location.reload(); } }); </script> </div><!-- end the wrapper used for relative/absolute positions --> <?cs # THIS DIV WAS OPENED IN INDEX.JD ?> <?cs else ?> <?cs # end if online ?> <?cs if:sdk.preview ?><?cs # it's preview offline docs ?> <p>Welcome developers! We are pleased to provide you with a preview SDK for the upcoming Android 3.0 release, to give you a head-start on developing applications for it. </p> <p>See the <a href="<?cs var:toroot ?>sdk/preview/start.html">Getting Started</a> document for more information about how to set up the preview SDK and get started.</p> <style type="text/css"> .non-preview { display:none; } </style> <?cs else ?><?cs # it's normal offline docs ?> <?cs ######## HERE IS THE JD DOC CONTENT FOR OFFLINE ######### ?> <?cs call:tag_list(root.descr) ?> <style type="text/css"> body .offline { display:block; } body .online { display:none; } </style> <script> $('.reqs').show(); </script> <?cs /if ?> <?cs /if ?> <?cs # end if/else online ?> <?cs /if ?> <?cs # end if/else NDK ?> <?cs /if ?> <?cs # end if/else redirect ?> </div><!-- end jd-content --> <?cs if:!sdk.redirect ?> <?cs include:"footer.cs" ?> <?cs /if ?> </div><!-- end g-unit --> <?cs include:"trailer.cs" ?> <!-- Start of Tag --> <script type="text/javascript"> var axel = Math.random() + ""; var a = axel * 10000000000000; document.write('<iframe src="https://2507573.fls.doubleclick.net/activityi;src=2507573;type=other026;cat=googl348;ord=' + a + '?" width="1" height="1" frameborder="0" style="display:none"></iframe>'); </script> <noscript> <iframe src="https://2507573.fls.doubleclick.net/activityi;src=2507573;type=other026;cat=googl348;ord=1?" width="1" height="1" frameborder="0" style="display:none"></iframe> </noscript> <!-- End of Tag --> </body> </html>
using System; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.UnitOfWork; using Umbraco.Core.Publishing; namespace Umbraco.Core.Services { /// <summary> /// The Umbraco ServiceContext, which provides access to the following services: /// <see cref="IContentService"/>, <see cref="IContentTypeService"/>, <see cref="IDataTypeService"/>, /// <see cref="IFileService"/>, <see cref="ILocalizationService"/> and <see cref="IMediaService"/>. /// </summary> public class ServiceContext { private Lazy<ITagService> _tagService; private Lazy<IContentService> _contentService; private Lazy<IUserService> _userService; private Lazy<IMemberService> _memberService; private Lazy<IMediaService> _mediaService; private Lazy<IContentTypeService> _contentTypeService; private Lazy<IDataTypeService> _dataTypeService; private Lazy<IFileService> _fileService; private Lazy<ILocalizationService> _localizationService; private Lazy<IPackagingService> _packagingService; private Lazy<ServerRegistrationService> _serverRegistrationService; private Lazy<IEntityService> _entityService; private Lazy<IRelationService> _relationService; private Lazy<IApplicationTreeService> _treeService; private Lazy<ISectionService> _sectionService; private Lazy<IMacroService> _macroService; private Lazy<IMemberTypeService> _memberTypeService; private Lazy<IMemberGroupService> _memberGroupService; private Lazy<INotificationService> _notificationService; /// <summary> /// public ctor - will generally just be used for unit testing /// </summary> /// <param name="contentService"></param> /// <param name="mediaService"></param> /// <param name="contentTypeService"></param> /// <param name="dataTypeService"></param> /// <param name="fileService"></param> /// <param name="localizationService"></param> /// <param name="packagingService"></param> /// <param name="entityService"></param> /// <param name="relationService"></param> /// <param name="memberGroupService"></param> /// <param name="memberTypeService"></param> /// <param name="memberService"></param> /// <param name="userService"></param> public ServiceContext( IContentService contentService, IMediaService mediaService, IContentTypeService contentTypeService, IDataTypeService dataTypeService, IFileService fileService, ILocalizationService localizationService, IPackagingService packagingService, IEntityService entityService, IRelationService relationService, IMemberGroupService memberGroupService, IMemberTypeService memberTypeService, IMemberService memberService, IUserService userService, ISectionService sectionService, IApplicationTreeService treeService, ITagService tagService) { _tagService = new Lazy<ITagService>(() => tagService); _contentService = new Lazy<IContentService>(() => contentService); _mediaService = new Lazy<IMediaService>(() => mediaService); _contentTypeService = new Lazy<IContentTypeService>(() => contentTypeService); _dataTypeService = new Lazy<IDataTypeService>(() => dataTypeService); _fileService = new Lazy<IFileService>(() => fileService); _localizationService = new Lazy<ILocalizationService>(() => localizationService); _packagingService = new Lazy<IPackagingService>(() => packagingService); _entityService = new Lazy<IEntityService>(() => entityService); _relationService = new Lazy<IRelationService>(() => relationService); _sectionService = new Lazy<ISectionService>(() => sectionService); _memberGroupService = new Lazy<IMemberGroupService>(() => memberGroupService); _memberTypeService = new Lazy<IMemberTypeService>(() => memberTypeService); _treeService = new Lazy<IApplicationTreeService>(() => treeService); _memberService = new Lazy<IMemberService>(() => memberService); _userService = new Lazy<IUserService>(() => userService); } /// <summary> /// Constructor used to instantiate the core services /// </summary> /// <param name="dbUnitOfWorkProvider"></param> /// <param name="fileUnitOfWorkProvider"></param> /// <param name="publishingStrategy"></param> /// <param name="cache"></param> internal ServiceContext(IDatabaseUnitOfWorkProvider dbUnitOfWorkProvider, IUnitOfWorkProvider fileUnitOfWorkProvider, BasePublishingStrategy publishingStrategy, CacheHelper cache) { BuildServiceCache(dbUnitOfWorkProvider, fileUnitOfWorkProvider, publishingStrategy, cache, //this needs to be lazy because when we create the service context it's generally before the //resolvers have been initialized! new Lazy<RepositoryFactory>(() => RepositoryResolver.Current.Factory)); } /// <summary> /// Builds the various services /// </summary> private void BuildServiceCache( IDatabaseUnitOfWorkProvider dbUnitOfWorkProvider, IUnitOfWorkProvider fileUnitOfWorkProvider, BasePublishingStrategy publishingStrategy, CacheHelper cache, Lazy<RepositoryFactory> repositoryFactory) { var provider = dbUnitOfWorkProvider; var fileProvider = fileUnitOfWorkProvider; if (_notificationService == null) _notificationService = new Lazy<INotificationService>(() => new NotificationService(provider, _userService.Value, _contentService.Value)); if (_serverRegistrationService == null) _serverRegistrationService = new Lazy<ServerRegistrationService>(() => new ServerRegistrationService(provider, repositoryFactory.Value)); if (_userService == null) _userService = new Lazy<IUserService>(() => new UserService(provider, repositoryFactory.Value)); if (_memberService == null) _memberService = new Lazy<IMemberService>(() => new MemberService(provider, repositoryFactory.Value, _memberGroupService.Value, _dataTypeService.Value)); if (_contentService == null) _contentService = new Lazy<IContentService>(() => new ContentService(provider, repositoryFactory.Value, publishingStrategy, _dataTypeService.Value)); if (_mediaService == null) _mediaService = new Lazy<IMediaService>(() => new MediaService(provider, repositoryFactory.Value, _dataTypeService.Value)); if (_contentTypeService == null) _contentTypeService = new Lazy<IContentTypeService>(() => new ContentTypeService(provider, repositoryFactory.Value, _contentService.Value, _mediaService.Value)); if (_dataTypeService == null) _dataTypeService = new Lazy<IDataTypeService>(() => new DataTypeService(provider, repositoryFactory.Value)); if (_fileService == null) _fileService = new Lazy<IFileService>(() => new FileService(fileProvider, provider, repositoryFactory.Value)); if (_localizationService == null) _localizationService = new Lazy<ILocalizationService>(() => new LocalizationService(provider, repositoryFactory.Value)); if (_packagingService == null) _packagingService = new Lazy<IPackagingService>(() => new PackagingService(_contentService.Value, _contentTypeService.Value, _mediaService.Value, _macroService.Value, _dataTypeService.Value, _fileService.Value, _localizationService.Value, repositoryFactory.Value, provider)); if (_entityService == null) _entityService = new Lazy<IEntityService>(() => new EntityService(provider, repositoryFactory.Value, _contentService.Value, _contentTypeService.Value, _mediaService.Value, _dataTypeService.Value)); if (_relationService == null) _relationService = new Lazy<IRelationService>(() => new RelationService(provider, repositoryFactory.Value, _entityService.Value)); if (_treeService == null) _treeService = new Lazy<IApplicationTreeService>(() => new ApplicationTreeService(cache)); if (_sectionService == null) _sectionService = new Lazy<ISectionService>(() => new SectionService(_userService.Value, _treeService.Value, cache)); if (_macroService == null) _macroService = new Lazy<IMacroService>(() => new MacroService(provider, repositoryFactory.Value)); if (_memberTypeService == null) _memberTypeService = new Lazy<IMemberTypeService>(() => new MemberTypeService(provider, repositoryFactory.Value, _memberService.Value)); if (_tagService == null) _tagService = new Lazy<ITagService>(() => new TagService(provider, repositoryFactory.Value)); if (_memberGroupService == null) _memberGroupService = new Lazy<IMemberGroupService>(() => new MemberGroupService(provider, repositoryFactory.Value)); } /// <summary> /// Gets the <see cref="INotificationService"/> /// </summary> internal INotificationService NotificationService { get { return _notificationService.Value; } } /// <summary> /// Gets the <see cref="ServerRegistrationService"/> /// </summary> internal ServerRegistrationService ServerRegistrationService { get { return _serverRegistrationService.Value; } } /// <summary> /// Gets the <see cref="ITagService"/> /// </summary> public ITagService TagService { get { return _tagService.Value; } } /// <summary> /// Gets the <see cref="IMacroService"/> /// </summary> public IMacroService MacroService { get { return _macroService.Value; } } /// <summary> /// Gets the <see cref="IEntityService"/> /// </summary> public IEntityService EntityService { get { return _entityService.Value; } } /// <summary> /// Gets the <see cref="IRelationService"/> /// </summary> public IRelationService RelationService { get { return _relationService.Value; } } /// <summary> /// Gets the <see cref="IContentService"/> /// </summary> public IContentService ContentService { get { return _contentService.Value; } } /// <summary> /// Gets the <see cref="IContentTypeService"/> /// </summary> public IContentTypeService ContentTypeService { get { return _contentTypeService.Value; } } /// <summary> /// Gets the <see cref="IDataTypeService"/> /// </summary> public IDataTypeService DataTypeService { get { return _dataTypeService.Value; } } /// <summary> /// Gets the <see cref="IFileService"/> /// </summary> public IFileService FileService { get { return _fileService.Value; } } /// <summary> /// Gets the <see cref="ILocalizationService"/> /// </summary> public ILocalizationService LocalizationService { get { return _localizationService.Value; } } /// <summary> /// Gets the <see cref="IMediaService"/> /// </summary> public IMediaService MediaService { get { return _mediaService.Value; } } /// <summary> /// Gets the <see cref="PackagingService"/> /// </summary> public IPackagingService PackagingService { get { return _packagingService.Value; } } /// <summary> /// Gets the <see cref="UserService"/> /// </summary> public IUserService UserService { get { return _userService.Value; } } /// <summary> /// Gets the <see cref="MemberService"/> /// </summary> public IMemberService MemberService { get { return _memberService.Value; } } /// <summary> /// Gets the <see cref="SectionService"/> /// </summary> public ISectionService SectionService { get { return _sectionService.Value; } } /// <summary> /// Gets the <see cref="ApplicationTreeService"/> /// </summary> public IApplicationTreeService ApplicationTreeService { get { return _treeService.Value; } } /// <summary> /// Gets the MemberTypeService /// </summary> public IMemberTypeService MemberTypeService { get { return _memberTypeService.Value; } } /// <summary> /// Gets the MemberGroupService /// </summary> public IMemberGroupService MemberGroupService { get { return _memberGroupService.Value; } } } }
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 HTTPOptions.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
/******************************************************************************* * Copyright 2008-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET * API Version: 2009-04-15 */ using System; using System.Net; using Amazon.Util; namespace Amazon.SimpleDB { /// <summary> /// Configuration for accessing Amazon Simple DB service /// </summary> public class AmazonSimpleDBConfig { private string serviceVersion = "2009-04-15"; private RegionEndpoint regionEndpoint; private string serviceURL = "https://sdb.amazonaws.com"; private string userAgent = Amazon.Util.AWSSDKUtils.SDKUserAgent; private string signatureVersion = "2"; private string signatureMethod = "HmacSHA256"; private string proxyHost = null; private int proxyPort = -1; private int maxErrorRetry = 3; private bool fUseSecureString = true; private string proxyUsername; private string proxyPassword; private int? connectionLimit; private ICredentials proxyCredentials; /// <summary> /// Gets Service Version /// </summary> public string ServiceVersion { get { return this.serviceVersion; } } /// <summary> /// Gets and sets of the signatureMethod property. /// </summary> public string SignatureMethod { get { return this.signatureMethod; } set { this.signatureMethod = value; } } /// <summary> /// Sets the SignatureMethod property /// </summary> /// <param name="signatureMethod">SignatureMethod property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AmazonSimpleDBConfig WithSignatureMethod(string signatureMethod) { this.signatureMethod = signatureMethod; return this; } /// <summary> /// Checks if SignatureMethod property is set /// </summary> /// <returns>true if SignatureMethod property is set</returns> public bool IsSetSignatureMethod() { return this.signatureMethod != null; } /// <summary> /// Gets and sets of the SignatureVersion property. /// </summary> public string SignatureVersion { get { return this.signatureVersion; } set { this.signatureVersion = value; } } /// <summary> /// Sets the SignatureVersion property /// </summary> /// <param name="signatureVersion">SignatureVersion property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AmazonSimpleDBConfig WithSignatureVersion(string signatureVersion) { this.signatureVersion = signatureVersion; return this; } /// <summary> /// Checks if SignatureVersion property is set /// </summary> /// <returns>true if SignatureVersion property is set</returns> public bool IsSetSignatureVersion() { return this.signatureVersion != null; } /// <summary> /// Gets and sets of the UserAgent property. /// </summary> public string UserAgent { get { return this.userAgent; } set { this.userAgent = value; } } /// <summary> /// Sets the UserAgent property /// </summary> /// <param name="userAgent">UserAgent property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AmazonSimpleDBConfig WithUserAgent(string userAgent) { this.userAgent = userAgent; return this; } /// <summary> /// Checks if UserAgent property is set /// </summary> /// <returns>true if UserAgent property is set</returns> public bool IsSetUserAgent() { return this.userAgent != null; } /// <summary> /// Gets and sets the RegionEndpoint property. The region constant to use that /// determines the endpoint to use. If this is not set /// then the client will fallback to the value of ServiceURL. /// </summary> public RegionEndpoint RegionEndpoint { get { return regionEndpoint; } set { this.regionEndpoint = value; } } /// <summary> /// The constant used to lookup in the region hash the endpoint. /// </summary> internal string RegionEndpointServiceName { get { return "sdb"; } } /// <summary> /// Gets and sets of the ServiceURL property. /// This is an optional property; change it /// only if you want to try a different service /// endpoint or want to switch between https and http. /// </summary> public string ServiceURL { get { return this.serviceURL; } set { this.serviceURL = value; } } /// <summary> /// Sets the ServiceURL property /// </summary> /// <param name="serviceURL">ServiceURL property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AmazonSimpleDBConfig WithServiceURL(string serviceURL) { this.serviceURL = serviceURL; return this; } /// <summary> /// Checks if ServiceURL property is set /// </summary> /// <returns>true if ServiceURL property is set</returns> public bool IsSetServiceURL() { return this.serviceURL != null; } /// <summary> /// Gets and sets of the ProxyHost property. /// </summary> public string ProxyHost { get { return this.proxyHost; } set { this.proxyHost = value; } } /// <summary> /// Sets the ProxyHost property /// </summary> /// <param name="proxyHost">ProxyHost property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AmazonSimpleDBConfig WithProxyHost(string proxyHost) { this.proxyHost = proxyHost; return this; } /// <summary> /// Checks if ProxyHost property is set /// </summary> /// <returns>true if ProxyHost property is set</returns> public bool IsSetProxyHost() { return this.proxyHost != null; } /// <summary> /// Gets and sets of the ProxyPort property. /// </summary> public int ProxyPort { get { return this.proxyPort; } set { this.proxyPort = value; } } /// <summary> /// Sets the ProxyPort property /// </summary> /// <param name="proxyPort">ProxyPort property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AmazonSimpleDBConfig WithProxyPort(int proxyPort) { this.proxyPort = proxyPort; return this; } /// <summary> /// Checks if ProxyPort property is set /// </summary> /// <returns>true if ProxyPort property is set</returns> public bool IsSetProxyPort() { return this.proxyPort >= 0; } /// <summary> /// Gets and sets of the MaxErrorRetry property. /// </summary> public int MaxErrorRetry { get { return this.maxErrorRetry; } set { this.maxErrorRetry = value; } } /// <summary> /// Sets the MaxErrorRetry property /// </summary> /// <param name="maxErrorRetry">MaxErrorRetry property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AmazonSimpleDBConfig WithMaxErrorRetry(int maxErrorRetry) { this.maxErrorRetry = maxErrorRetry; return this; } /// <summary> /// Checks if MaxErrorRetry property is set /// </summary> /// <returns>true if MaxErrorRetry property is set</returns> public bool IsSetMaxErrorRetry() { return this.maxErrorRetry >= 0; } /// <summary> /// Gets and Sets the UseSecureStringForAwsSecretKey property. /// By default, the AWS Secret Access Key is stored /// in a SecureString (true) - this is one of the secure /// ways to store a secret provided by the .NET Framework. /// But, the use of SecureStrings is not supported in Medium /// Trust Windows Hosting environments. If you are building an /// ASP.NET application that needs to run with Medium Trust, /// set this property to false, and the client will /// not save your AWS Secret Key in a secure string. Changing /// the default to false can result in the Secret Key being /// vulnerable; please use this property judiciously. /// </summary> /// <remarks>Storing the AWS Secret Access Key is not /// recommended unless absolutely necessary. /// </remarks> /// <seealso cref="T:System.Security.SecureString"/> public bool UseSecureStringForAwsSecretKey { get { return this.fUseSecureString; } set { this.fUseSecureString = value; } } /// <summary> /// Sets the UseSecureString property. /// By default, the AWS Secret Access Key is stored /// in a SecureString (true) - this is one of the secure /// ways to store a secret provided by the .NET Framework. /// But, the use of SecureStrings is not supported in Medium /// Trust Windows Hosting environments. If you are building an /// ASP.NET application that needs to run with Medium Trust, /// set this property to false, and the client will /// not save your AWS Secret Key in a secure string. Changing /// the default to false can result in the Secret Key being /// vulnerable; please use this property judiciously. /// </summary> /// <param name="fSecure"> /// Whether a secure string should be used or not. /// </param> /// <returns>The Config object with the property set</returns> /// <remarks>Storing the AWS Secret Access Key is not /// recommended unless absolutely necessary. /// </remarks> /// <seealso cref="T:System.Security.SecureString"/> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AmazonSimpleDBConfig WithUseSecureStringForAwsSecretKey(bool fSecure) { fUseSecureString = fSecure; return this; } /// <summary> /// Gets and sets the ProxyUsername property. /// Used in conjunction with the ProxyPassword /// property to authenticate requests with the /// specified Proxy server. /// </summary> [Obsolete("Use ProxyCredentials instead")] public string ProxyUsername { get { return this.proxyUsername; } set { this.proxyUsername = value; } } /// <summary> /// Sets the ProxyUsername property /// </summary> /// <param name="userName">Value for the ProxyUsername property</param> /// <returns>this instance</returns> [Obsolete("Use WithProxyCredentials instead")] public AmazonSimpleDBConfig WithProxyUsername(string userName) { this.proxyUsername = userName; return this; } /// <summary> /// Checks if ProxyUsername property is set /// </summary> /// <returns>true if ProxyUsername property is set</returns> internal bool IsSetProxyUsername() { return !System.String.IsNullOrEmpty(this.proxyUsername); } /// <summary> /// Gets and sets the ProxyPassword property. /// Used in conjunction with the ProxyUsername /// property to authenticate requests with the /// specified Proxy server. /// </summary> /// <remarks> /// If this property isn't set, String.Empty is used as /// the proxy password. This property isn't /// used if ProxyUsername is null or empty. /// </remarks> [Obsolete("Use ProxyCredentials instead")] public string ProxyPassword { get { return this.proxyPassword; } set { this.proxyPassword = value; } } /// <summary> /// Sets the ProxyPassword property. /// Used in conjunction with the ProxyUsername /// property to authenticate requests with the /// specified Proxy server. /// </summary> /// <remarks> /// If this property isn't set, String.Empty is used as /// the proxy password. This property isn't /// used if ProxyUsername is null or empty. /// </remarks> /// <param name="password">ProxyPassword property</param> /// <returns>this instance</returns> [Obsolete("Use WithProxyCredentials instead")] public AmazonSimpleDBConfig WithProxyPassword(string password) { this.proxyPassword = password; return this; } /// <summary> /// Checks if ProxyPassword property is set /// </summary> /// <returns>true if ProxyPassword property is set</returns> internal bool IsSetProxyPassword() { return !System.String.IsNullOrEmpty(this.proxyPassword); } /// <summary> /// Credentials to use with a proxy. /// </summary> public ICredentials ProxyCredentials { get { ICredentials credentials = this.proxyCredentials; if (credentials == null && this.IsSetProxyUsername()) { credentials = new NetworkCredential(this.proxyUsername, this.proxyPassword ?? String.Empty); } return credentials; } set { this.proxyCredentials = value; } } /// <summary> /// Sets the ProxyCredentials property. /// </summary> /// <param name="proxyCredentials">ProxyCredentials property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AmazonSimpleDBConfig WithProxyCredentials(ICredentials proxyCredentials) { this.proxyCredentials = proxyCredentials; return this; } /// <summary> /// Checks if ProxyCredentials property is set /// </summary> /// <returns>true if ProxyCredentials property is set</returns> internal bool IsSetProxyCredentials() { return (this.ProxyCredentials != null); } /// <summary> /// Gets and sets the connection limit set on the ServicePoint for the WebRequest. /// Default value is 50 connections unless ServicePointManager.DefaultConnectionLimit is set in /// which case ServicePointManager.DefaultConnectionLimit will be used as the default. /// </summary> public int ConnectionLimit { get { return AWSSDKUtils.GetConnectionLimit(this.connectionLimit); } set { this.connectionLimit = value; } } } }
using System; using System.Linq; using System.Collections.Generic; namespace Orleans.Runtime.ConsistentRing { /// <summary> /// We use the 'backward/clockwise' definition to assign responsibilities on the ring. /// E.g. in a ring of nodes {5, 10, 15} the responsible for key 7 is 10 (the node is responsible for its predecessing range). /// The backwards/clockwise approach is consistent with many overlays, e.g., Chord, Cassandra, etc. /// Note: MembershipOracle uses 'forward/counter-clockwise' definition to assign responsibilities. /// E.g. in a ring of nodes {5, 10, 15}, the responsible of key 7 is node 5 (the node is responsible for its sucessing range).. /// </summary> internal class VirtualBucketsRingProvider : MarshalByRefObject, IConsistentRingProvider, ISiloStatusListener { private readonly List<IRingRangeListener> statusListeners; private readonly SortedDictionary<uint, SiloAddress> bucketsMap; private List<Tuple<uint, SiloAddress>> sortedBucketsList; // flattened sorted bucket list for fast lock-free calculation of CalculateTargetSilo private readonly Logger logger; private readonly SiloAddress myAddress; private readonly int numBucketsPerSilo; private readonly object lockable; private bool running; private IRingRange myRange; internal VirtualBucketsRingProvider(SiloAddress siloAddr, int nBucketsPerSilo) { if (nBucketsPerSilo <= 0 ) throw new IndexOutOfRangeException("numBucketsPerSilo is out of the range. numBucketsPerSilo = " + nBucketsPerSilo); logger = LogManager.GetLogger(typeof(VirtualBucketsRingProvider).Name); statusListeners = new List<IRingRangeListener>(); bucketsMap = new SortedDictionary<uint, SiloAddress>(); sortedBucketsList = new List<Tuple<uint, SiloAddress>>(); myAddress = siloAddr; numBucketsPerSilo = nBucketsPerSilo; lockable = new object(); running = true; myRange = RangeFactory.CreateFullRange(); logger.Info("Starting {0} on silo {1}.", typeof(VirtualBucketsRingProvider).Name, siloAddr.ToStringWithHashCode()); StringValueStatistic.FindOrCreate(StatisticNames.CONSISTENTRING_RING, ToString); IntValueStatistic.FindOrCreate(StatisticNames.CONSISTENTRING_RINGSIZE, () => GetRingSize()); StringValueStatistic.FindOrCreate(StatisticNames.CONSISTENTRING_MYRANGE_RINGDISTANCE, () => String.Format("x{0,8:X8}", ((IRingRangeInternal)myRange).RangeSize())); FloatValueStatistic.FindOrCreate(StatisticNames.CONSISTENTRING_MYRANGE_RINGPERCENTAGE, () => (float)((IRingRangeInternal)myRange).RangePercentage()); FloatValueStatistic.FindOrCreate(StatisticNames.CONSISTENTRING_AVERAGERINGPERCENTAGE, () => { int size = GetRingSize(); return size == 0 ? 0 : ((float)100.0/(float) size); }); // add myself to the list of members AddServer(myAddress); } private void Stop() { running = false; } public IRingRange GetMyRange() { return myRange; } private int GetRingSize() { lock (lockable) { return bucketsMap.Values.Distinct().Count(); } } public bool SubscribeToRangeChangeEvents(IRingRangeListener observer) { lock (statusListeners) { if (statusListeners.Contains(observer)) return false; statusListeners.Add(observer); return true; } } public bool UnSubscribeFromRangeChangeEvents(IRingRangeListener observer) { lock (statusListeners) { return statusListeners.Contains(observer) && statusListeners.Remove(observer); } } private void NotifyLocalRangeSubscribers(IRingRange old, IRingRange now, bool increased) { logger.Info(ErrorCode.CRP_Notify, "-NotifyLocalRangeSubscribers about old {0} new {1} increased? {2}", old.ToString(), now.ToString(), increased); List<IRingRangeListener> copy; lock (statusListeners) { copy = statusListeners.ToList(); } foreach (IRingRangeListener listener in copy) { try { listener.RangeChangeNotification(old, now, increased); } catch (Exception exc) { logger.Error(ErrorCode.CRP_Local_Subscriber_Exception, String.Format("Local IRangeChangeListener {0} has thrown an exception when was notified about RangeChangeNotification about old {1} new {2} increased? {3}", listener.GetType().FullName, old, now, increased), exc); } } } private void AddServer(SiloAddress silo) { lock (lockable) { List<uint> hashes = silo.GetUniformHashCodes(numBucketsPerSilo); foreach (var hash in hashes) { if (bucketsMap.ContainsKey(hash)) { var other = bucketsMap[hash]; // If two silos conflict, take the lesser of the two (usually the older one; that is, the lower epoch) if (silo.CompareTo(other) > 0) continue; } bucketsMap[hash] = silo; } var myOldRange = myRange; var bucketsList = bucketsMap.Select(pair => new Tuple<uint, SiloAddress>(pair.Key, pair.Value)).ToList(); var myNewRange = CalculateRange(bucketsList, myAddress); // capture my range and sortedBucketsList for later lock-free access. myRange = myNewRange; sortedBucketsList = bucketsList; logger.Info(ErrorCode.CRP_Added_Silo, "Added Server {0}. Current view: {1}", silo.ToStringWithHashCode(), this.ToString()); NotifyLocalRangeSubscribers(myOldRange, myNewRange, true); } } internal void RemoveServer(SiloAddress silo) { lock (lockable) { if (!bucketsMap.ContainsValue(silo)) return; // we have already removed this silo List<uint> hashes = silo.GetUniformHashCodes(numBucketsPerSilo); foreach (var hash in hashes) { bucketsMap.Remove(hash); } var myOldRange = this.myRange; var bucketsList = bucketsMap.Select(pair => new Tuple<uint, SiloAddress>(pair.Key, pair.Value)).ToList(); var myNewRange = CalculateRange(bucketsList, myAddress); // capture my range and sortedBucketsList for later lock-free access. myRange = myNewRange; sortedBucketsList = bucketsList; logger.Info(ErrorCode.CRP_Removed_Silo, "Removed Server {0}. Current view: {1}", silo.ToStringWithHashCode(), this.ToString()); NotifyLocalRangeSubscribers(myOldRange, myNewRange, true); } } private static IRingRange CalculateRange(List<Tuple<uint, SiloAddress>> list, SiloAddress silo) { var ranges = new List<IRingRange>(); for (int i = 0; i < list.Count; i++) { var curr = list[i]; var next = list[(i + 1) % list.Count]; // 'backward/clockwise' definition to assign responsibilities on the ring. if (next.Item2.Equals(silo)) { IRingRange range = RangeFactory.CreateRange(curr.Item1, next.Item1); ranges.Add(range); } } return RangeFactory.CreateRange(ranges); } // just for debugging public override string ToString() { Dictionary<SiloAddress, IRingRangeInternal> ranges = GetRanges(); List<KeyValuePair<SiloAddress, IRingRangeInternal>> sortedList = ranges.AsEnumerable().ToList(); sortedList.Sort((t1, t2) => t1.Value.RangePercentage().CompareTo(t2.Value.RangePercentage())); return Utils.EnumerableToString(sortedList, kv => String.Format("{0} -> {1}", kv.Key, kv.Value.ToString())); } // Internal: for testing only! internal Dictionary<SiloAddress, IRingRangeInternal> GetRanges() { List<SiloAddress> silos; List<Tuple<uint, SiloAddress>> snapshotBucketsList; lock (lockable) { silos = bucketsMap.Values.Distinct().ToList(); snapshotBucketsList = sortedBucketsList; } var ranges = new Dictionary<SiloAddress, IRingRangeInternal>(); foreach (var silo in silos) { var range = (IRingRangeInternal)CalculateRange(snapshotBucketsList, silo); ranges.Add(silo, range); } return ranges; } public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status) { // This silo's status has changed if (updatedSilo.Equals(myAddress)) { if (status.IsTerminating()) { Stop(); } } else // Status change for some other silo { if (status.IsTerminating()) { RemoveServer(updatedSilo); } else if (status.Equals(SiloStatus.Active)) // do not do anything with SiloStatus.Created or SiloStatus.Joining -- wait until it actually becomes active { AddServer(updatedSilo); } } } public SiloAddress GetPrimaryTargetSilo(uint key) { return CalculateTargetSilo(key); } /// <summary> /// Finds the silo that owns the given hash value. /// This routine will always return a non-null silo address unless the excludeThisSiloIfStopping parameter is true, /// this is the only silo known, and this silo is stopping. /// </summary> /// <param name="hash"></param> /// <param name="excludeThisSiloIfStopping"></param> /// <returns></returns> private SiloAddress CalculateTargetSilo(uint hash, bool excludeThisSiloIfStopping = true) { // put a private reference to point to sortedBucketsList, // so if someone is changing the sortedBucketsList reference, we won't get it changed in the middle of our operation. // The tricks of writing lock-free code! var snapshotBucketsList = sortedBucketsList; // excludeMySelf from being a TargetSilo if we're not running and the excludeThisSIloIfStopping flag is true. see the comment in the Stop method. bool excludeMySelf = excludeThisSiloIfStopping && !running; if (snapshotBucketsList.Count == 0) { // If the membership ring is empty, then we're the owner by default unless we're stopping. return excludeMySelf ? null : myAddress; } // use clockwise ... current code in membershipOracle.CalculateTargetSilo() does counter-clockwise ... // if you want to stick to counter-clockwise, change the responsibility definition in 'In()' method & responsibility defs in OrleansReminderMemory // need to implement a binary search, but for now simply traverse the list of silos sorted by their hashes Tuple<uint, SiloAddress> s = snapshotBucketsList.Find(tuple => (tuple.Item1 >= hash) && // <= hash for counter-clockwise responsibilities (!tuple.Item2.Equals(myAddress) || !excludeMySelf)); if (s == null) { // if not found in traversal, then first silo should be returned (we are on a ring) // if you go back to their counter-clockwise policy, then change the 'In()' method in OrleansReminderMemory s = snapshotBucketsList[0]; // vs [membershipRingList.Count - 1]; for counter-clockwise policy // Make sure it's not us... if (s.Item2.Equals(myAddress) && excludeMySelf) { // vs [membershipRingList.Count - 2]; for counter-clockwise policy s = snapshotBucketsList.Count > 1 ? snapshotBucketsList[1] : null; } } if (logger.IsVerbose2) logger.Verbose2("Calculated ring partition owner silo {0} for key {1}: {2} --> {3}", s.Item2, hash, hash, s.Item1); return s.Item2; } } }
using System; using System.Collections.Generic; using System.Reflection; using System.Text; using System.IO; using System.Xml; using System.Xml.Schema; using System.Xml.XPath; namespace OpenHome.Net.Xml.UpnpServiceXml { public class UpnpServiceXmlException : Exception { public UpnpServiceXmlException(string aMessage) : base(aMessage) { } } public class Argument { public string name; public string related; public Variable variable; internal Argument(XPathNavigator navigator, string nspace) { XmlNamespaceManager nsmanager = new XmlNamespaceManager(navigator.NameTable); nsmanager.AddNamespace("u", nspace); name = navigator.SelectSingleNode("u:name", nsmanager).Value; name = name.Trim(); related = navigator.SelectSingleNode("u:relatedStateVariable", nsmanager).Value; related = related.Trim(); } internal void Resolve(Variable variable) { this.variable = variable; } } public class Method { public string name; public List<Argument> inargs = new List<Argument>(); public List<Argument> outargs = new List<Argument>(); internal Method(XPathNavigator navigator, string nspace) { XmlNamespaceManager nsmanager = new XmlNamespaceManager(navigator.NameTable); nsmanager.AddNamespace("u", nspace); name = navigator.SelectSingleNode("u:name", nsmanager).Value; name = name.Trim(); foreach (XPathNavigator a in navigator.Select("u:argumentList/u:argument", nsmanager)) { if (a.SelectSingleNode("u:direction", nsmanager).Value == "out") { outargs.Add(new Argument(a, nspace)); } else { inargs.Add(new Argument(a, nspace)); } } } } public class Variable { public string name; public string type; public string prettyname; public bool evented = false; public bool isnumeric = false; public bool issigned = false; public bool isunsigned = false; public uint numericbytes = 0; public List<string> values = new List<string>(); public long min; public long max; public long step; public bool minspecified = false; public bool maxspecified = false; public bool stepspecified = false; internal Variable(XPathNavigator navigator, string nspace, string eventedTag) { XmlNamespaceManager nsmanager = new XmlNamespaceManager(navigator.NameTable); nsmanager.AddNamespace("u", nspace); name = navigator.SelectSingleNode("u:name", nsmanager).Value; type = navigator.SelectSingleNode("u:dataType", nsmanager).Value; name = name.Trim(); type = type.Trim(); prettyname = name; if (prettyname.StartsWith("A_ARG_TYPE_")) { prettyname = prettyname.Substring(11); } XPathNavigator e = navigator.SelectSingleNode(eventedTag, nsmanager); if (e != null) { if (e.Value == "yes") { evented = true; } } if (type == "string") { foreach (XPathNavigator v in navigator.Select("u:allowedValueList/u:allowedValue", nsmanager)) { values.Add(v.Value); } } if (type.StartsWith("i")) { isnumeric = true; issigned = true; if (type == "i1") { numericbytes = 1; } else if (type == "i2") { numericbytes = 2; } else if (type == "i4") { numericbytes = 4; } else { throw (new UpnpServiceXmlException("Invalid numeric type in state variable " + name)); } XPathNavigator v; v = navigator.SelectSingleNode("u:allowedValueRange/u:minimum", nsmanager); if (v != null) { min = Convert.ToInt64(v.Value); minspecified = true; } v = navigator.SelectSingleNode("u:allowedValueRange/u:maximum", nsmanager); if (v != null) { max = Convert.ToInt64(v.Value); maxspecified = true; } v = navigator.SelectSingleNode("u:allowedValueRange/u:step", nsmanager); if (v != null) { step = Convert.ToInt64(v.Value); stepspecified = true; if (step < 1) { throw (new UpnpServiceXmlException("Invalid step value specified in state variable " + name)); } } if (minspecified && maxspecified) { if (max < min) { throw (new UpnpServiceXmlException("Maximum value less than minimum value in state variable " + name)); } } } else if (type.StartsWith("ui")) { isnumeric = true; isunsigned = true; if (type == "ui1") { numericbytes = 1; } else if (type == "ui2") { numericbytes = 2; } else if (type == "ui4") { numericbytes = 4; } else { throw (new UpnpServiceXmlException("Invalid numeric type in state variable " + name)); } XPathNavigator v; v = navigator.SelectSingleNode("u:allowedValueRange/u:minimum", nsmanager); if (v != null) { min = Convert.ToInt64(v.Value); minspecified = true; if (min < 0) { throw (new UpnpServiceXmlException("Negative minimum value specified in unsigned state variable " + name)); } } v = navigator.SelectSingleNode("u:allowedValueRange/u:maximum", nsmanager); if (v != null) { max = Convert.ToInt64(v.Value); maxspecified = true; if (max < 0) { throw (new UpnpServiceXmlException("Negative maximum value specified in unsigned state variable " + name)); } } v = navigator.SelectSingleNode("u:allowedValueRange/u:step", nsmanager); if (v != null) { step = Convert.ToInt64(v.Value); stepspecified = true; if (step < 1) { throw (new UpnpServiceXmlException("Invalid step value specified in state variable " + name)); } } if (minspecified && maxspecified) { if (max < min) { throw (new UpnpServiceXmlException("Maximum value less than minimum value in state variable " + name)); } } } } } public class Document { public bool specversionspecified = false; public uint specversionmajor; public uint specversionminor; public List<Method> methods = new List<Method>(); public List<Variable> variables = new List<Variable>(); public List<Variable> evented = new List<Variable>(); private static void XmlValidationEventHandler(object sender, ValidationEventArgs e) { throw (e.Exception); } private XPathDocument CreateDocument(string uri, string aSchema) { ValidationEventHandler validator = new ValidationEventHandler(XmlValidationEventHandler); // Read the schema from the same directory as this library Assembly assembly = Assembly.GetExecutingAssembly(); string path = System.IO.Path.GetDirectoryName(assembly.Location) + "/" + aSchema; XmlSchema schema = XmlSchema.Read(new StreamReader(path), validator); XmlReaderSettings settings = new XmlReaderSettings(); settings.CloseInput = true; settings.IgnoreComments = true; settings.IgnoreWhitespace = true; settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings; settings.ValidationType = ValidationType.Schema; settings.ValidationEventHandler += validator; settings.Schemas.Add(schema); XmlReader reader = XmlReader.Create(uri, settings); return new XPathDocument(reader); } public Document(string uri) { string nspace = "urn:schemas-upnp-org:service-1-0"; string eventedTag = "@sendEvents"; //Console.WriteLine("\nProcessing " + uri + "\n"); XPathDocument document; try { document = CreateDocument(uri, "UpnpServiceDescription.xsd"); } catch { document = CreateDocument(uri, "UpnpServiceTemplate.xsd"); nspace = ""; eventedTag = "u:sendEventsAttribute"; } XPathNavigator navigator = document.CreateNavigator(); XmlNamespaceManager nsmanager = new XmlNamespaceManager(navigator.NameTable); nsmanager.AddNamespace("u", nspace); // Process the xml file XPathNavigator major = navigator.SelectSingleNode("/u:scpd/u:specVersion/u:major", nsmanager); if (major != null) { specversionspecified = true; specversionmajor = Convert.ToUInt32(major.Value); specversionminor = Convert.ToUInt32(navigator.SelectSingleNode("/u:scpd/u:specVersion/u:minor", nsmanager).Value); } foreach (XPathNavigator a in navigator.Select("/u:scpd/u:actionList/u:action", nsmanager)) { methods.Add(new Method(a, nspace)); } foreach (XPathNavigator s in navigator.Select("/u:scpd/u:serviceStateTable/u:stateVariable", nsmanager)) { variables.Add(new Variable(s, nspace, eventedTag)); } foreach (Variable s in variables) { if (s.evented) { evented.Add(s); } } foreach (Method action in methods) { foreach (Argument argument in action.inargs) { foreach (Variable v in variables) { if (argument.related == v.name) { argument.Resolve(v); break; } } if (argument.variable == null) { throw (new UpnpServiceXmlException("Variable " + argument.related + " referenced by " + argument.name + " in " + action.name + " not found.")); } } foreach (Argument argument in action.outargs) { foreach (Variable v in variables) { if (argument.related == v.name) { argument.Resolve(v); break; } } if (argument.variable == null) { throw (new UpnpServiceXmlException("Variable " + argument.related + " referenced by " + argument.name + " in " + action.name + " not found.")); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq; using System.Runtime.InteropServices; using Xunit; namespace System.IO.Tests { public class File_Copy_str_str : FileSystemTest { #region Utilities public static string[] WindowsInvalidUnixValid = new string[] { " ", " ", "\n", ">", "<", "\t" }; public virtual void Copy(string source, string dest) { File.Copy(source, dest); } #endregion #region UniversalTests [Fact] public void NullFileName() { Assert.Throws<ArgumentNullException>(() => Copy(null, ".")); Assert.Throws<ArgumentNullException>(() => Copy(".", null)); } [Fact] public void EmptyFileName() { Assert.Throws<ArgumentException>(() => Copy(string.Empty, ".")); Assert.Throws<ArgumentException>(() => Copy(".", string.Empty)); } [Fact] public void CopyOntoDirectory() { string testFile = GetTestFilePath(); File.Create(testFile).Dispose(); Assert.Throws<IOException>(() => Copy(testFile, TestDirectory)); } [Fact] public void CopyOntoSelf() { string testFile = GetTestFilePath(); File.Create(testFile).Dispose(); Assert.Throws<IOException>(() => Copy(testFile, testFile)); } [Fact] public void NonExistentPath() { FileInfo testFile = new FileInfo(GetTestFilePath()); testFile.Create().Dispose(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Assert.Throws<FileNotFoundException>(() => Copy(GetTestFilePath(), testFile.FullName)); Assert.Throws<DirectoryNotFoundException>(() => Copy(testFile.FullName, Path.Combine(TestDirectory, GetTestFileName(), GetTestFileName()))); Assert.Throws<DirectoryNotFoundException>(() => Copy(Path.Combine(TestDirectory, GetTestFileName(), GetTestFileName()), testFile.FullName)); } else { Assert.Throws<FileNotFoundException>(() => Copy(GetTestFilePath(), testFile.FullName)); Assert.Throws<DirectoryNotFoundException>(() => Copy(testFile.FullName, Path.Combine(TestDirectory, GetTestFileName(), GetTestFileName()))); Assert.Throws<FileNotFoundException>(() => Copy(Path.Combine(TestDirectory, GetTestFileName(), GetTestFileName()), testFile.FullName)); } } [Fact] public void CopyValid() { string testFileSource = GetTestFilePath(); string testFileDest = GetTestFilePath(); File.Create(testFileSource).Dispose(); Copy(testFileSource, testFileDest); Assert.True(File.Exists(testFileDest)); Assert.True(File.Exists(testFileSource)); } [Fact] public void ShortenLongPath() { string testFileSource = GetTestFilePath(); string testFileDest = Path.GetDirectoryName(testFileSource) + string.Concat(Enumerable.Repeat(Path.DirectorySeparatorChar + ".", 90).ToArray()) + Path.DirectorySeparatorChar + Path.GetFileName(testFileSource); File.Create(testFileSource).Dispose(); Assert.Throws<IOException>(() => Copy(testFileSource, testFileDest)); } [Fact] public void InvalidFileNames() { string testFile = GetTestFilePath(); File.Create(testFile).Dispose(); Assert.Throws<ArgumentException>(() => Copy(testFile, "\0")); Assert.Throws<ArgumentException>(() => Copy(testFile, "*\0*")); Assert.Throws<ArgumentException>(() => Copy("*\0*", testFile)); Assert.Throws<ArgumentException>(() => Copy("\0", testFile)); } [Fact] public void CopyFileWithData() { string testFileSource = GetTestFilePath(); string testFileDest = GetTestFilePath(); char[] data = { 'a', 'A', 'b' }; // Write and copy file using (StreamWriter stream = new StreamWriter(File.Create(testFileSource))) { stream.Write(data, 0, data.Length); stream.Flush(); } Copy(testFileSource, testFileDest); // Ensure copy transferred written data using (StreamReader stream = new StreamReader(File.OpenRead(testFileDest))) { char[] readData = new char[data.Length]; stream.Read(readData, 0, data.Length); Assert.Equal(data, readData); } } #endregion #region PlatformSpecific [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsWhitespacePath() { string testFile = GetTestFilePath(); File.Create(testFile).Dispose(); foreach (string invalid in WindowsInvalidUnixValid) { Assert.Throws<ArgumentException>(() => Copy(testFile, invalid)); Assert.Throws<ArgumentException>(() => Copy(invalid, testFile)); } } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void UnixWhitespacePath() { string testFile = GetTestFilePath(); File.Create(testFile).Dispose(); foreach (string valid in WindowsInvalidUnixValid) { Copy(testFile, Path.Combine(TestDirectory, valid)); Assert.True(File.Exists(testFile)); Assert.True(File.Exists(Path.Combine(TestDirectory, valid))); } } #endregion } public class File_Copy_str_str_b : File_Copy_str_str { #region Utilities public override void Copy(string source, string dest) { File.Copy(source, dest, false); } public virtual void Copy(string source, string dest, bool overwrite) { File.Copy(source, dest, overwrite); } #endregion #region UniversalTests [Fact] public void OverwriteTrue() { string testFileSource = GetTestFilePath(); string testFileDest = GetTestFilePath(); char[] sourceData = { 'a', 'A', 'b' }; char[] destData = { 'x', 'X', 'y' }; // Write and copy file using (StreamWriter sourceStream = new StreamWriter(File.Create(testFileSource))) using (StreamWriter destStream = new StreamWriter(File.Create(testFileDest))) { sourceStream.Write(sourceData, 0, sourceData.Length); destStream.Write(destData, 0, destData.Length); } Copy(testFileSource, testFileDest, true); // Ensure copy transferred written data using (StreamReader stream = new StreamReader(File.OpenRead(testFileDest))) { char[] readData = new char[sourceData.Length]; stream.Read(readData, 0, sourceData.Length); Assert.Equal(sourceData, readData); } } [Fact] public void OverwriteFalse() { string testFileSource = GetTestFilePath(); string testFileDest = GetTestFilePath(); char[] sourceData = { 'a', 'A', 'b' }; char[] destData = { 'x', 'X', 'y' }; // Write and copy file using (StreamWriter sourceStream = new StreamWriter(File.Create(testFileSource))) using (StreamWriter destStream = new StreamWriter(File.Create(testFileDest))) { sourceStream.Write(sourceData, 0, sourceData.Length); destStream.Write(destData, 0, destData.Length); } Assert.Throws<IOException>(() => Copy(testFileSource, testFileDest, false)); // Ensure copy didn't overwrite existing data using (StreamReader stream = new StreamReader(File.OpenRead(testFileDest))) { char[] readData = new char[sourceData.Length]; stream.Read(readData, 0, sourceData.Length); Assert.Equal(destData, readData); } } #endregion } }
// // Copyright (c) Microsoft. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using Newtonsoft.Json.Linq; using Xunit; using Microsoft.Rest; using Microsoft.Azure.Management.ResourceManager; using Microsoft.Azure.Management.ResourceManager.Models; using Microsoft.Rest.Azure.OData; namespace ResourceGroups.Tests { public class InMemoryDeploymentTests { public ResourceManagementClient GetResourceManagementClient(RecordedDelegatingHandler handler) { var subscriptionId = Guid.NewGuid().ToString(); var token = new TokenCredentials(subscriptionId, "abc123"); handler.IsPassThrough = false; var client = new ResourceManagementClient(token, handler); client.SubscriptionId = subscriptionId; return client; } [Fact] public void DeploymentTestsCreateValidateMessage() { var response = new HttpResponseMessage(HttpStatusCode.Created) { Content = new StringContent(@"{ 'id': 'foo', 'name':'myrealease-3.14', 'properties':{ 'provisioningState':'Succeeded', 'timestamp':'2014-01-05T12:30:43.00Z', 'mode':'Incremental', 'template': { 'api-version' : '123' }, 'templateLink': { 'uri': 'http://wa/template.json', 'contentVersion': '1.0.0.0', 'contentHash': { 'algorithm': 'sha256', 'value': 'yyz7xhhshfasf', } }, 'parametersLink': { /* use either one of parameters or parametersLink */ 'uri': 'http://wa/parameters.json', 'contentVersion': '1.0.0.0', 'contentHash': { 'algorithm': 'sha256', 'value': 'yyz7xhhshfasf', } }, 'parameters': { 'key' : { 'type':'string', 'value':'user' } }, 'outputs': { 'key' : { 'type':'string', 'value':'user' } } } }") }; var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.Created }; var client = GetResourceManagementClient(handler); var dictionary = new Dictionary<string, object> { {"param1", "value1"}, {"param2", true}, {"param3", new Dictionary<string, object>() { {"param3_1", 123}, {"param3_2", "value3_2"}, }} }; var parameters = new Deployment { Properties = new DeploymentProperties() { Template = JObject.Parse("{'api-version':'123'}"), TemplateLink = new TemplateLink { Uri = "http://abc/def/template.json", ContentVersion = "1.0.0.0" }, Parameters = dictionary, ParametersLink = new ParametersLink { Uri = "http://abc/def/template.json", ContentVersion = "1.0.0.0" }, Mode = DeploymentMode.Incremental } }; var result = client.Deployments.CreateOrUpdate("foo", "myrealease-3.14", parameters); JObject json = JObject.Parse(handler.Request); // Validate headers Assert.Equal("application/json; charset=utf-8", handler.ContentHeaders.GetValues("Content-Type").First()); Assert.Equal(HttpMethod.Put, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); // Validate payload Assert.Equal("Incremental", json["properties"]["mode"].Value<string>()); Assert.Equal("http://abc/def/template.json", json["properties"]["templateLink"]["uri"].Value<string>()); Assert.Equal("1.0.0.0", json["properties"]["templateLink"]["contentVersion"].Value<string>()); Assert.Equal("1.0.0.0", json["properties"]["parametersLink"]["contentVersion"].Value<string>()); Assert.Equal("value1", json["properties"]["parameters"]["param1"].Value<string>()); Assert.Equal(true, json["properties"]["parameters"]["param2"].Value<bool>()); Assert.Equal(123, json["properties"]["parameters"]["param3"]["param3_1"].Value<int>()); Assert.Equal("value3_2", json["properties"]["parameters"]["param3"]["param3_2"].Value<string>()); Assert.Equal(123, json["properties"]["template"]["api-version"].Value<int>()); // Validate result Assert.Equal("foo", result.Id); Assert.Equal("myrealease-3.14", result.Name); Assert.Equal("Succeeded", result.Properties.ProvisioningState); Assert.Equal(new DateTime(2014, 1, 5, 12, 30, 43), result.Properties.Timestamp); Assert.Equal(DeploymentMode.Incremental, result.Properties.Mode); Assert.Equal("http://wa/template.json", result.Properties.TemplateLink.Uri); Assert.Equal("1.0.0.0", result.Properties.TemplateLink.ContentVersion); Assert.True(result.Properties.Parameters.ToString().Contains("\"type\": \"string\"")); Assert.True(result.Properties.Outputs.ToString().Contains("\"type\": \"string\"")); } [Fact] public void DeploymentTestsTemplateAsJsonString() { var responseBody = @"{ 'id': 'foo', 'name': 'test-release-3', 'properties': { 'parameters': { 'storageAccountName': { 'type': 'String', 'value': 'tianotest04' } }, 'mode': 'Incremental', 'provisioningState': 'Succeeded', 'timestamp': '2016-07-12T17:36:39.2398177Z', 'duration': 'PT0.5966357S', 'correlationId': 'c0d728d5-5b97-41b9-b79a-abcd9eb5fe4a' } }"; var templateString = @"{ '$schema': 'http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#', 'contentVersion': '1.0.0.0', 'parameters': { 'storageAccountName': { 'type': 'string' } }, 'resources': [ ], 'outputs': { } }"; var parametersStringFull = @"{ '$schema': 'http://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#', 'contentVersion': '1.0.0.0', 'parameters': { 'storageAccountName': { 'value': 'tianotest04' } } }"; var parametersStringsShort = @"{ 'storageAccountName': { 'value': 'tianotest04' } }"; for (int i = 0; i < 2; i++) { var response = new HttpResponseMessage(HttpStatusCode.Created) { Content = new StringContent(responseBody) }; var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.Created }; var client = GetResourceManagementClient(handler); var parameters = new Deployment { Properties = new DeploymentProperties() { Template = templateString, Parameters = i == 0 ? parametersStringFull: parametersStringsShort, Mode = DeploymentMode.Incremental } }; var result = client.Deployments.CreateOrUpdate("foo", "myrealease-3.14", parameters); JObject json = JObject.Parse(handler.Request); // Validate headers Assert.Equal("application/json; charset=utf-8", handler.ContentHeaders.GetValues("Content-Type").First()); Assert.Equal(HttpMethod.Put, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); // Validate payload Assert.Equal("Incremental", json["properties"]["mode"].Value<string>()); Assert.Equal("tianotest04", json["properties"]["parameters"]["storageAccountName"]["value"].Value<string>()); Assert.Equal("1.0.0.0", json["properties"]["template"]["contentVersion"].Value<string>()); // Validate result Assert.Equal("foo", result.Id); Assert.Equal("test-release-3", result.Name); Assert.Equal("Succeeded", result.Properties.ProvisioningState); Assert.Equal(DeploymentMode.Incremental, result.Properties.Mode); Assert.True(result.Properties.Parameters.ToString().Contains("\"value\": \"tianotest04\"")); } } [Fact] public void ListDeploymentOperationsReturnsMultipleObjects() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'value': [ { 'subscriptionId':'mysubid', 'resourceGroup': 'foo', 'deploymentName':'test-release-3', 'operationId': 'AEF2398', 'properties':{ 'targetResource':{ 'id': '/subscriptions/123abc/resourcegroups/foo/providers/ResourceProviderTestHost/TestResourceType/resource1', 'resourceName':'mySite1', 'resourceType': 'Microsoft.Web', }, 'provisioningState':'Succeeded', 'timestamp': '2014-02-25T23:08:21.8183932Z', 'correlationId': 'afb170c6-fe57-4b38-a43b-900fe09be4ca', 'statusCode': 'InternalServerError', 'statusMessage': 'InternalServerError', } } ], 'nextLink': 'https://wa.com/subscriptions/mysubid/resourcegroups/TestRG/deployments/test-release-3/operations?$skiptoken=983fknw' } ") }; var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); var result = client.DeploymentOperations.List("foo", "bar", null); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); // Validate response Assert.Equal(1, result.Count()); Assert.Equal("AEF2398", result.First().OperationId); Assert.Equal("/subscriptions/123abc/resourcegroups/foo/providers/ResourceProviderTestHost/TestResourceType/resource1", result.First().Properties.TargetResource.Id); Assert.Equal("mySite1", result.First().Properties.TargetResource.ResourceName); Assert.Equal("Microsoft.Web", result.First().Properties.TargetResource.ResourceType); Assert.Equal("Succeeded", result.First().Properties.ProvisioningState); Assert.Equal("InternalServerError", result.First().Properties.StatusCode); Assert.Equal("InternalServerError", result.First().Properties.StatusMessage); Assert.Equal("https://wa.com/subscriptions/mysubid/resourcegroups/TestRG/deployments/test-release-3/operations?$skiptoken=983fknw", result.NextPageLink); } [Fact] public void ListDeploymentOperationsReturnsEmptyArray() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'value': [], 'nextLink': 'https://wa.com/subscriptions/mysubid/resourcegroups/TestRG/deployments/test-release-3/operations?$skiptoken=983fknw' }") }; var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); var result = client.DeploymentOperations.List("foo", "bar", null); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); // Validate response Assert.Equal(0, result.Count()); } [Fact] public void ListDeploymentOperationsWithRealPayloadReadsJsonInStatusMessage() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'value': [ { 'id': '/subscriptions/abcd1234/resourcegroups/foo/deployments/testdeploy/operations/334558C2218CAEB0', 'subscriptionId': 'abcd1234', 'resourceGroup': 'foo', 'deploymentName': 'testdeploy', 'operationId': '334558C2218CAEB0', 'properties': { 'provisioningState': 'Failed', 'timestamp': '2014-03-14T23:43:31.8688746Z', 'trackingId': '4f258f91-edd5-4d71-87c2-fac9a4b5cbbd', 'statusCode': 'Conflict', 'statusMessage': { 'Code': 'Conflict', 'Message': 'Website with given name ilygreTest4 already exists.', 'Target': null, 'Details': [ { 'Message': 'Website with given name ilygreTest4 already exists.' }, { 'Code': 'Conflict' }, { 'ErrorEntity': { 'Code': 'Conflict', 'Message': 'Website with given name ilygreTest4 already exists.', 'ExtendedCode': '54001', 'MessageTemplate': 'Website with given name {0} already exists.', 'Parameters': [ 'ilygreTest4' ], 'InnerErrors': null } } ], 'Innererror': null }, 'targetResource': { 'id': '/subscriptions/abcd1234/resourcegroups/foo/providers/Microsoft.Web/Sites/ilygreTest4', 'subscriptionId': 'abcd1234', 'resourceGroup': 'foo', 'resourceType': 'Microsoft.Web/Sites', 'resourceName': 'ilygreTest4' } } }, { 'id': '/subscriptions/abcd1234/resourcegroups/foo/deployments/testdeploy/operations/6B9A5A38C94E6 F14', 'subscriptionId': 'abcd1234', 'resourceGroup': 'foo', 'deploymentName': 'testdeploy', 'operationId': '6B9A5A38C94E6F14', 'properties': { 'provisioningState': 'Succeeded', 'timestamp': '2014-03-14T23:43:25.2101422Z', 'trackingId': '2ff7a8ad-abf3-47f6-8ce0-e4aae8c26065', 'statusCode': 'OK', 'statusMessage': null, 'targetResource': { 'id': '/subscriptions/abcd1234/resourcegroups/foo/providers/Microsoft.Web/serverFarms/ilygreTest4 Host', 'subscriptionId': 'abcd1234', 'resourceGroup': 'foo', 'resourceType': 'Microsoft.Web/serverFarms', 'resourceName': 'ilygreTest4Host' } } } ] }") }; var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); var result = client.DeploymentOperations.List("foo", "bar", null); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); Assert.True(JObject.Parse(result.First().Properties.StatusMessage.ToString()).HasValues); } [Fact] public void ListDeploymentOperationsWorksWithNextLink() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'value': [ { 'subscriptionId':'mysubid', 'resourceGroup': 'foo', 'deploymentName':'test-release-3', 'operationId': 'AEF2398', 'properties':{ 'targetResource':{ 'subscriptionId':'mysubid', 'resourceGroup': 'TestRG', 'resourceName':'mySite1', 'resourceType': 'Microsoft.Web', }, 'provisioningState':'Succeeded', 'timestamp': '2014-02-25T23:08:21.8183932Z', 'correlationId': 'afb170c6-fe57-4b38-a43b-900fe09be4ca', 'statusCode': 'InternalServerError', 'statusMessage': 'InternalServerError', } } ], 'nextLink': 'https://wa.com/subscriptions/mysubid/resourcegroups/TestRG/deployments/test-release-3/operations?$skiptoken=983fknw' } ") }; var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); var result = client.DeploymentOperations.List("foo", "bar", null); response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'value': [] }") }; handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; client = GetResourceManagementClient(handler); result = client.DeploymentOperations.ListNext(result.NextPageLink); // Validate body Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); Assert.Equal("https://wa.com/subscriptions/mysubid/resourcegroups/TestRG/deployments/test-release-3/operations?$skiptoken=983fknw", handler.Uri.ToString()); // Validate response Assert.Equal(0, result.Count()); Assert.Equal(null, result.NextPageLink); } [Fact] public void GetDeploymentOperationsReturnsValue() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'subscriptionId':'mysubid', 'resourceGroup': 'foo', 'deploymentName':'test-release-3', 'operationId': 'AEF2398', 'properties':{ 'targetResource':{ 'id':'/subscriptions/123abc/resourcegroups/foo/providers/ResourceProviderTestHost/TestResourceType/resource1', 'resourceName':'mySite1', 'resourceType': 'Microsoft.Web', }, 'provisioningState':'Succeeded', 'timestamp': '2014-02-25T23:08:21.8183932Z', 'correlationId': 'afb170c6-fe57-4b38-a43b-900fe09be4ca', 'statusCode': 'OK', 'statusMessage': 'OK', } }") }; var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); var result = client.DeploymentOperations.Get("foo", "bar", "123"); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); // Validate response Assert.Equal("AEF2398", result.OperationId); Assert.Equal("mySite1", result.Properties.TargetResource.ResourceName); Assert.Equal("/subscriptions/123abc/resourcegroups/foo/providers/ResourceProviderTestHost/TestResourceType/resource1", result.Properties.TargetResource.Id); Assert.Equal("Microsoft.Web", result.Properties.TargetResource.ResourceType); Assert.Equal("Succeeded", result.Properties.ProvisioningState); Assert.Equal("OK", result.Properties.StatusCode); Assert.Equal("OK", result.Properties.StatusMessage); } [Fact(Skip = "Parameter validation using pattern match is not supported yet at code-gen, the work is on-going.")] public void DeploymentTestsCreateThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = GetResourceManagementClient(handler); Assert.Throws<ArgumentNullException>(() => client.Deployments.CreateOrUpdate(null, "bar", new Deployment())); Assert.Throws<ArgumentNullException>(() => client.Deployments.CreateOrUpdate("foo", null, new Deployment())); Assert.Throws<ArgumentNullException>(() => client.Deployments.CreateOrUpdate("foo", "bar", null)); Assert.Throws<ArgumentOutOfRangeException>(() => client.Deployments.CreateOrUpdate("~`123", "bar", new Deployment())); } [Fact] public void DeploymentTestsValidateCheckPayload() { var response = new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent(@"{ 'error': { 'code': 'InvalidTemplate', 'message': 'Deployment template validation failed.' } }") }; var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.BadRequest }; var client = GetResourceManagementClient(handler); var dictionary = new Dictionary<string, object> { {"param1", "value1"}, {"param2", true}, {"param3", new Dictionary<string, object>() { {"param3_1", 123}, {"param3_2", "value3_2"}, }} }; var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Uri = "http://abc/def/template.json", ContentVersion = "1.0.0.0", }, Parameters = dictionary, Mode = DeploymentMode.Incremental } }; var result = client.Deployments.Validate("foo", "bar", parameters); JObject json = JObject.Parse(handler.Request); // Validate headers Assert.Equal("application/json; charset=utf-8", handler.ContentHeaders.GetValues("Content-Type").First()); Assert.Equal(HttpMethod.Post, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); // Validate payload Assert.Equal("Incremental", json["properties"]["mode"].Value<string>()); Assert.Equal("http://abc/def/template.json", json["properties"]["templateLink"]["uri"].Value<string>()); Assert.Equal("1.0.0.0", json["properties"]["templateLink"]["contentVersion"].Value<string>()); Assert.Equal("value1", json["properties"]["parameters"]["param1"].Value<string>()); Assert.Equal(true, json["properties"]["parameters"]["param2"].Value<bool>()); Assert.Equal(123, json["properties"]["parameters"]["param3"]["param3_1"].Value<int>()); Assert.Equal("value3_2", json["properties"]["parameters"]["param3"]["param3_2"].Value<string>()); } [Fact] public void DeploymentTestsValidateSimpleFailure() { var response = new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent(@"{ 'error': { 'code': 'InvalidTemplate', 'message': 'Deployment template validation failed: The template parameters hostingPlanName, siteMode, computeMode are not valid; they are not present.' } }") }; var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.BadRequest }; var client = GetResourceManagementClient(handler); var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Uri = "http://abc/def/template.json", ContentVersion = "1.0.0.0", }, Mode = DeploymentMode.Incremental } }; var result = client.Deployments.Validate("foo", "bar", parameters); // Validate result Assert.Equal("InvalidTemplate", result.Error.Code); Assert.Equal("Deployment template validation failed: The template parameters hostingPlanName, siteMode, computeMode are not valid; they are not present.", result.Error.Message); Assert.Null(result.Error.Target); Assert.Null(result.Error.Details); } [Fact] public void DeploymentTestsValidateComplexFailure() { var response = new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent(@"{ 'error': { 'code': 'InvalidTemplate', 'target': '', 'message': 'Deployment template validation failed: The template parameters hostingPlanName, siteMode, computeMode are not valid; they are not present.', 'details': [ { 'code': 'Error1', 'message': 'Deployment template validation failed.' }, { 'code': 'Error2', 'message': 'Deployment template validation failed.' } ] } }") }; var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.BadRequest }; var client = GetResourceManagementClient(handler); var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Uri = "http://abc/def/template.json", ContentVersion = "1.0.0.0", }, Mode = DeploymentMode.Incremental } }; var result = client.Deployments.Validate("foo", "bar", parameters); JObject json = JObject.Parse(handler.Request); // Validate result Assert.Equal("InvalidTemplate", result.Error.Code); Assert.Equal("Deployment template validation failed: The template parameters hostingPlanName, siteMode, computeMode are not valid; they are not present.", result.Error.Message); Assert.Equal("", result.Error.Target); Assert.Equal(2, result.Error.Details.Count); Assert.Equal("Error1", result.Error.Details[0].Code); Assert.Equal("Error2", result.Error.Details[1].Code); } [Fact] public void DeploymentTestsValidateSuccess() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Uri = "http://abc/def/template.json", ContentVersion = "1.0.0.0", }, Mode = DeploymentMode.Incremental } }; var result = client.Deployments.Validate("foo", "bar", parameters); JObject json = JObject.Parse(handler.Request); // Validate headers Assert.Equal("application/json; charset=utf-8", handler.ContentHeaders.GetValues("Content-Type").First()); Assert.Equal(HttpMethod.Post, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); // Validate result Assert.Null(result); } [Fact(Skip = "Parameter validation using pattern match is not supported yet at code-gen, the work is on-going.")] public void DeploymentTestsValidateThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = GetResourceManagementClient(handler); Assert.Throws<ArgumentNullException>(() => client.Deployments.Validate(null, "bar", new Deployment())); Assert.Throws<ArgumentNullException>(() => client.Deployments.Validate("foo", "bar", null)); Assert.Throws<ArgumentOutOfRangeException>(() => client.Deployments.Validate("~`123", "bar", new Deployment())); } [Fact] public void DeploymentTestsCancelValidateMessage() { var response = new HttpResponseMessage(HttpStatusCode.NoContent) { Content = new StringContent("") }; var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.NoContent, }; var client = GetResourceManagementClient(handler); client.Deployments.Cancel("foo", "bar"); } [Fact] public void DeploymentTestsCancelThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = GetResourceManagementClient(handler); Assert.Throws<Microsoft.Rest.ValidationException>(() => client.Deployments.Cancel(null, "bar")); Assert.Throws<Microsoft.Rest.ValidationException>(() => client.Deployments.Cancel("foo", null)); } [Fact] public void DeploymentTestsGetValidateMessage() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'resourceGroup': 'foo', 'name':'myrealease-3.14', 'properties':{ 'provisioningState':'Succeeded', 'timestamp':'2014-01-05T12:30:43.00Z', 'mode':'Incremental', 'correlationId':'12345', 'templateLink': { 'uri': 'http://wa/template.json', 'contentVersion': '1.0.0.0', 'contentHash': { 'algorithm': 'sha256', 'value': 'yyz7xhhshfasf', } }, 'parametersLink': { /* use either one of parameters or parametersLink */ 'uri': 'http://wa/parameters.json', 'contentVersion': '1.0.0.0', 'contentHash': { 'algorithm': 'sha256', 'value': 'yyz7xhhshfasf', } }, 'parameters': { 'key' : { 'type':'string', 'value':'user' } }, 'outputs': { 'key' : { 'type':'string', 'value':'user' } } } }") }; var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); var result = client.Deployments.Get("foo", "bar"); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); // Validate result Assert.Equal("myrealease-3.14", result.Name); Assert.Equal("Succeeded", result.Properties.ProvisioningState); Assert.Equal("12345", result.Properties.CorrelationId); Assert.Equal(new DateTime(2014, 1, 5, 12, 30, 43), result.Properties.Timestamp); Assert.Equal(DeploymentMode.Incremental, result.Properties.Mode); Assert.Equal("http://wa/template.json", result.Properties.TemplateLink.Uri.ToString()); Assert.Equal("1.0.0.0", result.Properties.TemplateLink.ContentVersion); Assert.True(result.Properties.Parameters.ToString().Contains("\"type\": \"string\"")); Assert.True(result.Properties.Outputs.ToString().Contains("\"type\": \"string\"")); } [Fact(Skip = "Parameter validation using pattern match is not supported yet at code-gen, the work is on-going.")] public void DeploymentGetValidateThrowsExceptions() { var handler = new RecordedDelegatingHandler(); var client = GetResourceManagementClient(handler); Assert.Throws<ArgumentNullException>(() => client.Deployments.Get(null, "bar")); Assert.Throws<ArgumentNullException>(() => client.Deployments.Get("foo", null)); Assert.Throws<ArgumentOutOfRangeException>(() => client.Deployments.Get("~`123", "bar")); } [Fact] public void DeploymentTestsListAllValidateMessage() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'value' : [ { 'resourceGroup': 'foo', 'name':'myrealease-3.14', 'properties':{ 'provisioningState':'Succeeded', 'timestamp':'2014-01-05T12:30:43.00Z', 'mode':'Incremental', 'templateLink': { 'uri': 'http://wa/template.json', 'contentVersion': '1.0.0.0', 'contentHash': { 'algorithm': 'sha256', 'value': 'yyz7xhhshfasf', } }, 'parametersLink': { /* use either one of parameters or parametersLink */ 'uri': 'http://wa/parameters.json', 'contentVersion': '1.0.0.0', 'contentHash': { 'algorithm': 'sha256', 'value': 'yyz7xhhshfasf', } }, 'parameters': { 'key' : { 'type':'string', 'value':'user' } }, 'outputs': { 'key' : { 'type':'string', 'value':'user' } } } }, { 'resourceGroup': 'bar', 'name':'myrealease-3.14', 'properties':{ 'provisioningState':'Succeeded', 'timestamp':'2014-01-05T12:30:43.00Z', 'mode':'Incremental', 'templateLink': { 'uri': 'http://wa/template.json', 'contentVersion': '1.0.0.0', 'contentHash': { 'algorithm': 'sha256', 'value': 'yyz7xhhshfasf', } }, 'parametersLink': { /* use either one of parameters or parametersLink */ 'uri': 'http://wa/parameters.json', 'contentVersion': '1.0.0.0', 'contentHash': { 'algorithm': 'sha256', 'value': 'yyz7xhhshfasf', } }, 'parameters': { 'key' : { 'type':'string', 'value':'user' } }, 'outputs': { 'key' : { 'type':'string', 'value':'user' } } } } ], 'nextLink': 'https://wa/subscriptions/subId/templateDeployments?$skiptoken=983fknw' }") }; var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); var result = client.Deployments.List("foo"); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); // Validate result Assert.Equal("myrealease-3.14", result.First().Name); Assert.Equal("Succeeded", result.First().Properties.ProvisioningState); Assert.Equal(new DateTime(2014, 1, 5, 12, 30, 43), result.First().Properties.Timestamp); Assert.Equal(DeploymentMode.Incremental, result.First().Properties.Mode); Assert.Equal("http://wa/template.json", result.First().Properties.TemplateLink.Uri.ToString()); Assert.Equal("1.0.0.0", result.First().Properties.TemplateLink.ContentVersion); Assert.True(result.First().Properties.Parameters.ToString().Contains("\"type\": \"string\"")); Assert.True(result.First().Properties.Outputs.ToString().Contains("\"type\": \"string\"")); Assert.Equal("https://wa/subscriptions/subId/templateDeployments?$skiptoken=983fknw", result.NextPageLink); } [Fact] public void DeploymentTestsListValidateMessage() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'value' : [ { 'resourceGroup': 'foo', 'name':'myrealease-3.14', 'properties':{ 'provisioningState':'Succeeded', 'timestamp':'2014-01-05T12:30:43.00Z', 'mode':'Incremental', 'templateLink': { 'uri': 'http://wa/template.json', 'contentVersion': '1.0.0.0', 'contentHash': { 'algorithm': 'sha256', 'value': 'yyz7xhhshfasf', } }, 'parametersLink': { /* use either one of parameters or parametersLink */ 'uri': 'http://wa/parameters.json', 'contentVersion': '1.0.0.0', 'contentHash': { 'algorithm': 'sha256', 'value': 'yyz7xhhshfasf', } }, 'parameters': { 'key' : { 'type':'string', 'value':'user' } }, 'outputs': { 'key' : { 'type':'string', 'value':'user' } } } }, { 'resourceGroup': 'bar', 'name':'myrealease-3.14', 'properties':{ 'provisioningState':'Succeeded', 'timestamp':'2014-01-05T12:30:43.00Z', 'mode':'Incremental', 'templateLink': { 'uri': 'http://wa/template.json', 'contentVersion': '1.0.0.0', 'contentHash': { 'algorithm': 'sha256', 'value': 'yyz7xhhshfasf', } }, 'parametersLink': { /* use either one of parameters or parametersLink */ 'uri': 'http://wa/parameters.json', 'contentVersion': '1.0.0.0', 'contentHash': { 'algorithm': 'sha256', 'value': 'yyz7xhhshfasf', } }, 'parameters': { 'key' : { 'type':'string', 'value':'user' } }, 'outputs': { 'key' : { 'type':'string', 'value':'user' } } } } ], 'nextLink': 'https://wa/subscriptions/subId/templateDeployments?$skiptoken=983fknw' }") }; var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); var result = client.Deployments.List("foo", new ODataQuery<DeploymentExtendedFilter>(d => d.ProvisioningState == "Succeeded") { Top = 10 }); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); Assert.True(handler.Uri.ToString().Contains("$top=10")); Assert.True(handler.Uri.ToString().Contains("$filter=provisioningState eq 'Succeeded'")); // Validate result Assert.Equal("myrealease-3.14", result.First().Name); Assert.Equal("Succeeded", result.First().Properties.ProvisioningState); Assert.Equal(new DateTime(2014, 1, 5, 12, 30, 43), result.First().Properties.Timestamp); Assert.Equal(DeploymentMode.Incremental, result.First().Properties.Mode); Assert.Equal("http://wa/template.json", result.First().Properties.TemplateLink.Uri.ToString()); Assert.Equal("1.0.0.0", result.First().Properties.TemplateLink.ContentVersion); Assert.True(result.First().Properties.Parameters.ToString().Contains("\"type\": \"string\"")); Assert.True(result.First().Properties.Outputs.ToString().Contains("\"type\": \"string\"")); Assert.Equal("https://wa/subscriptions/subId/templateDeployments?$skiptoken=983fknw", result.NextPageLink); } // TODO: Fix [Fact] public void DeploymentTestsListForGroupValidateMessage() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{ 'value' : [ { 'resourceGroup': 'foo', 'name':'myrealease-3.14', 'properties':{ 'provisioningState':'Succeeded', 'timestamp':'2014-01-05T12:30:43.00Z', 'mode':'Incremental', 'templateLink': { 'uri': 'http://wa/template.json', 'contentVersion': '1.0.0.0', 'contentHash': { 'algorithm': 'sha256', 'value': 'yyz7xhhshfasf', } }, 'parametersLink': { /* use either one of parameters or parametersLink */ 'uri': 'http://wa/parameters.json', 'contentVersion': '1.0.0.0', 'contentHash': { 'algorithm': 'sha256', 'value': 'yyz7xhhshfasf', } }, 'parameters': { 'key' : { 'type':'string', 'value':'user' } }, 'outputs': { 'key' : { 'type':'string', 'value':'user' } } } }, { 'resourceGroup': 'bar', 'name':'myrealease-3.14', 'properties':{ 'provisioningState':'Succeeded', 'timestamp':'2014-01-05T12:30:43.00Z', 'mode':'Incremental', 'templateLink': { 'uri': 'http://wa/template.json', 'contentVersion': '1.0.0.0', 'contentHash': { 'algorithm': 'sha256', 'value': 'yyz7xhhshfasf', } }, 'parametersLink': { /* use either one of parameters or parametersLink */ 'uri': 'http://wa/parameters.json', 'contentVersion': '1.0.0.0', 'contentHash': { 'algorithm': 'sha256', 'value': 'yyz7xhhshfasf', } }, 'parameters': { 'key' : { 'type':'string', 'value':'user' } }, 'outputs': { 'key' : { 'type':'string', 'value':'user' } } } } ], 'nextLink': 'https://wa/subscriptions/subId/templateDeployments?$skiptoken=983fknw' }") }; var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); var result = client.Deployments.List("foo", new ODataQuery<DeploymentExtendedFilter>(d => d.ProvisioningState == "Succeeded") { Top = 10 }); // Validate headers Assert.Equal(HttpMethod.Get, handler.Method); Assert.NotNull(handler.RequestHeaders.GetValues("Authorization")); Assert.True(handler.Uri.ToString().Contains("$top=10")); Assert.True(handler.Uri.ToString().Contains("$filter=provisioningState eq 'Succeeded'")); Assert.True(handler.Uri.ToString().Contains("resourcegroups/foo/providers/Microsoft.Resources/deployments")); // Validate result Assert.Equal("myrealease-3.14", result.First().Name); Assert.Equal("Succeeded", result.First().Properties.ProvisioningState); Assert.Equal(new DateTime(2014, 1, 5, 12, 30, 43), result.First().Properties.Timestamp); Assert.Equal(DeploymentMode.Incremental, result.First().Properties.Mode); Assert.Equal("http://wa/template.json", result.First().Properties.TemplateLink.Uri.ToString()); Assert.Equal("1.0.0.0", result.First().Properties.TemplateLink.ContentVersion); Assert.True(result.First().Properties.Parameters.ToString().Contains("\"type\": \"string\"")); Assert.True(result.First().Properties.Outputs.ToString().Contains("\"type\": \"string\"")); Assert.Equal("https://wa/subscriptions/subId/templateDeployments?$skiptoken=983fknw", result.NextPageLink); } [Fact] public void DeploymentTestListDoesNotThrowExceptions() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("{'value' : []}") }; var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK }; var client = GetResourceManagementClient(handler); var result = client.Deployments.List("foo"); Assert.Empty(result); } } }
using System; using System.Diagnostics; namespace IDT4.Engine.CM { internal partial class CollisionModelManager { // returns true if any of the trm vertices is inside the brush bool TestTrmVertsInBrush(TraceWork tw, Brush b) { if (b.checkcount == this.checkCount) return false; b.checkcount = this.checkCount; if ((b.contents & tw.contents) == 0) return false; // if the brush bounds don't intersect the trace bounds if (!b.bounds.IntersectsBounds(tw.bounds)) return false; int numVerts = (tw.pointTrace ? 1 : tw.numVerts); for (int j = 0; j < numVerts; j++) { idVec3 p = tw.vertices[j].p; // see if the point is inside the brush int bestPlane = 0; float bestd = float.NegativeInfinity; for (int i = 0; i < b.numPlanes; i++) { float d = b.planes[i].Distance(p); if (d >= 0.0f) break; if (d > bestd) { bestd = d; bestPlane = i; } } if (i >= b.numPlanes) { tw.trace.fraction = 0.0f; tw.trace.c.type = ContactType.CONTACT_TRMVERTEX; tw.trace.c.normal = b.planes[bestPlane].Normal(); tw.trace.c.dist = b.planes[bestPlane].Dist(); tw.trace.c.contents = b.contents; tw.trace.c.material = b.material; tw.trace.c.point = p; tw.trace.c.modelFeature = 0; tw.trace.c.trmFeature = j; return true; } } return false; } //#define CM_SetTrmEdgeSidedness( edge, bpl, epl, bitNum ) { \ // if ( !(edge->sideSet & (1<<bitNum)) ) { \ // float fl; \ // fl = (bpl).PermutedInnerProduct( epl ); \ // edge->side = (edge->side & ~(1<<bitNum)) | (FLOATSIGNBITSET(fl) << bitNum); \ // edge->sideSet |= (1 << bitNum); \ // } \ //} //#define CM_SetTrmPolygonSidedness( v, plane, bitNum ) { \ // if ( !((v)->sideSet & (1<<bitNum)) ) { \ // float fl; \ // fl = plane.Distance( (v)->p ); \ // /* cannot use float sign bit because it is undetermined when fl == 0.0f */ \ // if ( fl < 0.0f ) { \ // (v)->side |= (1 << bitNum); \ // } \ // else { \ // (v)->side &= ~(1 << bitNum); \ // } \ // (v)->sideSet |= (1 << bitNum); \ // } \ //} // returns true if the trm intersects the polygon bool TestTrmInPolygon(TraceWork tw, Polygon p) { // if already checked this polygon if (p.checkcount == this.checkCount) return false; p.checkcount = this.checkCount; // if this polygon does not have the right contents behind it if ((p.contents & tw.contents) == 0) return false; // if the polygon bounds don't intersect the trace bounds if (!p.bounds.IntersectsBounds(tw.bounds)) return false; // bounds should cross polygon plane switch (tw.bounds.PlaneSide(p.plane)) { case PLANESIDE_CROSS: break; case PLANESIDE_FRONT: if (tw.model.isConvex) { tw.quickExit = true; return true; } default: return false; } // if the trace model is convex if (tw.isConvex) { // test if any polygon vertices are inside the trm for (int i = 0; i < p.numEdges; i++) { int edgeNum = p.edges[i]; Edge edge = tw.model.edges[Math.Abs(edgeNum)]; // if this edge is already tested if (edge.checkcount == this.checkCount) continue; for (int j = 0; j < 2; j++) { Vertex v = tw.model.vertices[edge.vertexNum[j]]; // if this vertex is already tested if (v.checkcount == this.checkCount) continue; int bestPlane = 0; float bestd = float.NegativeInfinity; int k = 0; for (; k < tw.numPolys; k++) { float d = tw.polys[k].plane.Distance(v.p); if (d >= 0.0f) break; if (d > bestd) { bestd = d; bestPlane = k; } } if (k >= tw.numPolys) { tw.trace.fraction = 0.0f; tw.trace.c.type = ContactType.CONTACT_MODELVERTEX; tw.trace.c.normal = -tw.polys[bestPlane].plane.Normal(); tw.trace.c.dist = -tw.polys[bestPlane].plane.Dist(); tw.trace.c.contents = p.contents; tw.trace.c.material = p.material; tw.trace.c.point = v.p; tw.trace.c.modelFeature = edge.vertexNum[j]; tw.trace.c.trmFeature = 0; return true; } } } } for (int i = 0; i < p.numEdges; i++) { int edgeNum = p.edges[i]; Edge edge = tw.model.edges[Math.Abs(edgeNum)]; // reset sidedness cache if this is the first time we encounter this edge if (edge.checkcount != this.checkCount) edge.sideSet = 0; // pluecker coordinate for edge tw.polygonEdgePlueckerCache[i].FromLine(tw.model.vertices[edge.vertexNum[0]].p, tw.model.vertices[edge.vertexNum[1]].p); Vertex v = tw.model.vertices[edge.vertexNum[MathEx.INTSIGNBITSET(edgeNum)]]; // reset sidedness cache if this is the first time we encounter this vertex if (v.checkcount != this.checkCount) v.sideSet = 0; v.checkcount = this.checkCount; } // get side of polygon for each trm vertex int[] sides = new int[CM.MAX_TRACEMODEL_VERTS]; for (int i = 0; i < tw.numVerts; i++) { float d = p.plane.Distance(tw.vertices[i].p); sides[i] = (d < 0.0f ? -1 : 1); } // test if any trm edges go through the polygon for (int i = 1; i <= tw.numEdges; i++) { // if the trm edge does not cross the polygon plane if (sides[tw.edges[i].vertexNum[0]] == sides[tw.edges[i].vertexNum[1]]) continue; // check from which side to which side the trm edge goes bool flip = MathEx.INTSIGNBITSET(sides[tw.edges[i].vertexNum[0]]); // test if trm edge goes through the polygon between the polygon edges for (int j = 0; j < p.numEdges; j++) { int edgeNum = p.edges[j]; Edge edge = tw.model.edges[Math.Abs(edgeNum)]; #if true CM_SetTrmEdgeSidedness(edge, tw.edges[i].pl, tw.polygonEdgePlueckerCache[j], i); if (MathEx.INTSIGNBITSET(edgeNum) ^ ((edge.side >> i) & 1) ^ flip) break; #else float d = tw.edges[i].pl.PermutedInnerProduct(tw.polygonEdgePlueckerCache[j]); if (flip) d = -d; if (edgeNum > 0) { if (d <= 0.0f) break; } else { if (d >= 0.0f) break; } #endif } if (j >= p.numEdges) { tw.trace.fraction = 0.0f; tw.trace.c.type = ContactType.CONTACT_EDGE; tw.trace.c.normal = p.plane.Normal(); tw.trace.c.dist = p.plane.Dist(); tw.trace.c.contents = p.contents; tw.trace.c.material = p.material; tw.trace.c.point = tw.vertices[tw.edges[i].vertexNum[!flip]].p; tw.trace.c.modelFeature = p; tw.trace.c.trmFeature = i; return true; } } // test if any polygon edges go through the trm polygons for (int i = 0; i < p.numEdges; i++) { int edgeNum = p.edges[i]; Edge edge = tw.model.edges[Math.Abs(edgeNum)]; if (edge.checkcount == this.checkCount) continue; edge.checkcount = this.checkCount; for (int j = 0; j < tw.numPolys; j++) { #if true Vertex v1 = tw.model.vertices + edge.vertexNum[0]; CM_SetTrmPolygonSidedness(v1, tw.polys[j].plane, j); Vertex v2 = tw.model.vertices + edge.vertexNum[1]; CM_SetTrmPolygonSidedness(v2, tw.polys[j].plane, j); // if the polygon edge does not cross the trm polygon plane if ((((v1.side ^ v2.side) >> j) & 1) == 0) continue; bool flip = (v1.side >> j) & 1; #else Vertex v1 = tw.model.vertices + edge.vertexNum[0]; float d1 = tw.polys[j].plane.Distance(v1.p); Vertex v2 = tw.model.vertices + edge.vertexNum[1]; float d2 = tw.polys[j].plane.Distance(v2.p); // if the polygon edge does not cross the trm polygon plane if ((d1 >= 0.0f && d2 >= 0.0f) || (d1 <= 0.0f && d2 <= 0.0f)) continue; bool flip = false; if (d1 < 0.0f) flip = true; #endif // test if polygon edge goes through the trm polygon between the trm polygon edges int k = 0; for (; k < tw.polys[j].numEdges; k++) { int trmEdgeNum = tw.polys[j].edges[k]; TrmEdge trmEdge = tw.edges[Math.Abs(trmEdgeNum)]; #if true int bitNum = Math.Abs(trmEdgeNum); CM_SetTrmEdgeSidedness(edge, trmEdge.pl, tw.polygonEdgePlueckerCache[i], bitNum); if (MathEx.INTSIGNBITSET(trmEdgeNum) ^ ((edge.side >> bitNum) & 1) ^ flip) break; #else float d = trmEdge.pl.PermutedInnerProduct(tw.polygonEdgePlueckerCache[i]); if (flip) d = -d; if (trmEdgeNum > 0) { if (d <= 0.0f) break; } else { if (d >= 0.0f) break; } #endif } if (k >= tw.polys[j].numEdges) { tw.trace.fraction = 0.0f; tw.trace.c.type = ContactType.CONTACT_EDGE; tw.trace.c.normal = -tw.polys[j].plane.Normal(); tw.trace.c.dist = -tw.polys[j].plane.Dist(); tw.trace.c.contents = p.contents; tw.trace.c.material = p.material; tw.trace.c.point = tw.model.vertices[edge.vertexNum[!flip]].p; tw.trace.c.modelFeature = edgeNum; tw.trace.c.trmFeature = j; return true; } } } return false; } Node PointNode(ref idVec3 p, Model model) { Node node = model.node; while (node.planeType != -1) { node = (p[node.planeType] > node.planeDist ? node.children[0] : node.children[1]); Debug.Assert(node != null); } return node; } int PointContents(idVec3 p, CmHandle model) { int i; Node node = PointNode(p, this.models[(int)model]); for (BrushRef bref = node.brushes; bref != null; bref = bref.next) { Brush b = bref.b; // test if the point is within the brush bounds for (i = 0; i < 3; i++) { if (p[i] < b.bounds[0][i]) break; if (p[i] > b.bounds[1][i]) break; } if (i < 3) continue; // test if the point is inside the brush idPlane plane = b.planes; for (i = 0; i < b.numPlanes; i++, plane++) { float d = plane.Distance(p); if (d >= 0) break; } if (i >= b.numPlanes) return b.contents; } return 0; } int TransformedPointContents(ref idVec3 p, CmHandle model, ref idVec3 origin, ref idMat3 modelAxis) { // subtract origin offset idVec3 p_l = p - origin; if (modelAxis.IsRotated()) p_l *= modelAxis; return PointContents(p_l, model); } int ContentsTrm(Trace results, ref idVec3 start, idTraceModel trm, ref idMat3 trmAxis, int contentMask, CmHandle model, ref idVec3 modelOrigin, ref idMat3 modelAxis) { // fast point case if (!trm || (trm.bounds[1][0] - trm.bounds[0][0] <= 0.0f && trm.bounds[1][1] - trm.bounds[0][1] <= 0.0f && trm.bounds[1][2] - trm.bounds[0][2] <= 0.0f)) { results.c.contents = TransformedPointContents(start, model, modelOrigin, modelAxis); results.fraction = (results.c.contents == 0); results.endpos = start; results.endAxis = trmAxis; return results.c.contents; } this.checkCount++; TraceWork tw = new TraceWork(); tw.trace.fraction = 1.0f; tw.trace.c.contents = 0; tw.trace.c.type = ContactType.CONTACT_NONE; tw.contents = contentMask; tw.isConvex = true; tw.rotation = false; tw.positionTest = true; tw.pointTrace = false; tw.quickExit = false; tw.numContacts = 0; tw.model = this.models[(int)model]; tw.start = start - modelOrigin; tw.end = tw.start; bool model_rotated = modelAxis.IsRotated(); if (model_rotated) invModelAxis = modelAxis.Transpose(); // setup trm structure SetupTrm(ref tw, trm); bool trm_rotated = trmAxis.IsRotated(); // calculate vertex positions if (trm_rotated) for (int i = 0; i < tw.numVerts; i++) // rotate trm around the start position tw.vertices[i].p *= trmAxis; for (int i = 0; i < tw.numVerts; i++) // set trm at start position tw.vertices[i].p += tw.start; if (model_rotated) for (int i = 0; i < tw.numVerts; i++) // rotate trm around model instead of rotating the model tw.vertices[i].p *= invModelAxis; // add offset to start point if (trm_rotated) { idVec3 dir = trm->offset * trmAxis; tw.start += dir; tw.end += dir; } else { tw.start += trm->offset; tw.end += trm->offset; } if (model_rotated) { // rotate trace instead of model tw.start *= invModelAxis; tw.end *= invModelAxis; } // setup trm vertices tw.size.Clear(); for (int i = 0; i < tw.numVerts; i++) // get axial trm size after rotations tw.size.AddPoint(tw.vertices[i].p - tw.start); // setup trm edges for (int i = 1; i <= tw.numEdges; i++) { // edge start, end and pluecker coordinate tw.edges[i].start = tw.vertices[tw.edges[i].vertexNum[0]].p; tw.edges[i].end = tw.vertices[tw.edges[i].vertexNum[1]].p; tw.edges[i].pl.FromLine(tw.edges[i].start, tw.edges[i].end); } // setup trm polygons if (trm_rotated & model_rotated) { idMat3 tmpAxis = trmAxis * invModelAxis; for (int i = 0; i < tw.numPolys; i++) tw.polys[i].plane *= tmpAxis; } else if (trm_rotated) { for (int i = 0; i < tw.numPolys; i++) tw.polys[i].plane *= trmAxis; } else if (model_rotated) { for (int i = 0; i < tw.numPolys; i++) tw.polys[i].plane *= invModelAxis; } for (int i = 0; i < tw.numPolys; i++) tw.polys[i].plane.FitThroughPoint(tw.edges[abs(tw.polys[i].edges[0])].start); // bounds for full trace, a little bit larger for epsilons for (int i = 0; i < 3; i++) { if (tw.start[i] < tw.end[i]) { tw.bounds[0][i] = tw.start[i] + tw.size[0][i] - CM_BOX_EPSILON; tw.bounds[1][i] = tw.end[i] + tw.size[1][i] + CM_BOX_EPSILON; } else { tw.bounds[0][i] = tw.end[i] + tw.size[0][i] - CM_BOX_EPSILON; tw.bounds[1][i] = tw.start[i] + tw.size[1][i] + CM_BOX_EPSILON; } if (idMath.Fabs(tw.size[0][i]) > idMath.Fabs(tw.size[1][i])) tw.extents[i] = idMath.Fabs(tw.size[0][i]) + CM_BOX_EPSILON; else tw.extents[i] = idMath.Fabs(tw.size[1][i]) + CM_BOX_EPSILON; } // trace through the model TraceThroughModel(ref tw); results = tw.trace; results.fraction = (results.c.contents == 0); results.endpos = start; results.endAxis = trmAxis; return results.c.contents; } int Contents(ref idVec3 start, idTraceModel trm, ref idMat3 trmAxis, int contentMask, CmHandle model, ref idVec3 modelOrigin, ref idMat3 modelAxis) { if (model < 0 || model > this.maxModels || model > MAX_SUBMODELS) { common.Printf("CollisionModelManager::Contents: invalid model handle\n"); return 0; } if (this.models == null || this.models[model] == null) { common.Printf("CollisionModelManager::Contents: invalid model\n"); return 0; } Trace results; return ContentsTrm(out results, start, trm, trmAxis, contentMask, model, modelOrigin, modelAxis); } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information // // XmlDsigC14NTransformTest.cs - Test Cases for XmlDsigC14NTransform // // Author: // Sebastien Pouliot <sebastien@ximian.com> // Aleksey Sanin (aleksey@aleksey.com) // // (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com) // (C) 2003 Aleksey Sanin (aleksey@aleksey.com) // (C) 2004 Novell (http://www.novell.com) // // Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. using System.IO; using System.Text; using System.Xml; using System.Xml.Resolvers; using Xunit; namespace System.Security.Cryptography.Xml.Tests { // Note: GetInnerXml is protected in XmlDsigC14NTransform making it // difficult to test properly. This class "open it up" :-) public class UnprotectedXmlDsigC14NTransform : XmlDsigC14NTransform { public XmlNodeList UnprotectedGetInnerXml() { return base.GetInnerXml(); } } public class XmlDsigC14NTransformTest { [Fact] public void Constructor_Empty() { XmlDsigC14NTransform transform = new XmlDsigC14NTransform(); Assert.Equal("http://www.w3.org/TR/2001/REC-xml-c14n-20010315", transform.Algorithm); CheckProperties(transform); } [Theory] [InlineData(true, "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments")] [InlineData(false, "http://www.w3.org/TR/2001/REC-xml-c14n-20010315")] public void Constructor_Bool(bool includeComments, string expectedAlgorithm) { XmlDsigC14NTransform transform = new XmlDsigC14NTransform(includeComments); Assert.Equal(expectedAlgorithm, transform.Algorithm); CheckProperties(transform); } public void CheckProperties(XmlDsigC14NTransform transform) { Assert.Null(transform.Context); Assert.Equal(new[] { typeof(Stream), typeof(XmlDocument), typeof(XmlNodeList) }, transform.InputTypes); Assert.Equal(new[] { typeof(Stream) }, transform.OutputTypes); } [Fact] public void GetInnerXml() { UnprotectedXmlDsigC14NTransform transform = new UnprotectedXmlDsigC14NTransform(); XmlNodeList xnl = transform.UnprotectedGetInnerXml(); Assert.Null(xnl); } static string xml = "<Test attrib='at ' xmlns=\"http://www.go-mono.com/\" > \r\n &#xD; <Toto/> text &amp; </Test >"; // GOOD for Stream input static string c14xml2 = "<Test xmlns=\"http://www.go-mono.com/\" attrib=\"at \"> \n &#xD; <Toto></Toto> text &amp; </Test>"; // GOOD for XmlDocument input. The difference is because once // xml string is loaded to XmlDocument, there is no difference // between \r and &#xD;, so every \r must be handled as &#xD;. static string c14xml3 = "<Test xmlns=\"http://www.go-mono.com/\" attrib=\"at \"> &#xD;\n &#xD; <Toto></Toto> text &amp; </Test>"; private XmlDocument GetDoc() { XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.LoadXml(xml); return doc; } [Fact] public void LoadInputAsXmlDocument() { XmlDsigC14NTransform transform = new XmlDsigC14NTransform(); XmlDocument doc = GetDoc(); transform.LoadInput(doc); Stream s = (Stream)transform.GetOutput(); string output = TestHelpers.StreamToString(s, Encoding.UTF8); Assert.Equal(c14xml3, output); } [Fact] // see LoadInputAsXmlNodeList2 description public void LoadInputAsXmlNodeList() { XmlDsigC14NTransform transform = new XmlDsigC14NTransform(); XmlDocument doc = GetDoc(); // Argument list just contains element Test. transform.LoadInput(doc.ChildNodes); Stream s = (Stream)transform.GetOutput(); string output = TestHelpers.StreamToString(s, Encoding.UTF8); Assert.Equal(@"<Test xmlns=""http://www.go-mono.com/""></Test>", output); } [Fact] // MS has a bug that those namespace declaration nodes in // the node-set are written to output. Related spec section is: // http://www.w3.org/TR/2001/REC-xml-c14n-20010315#ProcessingModel public void LoadInputAsXmlNodeList2() { XmlDsigC14NTransform transform = new XmlDsigC14NTransform(); XmlDocument doc = GetDoc(); transform.LoadInput(doc.SelectNodes("//*")); Stream s = (Stream)transform.GetOutput(); string output = TestHelpers.StreamToString(s, Encoding.UTF8); string expected = @"<Test xmlns=""http://www.go-mono.com/""><Toto></Toto></Test>"; Assert.Equal(expected, output); } [Fact] public void LoadInputAsStream() { XmlDsigC14NTransform transform = new XmlDsigC14NTransform(); MemoryStream ms = new MemoryStream(); byte[] x = Encoding.ASCII.GetBytes(xml); ms.Write(x, 0, x.Length); ms.Position = 0; transform.LoadInput(ms); Stream s = (Stream)transform.GetOutput(); string output = TestHelpers.StreamToString(s, Encoding.UTF8); Assert.Equal(c14xml2, output); } [Fact] public void LoadInputWithUnsupportedType() { XmlDsigC14NTransform transform = new XmlDsigC14NTransform(); byte[] bad = { 0xBA, 0xD }; AssertExtensions.Throws<ArgumentException>("obj", () => transform.LoadInput(bad)); } [Fact] public void UnsupportedOutput() { XmlDsigC14NTransform transform = new XmlDsigC14NTransform(); XmlDocument doc = new XmlDocument(); AssertExtensions.Throws<ArgumentException>("type", () => transform.GetOutput(doc.GetType())); } [Fact] public void C14NSpecExample1() { XmlPreloadedResolver resolver = new XmlPreloadedResolver(); resolver.Add(new Uri("doc.xsl", UriKind.Relative), ""); string result = TestHelpers.ExecuteTransform(C14NSpecExample1Input, new XmlDsigC14NTransform()); Assert.Equal(C14NSpecExample1Output, result); } [Theory] [InlineData(C14NSpecExample2Input, C14NSpecExample2Output)] [InlineData(C14NSpecExample3Input, C14NSpecExample3Output)] [InlineData(C14NSpecExample4Input, C14NSpecExample4Output)] public void C14NSpecExample(string input, string expectedOutput) { string result = TestHelpers.ExecuteTransform(input, new XmlDsigC14NTransform()); Assert.Equal(expectedOutput, result); } [Fact] public void C14NSpecExample5() { XmlPreloadedResolver resolver = new XmlPreloadedResolver(); resolver.Add(TestHelpers.ToUri("doc.txt"), "world"); string result = TestHelpers.ExecuteTransform(C14NSpecExample5Input, new XmlDsigC14NTransform(), Encoding.UTF8, resolver); Assert.Equal(C14NSpecExample5Output, result); } [Fact] public void C14NSpecExample6() { string result = TestHelpers.ExecuteTransform(C14NSpecExample6Input, new XmlDsigC14NTransform(), Encoding.GetEncoding("ISO-8859-1")); Assert.Equal(C14NSpecExample6Output, result); } // // Example 1 from C14N spec - PIs, Comments, and Outside of Document Element: // http://www.w3.org/TR/xml-c14n#Example-OutsideDoc // // Aleksey: // removed reference to an empty external DTD // static string C14NSpecExample1Input = "<?xml version=\"1.0\"?>\n" + "\n" + "<?xml-stylesheet href=\"doc.xsl\"\n" + " type=\"text/xsl\" ?>\n" + "\n" + "\n" + "<doc>Hello, world!<!-- Comment 1 --></doc>\n" + "\n" + "<?pi-without-data ?>\n\n" + "<!-- Comment 2 -->\n\n" + "<!-- Comment 3 -->\n"; static string C14NSpecExample1Output = "<?xml-stylesheet href=\"doc.xsl\"\n" + " type=\"text/xsl\" ?>\n" + "<doc>Hello, world!</doc>\n" + "<?pi-without-data?>"; // // Example 2 from C14N spec - Whitespace in Document Content: // http://www.w3.org/TR/xml-c14n#Example-WhitespaceInContent // const string C14NSpecExample2Input = "<doc>\n" + " <clean> </clean>\n" + " <dirty> A B </dirty>\n" + " <mixed>\n" + " A\n" + " <clean> </clean>\n" + " B\n" + " <dirty> A B </dirty>\n" + " C\n" + " </mixed>\n" + "</doc>\n"; const string C14NSpecExample2Output = "<doc>\n" + " <clean> </clean>\n" + " <dirty> A B </dirty>\n" + " <mixed>\n" + " A\n" + " <clean> </clean>\n" + " B\n" + " <dirty> A B </dirty>\n" + " C\n" + " </mixed>\n" + "</doc>"; // // Example 3 from C14N spec - Start and End Tags: // http://www.w3.org/TR/xml-c14n#Example-SETags // const string C14NSpecExample3Input = "<!DOCTYPE doc [<!ATTLIST e9 attr CDATA \"default\">]>\n" + "<doc>\n" + " <e1 />\n" + " <e2 ></e2>\n" + " <e3 name = \"elem3\" id=\"elem3\" />\n" + " <e4 name=\"elem4\" id=\"elem4\" ></e4>\n" + " <e5 a:attr=\"out\" b:attr=\"sorted\" attr2=\"all\" attr=\"I\'m\"\n" + " xmlns:b=\"http://www.ietf.org\" \n" + " xmlns:a=\"http://www.w3.org\"\n" + " xmlns=\"http://www.uvic.ca\"/>\n" + " <e6 xmlns=\"\" xmlns:a=\"http://www.w3.org\">\n" + " <e7 xmlns=\"http://www.ietf.org\">\n" + " <e8 xmlns=\"\" xmlns:a=\"http://www.w3.org\">\n" + " <e9 xmlns=\"\" xmlns:a=\"http://www.ietf.org\"/>\n" + " </e8>\n" + " </e7>\n" + " </e6>\n" + "</doc>\n"; const string C14NSpecExample3Output = "<doc>\n" + " <e1></e1>\n" + " <e2></e2>\n" + " <e3 id=\"elem3\" name=\"elem3\"></e3>\n" + " <e4 id=\"elem4\" name=\"elem4\"></e4>\n" + " <e5 xmlns=\"http://www.uvic.ca\" xmlns:a=\"http://www.w3.org\" xmlns:b=\"http://www.ietf.org\" attr=\"I\'m\" attr2=\"all\" b:attr=\"sorted\" a:attr=\"out\"></e5>\n" + " <e6 xmlns:a=\"http://www.w3.org\">\n" + " <e7 xmlns=\"http://www.ietf.org\">\n" + " <e8 xmlns=\"\">\n" + " <e9 xmlns:a=\"http://www.ietf.org\" attr=\"default\"></e9>\n" + // " <e9 xmlns:a=\"http://www.ietf.org\"></e9>\n" + " </e8>\n" + " </e7>\n" + " </e6>\n" + "</doc>"; // // Example 4 from C14N spec - Character Modifications and Character References: // http://www.w3.org/TR/xml-c14n#Example-Chars // // Aleksey: // This test does not include "normId" element // because it has an invalid ID attribute "id" which // should be normalized by XML parser. Currently Mono // does not support this (see comment after this example // in the spec). const string C14NSpecExample4Input = "<!DOCTYPE doc [<!ATTLIST normId id ID #IMPLIED>]>\n" + "<doc>\n" + " <text>First line&#x0d;&#10;Second line</text>\n" + " <value>&#x32;</value>\n" + " <compute><![CDATA[value>\"0\" && value<\"10\" ?\"valid\":\"error\"]]></compute>\n" + " <compute expr=\'value>\"0\" &amp;&amp; value&lt;\"10\" ?\"valid\":\"error\"\'>valid</compute>\n" + " <norm attr=\' &apos; &#x20;&#13;&#xa;&#9; &apos; \'/>\n" + // " <normId id=\' &apos; &#x20;&#13;&#xa;&#9; &apos; \'/>\n" + "</doc>\n"; const string C14NSpecExample4Output = "<doc>\n" + " <text>First line&#xD;\n" + "Second line</text>\n" + " <value>2</value>\n" + " <compute>value&gt;\"0\" &amp;&amp; value&lt;\"10\" ?\"valid\":\"error\"</compute>\n" + " <compute expr=\"value>&quot;0&quot; &amp;&amp; value&lt;&quot;10&quot; ?&quot;valid&quot;:&quot;error&quot;\">valid</compute>\n" + " <norm attr=\" \' &#xD;&#xA;&#x9; \' \"></norm>\n" + // " <normId id=\"\' &#xD;&#xA;&#x9; \'\"></normId>\n" + "</doc>"; // // Example 5 from C14N spec - Entity References: // http://www.w3.org/TR/xml-c14n#Example-Entities // static string C14NSpecExample5Input => "<!DOCTYPE doc [\n" + "<!ATTLIST doc attrExtEnt ENTITY #IMPLIED>\n" + "<!ENTITY ent1 \"Hello\">\n" + $"<!ENTITY ent2 SYSTEM \"doc.txt\">\n" + "<!ENTITY entExt SYSTEM \"earth.gif\" NDATA gif>\n" + "<!NOTATION gif SYSTEM \"viewgif.exe\">\n" + "]>\n" + "<doc attrExtEnt=\"entExt\">\n" + " &ent1;, &ent2;!\n" + "</doc>\n" + "\n" + "<!-- Let world.txt contain \"world\" (excluding the quotes) -->\n"; static string C14NSpecExample5Output = "<doc attrExtEnt=\"entExt\">\n" + " Hello, world!\n" + "</doc>"; // // Example 6 from C14N spec - UTF-8 Encoding: // http://www.w3.org/TR/xml-c14n#Example-UTF8 // static string C14NSpecExample6Input = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n" + "<doc>&#169;</doc>\n"; static string C14NSpecExample6Output = "<doc>\xC2\xA9</doc>"; [Fact] public void SimpleNamespacePrefixes() { string input = "<a:Action xmlns:a='urn:foo'>http://tempuri.org/IFoo/Echo</a:Action>"; string expected = @"<a:Action xmlns:a=""urn:foo"">http://tempuri.org/IFoo/Echo</a:Action>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(input); XmlDsigC14NTransform t = new XmlDsigC14NTransform(); t.LoadInput(doc); Stream s = t.GetOutput() as Stream; Assert.Equal(new StreamReader(s, Encoding.UTF8).ReadToEnd(), expected); } [Fact] public void OrdinalSortForAttributes() { XmlDsigC14NTransform transform = new XmlDsigC14NTransform(); XmlDocument doc = new XmlDocument(); string xml = "<foo Aa=\"one\" Bb=\"two\" aa=\"three\" bb=\"four\"><bar></bar></foo>"; doc.LoadXml(xml); transform.LoadInput(doc); Stream s = (Stream)transform.GetOutput(); string output = TestHelpers.StreamToString(s, Encoding.UTF8); Assert.Equal(xml, output); } [Fact(Skip = "https://github.com/dotnet/corefx/issues/16780")] public void PrefixlessNamespaceOutput() { XmlDocument doc = new XmlDocument(); doc.AppendChild(doc.CreateElement("foo", "urn:foo")); doc.DocumentElement.AppendChild(doc.CreateElement("bar", "urn:bar")); Assert.Equal(string.Empty, doc.DocumentElement.GetAttribute("xmlns")); XmlDsigC14NTransform t = new XmlDsigC14NTransform(); t.LoadInput(doc); Stream s = t.GetOutput() as Stream; Assert.Equal(new StreamReader(s, Encoding.UTF8).ReadToEnd(), "<foo xmlns=\"urn:foo\"><bar xmlns=\"urn:bar\"></bar></foo>"); Assert.Equal("urn:foo", doc.DocumentElement.GetAttribute("xmlns")); } [Fact] public void GetDigestedOutput_Null() { Assert.Throws< NullReferenceException>(() => new XmlDsigExcC14NTransform().GetDigestedOutput(null)); } } }
using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Reflection; using System.Runtime.CompilerServices; using Xamarin.Forms.CustomAttributes; using Xamarin.Forms.Internals; #if UITEST using NUnit.Framework; using Xamarin.UITest; #endif namespace Xamarin.Forms.Controls.TestCasesPages { [Preserve (AllMembers=true)] [Issue (IssueTracker.Bugzilla, 31333, "Focus() on Entry in ViewCell brings up keyboard, but doesn't have cursor in EditText", PlatformAffected.Android)] public class Bugzilla31333 : TestContentPage { [Preserve (AllMembers=true)] public class Model31333 : INotifyPropertyChanged { public string Data { get { return _data; } set { _data = value; OnPropertyChanged (); } } bool _isFocused = false; string _data; public bool IsFocused { get { return _isFocused; } set { _isFocused = value; OnPropertyChanged (); } } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged ([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke (this, new PropertyChangedEventArgs (propertyName)); } } [Preserve (AllMembers=true)] public interface IHaveControlFocusedProperty { void SetBinding (); } [Preserve (AllMembers=true)] public class ExtendedEntry : Entry, IHaveControlFocusedProperty { public static readonly BindableProperty IsControlFocusedProperty = BindableProperty.Create ("IsControlFocused", typeof(bool), typeof(ExtendedEntry), false); public bool IsControlFocused { get { return (bool)GetValue (IsControlFocusedProperty); } set { SetValue (IsControlFocusedProperty, value); } } protected override void OnPropertyChanged (string propertyName = null) { base.OnPropertyChanged (propertyName); if (propertyName == IsControlFocusedProperty.PropertyName) { if (IsControlFocused) { Focus (); } else { Unfocus (); } } } public void SetBinding () { this.SetBinding (IsControlFocusedProperty, "IsFocused"); } } [Preserve (AllMembers=true)] public class ExtendedEditor : Editor, IHaveControlFocusedProperty { public static readonly BindableProperty IsControlFocusedProperty = BindableProperty.Create ("IsControlFocused", typeof(bool), typeof(ExtendedEditor), false); public bool IsControlFocused { get { return (bool)GetValue (IsControlFocusedProperty); } set { SetValue (IsControlFocusedProperty, value); } } protected override void OnPropertyChanged (string propertyName = null) { base.OnPropertyChanged (propertyName); if (propertyName == IsControlFocusedProperty.PropertyName) { if (IsControlFocused) { Focus (); } else { Unfocus (); } } } public void SetBinding () { this.SetBinding (IsControlFocusedProperty, "IsFocused"); } } [Preserve (AllMembers=true)] public class ExtendedCell<T> : ViewCell where T : View, IHaveControlFocusedProperty { public ExtendedCell () { var control = (T)Activator.CreateInstance (typeof(T)); control.SetBinding (); control.HorizontalOptions = LayoutOptions.FillAndExpand; View = new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.StartAndExpand, Children = { control } }; } } StackLayout CreateListViewTestSection (Type controlType) { var name = controlType.GenericTypeArguments[0].Name; name = name.Replace ("Extended", ""); var button = new Button () { Text = $"Focus {name} in ListView" }; var data = new ObservableCollection<Model31333> { new Model31333 () }; var listView = new ListView { VerticalOptions = LayoutOptions.Start, ItemsSource = data, ItemTemplate = new DataTemplate (controlType) }; button.Clicked += (sender, args) => { var item = data[0]; if (item != null) { item.IsFocused = !item.IsFocused; } }; return new StackLayout () { Children = { button, listView } }; } StackLayout CreateTableViewTestSection<T> () where T : View, IHaveControlFocusedProperty { var name = typeof(T).Name; name = name.Replace ("Extended", ""); var button = new Button () { Text = $"Focus {name} in Table" }; var data = new Model31333 (); var tableView = new TableView { VerticalOptions = LayoutOptions.Start }; var tableRoot = new TableRoot(); var tableSection = new TableSection(); var cell = new ExtendedCell<T> (); cell.BindingContext = data; tableSection.Add(cell); tableRoot.Add (tableSection); tableView.Root = tableRoot; button.Clicked += (sender, args) => { var item = data; if (item != null) { item.IsFocused = !item.IsFocused; } }; return new StackLayout () { Children = { button, tableView } }; } protected override void Init () { var entrySection = CreateListViewTestSection (typeof(ExtendedCell<ExtendedEntry>)); var editorSection = CreateListViewTestSection (typeof(ExtendedCell<ExtendedEditor>)); var entryTableSection = CreateTableViewTestSection<ExtendedEntry> (); var editorTableSection = CreateTableViewTestSection<ExtendedEditor> (); Content = new StackLayout () { Children = { entrySection, editorSection, entryTableSection, editorTableSection } }; } #if UITEST [Test] [UiTest (typeof(NavigationPage))] public void Issue31333FocusEntryInListViewCell () { RunningApp.Tap (q => q.Marked ("Focus Entry in ListView")); RunningApp.Screenshot ("Entry control in ListView cell is focused"); RunningApp.EnterText ("Entry in ListView Success"); Assert.True(RunningApp.Query(query => query.Text("Entry in ListView Success")).Length > 0); RunningApp.Screenshot ("Entry in ListView Success"); } [Test] [UiTest (typeof(NavigationPage))] public void Issue31333FocusEditorInListViewCell () { RunningApp.Tap (q => q.Marked ("Focus Editor in ListView")); RunningApp.Screenshot ("Editor control in ListView cell is focused"); RunningApp.EnterText ("Editor in ListView Success"); Assert.True(RunningApp.Query(query => query.Text("Editor in ListView Success")).Length > 0); RunningApp.Screenshot ("Editor in ListView Success"); } [Test] [UiTest (typeof(NavigationPage))] public void Issue31333FocusEntryInTableViewCell () { RunningApp.Tap (q => q.Marked ("Focus Entry in Table")); RunningApp.Screenshot ("Entry control in TableView cell is focused"); RunningApp.EnterText ("Entry in TableView Success"); Assert.True(RunningApp.Query(query => query.Text("Entry in TableView Success")).Length > 0); RunningApp.Screenshot ("Entry in TableView Success"); } [Test] [UiTest (typeof(NavigationPage))] public void Issue31333FocusEditorInTableViewCell () { RunningApp.Tap (q => q.Marked ("Focus Editor in Table")); RunningApp.Screenshot ("Editor control in TableView cell is focused"); RunningApp.EnterText ("Editor in TableView Success"); Assert.True(RunningApp.Query(query => query.Text("Editor in TableView Success")).Length > 0); RunningApp.Screenshot ("Editor in TableView Success"); } #endif } }
/* **************************************************************************** * * 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 * ironpy@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. * * ***************************************************************************/ using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using EnvDTE; using VSLangProj; namespace Microsoft.VisualStudio.Project.Automation { /// <summary> /// Represents an automation friendly version of a language-specific project. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "OAVS")] [ComVisible(true), CLSCompliant(false)] public class OAVSProject : VSProject { #region fields private ProjectNode project; private OAVSProjectEvents events; #endregion #region ctors public OAVSProject(ProjectNode project) { this.project = project; } #endregion #region VSProject Members public virtual ProjectItem AddWebReference(string bstrUrl) { throw new NotImplementedException(); } public virtual BuildManager BuildManager { get { return new OABuildManager(this.project); } } public virtual void CopyProject(string bstrDestFolder, string bstrDestUNCPath, prjCopyProjectOption copyProjectOption, string bstrUsername, string bstrPassword) { throw new NotImplementedException(); } public virtual ProjectItem CreateWebReferencesFolder() { throw new NotImplementedException(); } public virtual DTE DTE { get { return (EnvDTE.DTE)this.project.Site.GetService(typeof(EnvDTE.DTE)); } } public virtual VSProjectEvents Events { get { if(events == null) events = new OAVSProjectEvents(this); return events; } } public virtual void Exec(prjExecCommand command, int bSuppressUI, object varIn, out object pVarOut) { throw new NotImplementedException(); ; } public virtual void GenerateKeyPairFiles(string strPublicPrivateFile, string strPublicOnlyFile) { throw new NotImplementedException(); ; } public virtual string GetUniqueFilename(object pDispatch, string bstrRoot, string bstrDesiredExt) { throw new NotImplementedException(); ; } public virtual Imports Imports { get { throw new NotImplementedException(); } } public virtual EnvDTE.Project Project { get { return this.project.GetAutomationObject() as EnvDTE.Project; } } public virtual References References { get { ReferenceContainerNode references = project.GetReferenceContainer() as ReferenceContainerNode; if(null == references) { return null; } return references.Object as References; } } public virtual void Refresh() { throw new NotImplementedException(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public virtual string TemplatePath { get { throw new NotImplementedException(); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public virtual ProjectItem WebReferencesFolder { get { throw new NotImplementedException(); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public virtual bool WorkOffline { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } #endregion } /// <summary> /// Provides access to language-specific project events /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "OAVS")] [ComVisible(true), CLSCompliant(false)] public class OAVSProjectEvents : VSProjectEvents { #region fields private OAVSProject vsProject; #endregion #region ctors public OAVSProjectEvents(OAVSProject vsProject) { this.vsProject = vsProject; } #endregion #region VSProjectEvents Members public virtual BuildManagerEvents BuildManagerEvents { get { return vsProject.BuildManager as BuildManagerEvents; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public virtual ImportsEvents ImportsEvents { get { throw new NotImplementedException(); } } public virtual ReferencesEvents ReferencesEvents { get { return vsProject.References as ReferencesEvents; } } #endregion } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Apis.CloudNaturalLanguage.v1 { /// <summary>The CloudNaturalLanguage Service.</summary> public class CloudNaturalLanguageService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public CloudNaturalLanguageService() : this(new Google.Apis.Services.BaseClientService.Initializer()) { } /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public CloudNaturalLanguageService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { Documents = new DocumentsResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features => new string[0]; /// <summary>Gets the service name.</summary> public override string Name => "language"; /// <summary>Gets the service base URI.</summary> public override string BaseUri => #if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45 BaseUriOverride ?? "https://language.googleapis.com/"; #else "https://language.googleapis.com/"; #endif /// <summary>Gets the service base path.</summary> public override string BasePath => ""; #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri => "https://language.googleapis.com/batch"; /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath => "batch"; #endif /// <summary>Available OAuth 2.0 scopes for use with the Cloud Natural Language API.</summary> public class Scope { /// <summary>Apply machine learning models to reveal the structure and meaning of text</summary> public static string CloudLanguage = "https://www.googleapis.com/auth/cloud-language"; /// <summary> /// See, edit, configure, and delete your Google Cloud data and see the email address for your Google /// Account. /// </summary> public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; } /// <summary>Available OAuth 2.0 scope constants for use with the Cloud Natural Language API.</summary> public static class ScopeConstants { /// <summary>Apply machine learning models to reveal the structure and meaning of text</summary> public const string CloudLanguage = "https://www.googleapis.com/auth/cloud-language"; /// <summary> /// See, edit, configure, and delete your Google Cloud data and see the email address for your Google /// Account. /// </summary> public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; } /// <summary>Gets the Documents resource.</summary> public virtual DocumentsResource Documents { get; } } /// <summary>A base abstract class for CloudNaturalLanguage requests.</summary> public abstract class CloudNaturalLanguageBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { /// <summary>Constructs a new CloudNaturalLanguageBaseServiceRequest instance.</summary> protected CloudNaturalLanguageBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<XgafvEnum> Xgafv { get; set; } /// <summary>V1 error format.</summary> public enum XgafvEnum { /// <summary>v1 error format</summary> [Google.Apis.Util.StringValueAttribute("1")] Value1 = 0, /// <summary>v2 error format</summary> [Google.Apis.Util.StringValueAttribute("2")] Value2 = 1, } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json = 0, /// <summary>Media download with context-dependent Content-Type</summary> [Google.Apis.Util.StringValueAttribute("media")] Media = 1, /// <summary>Responses with Content-Type of application/x-protobuf</summary> [Google.Apis.Util.StringValueAttribute("proto")] Proto = 2, } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary> /// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required /// unless you provide an OAuth 2.0 token. /// </summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary> /// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a /// user, but should not exceed 40 characters. /// </summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes CloudNaturalLanguage parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "documents" collection of methods.</summary> public class DocumentsResource { private const string Resource = "documents"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public DocumentsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary> /// Finds named entities (currently proper names and common nouns) in the text along with entity types, /// salience, mentions for each entity, and other properties. /// </summary> /// <param name="body">The body of the request.</param> public virtual AnalyzeEntitiesRequest AnalyzeEntities(Google.Apis.CloudNaturalLanguage.v1.Data.AnalyzeEntitiesRequest body) { return new AnalyzeEntitiesRequest(service, body); } /// <summary> /// Finds named entities (currently proper names and common nouns) in the text along with entity types, /// salience, mentions for each entity, and other properties. /// </summary> public class AnalyzeEntitiesRequest : CloudNaturalLanguageBaseServiceRequest<Google.Apis.CloudNaturalLanguage.v1.Data.AnalyzeEntitiesResponse> { /// <summary>Constructs a new AnalyzeEntities request.</summary> public AnalyzeEntitiesRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudNaturalLanguage.v1.Data.AnalyzeEntitiesRequest body) : base(service) { Body = body; InitParameters(); } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudNaturalLanguage.v1.Data.AnalyzeEntitiesRequest Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "analyzeEntities"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/documents:analyzeEntities"; /// <summary>Initializes AnalyzeEntities parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } /// <summary> /// Finds entities, similar to AnalyzeEntities in the text and analyzes sentiment associated with each entity /// and its mentions. /// </summary> /// <param name="body">The body of the request.</param> public virtual AnalyzeEntitySentimentRequest AnalyzeEntitySentiment(Google.Apis.CloudNaturalLanguage.v1.Data.AnalyzeEntitySentimentRequest body) { return new AnalyzeEntitySentimentRequest(service, body); } /// <summary> /// Finds entities, similar to AnalyzeEntities in the text and analyzes sentiment associated with each entity /// and its mentions. /// </summary> public class AnalyzeEntitySentimentRequest : CloudNaturalLanguageBaseServiceRequest<Google.Apis.CloudNaturalLanguage.v1.Data.AnalyzeEntitySentimentResponse> { /// <summary>Constructs a new AnalyzeEntitySentiment request.</summary> public AnalyzeEntitySentimentRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudNaturalLanguage.v1.Data.AnalyzeEntitySentimentRequest body) : base(service) { Body = body; InitParameters(); } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudNaturalLanguage.v1.Data.AnalyzeEntitySentimentRequest Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "analyzeEntitySentiment"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/documents:analyzeEntitySentiment"; /// <summary>Initializes AnalyzeEntitySentiment parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } /// <summary>Analyzes the sentiment of the provided text.</summary> /// <param name="body">The body of the request.</param> public virtual AnalyzeSentimentRequest AnalyzeSentiment(Google.Apis.CloudNaturalLanguage.v1.Data.AnalyzeSentimentRequest body) { return new AnalyzeSentimentRequest(service, body); } /// <summary>Analyzes the sentiment of the provided text.</summary> public class AnalyzeSentimentRequest : CloudNaturalLanguageBaseServiceRequest<Google.Apis.CloudNaturalLanguage.v1.Data.AnalyzeSentimentResponse> { /// <summary>Constructs a new AnalyzeSentiment request.</summary> public AnalyzeSentimentRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudNaturalLanguage.v1.Data.AnalyzeSentimentRequest body) : base(service) { Body = body; InitParameters(); } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudNaturalLanguage.v1.Data.AnalyzeSentimentRequest Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "analyzeSentiment"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/documents:analyzeSentiment"; /// <summary>Initializes AnalyzeSentiment parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } /// <summary> /// Analyzes the syntax of the text and provides sentence boundaries and tokenization along with part of speech /// tags, dependency trees, and other properties. /// </summary> /// <param name="body">The body of the request.</param> public virtual AnalyzeSyntaxRequest AnalyzeSyntax(Google.Apis.CloudNaturalLanguage.v1.Data.AnalyzeSyntaxRequest body) { return new AnalyzeSyntaxRequest(service, body); } /// <summary> /// Analyzes the syntax of the text and provides sentence boundaries and tokenization along with part of speech /// tags, dependency trees, and other properties. /// </summary> public class AnalyzeSyntaxRequest : CloudNaturalLanguageBaseServiceRequest<Google.Apis.CloudNaturalLanguage.v1.Data.AnalyzeSyntaxResponse> { /// <summary>Constructs a new AnalyzeSyntax request.</summary> public AnalyzeSyntaxRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudNaturalLanguage.v1.Data.AnalyzeSyntaxRequest body) : base(service) { Body = body; InitParameters(); } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudNaturalLanguage.v1.Data.AnalyzeSyntaxRequest Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "analyzeSyntax"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/documents:analyzeSyntax"; /// <summary>Initializes AnalyzeSyntax parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } /// <summary> /// A convenience method that provides all the features that analyzeSentiment, analyzeEntities, and /// analyzeSyntax provide in one call. /// </summary> /// <param name="body">The body of the request.</param> public virtual AnnotateTextRequest AnnotateText(Google.Apis.CloudNaturalLanguage.v1.Data.AnnotateTextRequest body) { return new AnnotateTextRequest(service, body); } /// <summary> /// A convenience method that provides all the features that analyzeSentiment, analyzeEntities, and /// analyzeSyntax provide in one call. /// </summary> public class AnnotateTextRequest : CloudNaturalLanguageBaseServiceRequest<Google.Apis.CloudNaturalLanguage.v1.Data.AnnotateTextResponse> { /// <summary>Constructs a new AnnotateText request.</summary> public AnnotateTextRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudNaturalLanguage.v1.Data.AnnotateTextRequest body) : base(service) { Body = body; InitParameters(); } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudNaturalLanguage.v1.Data.AnnotateTextRequest Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "annotateText"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/documents:annotateText"; /// <summary>Initializes AnnotateText parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } /// <summary>Classifies a document into categories.</summary> /// <param name="body">The body of the request.</param> public virtual ClassifyTextRequest ClassifyText(Google.Apis.CloudNaturalLanguage.v1.Data.ClassifyTextRequest body) { return new ClassifyTextRequest(service, body); } /// <summary>Classifies a document into categories.</summary> public class ClassifyTextRequest : CloudNaturalLanguageBaseServiceRequest<Google.Apis.CloudNaturalLanguage.v1.Data.ClassifyTextResponse> { /// <summary>Constructs a new ClassifyText request.</summary> public ClassifyTextRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudNaturalLanguage.v1.Data.ClassifyTextRequest body) : base(service) { Body = body; InitParameters(); } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudNaturalLanguage.v1.Data.ClassifyTextRequest Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "classifyText"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/documents:classifyText"; /// <summary>Initializes ClassifyText parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } } } namespace Google.Apis.CloudNaturalLanguage.v1.Data { /// <summary>The entity analysis request message.</summary> public class AnalyzeEntitiesRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Required. Input document.</summary> [Newtonsoft.Json.JsonPropertyAttribute("document")] public virtual Document Document { get; set; } /// <summary>The encoding type used by the API to calculate offsets.</summary> [Newtonsoft.Json.JsonPropertyAttribute("encodingType")] public virtual string EncodingType { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The entity analysis response message.</summary> public class AnalyzeEntitiesResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The recognized entities in the input document.</summary> [Newtonsoft.Json.JsonPropertyAttribute("entities")] public virtual System.Collections.Generic.IList<Entity> Entities { get; set; } /// <summary> /// The language of the text, which will be the same as the language specified in the request or, if not /// specified, the automatically-detected language. See Document.language field for more details. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("language")] public virtual string Language { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The entity-level sentiment analysis request message.</summary> public class AnalyzeEntitySentimentRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Required. Input document.</summary> [Newtonsoft.Json.JsonPropertyAttribute("document")] public virtual Document Document { get; set; } /// <summary>The encoding type used by the API to calculate offsets.</summary> [Newtonsoft.Json.JsonPropertyAttribute("encodingType")] public virtual string EncodingType { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The entity-level sentiment analysis response message.</summary> public class AnalyzeEntitySentimentResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The recognized entities in the input document with associated sentiments.</summary> [Newtonsoft.Json.JsonPropertyAttribute("entities")] public virtual System.Collections.Generic.IList<Entity> Entities { get; set; } /// <summary> /// The language of the text, which will be the same as the language specified in the request or, if not /// specified, the automatically-detected language. See Document.language field for more details. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("language")] public virtual string Language { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The sentiment analysis request message.</summary> public class AnalyzeSentimentRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Required. Input document.</summary> [Newtonsoft.Json.JsonPropertyAttribute("document")] public virtual Document Document { get; set; } /// <summary>The encoding type used by the API to calculate sentence offsets.</summary> [Newtonsoft.Json.JsonPropertyAttribute("encodingType")] public virtual string EncodingType { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The sentiment analysis response message.</summary> public class AnalyzeSentimentResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The overall sentiment of the input document.</summary> [Newtonsoft.Json.JsonPropertyAttribute("documentSentiment")] public virtual Sentiment DocumentSentiment { get; set; } /// <summary> /// The language of the text, which will be the same as the language specified in the request or, if not /// specified, the automatically-detected language. See Document.language field for more details. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("language")] public virtual string Language { get; set; } /// <summary>The sentiment for all the sentences in the document.</summary> [Newtonsoft.Json.JsonPropertyAttribute("sentences")] public virtual System.Collections.Generic.IList<Sentence> Sentences { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The syntax analysis request message.</summary> public class AnalyzeSyntaxRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Required. Input document.</summary> [Newtonsoft.Json.JsonPropertyAttribute("document")] public virtual Document Document { get; set; } /// <summary>The encoding type used by the API to calculate offsets.</summary> [Newtonsoft.Json.JsonPropertyAttribute("encodingType")] public virtual string EncodingType { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The syntax analysis response message.</summary> public class AnalyzeSyntaxResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// The language of the text, which will be the same as the language specified in the request or, if not /// specified, the automatically-detected language. See Document.language field for more details. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("language")] public virtual string Language { get; set; } /// <summary>Sentences in the input document.</summary> [Newtonsoft.Json.JsonPropertyAttribute("sentences")] public virtual System.Collections.Generic.IList<Sentence> Sentences { get; set; } /// <summary>Tokens, along with their syntactic information, in the input document.</summary> [Newtonsoft.Json.JsonPropertyAttribute("tokens")] public virtual System.Collections.Generic.IList<Token> Tokens { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// The request message for the text annotation API, which can perform multiple analysis types (sentiment, entities, /// and syntax) in one call. /// </summary> public class AnnotateTextRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Required. Input document.</summary> [Newtonsoft.Json.JsonPropertyAttribute("document")] public virtual Document Document { get; set; } /// <summary>The encoding type used by the API to calculate offsets.</summary> [Newtonsoft.Json.JsonPropertyAttribute("encodingType")] public virtual string EncodingType { get; set; } /// <summary>Required. The enabled features.</summary> [Newtonsoft.Json.JsonPropertyAttribute("features")] public virtual Features Features { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The text annotations response message.</summary> public class AnnotateTextResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Categories identified in the input document.</summary> [Newtonsoft.Json.JsonPropertyAttribute("categories")] public virtual System.Collections.Generic.IList<ClassificationCategory> Categories { get; set; } /// <summary> /// The overall sentiment for the document. Populated if the user enables /// AnnotateTextRequest.Features.extract_document_sentiment. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("documentSentiment")] public virtual Sentiment DocumentSentiment { get; set; } /// <summary> /// Entities, along with their semantic information, in the input document. Populated if the user enables /// AnnotateTextRequest.Features.extract_entities. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("entities")] public virtual System.Collections.Generic.IList<Entity> Entities { get; set; } /// <summary> /// The language of the text, which will be the same as the language specified in the request or, if not /// specified, the automatically-detected language. See Document.language field for more details. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("language")] public virtual string Language { get; set; } /// <summary> /// Sentences in the input document. Populated if the user enables AnnotateTextRequest.Features.extract_syntax. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("sentences")] public virtual System.Collections.Generic.IList<Sentence> Sentences { get; set; } /// <summary> /// Tokens, along with their syntactic information, in the input document. Populated if the user enables /// AnnotateTextRequest.Features.extract_syntax. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("tokens")] public virtual System.Collections.Generic.IList<Token> Tokens { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Represents a category returned from the text classifier.</summary> public class ClassificationCategory : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// The classifier's confidence of the category. Number represents how certain the classifier is that this /// category represents the given text. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("confidence")] public virtual System.Nullable<float> Confidence { get; set; } /// <summary> /// The name of the category representing the document, from the [predefined /// taxonomy](https://cloud.google.com/natural-language/docs/categories). /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The document classification request message.</summary> public class ClassifyTextRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Required. Input document.</summary> [Newtonsoft.Json.JsonPropertyAttribute("document")] public virtual Document Document { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The document classification response message.</summary> public class ClassifyTextResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Categories representing the input document.</summary> [Newtonsoft.Json.JsonPropertyAttribute("categories")] public virtual System.Collections.Generic.IList<ClassificationCategory> Categories { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// Represents dependency parse tree information for a token. (For more information on dependency labels, see /// http://www.aclweb.org/anthology/P13-2017 /// </summary> public class DependencyEdge : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Represents the head of this token in the dependency tree. This is the index of the token which has an arc /// going to this token. The index is the position of the token in the array of tokens returned by the API /// method. If this token is a root token, then the `head_token_index` is its own index. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("headTokenIndex")] public virtual System.Nullable<int> HeadTokenIndex { get; set; } /// <summary>The parse label for the token.</summary> [Newtonsoft.Json.JsonPropertyAttribute("label")] public virtual string Label { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// ################################################################ # Represents the input to API methods. /// </summary> public class Document : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// The content of the input in string format. Cloud audit logging exempt since it is based on user data. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("content")] public virtual string Content { get; set; } /// <summary> /// The Google Cloud Storage URI where the file content is located. This URI must be of the form: /// gs://bucket_name/object_name. For more details, see https://cloud.google.com/storage/docs/reference-uris. /// NOTE: Cloud Storage object versioning is not supported. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("gcsContentUri")] public virtual string GcsContentUri { get; set; } /// <summary> /// The language of the document (if not specified, the language is automatically detected). Both ISO and BCP-47 /// language codes are accepted. [Language Support](https://cloud.google.com/natural-language/docs/languages) /// lists currently supported languages for each API method. If the language (either specified by the caller or /// automatically detected) is not supported by the called API method, an `INVALID_ARGUMENT` error is returned. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("language")] public virtual string Language { get; set; } /// <summary> /// Required. If the type is not set or is `TYPE_UNSPECIFIED`, returns an `INVALID_ARGUMENT` error. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("type")] public virtual string Type { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// Represents a phrase in the text that is a known entity, such as a person, an organization, or location. The API /// associates information, such as salience and mentions, with entities. /// </summary> public class Entity : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// The mentions of this entity in the input document. The API currently supports proper noun mentions. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("mentions")] public virtual System.Collections.Generic.IList<EntityMention> Mentions { get; set; } /// <summary> /// Metadata associated with the entity. For most entity types, the metadata is a Wikipedia URL /// (`wikipedia_url`) and Knowledge Graph MID (`mid`), if they are available. For the metadata associated with /// other entity types, see the Type table below. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("metadata")] public virtual System.Collections.Generic.IDictionary<string, string> Metadata { get; set; } /// <summary>The representative name for the entity.</summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary> /// The salience score associated with the entity in the [0, 1.0] range. The salience score for an entity /// provides information about the importance or centrality of that entity to the entire document text. Scores /// closer to 0 are less salient, while scores closer to 1.0 are highly salient. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("salience")] public virtual System.Nullable<float> Salience { get; set; } /// <summary> /// For calls to AnalyzeEntitySentiment or if AnnotateTextRequest.Features.extract_entity_sentiment is set to /// true, this field will contain the aggregate sentiment expressed for this entity in the provided document. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("sentiment")] public virtual Sentiment Sentiment { get; set; } /// <summary>The entity type.</summary> [Newtonsoft.Json.JsonPropertyAttribute("type")] public virtual string Type { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// Represents a mention for an entity in the text. Currently, proper noun mentions are supported. /// </summary> public class EntityMention : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// For calls to AnalyzeEntitySentiment or if AnnotateTextRequest.Features.extract_entity_sentiment is set to /// true, this field will contain the sentiment expressed for this mention of the entity in the provided /// document. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("sentiment")] public virtual Sentiment Sentiment { get; set; } /// <summary>The mention text.</summary> [Newtonsoft.Json.JsonPropertyAttribute("text")] public virtual TextSpan Text { get; set; } /// <summary>The type of the entity mention.</summary> [Newtonsoft.Json.JsonPropertyAttribute("type")] public virtual string Type { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// All available features for sentiment, syntax, and semantic analysis. Setting each one to true will enable that /// specific analysis for the input. /// </summary> public class Features : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Classify the full document into categories.</summary> [Newtonsoft.Json.JsonPropertyAttribute("classifyText")] public virtual System.Nullable<bool> ClassifyText { get; set; } /// <summary>Extract document-level sentiment.</summary> [Newtonsoft.Json.JsonPropertyAttribute("extractDocumentSentiment")] public virtual System.Nullable<bool> ExtractDocumentSentiment { get; set; } /// <summary>Extract entities.</summary> [Newtonsoft.Json.JsonPropertyAttribute("extractEntities")] public virtual System.Nullable<bool> ExtractEntities { get; set; } /// <summary>Extract entities and their associated sentiment.</summary> [Newtonsoft.Json.JsonPropertyAttribute("extractEntitySentiment")] public virtual System.Nullable<bool> ExtractEntitySentiment { get; set; } /// <summary>Extract syntax information.</summary> [Newtonsoft.Json.JsonPropertyAttribute("extractSyntax")] public virtual System.Nullable<bool> ExtractSyntax { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// Represents part of speech information for a token. Parts of speech are as defined in /// http://www.lrec-conf.org/proceedings/lrec2012/pdf/274_Paper.pdf /// </summary> public class PartOfSpeech : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The grammatical aspect.</summary> [Newtonsoft.Json.JsonPropertyAttribute("aspect")] public virtual string Aspect { get; set; } /// <summary>The grammatical case.</summary> [Newtonsoft.Json.JsonPropertyAttribute("case")] public virtual string Case__ { get; set; } /// <summary>The grammatical form.</summary> [Newtonsoft.Json.JsonPropertyAttribute("form")] public virtual string Form { get; set; } /// <summary>The grammatical gender.</summary> [Newtonsoft.Json.JsonPropertyAttribute("gender")] public virtual string Gender { get; set; } /// <summary>The grammatical mood.</summary> [Newtonsoft.Json.JsonPropertyAttribute("mood")] public virtual string Mood { get; set; } /// <summary>The grammatical number.</summary> [Newtonsoft.Json.JsonPropertyAttribute("number")] public virtual string Number { get; set; } /// <summary>The grammatical person.</summary> [Newtonsoft.Json.JsonPropertyAttribute("person")] public virtual string Person { get; set; } /// <summary>The grammatical properness.</summary> [Newtonsoft.Json.JsonPropertyAttribute("proper")] public virtual string Proper { get; set; } /// <summary>The grammatical reciprocity.</summary> [Newtonsoft.Json.JsonPropertyAttribute("reciprocity")] public virtual string Reciprocity { get; set; } /// <summary>The part of speech tag.</summary> [Newtonsoft.Json.JsonPropertyAttribute("tag")] public virtual string Tag { get; set; } /// <summary>The grammatical tense.</summary> [Newtonsoft.Json.JsonPropertyAttribute("tense")] public virtual string Tense { get; set; } /// <summary>The grammatical voice.</summary> [Newtonsoft.Json.JsonPropertyAttribute("voice")] public virtual string Voice { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Represents a sentence in the input document.</summary> public class Sentence : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// For calls to AnalyzeSentiment or if AnnotateTextRequest.Features.extract_document_sentiment is set to true, /// this field will contain the sentiment for the sentence. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("sentiment")] public virtual Sentiment Sentiment { get; set; } /// <summary>The sentence text.</summary> [Newtonsoft.Json.JsonPropertyAttribute("text")] public virtual TextSpan Text { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Represents the feeling associated with the entire text or entities in the text.</summary> public class Sentiment : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// A non-negative number in the [0, +inf) range, which represents the absolute magnitude of sentiment /// regardless of score (positive or negative). /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("magnitude")] public virtual System.Nullable<float> Magnitude { get; set; } /// <summary>Sentiment score between -1.0 (negative sentiment) and 1.0 (positive sentiment).</summary> [Newtonsoft.Json.JsonPropertyAttribute("score")] public virtual System.Nullable<float> Score { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// The `Status` type defines a logical error model that is suitable for different programming environments, /// including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains /// three pieces of data: error code, error message, and error details. You can find out more about this error model /// and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors). /// </summary> public class Status : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The status code, which should be an enum value of google.rpc.Code.</summary> [Newtonsoft.Json.JsonPropertyAttribute("code")] public virtual System.Nullable<int> Code { get; set; } /// <summary> /// A list of messages that carry the error details. There is a common set of message types for APIs to use. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("details")] public virtual System.Collections.Generic.IList<System.Collections.Generic.IDictionary<string, object>> Details { get; set; } /// <summary> /// A developer-facing error message, which should be in English. Any user-facing error message should be /// localized and sent in the google.rpc.Status.details field, or localized by the client. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("message")] public virtual string Message { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Represents an output piece of text.</summary> public class TextSpan : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// The API calculates the beginning offset of the content in the original document according to the /// EncodingType specified in the API request. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("beginOffset")] public virtual System.Nullable<int> BeginOffset { get; set; } /// <summary>The content of the output text.</summary> [Newtonsoft.Json.JsonPropertyAttribute("content")] public virtual string Content { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Represents the smallest syntactic building block of the text.</summary> public class Token : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Dependency tree parse for this token.</summary> [Newtonsoft.Json.JsonPropertyAttribute("dependencyEdge")] public virtual DependencyEdge DependencyEdge { get; set; } /// <summary>[Lemma](https://en.wikipedia.org/wiki/Lemma_%28morphology%29) of the token.</summary> [Newtonsoft.Json.JsonPropertyAttribute("lemma")] public virtual string Lemma { get; set; } /// <summary>Parts of speech tag for this token.</summary> [Newtonsoft.Json.JsonPropertyAttribute("partOfSpeech")] public virtual PartOfSpeech PartOfSpeech { get; set; } /// <summary>The token text.</summary> [Newtonsoft.Json.JsonPropertyAttribute("text")] public virtual TextSpan Text { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
#pragma warning disable 626 using System; using System.Collections.Generic; using FezEngine.Mod; using FezEngine.Structure.Input; using Microsoft.Xna.Framework; namespace FezEngine.Components { public class InputManager { public extern ControllerIndex orig_get_ActiveControllers(); public extern void orig_set_ActiveControllers(ControllerIndex value); public extern FezButtonState orig_get_GrabThrow(); public extern void orig_set_GrabThrow(FezButtonState value); public extern Vector2 orig_get_Movement(); public extern void orig_set_Movement(Vector2 value); public extern Vector2 orig_get_FreeLook(); public extern void orig_set_FreeLook(Vector2 value); public extern FezButtonState orig_get_Jump(); public extern void orig_set_Jump(FezButtonState value); public extern FezButtonState orig_get_Back(); public extern void orig_set_Back(FezButtonState value); public extern FezButtonState orig_get_OpenInventory(); public extern void orig_set_OpenInventory(FezButtonState value); public extern FezButtonState orig_get_Start(); public extern void orig_set_Start(FezButtonState value); public extern FezButtonState orig_get_RotateLeft(); public extern void orig_set_RotateLeft(FezButtonState value); public extern FezButtonState orig_get_RotateRight(); public extern void orig_set_RotateRight(FezButtonState value); public extern FezButtonState orig_get_CancelTalk(); public extern void orig_set_CancelTalk(FezButtonState value); public extern FezButtonState orig_get_Up(); public extern void orig_set_Up(FezButtonState value); public extern FezButtonState orig_get_Down(); public extern void orig_set_Down(FezButtonState value); public extern FezButtonState orig_get_Left(); public extern void orig_set_Left(FezButtonState value); public extern FezButtonState orig_get_Right(); public extern void orig_set_Right(FezButtonState value); public extern FezButtonState orig_get_ClampLook(); public extern void orig_set_ClampLook(FezButtonState value); public extern FezButtonState orig_get_FpsToggle(); public extern void orig_set_FpsToggle(FezButtonState value); public extern FezButtonState orig_get_ExactUp(); public extern void orig_set_ExactUp(FezButtonState value); public extern FezButtonState orig_get_MapZoomIn(); public extern void orig_set_MapZoomIn(FezButtonState value); public extern FezButtonState orig_get_MapZoomOut(); public extern void orig_set_MapZoomOut(FezButtonState value); public ControllerIndex ActiveControllers { get { if (FakeInputHelper.get_ActiveControllers != null) { return FakeInputHelper.get_ActiveControllers(); } return orig_get_ActiveControllers(); } private set { if (FakeInputHelper.set_ActiveControllers != null) { FakeInputHelper.set_ActiveControllers(value); return; } orig_set_ActiveControllers(value); } } public FezButtonState GrabThrow { get { if (FakeInputHelper.get_GrabThrow != null) { return FakeInputHelper.get_GrabThrow(); } return orig_get_GrabThrow(); } private set { if (FakeInputHelper.set_GrabThrow != null) { FakeInputHelper.set_GrabThrow(value); return; } orig_set_GrabThrow(value); } } public Vector2 Movement { get { if (FakeInputHelper.get_Movement != null) { return FakeInputHelper.get_Movement(); } return orig_get_Movement(); } private set { if (FakeInputHelper.set_Movement != null) { FakeInputHelper.set_Movement(value); return; } orig_set_Movement(value); } } public Vector2 FreeLook { get { if (FakeInputHelper.get_FreeLook != null) { return FakeInputHelper.get_FreeLook(); } return orig_get_FreeLook(); } private set { if (FakeInputHelper.set_FreeLook != null) { FakeInputHelper.set_FreeLook(value); return; } orig_set_FreeLook(value); } } public FezButtonState Jump { get { if (FakeInputHelper.get_Jump != null) { return FakeInputHelper.get_Jump(); } return orig_get_Jump(); } private set { if (FakeInputHelper.set_Jump != null) { FakeInputHelper.set_Jump(value); return; } orig_set_Jump(value); } } public FezButtonState Back { get { if (FakeInputHelper.get_Back != null) { return FakeInputHelper.get_Back(); } return orig_get_Back(); } private set { if (FakeInputHelper.set_Back != null) { FakeInputHelper.set_Back(value); return; } orig_set_Back(value); } } public FezButtonState OpenInventory { get { if (FakeInputHelper.get_OpenInventory != null) { return FakeInputHelper.get_OpenInventory(); } return orig_get_OpenInventory(); } private set { if (FakeInputHelper.set_OpenInventory != null) { FakeInputHelper.set_OpenInventory(value); return; } orig_set_OpenInventory(value); } } public FezButtonState Start { get { if (FakeInputHelper.get_Start != null) { return FakeInputHelper.get_Start(); } return orig_get_Start(); } private set { if (FakeInputHelper.set_Start != null) { FakeInputHelper.set_Start(value); return; } orig_set_Start(value); } } public FezButtonState RotateLeft { get { if (FakeInputHelper.get_RotateLeft != null) { return FakeInputHelper.get_RotateLeft(); } return orig_get_RotateLeft(); } private set { if (FakeInputHelper.set_RotateLeft != null) { FakeInputHelper.set_RotateLeft(value); return; } orig_set_RotateLeft(value); } } public FezButtonState RotateRight { get { if (FakeInputHelper.get_RotateRight != null) { return FakeInputHelper.get_RotateRight(); } return orig_get_RotateRight(); } private set { if (FakeInputHelper.set_RotateRight != null) { FakeInputHelper.set_RotateRight(value); return; } orig_set_RotateRight(value); } } public FezButtonState CancelTalk { get { if (FakeInputHelper.get_CancelTalk != null) { return FakeInputHelper.get_CancelTalk(); } return orig_get_CancelTalk(); } private set { if (FakeInputHelper.set_CancelTalk != null) { FakeInputHelper.set_CancelTalk(value); return; } orig_set_CancelTalk(value); } } public FezButtonState Up { get { if (FakeInputHelper.get_Up != null) { return FakeInputHelper.get_Up(); } return orig_get_Up(); } private set { if (FakeInputHelper.set_Up != null) { FakeInputHelper.set_Up(value); return; } orig_set_Up(value); } } public FezButtonState Down { get { if (FakeInputHelper.get_Down != null) { return FakeInputHelper.get_Down(); } return orig_get_Down(); } private set { if (FakeInputHelper.set_Down != null) { FakeInputHelper.set_Down(value); return; } orig_set_Down(value); } } public FezButtonState Left { get { if (FakeInputHelper.get_Left != null) { return FakeInputHelper.get_Left(); } return orig_get_Left(); } private set { if (FakeInputHelper.set_Left != null) { FakeInputHelper.set_Left(value); return; } orig_set_Left(value); } } public FezButtonState Right { get { if (FakeInputHelper.get_Right != null) { return FakeInputHelper.get_Right(); } return orig_get_Right(); } private set { if (FakeInputHelper.set_Right != null) { FakeInputHelper.set_Right(value); return; } orig_set_Right(value); } } public FezButtonState ClampLook { get { if (FakeInputHelper.get_ClampLook != null) { return FakeInputHelper.get_ClampLook(); } return orig_get_ClampLook(); } private set { if (FakeInputHelper.set_ClampLook != null) { FakeInputHelper.set_ClampLook(value); return; } orig_set_ClampLook(value); } } public FezButtonState FpsToggle { get { if (FakeInputHelper.get_FpsToggle != null) { return FakeInputHelper.get_FpsToggle(); } return orig_get_FpsToggle(); } private set { if (FakeInputHelper.set_FpsToggle != null) { FakeInputHelper.set_FpsToggle(value); return; } orig_set_FpsToggle(value); } } public FezButtonState ExactUp { get { if (FakeInputHelper.get_ExactUp != null) { return FakeInputHelper.get_ExactUp(); } return orig_get_ExactUp(); } private set { if (FakeInputHelper.set_ExactUp != null) { FakeInputHelper.set_ExactUp(value); return; } orig_set_ExactUp(value); } } public FezButtonState MapZoomIn { get { if (FakeInputHelper.get_MapZoomIn != null) { return FakeInputHelper.get_MapZoomIn(); } return orig_get_MapZoomIn(); } private set { if (FakeInputHelper.set_MapZoomIn != null) { FakeInputHelper.set_MapZoomIn(value); return; } orig_set_MapZoomIn(value); } } public FezButtonState MapZoomOut { get { if (FakeInputHelper.get_MapZoomOut != null) { return FakeInputHelper.get_MapZoomOut(); } return orig_get_MapZoomOut(); } private set { if (FakeInputHelper.set_MapZoomOut != null) { FakeInputHelper.set_MapZoomOut(value); return; } orig_set_MapZoomOut(value); } } public extern void orig_Update(GameTime gameTime); public void Update(GameTime gameTime) { FakeInputHelper.Updating = true; orig_Update(gameTime); FakeInputHelper.PreUpdate(gameTime); foreach (KeyValuePair<CodeInputAll, FezButtonState> pair in FakeInputHelper.Overrides) { switch (pair.Key) { case CodeInputAll.Back: Back = pair.Value; break; case CodeInputAll.Start: Start = pair.Value; break; case CodeInputAll.Jump: Jump = pair.Value; break; case CodeInputAll.GrabThrow: GrabThrow = pair.Value; break; case CodeInputAll.CancelTalk: CancelTalk = pair.Value; break; case CodeInputAll.Down: Down = pair.Value; if (pair.Value.IsDown()) { Movement = new Vector2(Movement.X, -1f); } break; case CodeInputAll.Up: ExactUp = Up = pair.Value; if (pair.Value.IsDown()) { Movement = new Vector2(Movement.X, 1f); } break; case CodeInputAll.Left: Left = pair.Value; if (pair.Value.IsDown()) { Movement = new Vector2(-1f, Movement.Y); } break; case CodeInputAll.Right: Right = pair.Value; if (pair.Value.IsDown()) { Movement = new Vector2(1f, Movement.Y); } break; case CodeInputAll.OpenInventory: OpenInventory = pair.Value; break; case CodeInputAll.RotateLeft: RotateLeft = pair.Value; break; case CodeInputAll.RotateRight: RotateRight = pair.Value; break; case CodeInputAll.MapZoomIn: MapZoomIn = pair.Value; break; case CodeInputAll.MapZoomOut: MapZoomOut = pair.Value; break; case CodeInputAll.FpsToggle: FpsToggle = pair.Value; break; case CodeInputAll.ClampLook: ClampLook = pair.Value; break; default: throw new ArgumentOutOfRangeException(); } } FakeInputHelper.PostUpdate(gameTime); FakeInputHelper.Updating = false; } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Collections.ObjectModel; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Management.Automation.Language; using System.Management.Automation.Runspaces; using System.Text.RegularExpressions; using Microsoft.PowerShell.Telemetry.Internal; namespace System.Management.Automation { /// <summary> /// Provides a set of possible completions for given input. /// </summary> public class CommandCompletion { /// <summary> /// Construct the result CompleteInput or TabExpansion2. /// </summary> public CommandCompletion(Collection<CompletionResult> matches, int currentMatchIndex, int replacementIndex, int replacementLength) { this.CompletionMatches = matches; this.CurrentMatchIndex = currentMatchIndex; this.ReplacementIndex = replacementIndex; this.ReplacementLength = replacementLength; } #region Fields and Properties /// <summary> /// Current index in <see cref="CompletionMatches"/>. /// </summary> public int CurrentMatchIndex { get; set; } /// <summary> /// Returns the starting replacement index from the original input. /// </summary> public int ReplacementIndex { get; set; } /// <summary> /// Returns the length of the text to replace from the original input. /// </summary> public int ReplacementLength { get; set; } /// <summary> /// Gets all the completion results. /// </summary> [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public Collection<CompletionResult> CompletionMatches { get; set; } internal static readonly IList<CompletionResult> EmptyCompletionResult = Utils.EmptyArray<CompletionResult>(); private static readonly CommandCompletion s_emptyCommandCompletion = new CommandCompletion( new Collection<CompletionResult>(EmptyCompletionResult), -1, -1, -1); #endregion Fields and Properties #region public methods /// <summary> /// /// </summary> /// <param name="input"></param> /// <param name="cursorIndex"></param> /// <returns></returns> public static Tuple<Ast, Token[], IScriptPosition> MapStringInputToParsedInput(string input, int cursorIndex) { if (cursorIndex > input.Length) { throw PSTraceSource.NewArgumentException("cursorIndex"); } Token[] tokens; ParseError[] errors; var ast = Parser.ParseInput(input, out tokens, out errors); IScriptPosition cursorPosition = ((InternalScriptPosition)ast.Extent.StartScriptPosition).CloneWithNewOffset(cursorIndex); return Tuple.Create<Ast, Token[], IScriptPosition>(ast, tokens, cursorPosition); } /// <summary> /// /// </summary> /// <param name="input">The input to complete</param> /// <param name="cursorIndex">The index of the cursor in the input</param> /// <param name="options">Optional options to configure how completion is performed</param> /// <returns></returns> public static CommandCompletion CompleteInput(string input, int cursorIndex, Hashtable options) { if (input == null) { return s_emptyCommandCompletion; } var parsedInput = MapStringInputToParsedInput(input, cursorIndex); return CompleteInputImpl(parsedInput.Item1, parsedInput.Item2, parsedInput.Item3, options); } /// <summary> /// /// </summary> /// <param name="ast">Ast for pre-parsed input</param> /// <param name="tokens">Tokens for pre-parsed input</param> /// <param name="positionOfCursor"></param> /// <param name="options">Optional options to configure how completion is performed</param> /// <returns></returns> public static CommandCompletion CompleteInput(Ast ast, Token[] tokens, IScriptPosition positionOfCursor, Hashtable options) { if (ast == null) { throw PSTraceSource.NewArgumentNullException("ast"); } if (tokens == null) { throw PSTraceSource.NewArgumentNullException("tokens"); } if (positionOfCursor == null) { throw PSTraceSource.NewArgumentNullException("positionOfCursor"); } return CompleteInputImpl(ast, tokens, positionOfCursor, options); } /// <summary> /// Invokes the script function TabExpansion2. /// For legacy support, TabExpansion2 will indirectly call TabExpansion if it exists. /// </summary> /// <param name="input">The input script to complete</param> /// <param name="cursorIndex">The offset in <paramref name="input"/> where completion is requested</param> /// <param name="options">Optional parameter that specifies configurable options for completion.</param> /// <param name="powershell">The powershell to use to invoke the script function TabExpansion2</param> /// <returns>A collection of completions with the replacement start and length.</returns> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "powershell")] public static CommandCompletion CompleteInput(string input, int cursorIndex, Hashtable options, PowerShell powershell) { if (input == null) { return s_emptyCommandCompletion; } if (cursorIndex > input.Length) { throw PSTraceSource.NewArgumentException("cursorIndex"); } if (powershell == null) { throw PSTraceSource.NewArgumentNullException("powershell"); } // If we are in a debugger stop, let the debugger do the command completion. var debugger = (powershell.Runspace != null) ? powershell.Runspace.Debugger : null; if ((debugger != null) && debugger.InBreakpoint) { return CompleteInputInDebugger(input, cursorIndex, options, debugger); } var remoteRunspace = powershell.Runspace as RemoteRunspace; if (remoteRunspace != null) { // If the runspace is not available to run commands then exit here because nested commands are not // supported on remote runspaces. if (powershell.IsNested || (remoteRunspace.RunspaceAvailability != RunspaceAvailability.Available)) { return s_emptyCommandCompletion; } // If it's in the nested prompt, the powershell instance is created by "PowerShell.Create(RunspaceMode.CurrentRunspace);". // In this case, the powershell._runspace is null but if we try to access the property "Runspace", it will create a new // local runspace - the default local runspace will be abandoned. So we check the powershell.IsChild first to make sure // not to access the property "Runspace" in this case - powershell.isChild will be set to true only in this case. if (!powershell.IsChild) { CheckScriptCallOnRemoteRunspace(remoteRunspace); if (remoteRunspace.GetCapabilities().Equals(Runspaces.RunspaceCapability.Default)) { // Capability: // NamedPipeTransport (0x2) -> If remoteMachine is Threshold or later // SupportsDisconnect (0x1) -> If remoteMachine is Win8 or later // Default (0x0) -> If remoteMachine is Win7 // Remoting to a Win7 machine. Use the legacy tab completion function from V1/V2 int replacementIndex; int replacementLength; powershell.Commands.Clear(); var results = InvokeLegacyTabExpansion(powershell, input, cursorIndex, true, out replacementIndex, out replacementLength); return new CommandCompletion( new Collection<CompletionResult>(results ?? EmptyCompletionResult), -1, replacementIndex, replacementLength); } } } return CallScriptWithStringParameterSet(input, cursorIndex, options, powershell); } /// <summary> /// Invokes the script function TabExpansion2. /// For legacy support, TabExpansion2 will indirectly call TabExpansion if it exists. /// </summary> /// <param name="ast">The ast for pre-parsed input</param> /// <param name="tokens"></param> /// <param name="cursorPosition"></param> /// <param name="options">Optional options to configure how completion is performed</param> /// <param name="powershell">The powershell to use to invoke the script function TabExpansion2</param> /// <returns></returns> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "powershell")] public static CommandCompletion CompleteInput(Ast ast, Token[] tokens, IScriptPosition cursorPosition, Hashtable options, PowerShell powershell) { if (ast == null) { throw PSTraceSource.NewArgumentNullException("ast"); } if (tokens == null) { throw PSTraceSource.NewArgumentNullException("tokens"); } if (cursorPosition == null) { throw PSTraceSource.NewArgumentNullException("cursorPosition"); } if (powershell == null) { throw PSTraceSource.NewArgumentNullException("powershell"); } // If we are in a debugger stop, let the debugger do the command completion. var debugger = (powershell.Runspace != null) ? powershell.Runspace.Debugger : null; if ((debugger != null) && debugger.InBreakpoint) { return CompleteInputInDebugger(ast, tokens, cursorPosition, options, debugger); } var remoteRunspace = powershell.Runspace as RemoteRunspace; if (remoteRunspace != null) { // If the runspace is not available to run commands then exit here because nested commands are not // supported on remote runspaces. if (powershell.IsNested || (remoteRunspace.RunspaceAvailability != RunspaceAvailability.Available)) { return s_emptyCommandCompletion; } if (!powershell.IsChild) { CheckScriptCallOnRemoteRunspace(remoteRunspace); if (remoteRunspace.GetCapabilities().Equals(Runspaces.RunspaceCapability.Default)) { // Capability: // SupportsDisconnect (0x1) -> If remoteMachine is Win8 or later // Default (0x0) -> If remoteMachine is Win7 // Remoting to a Win7 machine. Use the legacy tab completion function from V1/V2 int replacementIndex; int replacementLength; // When call the win7 TabExpansion script, the input should be the single current line powershell.Commands.Clear(); var inputAndCursor = GetInputAndCursorFromAst(cursorPosition); var results = InvokeLegacyTabExpansion(powershell, inputAndCursor.Item1, inputAndCursor.Item2, true, out replacementIndex, out replacementLength); return new CommandCompletion( new Collection<CompletionResult>(results ?? EmptyCompletionResult), -1, replacementIndex + inputAndCursor.Item3, replacementLength); } else { // Call script on a remote win8 machine // when call the win8 TabExpansion2 script, the input should be the whole script text string input = ast.Extent.Text; int cursorIndex = ((InternalScriptPosition)cursorPosition).Offset; return CallScriptWithStringParameterSet(input, cursorIndex, options, powershell); } } } return CallScriptWithAstParameterSet(ast, tokens, cursorPosition, options, powershell); } /// <summary> /// Get the next result, moving forward or backward. Supports wraparound, so if there are any results at all, /// this method will never fail and never return null. /// </summary> /// <param name="forward">True if we should move forward through the list, false if backwards.</param> /// <returns>The next completion result, or null if no results.</returns> public CompletionResult GetNextResult(bool forward) { CompletionResult result = null; var count = CompletionMatches.Count; if (count > 0) { CurrentMatchIndex += forward ? 1 : -1; if (CurrentMatchIndex >= count) { CurrentMatchIndex = 0; } else if (CurrentMatchIndex < 0) { CurrentMatchIndex = count - 1; } result = CompletionMatches[CurrentMatchIndex]; } return result; } #endregion public methods #region Internal methods /// <summary> /// Command completion while in debug break mode. /// </summary> /// <param name="input">The input script to complete.</param> /// <param name="cursorIndex">The offset in <paramref name="input"/> where completion is requested.</param> /// <param name="options">Optional parameter that specifies configurable options for completion.</param> /// <param name="debugger">Current debugger.</param> /// <returns>A collection of completions with the replacement start and length.</returns> internal static CommandCompletion CompleteInputInDebugger(string input, int cursorIndex, Hashtable options, Debugger debugger) { if (input == null) { return s_emptyCommandCompletion; } if (cursorIndex > input.Length) { throw PSTraceSource.NewArgumentException("cursorIndex"); } if (debugger == null) { throw PSTraceSource.NewArgumentNullException("debugger"); } Command cmd = new Command("TabExpansion2"); cmd.Parameters.Add("InputScript", input); cmd.Parameters.Add("CursorColumn", cursorIndex); cmd.Parameters.Add("Options", options); return ProcessCompleteInputCommand(cmd, debugger); } /// <summary> /// Command completion while in debug break mode. /// </summary> /// <param name="ast">The ast for pre-parsed input</param> /// <param name="tokens"></param> /// <param name="cursorPosition"></param> /// <param name="options">Optional options to configure how completion is performed</param> /// <param name="debugger">Current debugger</param> /// <returns>Command completion</returns> internal static CommandCompletion CompleteInputInDebugger(Ast ast, Token[] tokens, IScriptPosition cursorPosition, Hashtable options, Debugger debugger) { if (ast == null) { throw PSTraceSource.NewArgumentNullException("ast"); } if (tokens == null) { throw PSTraceSource.NewArgumentNullException("tokens"); } if (cursorPosition == null) { throw PSTraceSource.NewArgumentNullException("cursorPosition"); } if (debugger == null) { throw PSTraceSource.NewArgumentNullException("debugger"); } // For remote debugging just pass string input. if ((debugger is RemoteDebugger) || debugger.IsPushed) { string input = ast.Extent.Text; int cursorIndex = ((InternalScriptPosition)cursorPosition).Offset; return CompleteInputInDebugger(input, cursorIndex, options, debugger); } Command cmd = new Command("TabExpansion2"); cmd.Parameters.Add("Ast", ast); cmd.Parameters.Add("Tokens", tokens); cmd.Parameters.Add("PositionOfCursor", cursorPosition); cmd.Parameters.Add("Options", options); return ProcessCompleteInputCommand(cmd, debugger); } private static CommandCompletion ProcessCompleteInputCommand( Command cmd, Debugger debugger) { PSCommand command = new PSCommand(cmd); PSDataCollection<PSObject> output = new PSDataCollection<PSObject>(); debugger.ProcessCommand(command, output); if (output.Count == 1) { var commandCompletion = output[0].BaseObject as CommandCompletion; if (commandCompletion != null) { return commandCompletion; } } return s_emptyCommandCompletion; } #endregion #region private methods private static void CheckScriptCallOnRemoteRunspace(RemoteRunspace remoteRunspace) { var remoteRunspaceInternal = remoteRunspace.RunspacePool.RemoteRunspacePoolInternal; if (remoteRunspaceInternal != null) { var transportManager = remoteRunspaceInternal.DataStructureHandler.TransportManager; if (transportManager != null && transportManager.TypeTable == null) { // The remote runspace was created without a TypeTable instance. // The tab completion results cannot be deserialized if the TypeTable is not available throw PSTraceSource.NewInvalidOperationException(TabCompletionStrings.CannotDeserializeTabCompletionResult); } } } private static CommandCompletion CallScriptWithStringParameterSet(string input, int cursorIndex, Hashtable options, PowerShell powershell) { try { powershell.Commands.Clear(); powershell.AddCommand("TabExpansion2") .AddArgument(input) .AddArgument(cursorIndex) .AddArgument(options); var results = powershell.Invoke(); if (results == null) { return s_emptyCommandCompletion; } if (results.Count == 1) { var result = PSObject.Base(results[0]); var commandCompletion = result as CommandCompletion; if (commandCompletion != null) { return commandCompletion; } } } catch (Exception e) { CommandProcessorBase.CheckForSevereException(e); } finally { powershell.Commands.Clear(); } return s_emptyCommandCompletion; } private static CommandCompletion CallScriptWithAstParameterSet(Ast ast, Token[] tokens, IScriptPosition cursorPosition, Hashtable options, PowerShell powershell) { try { powershell.Commands.Clear(); powershell.AddCommand("TabExpansion2") .AddArgument(ast) .AddArgument(tokens) .AddArgument(cursorPosition) .AddArgument(options); var results = powershell.Invoke(); if (results == null) { return s_emptyCommandCompletion; } if (results.Count == 1) { var result = PSObject.Base(results[0]); var commandCompletion = result as CommandCompletion; if (commandCompletion != null) { return commandCompletion; } } } catch (Exception e) { CommandProcessorBase.CheckForSevereException(e); } finally { powershell.Commands.Clear(); } return s_emptyCommandCompletion; } // This is the start of the real implementation of autocomplete/intellisense/tab completion private static CommandCompletion CompleteInputImpl(Ast ast, Token[] tokens, IScriptPosition positionOfCursor, Hashtable options) { var sw = new Stopwatch(); sw.Start(); using (var powershell = PowerShell.Create(RunspaceMode.CurrentRunspace)) { var context = LocalPipeline.GetExecutionContextFromTLS(); bool cleanupModuleAnalysisAppDomain = context.TakeResponsibilityForModuleAnalysisAppDomain(); try { // First, check if a V1/V2 implementation of TabExpansion exists. If so, the user had overridden // the built-in version, so we should continue to use theirs. int replacementIndex = -1; int replacementLength = -1; List<CompletionResult> results = null; if (NeedToInvokeLegacyTabExpansion(powershell)) { var inputAndCursor = GetInputAndCursorFromAst(positionOfCursor); results = InvokeLegacyTabExpansion(powershell, inputAndCursor.Item1, inputAndCursor.Item2, false, out replacementIndex, out replacementLength); replacementIndex += inputAndCursor.Item3; } if (results == null || results.Count == 0) { /* BROKEN code commented out, fix sometime // If we were invoked from TabExpansion2, we want to "remove" TabExpansion2 and anything it calls // from our results. We do this by faking out the session so that TabExpansion2 isn't anywhere to be found. MutableTuple tupleForFrameToSkipPast = null; foreach (var stackEntry in context.Debugger.GetCallStack()) { dynamic stackEntryAsPSObj = PSObject.AsPSObject(stackEntry); if (stackEntryAsPSObj.Command.Equals("TabExpansion2", StringComparison.OrdinalIgnoreCase)) { tupleForFrameToSkipPast = stackEntry.FunctionContext._localsTuple; break; } } SessionStateScope scopeToRestore = null; if (tupleForFrameToSkipPast != null) { // Find this tuple in the scope stack. scopeToRestore = context.EngineSessionState.CurrentScope; var scope = context.EngineSessionState.CurrentScope; while (scope != null && scope.LocalsTuple != tupleForFrameToSkipPast) { scope = scope.Parent; } if (scope != null) { context.EngineSessionState.CurrentScope = scope.Parent; } } try { */ var completionAnalysis = new CompletionAnalysis(ast, tokens, positionOfCursor, options); results = completionAnalysis.GetResults(powershell, out replacementIndex, out replacementLength); /* } finally { if (scopeToRestore != null) { context.EngineSessionState.CurrentScope = scopeToRestore; } } */ } var completionResults = results ?? EmptyCompletionResult; sw.Stop(); TelemetryAPI.ReportTabCompletionTelemetry(sw.ElapsedMilliseconds, completionResults.Count, completionResults.Count > 0 ? completionResults[0].ResultType : CompletionResultType.Text); return new CommandCompletion( new Collection<CompletionResult>(completionResults), -1, replacementIndex, replacementLength); } finally { if (cleanupModuleAnalysisAppDomain) { context.ReleaseResponsibilityForModuleAnalysisAppDomain(); } } } } private static Tuple<string, int, int> GetInputAndCursorFromAst(IScriptPosition cursorPosition) { var line = cursorPosition.Line; var cursor = cursorPosition.ColumnNumber - 1; var adjustment = cursorPosition.Offset - cursor; return Tuple.Create(line.Substring(0, cursor), cursor, adjustment); } private static bool NeedToInvokeLegacyTabExpansion(PowerShell powershell) { var executionContext = powershell.GetContextFromTLS(); // We don't want command discovery to search unloaded modules for TabExpansion. var functionInfo = executionContext.EngineSessionState.GetFunction("TabExpansion"); if (functionInfo != null) return true; var aliasInfo = executionContext.EngineSessionState.GetAlias("TabExpansion"); if (aliasInfo != null) return true; return false; } private static List<CompletionResult> InvokeLegacyTabExpansion(PowerShell powershell, string input, int cursorIndex, bool remoteToWin7, out int replacementIndex, out int replacementLength) { List<CompletionResult> results = null; var legacyInput = (cursorIndex != input.Length) ? input.Substring(0, cursorIndex) : input; char quote; var lastword = LastWordFinder.FindLastWord(legacyInput, out replacementIndex, out quote); replacementLength = legacyInput.Length - replacementIndex; var helper = new CompletionExecutionHelper(powershell); powershell.AddCommand("TabExpansion").AddArgument(legacyInput).AddArgument(lastword); Exception exceptionThrown; var oldResults = helper.ExecuteCurrentPowerShell(out exceptionThrown); if (oldResults != null) { results = new List<CompletionResult>(); foreach (var oldResult in oldResults) { var completionResult = PSObject.Base(oldResult) as CompletionResult; if (completionResult == null) { var oldResultStr = oldResult.ToString(); // Add back the quotes we removed if the result isn't quoted if (quote != '\0') { if (oldResultStr.Length > 2 && oldResultStr[0] != quote) { oldResultStr = quote + oldResultStr + quote; } } completionResult = new CompletionResult(oldResultStr); } results.Add(completionResult); } } if (remoteToWin7 && (results == null || results.Count == 0)) { string quoteStr = quote == '\0' ? string.Empty : quote.ToString(); results = PSv2CompletionCompleter.PSv2GenerateMatchSetOfFiles(helper, lastword, replacementIndex == 0, quoteStr); var cmdletResults = PSv2CompletionCompleter.PSv2GenerateMatchSetOfCmdlets(helper, lastword, quoteStr, replacementIndex == 0); if (cmdletResults != null && cmdletResults.Count > 0) { results.AddRange(cmdletResults); } } return results; } /// <summary> /// PSv2CompletionCompleter implements the algorithm we use to complete cmdlet/file names in PowerShell v2. This class /// exists for legacy purpose only. It is used only in a remote interactive session from Win8 to Win7. V3 and forward /// uses completely different completers. /// </summary> /// /// <remarks> /// The implementation of file name completion is completely different on V2 and V3 for remote scenarios. On PSv3, the /// CompletionResults are generated always on the target machine, and /// </remarks> private static class PSv2CompletionCompleter { private static readonly Regex s_cmdletTabRegex = new Regex(@"^[\w\*\?]+-[\w\*\?]*"); private static readonly char[] s_charsRequiringQuotedString = "`&@'#{}()$,;|<> \t".ToCharArray(); #region "Handle Command" /// <summary> /// Used when remoting from a win8 machine to a win7 machine /// </summary> /// <param name="lastWord"></param> /// <param name="isSnapinSpecified"></param> /// <returns></returns> private static bool PSv2IsCommandLikeCmdlet(string lastWord, out bool isSnapinSpecified) { isSnapinSpecified = false; string[] cmdletParts = lastWord.Split(Utils.Separators.Backslash); if (cmdletParts.Length == 1) { return s_cmdletTabRegex.IsMatch(lastWord); } if (cmdletParts.Length == 2) { isSnapinSpecified = PSSnapInInfo.IsPSSnapinIdValid(cmdletParts[0]); if (isSnapinSpecified) { return s_cmdletTabRegex.IsMatch(cmdletParts[1]); } } return false; } private struct CommandAndName { internal readonly PSObject Command; internal readonly PSSnapinQualifiedName CommandName; internal CommandAndName(PSObject command, PSSnapinQualifiedName commandName) { this.Command = command; this.CommandName = commandName; } } /// <summary> /// Used when remoting from a win8 machine to a win7 machine. Complete command names. /// </summary> /// <param name="helper"></param> /// <param name="lastWord"></param> /// <param name="quote"></param> /// <param name="completingAtStartOfLine"></param> /// <returns></returns> internal static List<CompletionResult> PSv2GenerateMatchSetOfCmdlets(CompletionExecutionHelper helper, string lastWord, string quote, bool completingAtStartOfLine) { var results = new List<CompletionResult>(); bool isSnapinSpecified; if (!PSv2IsCommandLikeCmdlet(lastWord, out isSnapinSpecified)) return results; helper.CurrentPowerShell .AddCommand("Get-Command") .AddParameter("Name", lastWord + "*") .AddCommand("Sort-Object") .AddParameter("Property", "Name"); Exception exceptionThrown; Collection<PSObject> commands = helper.ExecuteCurrentPowerShell(out exceptionThrown); if (commands != null && commands.Count > 0) { // convert the PSObjects into strings CommandAndName[] cmdlets = new CommandAndName[commands.Count]; // if the command causes cmdlets from multiple mshsnapin is returned, // append the mshsnapin name to disambiguate the cmdlets. for (int i = 0; i < commands.Count; ++i) { PSObject command = commands[i]; string cmdletFullName = CmdletInfo.GetFullName(command); cmdlets[i] = new CommandAndName(command, PSSnapinQualifiedName.GetInstance(cmdletFullName)); } if (isSnapinSpecified) { foreach (CommandAndName cmdlet in cmdlets) { AddCommandResult(cmdlet, true, completingAtStartOfLine, quote, results); } } else { PrependSnapInNameForSameCmdletNames(cmdlets, completingAtStartOfLine, quote, results); } } return results; } private static void AddCommandResult(CommandAndName commandAndName, bool useFullName, bool completingAtStartOfLine, string quote, List<CompletionResult> results) { Diagnostics.Assert(results != null, "Caller needs to make sure the result list is not null"); string name = useFullName ? commandAndName.CommandName.FullName : commandAndName.CommandName.ShortName; string quotedFileName = AddQuoteIfNecessary(name, quote, completingAtStartOfLine); var commandType = SafeGetProperty<CommandTypes?>(commandAndName.Command, "CommandType"); if (commandType == null) { return; } string toolTip; string displayName = SafeGetProperty<string>(commandAndName.Command, "Name"); if (commandType.Value == CommandTypes.Cmdlet || commandType.Value == CommandTypes.Application) { toolTip = SafeGetProperty<string>(commandAndName.Command, "Definition"); } else { toolTip = displayName; } results.Add(new CompletionResult(quotedFileName, displayName, CompletionResultType.Command, toolTip)); } private static void PrependSnapInNameForSameCmdletNames(CommandAndName[] cmdlets, bool completingAtStartOfLine, string quote, List<CompletionResult> results) { Diagnostics.Assert(cmdlets != null && cmdlets.Length > 0, "HasMultiplePSSnapIns must be called with a non-empty collection of PSObject"); int i = 0; bool previousMatched = false; while (true) { CommandAndName commandAndName = cmdlets[i]; int lookAhead = i + 1; if (lookAhead >= cmdlets.Length) { AddCommandResult(commandAndName, previousMatched, completingAtStartOfLine, quote, results); break; } CommandAndName nextCommandAndName = cmdlets[lookAhead]; if (string.Compare( commandAndName.CommandName.ShortName, nextCommandAndName.CommandName.ShortName, StringComparison.OrdinalIgnoreCase) == 0) { AddCommandResult(commandAndName, true, completingAtStartOfLine, quote, results); previousMatched = true; } else { AddCommandResult(commandAndName, previousMatched, completingAtStartOfLine, quote, results); previousMatched = false; } i++; } } #endregion "Handle Command" #region "Handle File Names" internal static List<CompletionResult> PSv2GenerateMatchSetOfFiles(CompletionExecutionHelper helper, string lastWord, bool completingAtStartOfLine, string quote) { var results = new List<CompletionResult>(); // lastWord is treated as an PSPath. The match set includes those items that match that // path, namely, the union of: // (S1) the sorted set of items matching the last word // (S2) the sorted set of items matching the last word + * // If the last word contains no wildcard characters, then S1 is the empty set. S1 is always // a subset of S2, but we want to present S1 first, then (S2 - S1) next. The idea is that // if the user typed some wildcard characters, they'd prefer to see those matches before // all of the rest. // Determine if we need to quote the paths we parse lastWord = lastWord ?? string.Empty; bool isLastWordEmpty = String.IsNullOrEmpty(lastWord); bool lastCharIsStar = !isLastWordEmpty && lastWord.EndsWith("*", StringComparison.Ordinal); bool containsGlobChars = WildcardPattern.ContainsWildcardCharacters(lastWord); string wildWord = lastWord + "*"; bool shouldFullyQualifyPaths = PSv2ShouldFullyQualifyPathsPath(helper, lastWord); // NTRAID#Windows Out Of Band Releases-927933-2006/03/13-JeffJon // Need to detect when the path is a provider-direct path and make sure // to remove the provider-qualifer when the resolved path is returned. bool isProviderDirectPath = lastWord.StartsWith(@"\\", StringComparison.Ordinal) || lastWord.StartsWith("//", StringComparison.Ordinal); List<PathItemAndConvertedPath> s1 = null; List<PathItemAndConvertedPath> s2 = null; if (containsGlobChars && !isLastWordEmpty) { s1 = PSv2FindMatches( helper, lastWord, shouldFullyQualifyPaths); } if (!lastCharIsStar) { s2 = PSv2FindMatches( helper, wildWord, shouldFullyQualifyPaths); } IEnumerable<PathItemAndConvertedPath> combinedMatches = CombineMatchSets(s1, s2); if (combinedMatches != null) { foreach (var combinedMatch in combinedMatches) { string combinedMatchPath = WildcardPattern.Escape(combinedMatch.Path); string combinedMatchConvertedPath = WildcardPattern.Escape(combinedMatch.ConvertedPath); string completionText = isProviderDirectPath ? combinedMatchConvertedPath : combinedMatchPath; completionText = AddQuoteIfNecessary(completionText, quote, completingAtStartOfLine); bool? isContainer = SafeGetProperty<bool?>(combinedMatch.Item, "PSIsContainer"); string childName = SafeGetProperty<string>(combinedMatch.Item, "PSChildName"); string toolTip = CompletionExecutionHelper.SafeToString(combinedMatch.ConvertedPath); if (isContainer != null && childName != null && toolTip != null) { CompletionResultType resultType = isContainer.Value ? CompletionResultType.ProviderContainer : CompletionResultType.ProviderItem; results.Add(new CompletionResult(completionText, childName, resultType, toolTip)); } } } return results; } private static string AddQuoteIfNecessary(string completionText, string quote, bool completingAtStartOfLine) { if (completionText.IndexOfAny(s_charsRequiringQuotedString) != -1) { bool needAmpersand = quote.Length == 0 && completingAtStartOfLine; string quoteInUse = quote.Length == 0 ? "'" : quote; completionText = quoteInUse == "'" ? completionText.Replace("'", "''") : completionText; completionText = quoteInUse + completionText + quoteInUse; completionText = needAmpersand ? "& " + completionText : completionText; } else { completionText = quote + completionText + quote; } return completionText; } private static IEnumerable<PathItemAndConvertedPath> CombineMatchSets(List<PathItemAndConvertedPath> s1, List<PathItemAndConvertedPath> s2) { if (s1 == null || s1.Count < 1) { // only s2 contains results; which may be null or empty return s2; } if (s2 == null || s2.Count < 1) { // only s1 contains results return s1; } // s1 and s2 contain results Diagnostics.Assert(s1 != null && s1.Count > 0, "s1 should have results"); Diagnostics.Assert(s2 != null && s2.Count > 0, "if s1 has results, s2 must also"); Diagnostics.Assert(s1.Count <= s2.Count, "s2 should always be larger than s1"); var result = new List<PathItemAndConvertedPath>(); // we need to remove from s2 those items in s1. Since the results from FindMatches will be sorted, // just copy out the unique elements from s2 and s1. We know that every element of S1 will be in S2, // so the result set will be S1 + (S2 - S1), which is the same size as S2. result.AddRange(s1); for (int i = 0, j = 0; i < s2.Count; ++i) { if (j < s1.Count && String.Compare(s2[i].Path, s1[j].Path, StringComparison.CurrentCultureIgnoreCase) == 0) { ++j; continue; } result.Add(s2[i]); } #if DEBUG Diagnostics.Assert(result.Count == s2.Count, "result should be the same size as s2, see the size comment above"); for (int i = 0; i < s1.Count; ++i) { string path = result[i].Path; int j = result.FindLastIndex(item => item.Path == path); Diagnostics.Assert(j == i, "elements of s1 should only come at the start of the results"); } #endif return result; } private static T SafeGetProperty<T>(PSObject psObject, string propertyName) { if (psObject == null) { return default(T); } PSPropertyInfo property = psObject.Properties[propertyName]; if (property == null) { return default(T); } object propertyValue = property.Value; if (propertyValue == null) { return default(T); } T returnValue; if (LanguagePrimitives.TryConvertTo(propertyValue, out returnValue)) { return returnValue; } return default(T); } private static bool PSv2ShouldFullyQualifyPathsPath(CompletionExecutionHelper helper, string lastWord) { // These are special cases, as they represent cases where the user expects to // see the full path. if (lastWord.StartsWith("~", StringComparison.OrdinalIgnoreCase) || lastWord.StartsWith("\\", StringComparison.OrdinalIgnoreCase) || lastWord.StartsWith("/", StringComparison.OrdinalIgnoreCase)) { return true; } helper.CurrentPowerShell .AddCommand("Split-Path") .AddParameter("Path", lastWord) .AddParameter("IsAbsolute", true); bool isAbsolute = helper.ExecuteCommandAndGetResultAsBool(); return isAbsolute; } private struct PathItemAndConvertedPath { internal readonly string Path; internal readonly PSObject Item; internal readonly string ConvertedPath; internal PathItemAndConvertedPath(string path, PSObject item, string convertedPath) { this.Path = path; this.Item = item; this.ConvertedPath = convertedPath; } } private static List<PathItemAndConvertedPath> PSv2FindMatches(CompletionExecutionHelper helper, string path, bool shouldFullyQualifyPaths) { Diagnostics.Assert(!String.IsNullOrEmpty(path), "path should have a value"); var result = new List<PathItemAndConvertedPath>(); Exception exceptionThrown; PowerShell powershell = helper.CurrentPowerShell; // It's OK to use script, since tab completion is useless when the remote Win7 machine is in nolanguage mode if (!shouldFullyQualifyPaths) { powershell.AddScript(String.Format( CultureInfo.InvariantCulture, "& {{ trap {{ continue }} ; resolve-path {0} -Relative -WarningAction SilentlyContinue | %{{,($_,(get-item $_ -WarningAction SilentlyContinue),(convert-path $_ -WarningAction SilentlyContinue))}} }}", path)); } else { powershell.AddScript(String.Format( CultureInfo.InvariantCulture, "& {{ trap {{ continue }} ; resolve-path {0} -WarningAction SilentlyContinue | %{{,($_,(get-item $_ -WarningAction SilentlyContinue),(convert-path $_ -WarningAction SilentlyContinue))}} }}", path)); } Collection<PSObject> paths = helper.ExecuteCurrentPowerShell(out exceptionThrown); if (paths == null || paths.Count == 0) { return null; } foreach (PSObject t in paths) { var pathsArray = t.BaseObject as IList; if (pathsArray != null && pathsArray.Count == 3) { object objectPath = pathsArray[0]; PSObject item = pathsArray[1] as PSObject; object convertedPath = pathsArray[1]; if (objectPath == null || item == null || convertedPath == null) { continue; } result.Add(new PathItemAndConvertedPath( CompletionExecutionHelper.SafeToString(objectPath), item, CompletionExecutionHelper.SafeToString(convertedPath))); } } if (result.Count == 0) { return null; } result.Sort(delegate (PathItemAndConvertedPath x, PathItemAndConvertedPath y) { Diagnostics.Assert(x.Path != null && y.Path != null, "SafeToString always returns a non-null string"); return string.Compare(x.Path, y.Path, StringComparison.CurrentCultureIgnoreCase); }); return result; } #endregion "Handle File Names" } /// <summary> /// LastWordFinder implements the algorithm we use to search for the last word in a line of input taken from the console. /// This class exists for legacy purposes only - V3 and forward uses a slightly different interface. /// </summary> private class LastWordFinder { internal static string FindLastWord(string sentence, out int replacementIndexOut, out char closingQuote) { return (new LastWordFinder(sentence)).FindLastWord(out replacementIndexOut, out closingQuote); } private LastWordFinder(string sentence) { _replacementIndex = 0; Diagnostics.Assert(sentence != null, "need to provide an instance"); _sentence = sentence; } /// <summary> /// Locates the last "word" in a string of text. A word is a conguous sequence of characters that are not /// whitespace, or a contiguous set grouped by single or double quotes. Can be called by at most 1 thread at a time /// per LastWordFinder instance. /// </summary> /// <param name="replacementIndexOut"> /// Receives the character index (from the front of the string) of the starting point of the located word, or 0 if /// the word starts at the beginning of the sentence. /// </param> /// <param name="closingQuote"> /// Receives the quote character that would be needed to end the sentence with a balanced pair of quotes. For /// instance, if sentence is "foo then " is returned, if sentence if "foo" then nothing is resturned, if sentence is /// 'foo then ' is returned, if sentence is 'foo' then nothing is returned. /// </param> /// <returns>The last word located, or the empty string if no word could be found.</returns> private string FindLastWord(out int replacementIndexOut, out char closingQuote) { bool inSingleQuote = false; bool inDoubleQuote = false; ReplacementIndex = 0; for (_sentenceIndex = 0; _sentenceIndex < _sentence.Length; ++_sentenceIndex) { Diagnostics.Assert( (inSingleQuote && !inDoubleQuote) || (inDoubleQuote && !inSingleQuote) || (!inSingleQuote && !inDoubleQuote), "Can't be in both single and double quotes"); char c = _sentence[_sentenceIndex]; // there are 3 possibilities: // 1) a new sequence is starting, // 2) a sequence is ending, or // 3) a sequence is due to end on the next matching quote, end-of-sentence, or whitespace if (c == '\'') { HandleQuote(ref inSingleQuote, ref inDoubleQuote, c); } else if (c == '"') { HandleQuote(ref inDoubleQuote, ref inSingleQuote, c); } else if (c == '`') { Consume(c); if (++_sentenceIndex < _sentence.Length) { Consume(_sentence[_sentenceIndex]); } } else if (IsWhitespace(c)) { if (_sequenceDueToEnd) { // we skipped a quote earlier, now end that sequence _sequenceDueToEnd = false; if (inSingleQuote) { inSingleQuote = false; } if (inDoubleQuote) { inDoubleQuote = false; } ReplacementIndex = _sentenceIndex + 1; } else if (inSingleQuote || inDoubleQuote) { // a sequence is started and we're in quotes Consume(c); } else { // no sequence is started, so ignore c ReplacementIndex = _sentenceIndex + 1; } } else { // a sequence is started and we're in it Consume(c); } } string result = new string(_wordBuffer, 0, _wordBufferIndex); closingQuote = inSingleQuote ? '\'' : inDoubleQuote ? '"' : '\0'; replacementIndexOut = ReplacementIndex; return result; } private void HandleQuote(ref bool inQuote, ref bool inOppositeQuote, char c) { if (inOppositeQuote) { // a sequence is started, and we're in it. Consume(c); return; } if (inQuote) { if (_sequenceDueToEnd) { // I've ended a sequence and am starting another; don't consume c, update replacementIndex ReplacementIndex = _sentenceIndex + 1; } _sequenceDueToEnd = !_sequenceDueToEnd; } else { // I'm starting a sequence; don't consume c, update replacementIndex inQuote = true; ReplacementIndex = _sentenceIndex; } } private void Consume(char c) { Diagnostics.Assert(_wordBuffer != null, "wordBuffer is not initialized"); Diagnostics.Assert(_wordBufferIndex < _wordBuffer.Length, "wordBufferIndex is out of range"); _wordBuffer[_wordBufferIndex++] = c; } private int ReplacementIndex { get { return _replacementIndex; } set { Diagnostics.Assert(value >= 0 && value < _sentence.Length + 1, "value out of range"); // when we set the replacement index, that means we're also resetting our word buffer. we know wordBuffer // will never be longer than sentence. _wordBuffer = new char[_sentence.Length]; _wordBufferIndex = 0; _replacementIndex = value; } } private static bool IsWhitespace(char c) { return (c == ' ') || (c == '\x0009'); } private readonly string _sentence; private char[] _wordBuffer; private int _wordBufferIndex; private int _replacementIndex; private int _sentenceIndex; private bool _sequenceDueToEnd; } #endregion private methods } }
/* httpcontext-simulator * a simulator used to simulate http context during integration testing * * Copyright (C) Phil Haack * http://code.google.com/p/httpcontext-simulator/ * * 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 HttpSimulator { #region using System; using System.Collections.Specialized; using System.IO; using System.Linq; using System.Text; using System.Web; using System.Web.Hosting; #endregion /// <summary> /// Used to simulate an HttpRequest. /// </summary> public class SimulatedHttpRequest : SimpleWorkerRequest { #region Constants and Fields /// <summary> /// The host. /// </summary> private readonly string host; /// <summary> /// The _physical file path. /// </summary> private readonly string physicalFilePath; /// <summary> /// The port. /// </summary> private readonly int port; /// <summary> /// The verb. /// </summary> private readonly string verb; /// <summary> /// The form variables. /// </summary> private readonly NameValueCollection formVariables = new NameValueCollection(); /// <summary> /// The headers. /// </summary> private readonly NameValueCollection headers = new NameValueCollection(); /// <summary> /// The referer. /// </summary> private Uri referer; #endregion #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="SimulatedHttpRequest" /> class. /// Creates a new <see cref="SimulatedHttpRequest" /> instance. /// </summary> /// <param name="applicationPath">App virtual dir.</param> /// <param name="physicalAppPath">Physical Path to the app.</param> /// <param name="physicalFilePath">Physical Path to the file.</param> /// <param name="page">The Part of the URL after the application.</param> /// <param name="query">Query.</param> /// <param name="output">Output.</param> /// <param name="host">Host.</param> /// <param name="port">Port to request.</param> /// <param name="verb">The HTTP Verb to use.</param> /// <exception cref="System.ArgumentNullException"> /// host;Host cannot be null. /// or /// applicationPath;Can't create a request with a null application path. Try empty string. /// </exception> /// <exception cref="System.ArgumentException">Host cannot be empty.;host</exception> public SimulatedHttpRequest( string applicationPath, string physicalAppPath, string physicalFilePath, string page, string query, TextWriter output, string host, int port, string verb) : base(applicationPath, physicalAppPath, page, query, output) { if (host == null) { throw new ArgumentNullException(nameof(host), "Host cannot be null."); } if (host.Length == 0) { throw new ArgumentException("Host cannot be empty.", nameof(host)); } if (applicationPath == null) { throw new ArgumentNullException( nameof(applicationPath), "Can't create a request with a null application path. Try empty string."); } this.host = host; this.verb = verb; this.port = port; this.physicalFilePath = physicalFilePath; //this.browser = new HttpBrowserCapabilities(); } #endregion #region Public Properties /// <summary> /// Gets the format exception. /// </summary> /// <value> The format exception. </value> public NameValueCollection Form => this.formVariables; /// <summary> /// Gets the headers. /// </summary> /// <value> The headers. </value> public NameValueCollection Headers => this.headers; #endregion #region Public Methods and Operators /// <summary> /// Returns the virtual path to the currently executing server application. /// </summary> /// <returns> /// The virtual path of the current application. /// </returns> public override string GetAppPath() { var appPath = base.GetAppPath(); return appPath; } /// <summary> /// The get app path translated. /// </summary> /// <returns> /// The <see cref="string"/>. /// </returns> public override string GetAppPathTranslated() { var path = base.GetAppPathTranslated(); return path; } /// <summary> /// The get file path translated. /// </summary> /// <returns> /// The <see cref="string"/>. /// </returns> public override string GetFilePathTranslated() { return this.physicalFilePath; } /// <summary> /// Returns the specified member of the request header. /// </summary> /// <returns> /// The HTTP verb returned in the request header. /// </returns> public override string GetHttpVerbName() { return this.verb; } /// <summary> /// The get known request header. /// </summary> /// <param name="index"> /// The index. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> public override string GetKnownRequestHeader(int index) { switch (index) { case 0x24: return this.referer == null ? string.Empty : this.referer.ToString(); case 12 when this.verb == "POST": return "application/x-www-form-urlencoded"; default: return base.GetKnownRequestHeader(index); } } /// <summary> /// The get local port. /// </summary> /// <returns> /// The get local port. /// </returns> public override int GetLocalPort() { return this.port; } /// <summary> /// Reads request data from the client (when not preloaded). /// </summary> /// <returns> /// The number of bytes read. /// </returns> public override byte[] GetPreloadedEntityBody() { var formText = this.formVariables.Keys.Cast<string>().Aggregate( string.Empty, (current, key) => $"{current}{key}={this.formVariables[key]}&"); return Encoding.UTF8.GetBytes(formText); } /// <summary> /// Gets the name of the server. /// </summary> /// <returns> /// The get server name. /// </returns> public override string GetServerName() { return this.host; } /// <summary> /// Get all nonstandard HTTP header name-value pairs. /// </summary> /// <returns> /// An array of header name-value pairs. /// </returns> public override string[][] GetUnknownRequestHeaders() { if (this.headers == null || this.headers.Count == 0) { return null; } var headersArray = new string[this.headers.Count][]; for (var i = 0; i < this.headers.Count; i++) { headersArray[i] = new string[2]; headersArray[i][0] = this.headers.Keys[i]; headersArray[i][1] = this.headers[i]; } return headersArray; } /// <summary> /// The get uri path. /// </summary> /// <returns> /// The get uri path. /// </returns> public override string GetUriPath() { var uriPath = base.GetUriPath(); return uriPath; } /// <summary> /// Returns a value indicating whether all request data is available and no further reads from the client are required. /// </summary> /// <returns> /// <see langword="true"/> if all request data is available; otherwise, <see langword="false"/> . /// </returns> public override bool IsEntireEntityBodyIsPreloaded() { return true; } #endregion #region Methods /// <summary> /// The set referer. /// </summary> /// <param name="referer"> /// The referer. /// </param> internal void SetReferer(Uri referer) { this.referer = referer; } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Text; using System.Threading; using System.Xml; using Orleans.Providers; namespace Orleans.Runtime.Configuration { /// <summary> /// Orleans client configuration parameters. /// </summary> public class ClientConfiguration : MessagingConfiguration, ITraceConfiguration, IStatisticsConfiguration { /// <summary> /// Specifies the type of the gateway provider. /// </summary> public enum GatewayProviderType { /// <summary>No provider specified</summary> None, /// <summary>use Azure, requires SystemStore element</summary> AzureTable, /// <summary>use SQL, requires SystemStore element</summary> SqlServer, /// <summary>use ZooKeeper, requires SystemStore element</summary> ZooKeeper, /// <summary>use Config based static list, requires Config element(s)</summary> Config, /// <summary>use provider from third-party assembly</summary> Custom } /// <summary> /// The name of this client. /// </summary> public string ClientName { get; set; } = "Client"; private string traceFilePattern; private readonly DateTime creationTimestamp; /// <summary>Gets the configuration source file path</summary> public string SourceFile { get; private set; } /// <summary> /// The list fo the gateways to use. /// Each GatewayNode element specifies an outside grain client gateway node. /// If outside (non-Orleans) clients are to connect to the Orleans system, then at least one gateway node must be specified. /// Additional gateway nodes may be specified if desired, and will add some failure resilience and scalability. /// If multiple gateways are specified, then each client will select one from the list at random. /// </summary> public IList<IPEndPoint> Gateways { get; set; } /// <summary> /// </summary> public int PreferedGatewayIndex { get; set; } /// <summary> /// </summary> public GatewayProviderType GatewayProvider { get; set; } /// <summary> /// Specifies a unique identifier of this deployment. /// If the silos are deployed on Azure (run as workers roles), deployment id is set automatically by Azure runtime, /// accessible to the role via RoleEnvironment.DeploymentId static variable and is passed to the silo automatically by the role via config. /// So if the silos are run as Azure roles this variable should not be specified in the OrleansConfiguration.xml (it will be overwritten if specified). /// If the silos are deployed on the cluster and not as Azure roles, this variable should be set by a deployment script in the OrleansConfiguration.xml file. /// </summary> public string DeploymentId { get; set; } /// <summary> /// Specifies the connection string for the gateway provider. /// If the silos are deployed on Azure (run as workers roles), DataConnectionString may be specified via RoleEnvironment.GetConfigurationSettingValue("DataConnectionString"); /// In such a case it is taken from there and passed to the silo automatically by the role via config. /// So if the silos are run as Azure roles and this config is specified via RoleEnvironment, /// this variable should not be specified in the OrleansConfiguration.xml (it will be overwritten if specified). /// If the silos are deployed on the cluster and not as Azure roles, this variable should be set in the OrleansConfiguration.xml file. /// If not set at all, DevelopmentStorageAccount will be used. /// </summary> public string DataConnectionString { get; set; } /// <summary> /// When using ADO, identifies the underlying data provider for the gateway provider. This three-part naming syntax is also used when creating a new factory /// and for identifying the provider in an application configuration file so that the provider name, along with its associated /// connection string, can be retrieved at run time. https://msdn.microsoft.com/en-us/library/dd0w4a2z%28v=vs.110%29.aspx /// </summary> public string AdoInvariant { get; set; } public string CustomGatewayProviderAssemblyName { get; set; } /// <inheritdoc /> public Severity DefaultTraceLevel { get; set; } /// <inheritdoc /> public IList<Tuple<string, Severity>> TraceLevelOverrides { get; private set; } /// <inheritdoc /> public bool TraceToConsole { get; set; } /// <inheritdoc /> public int LargeMessageWarningThreshold { get; set; } /// <inheritdoc /> public bool PropagateActivityId { get; set; } /// <inheritdoc /> public int BulkMessageLimit { get; set; } /// <summary> /// </summary> public AddressFamily PreferredFamily { get; set; } /// <summary> /// The Interface attribute specifies the name of the network interface to use to work out an IP address for this machine. /// </summary> public string NetInterface { get; private set; } /// <summary> /// The Port attribute specifies the specific listen port for this client machine. /// If value is zero, then a random machine-assigned port number will be used. /// </summary> public int Port { get; private set; } /// <summary>Gets the true host name, no IP address. It equals Dns.GetHostName()</summary> public string DNSHostName { get; private set; } /// <summary> /// </summary> public TimeSpan GatewayListRefreshPeriod { get; set; } public string StatisticsProviderName { get; set; } public TimeSpan StatisticsMetricsTableWriteInterval { get; set; } public TimeSpan StatisticsPerfCountersWriteInterval { get; set; } public TimeSpan StatisticsLogWriteInterval { get; set; } public bool StatisticsWriteLogStatisticsToTable { get; set; } public StatisticsLevel StatisticsCollectionLevel { get; set; } public LimitManager LimitManager { get; private set; } private static readonly TimeSpan DEFAULT_GATEWAY_LIST_REFRESH_PERIOD = TimeSpan.FromMinutes(1); private static readonly TimeSpan DEFAULT_STATS_METRICS_TABLE_WRITE_PERIOD = TimeSpan.FromSeconds(30); private static readonly TimeSpan DEFAULT_STATS_PERF_COUNTERS_WRITE_PERIOD = Constants.INFINITE_TIMESPAN; private static readonly TimeSpan DEFAULT_STATS_LOG_WRITE_PERIOD = TimeSpan.FromMinutes(5); /// <summary> /// </summary> public bool UseAzureSystemStore { get { return GatewayProvider == GatewayProviderType.AzureTable && !String.IsNullOrWhiteSpace(DeploymentId) && !String.IsNullOrWhiteSpace(DataConnectionString); } } /// <summary> /// </summary> public bool UseSqlSystemStore { get { return GatewayProvider == GatewayProviderType.SqlServer && !String.IsNullOrWhiteSpace(DeploymentId) && !String.IsNullOrWhiteSpace(DataConnectionString); } } private bool HasStaticGateways { get { return Gateways != null && Gateways.Count > 0; } } /// <summary> /// </summary> public IDictionary<string, ProviderCategoryConfiguration> ProviderConfigurations { get; set; } /// <inheritdoc /> public string TraceFilePattern { get { return traceFilePattern; } set { traceFilePattern = value; ConfigUtilities.SetTraceFileName(this, ClientName, this.creationTimestamp); } } /// <inheritdoc /> public string TraceFileName { get; set; } /// <summary>Initializes a new instance of <see cref="ClientConfiguration"/>.</summary> public ClientConfiguration() : base(false) { creationTimestamp = DateTime.UtcNow; SourceFile = null; PreferedGatewayIndex = -1; Gateways = new List<IPEndPoint>(); GatewayProvider = GatewayProviderType.None; PreferredFamily = AddressFamily.InterNetwork; NetInterface = null; Port = 0; DNSHostName = Dns.GetHostName(); DeploymentId = ""; DataConnectionString = ""; // Assume the ado invariant is for sql server storage if not explicitly specified AdoInvariant = Constants.INVARIANT_NAME_SQL_SERVER; DefaultTraceLevel = Severity.Info; TraceLevelOverrides = new List<Tuple<string, Severity>>(); TraceToConsole = ConsoleText.IsConsoleAvailable; TraceFilePattern = "{0}-{1}.log"; LargeMessageWarningThreshold = Constants.LARGE_OBJECT_HEAP_THRESHOLD; PropagateActivityId = Constants.DEFAULT_PROPAGATE_E2E_ACTIVITY_ID; BulkMessageLimit = Constants.DEFAULT_LOGGER_BULK_MESSAGE_LIMIT; GatewayListRefreshPeriod = DEFAULT_GATEWAY_LIST_REFRESH_PERIOD; StatisticsProviderName = null; StatisticsMetricsTableWriteInterval = DEFAULT_STATS_METRICS_TABLE_WRITE_PERIOD; StatisticsPerfCountersWriteInterval = DEFAULT_STATS_PERF_COUNTERS_WRITE_PERIOD; StatisticsLogWriteInterval = DEFAULT_STATS_LOG_WRITE_PERIOD; StatisticsWriteLogStatisticsToTable = true; StatisticsCollectionLevel = NodeConfiguration.DEFAULT_STATS_COLLECTION_LEVEL; LimitManager = new LimitManager(); ProviderConfigurations = new Dictionary<string, ProviderCategoryConfiguration>(); } public void Load(TextReader input) { var xml = new XmlDocument(); var xmlReader = XmlReader.Create(input); xml.Load(xmlReader); XmlElement root = xml.DocumentElement; LoadFromXml(root); } internal void LoadFromXml(XmlElement root) { foreach (XmlNode node in root.ChildNodes) { var child = node as XmlElement; if (child != null) { switch (child.LocalName) { case "Gateway": Gateways.Add(ConfigUtilities.ParseIPEndPoint(child).GetResult()); if (GatewayProvider == GatewayProviderType.None) { GatewayProvider = GatewayProviderType.Config; } break; case "Azure": // Throw exception with explicit deprecation error message throw new OrleansException( "The Azure element has been deprecated -- use SystemStore element instead."); case "SystemStore": if (child.HasAttribute("SystemStoreType")) { var sst = child.GetAttribute("SystemStoreType"); GatewayProvider = (GatewayProviderType)Enum.Parse(typeof(GatewayProviderType), sst); } if (child.HasAttribute("CustomGatewayProviderAssemblyName")) { CustomGatewayProviderAssemblyName = child.GetAttribute("CustomGatewayProviderAssemblyName"); if (CustomGatewayProviderAssemblyName.EndsWith(".dll")) throw new FormatException("Use fully qualified assembly name for \"CustomGatewayProviderAssemblyName\""); if (GatewayProvider != GatewayProviderType.Custom) throw new FormatException("SystemStoreType should be \"Custom\" when CustomGatewayProviderAssemblyName is specified"); } if (child.HasAttribute("DeploymentId")) { DeploymentId = child.GetAttribute("DeploymentId"); } if (child.HasAttribute(Constants.DATA_CONNECTION_STRING_NAME)) { DataConnectionString = child.GetAttribute(Constants.DATA_CONNECTION_STRING_NAME); if (String.IsNullOrWhiteSpace(DataConnectionString)) { throw new FormatException("SystemStore.DataConnectionString cannot be blank"); } if (GatewayProvider == GatewayProviderType.None) { // Assume the connection string is for Azure storage if not explicitly specified GatewayProvider = GatewayProviderType.AzureTable; } } if (child.HasAttribute(Constants.ADO_INVARIANT_NAME)) { AdoInvariant = child.GetAttribute(Constants.ADO_INVARIANT_NAME); if (String.IsNullOrWhiteSpace(AdoInvariant)) { throw new FormatException("SystemStore.AdoInvariant cannot be blank"); } } break; case "Tracing": ConfigUtilities.ParseTracing(this, child, ClientName); break; case "Statistics": ConfigUtilities.ParseStatistics(this, child, ClientName); break; case "Limits": ConfigUtilities.ParseLimitValues(LimitManager, child, ClientName); break; case "Debug": break; case "Messaging": base.Load(child); break; case "LocalAddress": if (child.HasAttribute("PreferredFamily")) { PreferredFamily = ConfigUtilities.ParseEnum<AddressFamily>(child.GetAttribute("PreferredFamily"), "Invalid address family for the PreferredFamily attribute on the LocalAddress element"); } else { throw new FormatException("Missing PreferredFamily attribute on the LocalAddress element"); } if (child.HasAttribute("Interface")) { NetInterface = child.GetAttribute("Interface"); } if (child.HasAttribute("Port")) { Port = ConfigUtilities.ParseInt(child.GetAttribute("Port"), "Invalid integer value for the Port attribute on the LocalAddress element"); } break; case "Telemetry": ConfigUtilities.ParseTelemetry(child); break; default: if (child.LocalName.EndsWith("Providers", StringComparison.Ordinal)) { var providerCategory = ProviderCategoryConfiguration.Load(child); if (ProviderConfigurations.ContainsKey(providerCategory.Name)) { var existingCategory = ProviderConfigurations[providerCategory.Name]; existingCategory.Merge(providerCategory); } else { ProviderConfigurations.Add(providerCategory.Name, providerCategory); } } break; } } } } /// <summary> /// </summary> public static ClientConfiguration LoadFromFile(string fileName) { if (fileName == null) { return null; } using (TextReader input = File.OpenText(fileName)) { var config = new ClientConfiguration(); config.Load(input); config.SourceFile = fileName; return config; } } /// <summary> /// Registers a given type of <typeparamref name="T"/> where <typeparamref name="T"/> is stream provider /// </summary> /// <typeparam name="T">Non-abstract type which implements <see cref="Orleans.Streams.IStreamProvider"/> stream</typeparam> /// <param name="providerName">Name of the stream provider</param> /// <param name="properties">Properties that will be passed to stream provider upon initialization</param> public void RegisterStreamProvider<T>(string providerName, IDictionary<string, string> properties = null) where T : Orleans.Streams.IStreamProvider { TypeInfo providerTypeInfo = typeof(T).GetTypeInfo(); if (providerTypeInfo.IsAbstract || providerTypeInfo.IsGenericType || !typeof(Orleans.Streams.IStreamProvider).IsAssignableFrom(typeof(T))) throw new ArgumentException("Expected non-generic, non-abstract type which implements IStreamProvider interface", "typeof(T)"); ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.STREAM_PROVIDER_CATEGORY_NAME, providerTypeInfo.FullName, providerName, properties); } /// <summary> /// Registers a given stream provider. /// </summary> /// <param name="providerTypeFullName">Full name of the stream provider type</param> /// <param name="providerName">Name of the stream provider</param> /// <param name="properties">Properties that will be passed to the stream provider upon initialization </param> public void RegisterStreamProvider(string providerTypeFullName, string providerName, IDictionary<string, string> properties = null) { ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.STREAM_PROVIDER_CATEGORY_NAME, providerTypeFullName, providerName, properties); } public void RegisterStatisticsProvider<T>(string providerName, IDictionary<string, string> properties = null) where T : IStatisticsPublisher, IClientMetricsDataPublisher { TypeInfo providerTypeInfo = typeof(T).GetTypeInfo(); if (providerTypeInfo.IsAbstract || providerTypeInfo.IsGenericType || providerTypeInfo.IsGenericType || !( typeof(IStatisticsPublisher).IsAssignableFrom(typeof(T)) && typeof(IClientMetricsDataPublisher).IsAssignableFrom(typeof(T)) )) throw new ArgumentException("Expected non-generic, non-abstract type which implements IStatisticsPublisher, IClientMetricsDataPublisher interface", "typeof(T)"); ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.STATISTICS_PROVIDER_CATEGORY_NAME, providerTypeInfo.FullName, providerName, properties); } public void RegisterStatisticsProvider(string providerTypeFullName, string providerName, IDictionary<string, string> properties = null) { ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.STATISTICS_PROVIDER_CATEGORY_NAME, providerTypeFullName, providerName, properties); } /// <summary> /// Retrieves an existing provider configuration /// </summary> /// <param name="providerTypeFullName">Full name of the stream provider type</param> /// <param name="providerName">Name of the stream provider</param> /// <param name="config">The provider configuration, if exists</param> /// <returns>True if a configuration for this provider already exists, false otherwise.</returns> public bool TryGetProviderConfiguration(string providerTypeFullName, string providerName, out IProviderConfiguration config) { return ProviderConfigurationUtility.TryGetProviderConfiguration(ProviderConfigurations, providerTypeFullName, providerName, out config); } /// <summary> /// Retrieves an enumeration of all currently configured provider configurations. /// </summary> /// <returns>An enumeration of all currently configured provider configurations.</returns> public IEnumerable<IProviderConfiguration> GetAllProviderConfigurations() { return ProviderConfigurationUtility.GetAllProviderConfigurations(ProviderConfigurations); } /// <summary> /// Loads the configuration from the standard paths, looking up the directory hierarchy /// </summary> /// <returns>Client configuration data if a configuration file was found.</returns> /// <exception cref="FileNotFoundException">Thrown if no configuration file could be found in any of the standard locations</exception> public static ClientConfiguration StandardLoad() { var fileName = ConfigUtilities.FindConfigFile(false); // Throws FileNotFoundException return LoadFromFile(fileName); } /// <summary>Returns a detailed human readable string that represents the current configuration. It does not contain every single configuration knob.</summary> public override string ToString() { var sb = new StringBuilder(); sb.AppendLine("Platform version info:").Append(ConfigUtilities.RuntimeVersionInfo()); sb.Append(" Host: ").AppendLine(Dns.GetHostName()); sb.Append(" Processor Count: ").Append(System.Environment.ProcessorCount).AppendLine(); sb.AppendLine("Client Configuration:"); sb.Append(" Config File Name: ").AppendLine(string.IsNullOrEmpty(SourceFile) ? "" : Path.GetFullPath(SourceFile)); sb.Append(" Start time: ").AppendLine(LogFormatter.PrintDate(DateTime.UtcNow)); sb.Append(" Gateway Provider: ").Append(GatewayProvider); if (GatewayProvider == GatewayProviderType.None) { sb.Append(". Gateway Provider that will be used instead: ").Append(GatewayProviderToUse); } sb.AppendLine(); if (Gateways != null && Gateways.Count > 0 ) { sb.AppendFormat(" Gateways[{0}]:", Gateways.Count).AppendLine(); foreach (var endpoint in Gateways) { sb.Append(" ").AppendLine(endpoint.ToString()); } } else { sb.Append(" Gateways: ").AppendLine("Unspecified"); } sb.Append(" Preferred Gateway Index: ").AppendLine(PreferedGatewayIndex.ToString()); if (Gateways != null && PreferedGatewayIndex >= 0 && PreferedGatewayIndex < Gateways.Count) { sb.Append(" Preferred Gateway Address: ").AppendLine(Gateways[PreferedGatewayIndex].ToString()); } sb.Append(" GatewayListRefreshPeriod: ").Append(GatewayListRefreshPeriod).AppendLine(); if (!String.IsNullOrEmpty(DeploymentId) || !String.IsNullOrEmpty(DataConnectionString)) { sb.Append(" Azure:").AppendLine(); sb.Append(" DeploymentId: ").Append(DeploymentId).AppendLine(); string dataConnectionInfo = ConfigUtilities.RedactConnectionStringInfo(DataConnectionString); // Don't print Azure account keys in log files sb.Append(" DataConnectionString: ").Append(dataConnectionInfo).AppendLine(); } if (!string.IsNullOrWhiteSpace(NetInterface)) { sb.Append(" Network Interface: ").AppendLine(NetInterface); } if (Port != 0) { sb.Append(" Network Port: ").Append(Port).AppendLine(); } sb.Append(" Preferred Address Family: ").AppendLine(PreferredFamily.ToString()); sb.Append(" DNS Host Name: ").AppendLine(DNSHostName); sb.Append(" Client Name: ").AppendLine(ClientName); sb.Append(ConfigUtilities.TraceConfigurationToString(this)); sb.Append(ConfigUtilities.IStatisticsConfigurationToString(this)); sb.Append(LimitManager); sb.AppendFormat(base.ToString()); #if !NETSTANDARD sb.Append(" .NET: ").AppendLine(); int workerThreads; int completionPortThreads; ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads); sb.AppendFormat(" .NET thread pool sizes - Min: Worker Threads={0} Completion Port Threads={1}", workerThreads, completionPortThreads).AppendLine(); ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads); sb.AppendFormat(" .NET thread pool sizes - Max: Worker Threads={0} Completion Port Threads={1}", workerThreads, completionPortThreads).AppendLine(); #endif sb.AppendFormat(" Providers:").AppendLine(); sb.Append(ProviderConfigurationUtility.PrintProviderConfigurations(ProviderConfigurations)); return sb.ToString(); } internal GatewayProviderType GatewayProviderToUse { get { // order is important here for establishing defaults. if (GatewayProvider != GatewayProviderType.None) return GatewayProvider; if (UseAzureSystemStore) return GatewayProviderType.AzureTable; return HasStaticGateways ? GatewayProviderType.Config : GatewayProviderType.None; } } internal void CheckGatewayProviderSettings() { switch (GatewayProvider) { case GatewayProviderType.AzureTable: if (!UseAzureSystemStore) throw new ArgumentException("Config specifies Azure based GatewayProviderType, but Azure element is not specified or not complete.", "GatewayProvider"); break; case GatewayProviderType.Config: if (!HasStaticGateways) throw new ArgumentException("Config specifies Config based GatewayProviderType, but Gateway element(s) is/are not specified.", "GatewayProvider"); break; case GatewayProviderType.Custom: if (String.IsNullOrEmpty(CustomGatewayProviderAssemblyName)) throw new ArgumentException("Config specifies Custom GatewayProviderType, but CustomGatewayProviderAssemblyName attribute is not specified", "GatewayProvider"); break; case GatewayProviderType.None: if (!UseAzureSystemStore && !HasStaticGateways) throw new ArgumentException("Config does not specify GatewayProviderType, and also does not have the adequate defaults: no Azure and or Gateway element(s) are specified.","GatewayProvider"); break; case GatewayProviderType.SqlServer: if (!UseSqlSystemStore) throw new ArgumentException("Config specifies SqlServer based GatewayProviderType, but DeploymentId or DataConnectionString are not specified or not complete.", "GatewayProvider"); break; case GatewayProviderType.ZooKeeper: break; } } /// <summary> /// Returns a ClientConfiguration object for connecting to a local silo (for testing). /// </summary> /// <param name="gatewayPort">Client gateway TCP port</param> /// <returns>ClientConfiguration object that can be passed to GrainClient class for initialization</returns> public static ClientConfiguration LocalhostSilo(int gatewayPort = 40000) { var config = new ClientConfiguration {GatewayProvider = GatewayProviderType.Config}; config.Gateways.Add(new IPEndPoint(IPAddress.Loopback, gatewayPort)); return config; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.IO.IsolatedStorage; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows; using rhodes; using rhoruntime; using Windows.Graphics.Display; using Windows.Storage; using Windows.Storage.FileProperties; using Windows.Storage.Pickers; using Windows.Media.Capture; using Windows.Storage.Streams; using Windows.Graphics.Imaging; using Windows.UI.Xaml.Media.Imaging; using Windows.Media.Editing; using Windows.Media.Core; using Windows.Foundation; using Windows.Devices.Enumeration; using Windows.System.Display; namespace rho { namespace CameraImpl { public class Camera : CameraBase { DeviceInformation cameraInformation = null; string cameraType = null; Dictionary<string, string> rhoParameters = new Dictionary<string, string>(); Size resolution; Size maxResolution; bool isFormatJPG = true; List<Size> imageResolutions = new List<Size>(); static Dictionary<string, DeviceInformation> availableCameras = new Dictionary<string, DeviceInformation>(); public static async Task<DeviceInformationCollection> getDevices() { DeviceInformationCollection result = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture); return result; } static public Dictionary<string, DeviceInformation> initCameraIDs() { deb("Finds all video capture devices"); if (availableCameras.Count == 0){ try{ var task = getDevices(); try{task.Start();} catch(Exception e){deb("Task not started: " + e.Message);} try{ if (task.Status == TaskStatus.Running){task.Wait();} } catch (Exception e){deb("Task not waited: " + e.Message);} DeviceInformationCollection devices = task.Result; deb("Trying to find camera from device list, size = " + devices.Count); foreach (var device in devices){ deb("Checking device"); try{ //if (MediaCapture.IsVideoProfileSupported(device.Id)){ if (device.EnclosureLocation.Panel.Equals(Windows.Devices.Enumeration.Panel.Front)){ availableCameras.Add(CAMERA_TYPE_FRONT, device); deb("Camera found: " + CAMERA_TYPE_FRONT); }else if (device.EnclosureLocation.Panel.Equals(Windows.Devices.Enumeration.Panel.Back)){ availableCameras.Add(CAMERA_TYPE_BACK, device); deb("Camera found: " + CAMERA_TYPE_BACK); }else{ deb("Found camera in strange place"); } //} } catch (Exception e){deb(e.Message);} } }catch(Exception e){deb(e.Message);} } return availableCameras; } public Camera(string id) : base(id) { initCameraIDs(); cameraType = id; deb("Creating camera with ID: " + cameraType); try{ cameraInformation = initCameraIDs()[cameraType]; } catch (Exception e) { try{ cameraInformation = initCameraIDs()["back"]; }catch(Exception exception){cameraInformation = null;} } CRhoRuntime.getInstance().logEvent("Camera class -->Constructor"); } #region CameraBase abstract class implimentation /// <summary> /// This is an overloaded method,We set the type of camera type. /// </summary> /// <param name="strID"></param> /// <param name="native"></param> public override void setNativeImpl(string strID, long native) { try{ CRhoRuntime.getInstance().logEvent(" Camera class--> setNativeImpl" + strID); base.setNativeImpl(strID, native); cameraType = strID; cameraInformation = initCameraIDs()[cameraType]; } catch (Exception ex){} try { var mediaInitSettings = new MediaCaptureInitializationSettings { VideoDeviceId = cameraInformation.Id }; IReadOnlyList<MediaCaptureVideoProfile> profiles = MediaCapture.FindAllVideoProfiles(cameraInformation.Id); foreach (MediaCaptureVideoProfile element in profiles){ foreach (MediaCaptureVideoProfileMediaDescription description in element.SupportedRecordMediaDescription){ try{ imageResolutions.Add(new Size(description.Width, description.Height)); } catch (Exception ex){ CRhoRuntime.getInstance().logEvent("Camera class->" + ex.Message); } } } } catch (Exception e) { } } /// <summary> /// Get the kind of Camera (front or Back) facing. /// </summary> /// <param name="oResult"></param> public override void getCameraType(IMethodResult oResult) { CRhoRuntime.getInstance().logEvent("Camera class-> getCameraType"); try{ oResult.set(cameraType); }catch (Exception ex){ CRhoRuntime.getInstance().logEvent("Camera class-> getMaxWidth" + ex.Message); } } /// <summary> /// Get Maximum Width of the Resolution. /// </summary> /// <param name="oResult"></param> public override void getMaxWidth(IMethodResult oResult) { CRhoRuntime.getInstance().logEvent("Camera class--> getMaxWidth"); try{ oResult.set(maxResolution.Width); } catch (Exception ex){ CRhoRuntime.getInstance().logEvent("Camera class-> getMaxWidth" + ex.Message); } } /// <summary> /// Get Maximum Height of the Resolution /// </summary> /// <param name="oResult"></param> public override void getMaxHeight(IMethodResult oResult) { CRhoRuntime.getInstance().logEvent("Camera class--> getMaxHeight"); try{ oResult.set(maxResolution.Height); } catch (Exception ex){ CRhoRuntime.getInstance().logEvent("Camera class->getMaxHeight" + ex.Message); } } /// <summary> /// Get all the Supported Resolution of the specified Camera type. /// </summary> /// <param name="oResult"></param> public override void getSupportedSizeList(IMethodResult oResult) { CRhoRuntime.getInstance().logEvent("Camera class--> Entered getSupportedSizeList"); List<Dictionary<string, string>> RTypes = new List<Dictionary<string, string>>(); foreach (Size size in imageResolutions){ Dictionary<string, string> Store_Resolution = new Dictionary<string, string>(); Store_Resolution.Add("width", size.Width.ToString()); Store_Resolution.Add("height", size.Height.ToString()); RTypes.Add(Store_Resolution); } oResult.set(RTypes); CRhoRuntime.getInstance().logEvent("Camera class--> End getSupportedSizeList"); } /// <summary> /// Get the setted Resolution Width of the Camera Type (Back/Front). /// </summary> /// <param name="oResult"></param> public override void getDesiredWidth(IMethodResult oResult) { CRhoRuntime.getInstance().logEvent("Camera class--> getDesiredWidth"); oResult.set(resolution.Width); } /// <summary> /// Sets the Width from the avaialble Resolution,if not available then sets to the nearest available Resolution. /// </summary> /// <param name="desiredWidth">Width to be setted </param> /// <param name="oResult"></param> public override void setDesiredWidth(int desiredWidth, IMethodResult oResult) { try{ CRhoRuntime.getInstance().logEvent("Camera class--> setDesiredWidth " + desiredWidth); resolution.Width = desiredWidth; } catch (Exception ex){ CRhoRuntime.getInstance().logEvent("Camera class-->setDesiredWidth--> Exception" + ex.ToString()); } } /// <summary> /// Get the setted Resolution Height of the Camera Type (Back/Front). /// </summary> /// <param name="oResult"></param> public override void getDesiredHeight(IMethodResult oResult) { CRhoRuntime.getInstance().logEvent("Camera class--> getDesiredHeight"); oResult.set(resolution.Height); } /// <summary> /// Sets the Height from the avaialble Resolution,if not available then sets to the nearest available Resolution. /// </summary> /// <param name="desiredWidth">Height from the Resolution </param> /// <param name="oResult"></param> public override void setDesiredHeight(int desiredHeight, IMethodResult oResult) { try{ CRhoRuntime.getInstance().logEvent("Camera class--> setDesiredHeight" + desiredHeight); resolution.Height = desiredHeight; }catch (Exception ex){ CRhoRuntime.getInstance().logEvent("Camera class-->setDesiredHeight--> Exception" + ex.ToString()); } } /// <summary> /// Gets the File Name to be used when picture to be saved under CameraRoll. /// </summary> /// <param name="oResult"></param> public override void getFileName(IMethodResult oResult) { CRhoRuntime.getInstance().logEvent("Camera class--> getFileName" + rhoParameters["filename"]); oResult.set(rhoParameters["filename"]); } /// <summary> /// Sets the File Name to be used when picture to be saved under CameraRoll. /// </summary> /// <param name="fileName"></param> /// <param name="oResult"></param> public override void setFileName(string fileName, IMethodResult oResult) { Dictionary<bool, bool> stringnullorempty = new Dictionary<bool, bool>(); stringnullorempty.Add(false, false); try{ bool filenameemptyornull = stringnullorempty[String.IsNullOrEmpty(fileName)]; CRhoRuntime.getInstance().logEvent("Camera class--> setFileName " + fileName); rhoParameters["filename"] = fileName; }catch (Exception ex){ rhoParameters["filename"] = "Img"; } } /// <summary> /// Gets the Compression Format in UWP we support only Jpeg /// </summary> /// <param name="oResult"></param> public override void getCompressionFormat(IMethodResult oResult) { oResult.set(rhoParameters["imageformat"]); } /// <summary> /// Not Supported in UWP /// </summary> /// <param name="compressionFormat"></param> /// <param name="oResult"></param> public override void setCompressionFormat(string compressionFormat, IMethodResult oResult) { //AS UWP does not support any other format apart from jpeg rhoParameters["ImageFormat"] = compressionFormat; } /// <summary> /// get either dataURI(Base64 shall be sent) or image(path of the captured jpeg file). /// </summary> /// <param name="oResult"></param> public override void getOutputFormat(IMethodResult oResult) { // AS UWP does not support any other format apart from jpg oResult.set(isFormatJPG?"jpg":"png"); } /// <summary> /// get either dataURI or image. /// </summary> /// <param name="outputFormat">dataURI(Base64 shall be sent) or image(path of the captured jpeg file) </param> /// <param name="oResult"></param> public override void setOutputFormat(string outputFormat, IMethodResult oResult) { CRhoRuntime.getInstance().logEvent("Camera class->setOutputFormat type"); try { /*string DataURI = Rho_OutputType[outputFormat.ToLower().Trim()]; Rho_OutPutFormat.Clear(); Rho_OutPutFormat.Add("outputformat", outputFormat.ToLower().Trim());*/ if (outputFormat.ToLower().Trim() == "png") { isFormatJPG = false; }else { isFormatJPG = true; } } catch (Exception ex) { CRhoRuntime.getInstance().logEvent("Camera class->invalid setOutputFormat " + outputFormat + " Exception " + ex.ToString()); } } /// <summary> /// Not supported in UWP. /// </summary> /// <param name="oResult"></param> public override void getColorModel(IMethodResult oResult) { // implement this method in C# here } /// <summary> /// Not supported in UWP. /// </summary> /// <param name="colorModel"></param> /// <param name="oResult"></param> public override void setColorModel(string colorModel, IMethodResult oResult) { // implement this method in C# here } /// <summary> /// Not supported in UWP. /// </summary> /// <param name="oResult"></param> public override void getEnableEditing(IMethodResult oResult) { } /// <summary> /// Not supported in UWP. /// </summary> /// <param name="enableEditing"></param> /// <param name="oResult"></param> public override void setEnableEditing(bool enableEditing, IMethodResult oResult) { // implement this method in C# here } /// <summary> /// Get the kind of flash mode setted (On,Off, Auto) /// </summary> /// <param name="oResult"></param> public override void getFlashMode(IMethodResult oResult) { string FlashModeType = FLASH_AUTO; oResult.set(FlashModeType); } /// <summary> /// Set the kind of flash mode (On,Off,Auto). /// </summary> /// <param name="flashMode"></param> /// <param name="oResult"></param> public override void setFlashMode(string flashMode, IMethodResult oResult) { CRhoRuntime.getInstance().logEvent("Camera class--> setFlashMode"); var Rho_FlashMode = flashMode; try { Rho_FlashMode = flashMode.ToLower().Trim(); } catch (Exception ex) { CRhoRuntime.getInstance().logEvent("Camera class->invalid setFlashMode " + ex.ToString()); } } /// <summary> /// Not supported in UWP. /// </summary> /// <param name="oResult"></param> public override void getSaveToDeviceGallery(IMethodResult oResult) { // implement this method in C# here } /// <summary> /// Not supported in UWP. /// </summary> /// <param name="saveToDeviceGallery"></param> /// <param name="oResult"></param> public override void setSaveToDeviceGallery(bool saveToDeviceGallery, IMethodResult oResult) { // implement this method in C# here } /// <summary> /// Not supported in UWP. /// </summary> /// <param name="oResult"></param> public override void getCaptureSound(IMethodResult oResult) { // implement this method in C# here //oResult.set(Rho_StringParameters["captureSound"]); } /// <summary> /// Not supported in UWP. /// </summary> /// <param name="captureSound"></param> /// <param name="oResult"></param> public override void setCaptureSound(string captureSound, IMethodResult oResult) { // implement this method in C# here //Rho_StringParameters["captureSound"] = captureSound; } /// <summary> /// Not supported in UWP. /// </summary> /// <param name="oResult"></param> public override void getPreviewLeft(IMethodResult oResult) { // implement this method in C# here } /// <summary> /// Not supported in UWP. /// </summary> /// <param name="previewLeft"></param> /// <param name="oResult"></param> public override void setPreviewLeft(int previewLeft, IMethodResult oResult) { // implement this method in C# here } /// <summary> /// Not supported in UWP. /// </summary> /// <param name="oResult"></param> public override void getPreviewTop(IMethodResult oResult) { // implement this method in C# here } /// <summary> /// Not supported in UWP. /// </summary> /// <param name="previewTop"></param> /// <param name="oResult"></param> public override void setPreviewTop(int previewTop, IMethodResult oResult) { // implement this method in C# here } /// <summary> /// Not supported in UWP. /// </summary> /// <param name="oResult"></param> public override void getPreviewWidth(IMethodResult oResult) { // implement this method in C# here } /// <summary> /// Not supported in UWP. /// </summary> /// <param name="previewWidth"></param> /// <param name="oResult"></param> public override void setPreviewWidth(int previewWidth, IMethodResult oResult) { // implement this method in C# here } /// <summary> /// Not supported in UWP. /// </summary> /// <param name="oResult"></param> public override void getPreviewHeight(IMethodResult oResult) { // implement this method in C# here } /// <summary> /// Not supported in UWP. /// </summary> /// <param name="previewHeight"></param> /// <param name="oResult"></param> public override void setPreviewHeight(int previewHeight, IMethodResult oResult) { // implement this method in C# here } /// <summary> /// Not supported in UWP. /// </summary> /// <param name="oResult"></param> public override void getUseSystemViewfinder(IMethodResult oResult) { // implement this method in C# here } /// <summary> /// Not supported in UWP. /// </summary> /// <param name="useSystemViewfinder"></param> /// <param name="oResult"></param> public override void setUseSystemViewfinder(bool useSystemViewfinder, IMethodResult oResult) { // implement this method in C# here } public override void getUseRotationBitmapByEXIF(IMethodResult oResult) { // implement this method in C# here } public override void setUseRotationBitmapByEXIF(bool useRotationBitmapByEXIF, IMethodResult oResult) { // implement this method in C# here } /// <summary> /// Not supported in UWP. /// </summary> /// <param name="oResult"></param> public override void getUseRealBitmapResize(IMethodResult oResult) { // implement this method in C# here } /// <summary> /// Not supported in UWP. /// </summary> /// <param name="useSystemViewfinder"></param> /// <param name="oResult"></param> public override void setUseRealBitmapResize(bool useSystemViewfinder, IMethodResult oResult) { // implement this method in C# here } /// <summary> /// Not supported in UWP. /// </summary> /// <param name="oResult"></param> public override void getAimMode(IMethodResult oResult) { // implement this method in C# here } /// <summary> /// Not supported in UWP. /// </summary> /// <param name="aimMode"></param> /// <param name="oResult"></param> public override void setAimMode(string aimMode, IMethodResult oResult) { // implement this method in C# here } /// <summary> /// Not supported in UWP. /// </summary> /// <param name="propertyMap"></param> /// <param name="oResult"></param> public override void showPreview(IReadOnlyDictionary<string, string> propertyMap, IMethodResult oResult) { // implement this method in C# here } /// <summary> /// Not supported in UWP. /// </summary> /// <param name="oResult"></param> public override void hidePreview(IMethodResult oResult) { // implement this method in C# here } /// <summary> /// Not supported in UWP. /// </summary> /// <param name="oResult"></param> public override void capture(IMethodResult oResult) { // implement this method in C# here } private async Task takePicturAsync(IReadOnlyDictionary<string, string> propertyMap, IMethodResult oResult) { Dictionary<string, string> takePictureOutput = new Dictionary<string, string>(); try { CameraCaptureUI captureUI = new CameraCaptureUI(); captureUI.PhotoSettings.Format = isFormatJPG ? CameraCaptureUIPhotoFormat.Jpeg : CameraCaptureUIPhotoFormat.Png; captureUI.PhotoSettings.MaxResolution = CameraCaptureUIMaxPhotoResolution.HighestAvailable; captureUI.PhotoSettings.CroppedAspectRatio = resolution; StorageFile file = await captureUI.CaptureFileAsync(CameraCaptureUIMode.Photo); if (file == null) { takePictureOutput["status"] = STATUS_CANCELLED; Task.Run(() => oResult.set(takePictureOutput)); return; } StorageFolder dbFolder = await StorageFolder.GetFolderFromPathAsync(MainPage.getDBDir().FullName); string fileName = null; try{ var n = DateTime.Now; fileName = "IMG_" + n.Year.ToString() + n.Month.ToString() + n.Day.ToString() + "_" + n.Hour.ToString() + n.Minute.ToString() + n.Second.ToString() + ".jpg"; deb("FileName is: " + fileName); file = await file.CopyAsync(dbFolder, fileName); deb("Image has been taken to file path: " + file.Path); }catch(Exception e){ throw new Exception("Can't create file in db-files"); } Uri imageUri = new Uri(file.Path); deb("Uri has been extracted: " + imageUri); if (propertyMap.ContainsKey("outputFormat")) { if (propertyMap["outputFormat"] == "image"){ deb("outputFormat is image"); takePictureOutput["image_uri"] = imageUri.AbsoluteUri; takePictureOutput["imageUri"] = imageUri.AbsoluteUri; } if (propertyMap["outputFormat"] == "imagePath"){ deb("outputFormat is imagePath"); takePictureOutput["image_uri"] = file.Path; takePictureOutput["imageUri"] = file.Path; } if (propertyMap["outputFormat"] == "dataUri"){ deb("outputFormat is dataUri"); MemoryStream ms1 = new MemoryStream(); (await file.GetThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.PicturesView)).AsStreamForRead().CopyTo(ms1); string strbase64 = System.Convert.ToBase64String(ms1.ToArray()); takePictureOutput["image_uri"] = "data:image/jpeg;base64," + strbase64; takePictureOutput["imageUri"] = "data:image/jpeg;base64," + strbase64; } deb("propertyMap[\"outputFormat\"] complited"); }else { takePictureOutput["image_uri"] = file.Path; takePictureOutput["imageUri"] = file.Path; } deb("Creating image"); var imageFile = await dbFolder.GetFileAsync(fileName); using (IRandomAccessStream stream = await imageFile.OpenAsync(FileAccessMode.Read)) { BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); SoftwareBitmap image = await decoder.GetSoftwareBitmapAsync(); deb("Image created"); takePictureOutput["status"] = STATUS_OK; takePictureOutput["imageHeight"] = image.PixelHeight.ToString(); takePictureOutput["imageWidth"] = image.PixelWidth.ToString(); takePictureOutput["image_height"] = image.PixelHeight.ToString(); takePictureOutput["image_width"] = image.PixelWidth.ToString(); deb("All properties wrote successfully"); } } catch (Exception ex) { deb("Exception: " + ex.Message); CRhoRuntime.getInstance().logEvent("Camera class--> takePicture exception" + ex.ToString()); takePictureOutput["status"] = STATUS_ERROR; takePictureOutput["message"] = ex.Message; takePictureOutput["image_format"] = string.Empty; takePictureOutput["imageFormat"] = string.Empty; } finally { deb("Setting result"); Task.Run(()=>oResult.set(takePictureOutput)); } } /// <summary> /// To show Still Camera, on taking the picture we shall move to previous screen. /// </summary> /// <param name="propertyMap">Contains the arguments set by user.</param> /// <param name="oResult"></param> public override void takePicture(IReadOnlyDictionary<string, string> propertyMap, IMethodResult oResult) { CRhoRuntime.getInstance().logEvent("Camera class--> takePicture"); dispatchInvoke(delegate () { Task task = takePicturAsync(propertyMap, oResult); }); CRhoRuntime.getInstance().logEvent("Camera class--> End takePicture"); } /// <summary> /// Set the default value for the call back parameters /// </summary> private void initializeTakePictureCallBack() { CRhoRuntime.getInstance().logEvent("Camera class-->Initialize_TakePictureCallBack"); /*m_Take_Picture_Output.Clear(); m_Take_Picture_Output.Add("status", "cancel"); m_Take_Picture_Output.Add("imageUri", string.Empty); m_Take_Picture_Output.Add("imageHeight", string.Empty); m_Take_Picture_Output.Add("imageWidth", string.Empty); m_Take_Picture_Output.Add("imageFormat", "jpg"); m_Take_Picture_Output.Add("message", string.Empty); m_Take_Picture_Output.Add("image_uri", string.Empty); m_Take_Picture_Output.Add("image_height", string.Empty); m_Take_Picture_Output.Add("image_width", string.Empty); m_Take_Picture_Output.Add("image_format", "jpg");*/ } /// <summary> /// Stores file in its own virtual drive rho\apps\app /// </summary> /// <param name="file">Stream of file that needs to be saved in the Location.</param> /// <param name="fileName">Name i n which the file needs to be saved</param> /// <param name="StorechoosePictureResult">Callback event</param> /// <param name="choosePicture_output">The path of the image needs to be stored</param> /// <returns>Successll or error</returns> public async Task SaveToLocalFolderAsync(Stream file, string fileName, IMethodResult StoreTakePictureResult, Dictionary<string, string> TakePicture_output) { string FileNameSuffix = "__DTF__"; StorageFolder localFolder = ApplicationData.Current.LocalFolder; string strLocalFolder = CRhoRuntime.getInstance().getRootPath(ApplicationData.Current.LocalFolder.Path.ToString()); string[] strFolders = strLocalFolder.Split(new string[] { ApplicationData.Current.LocalFolder.Path.ToString() }, StringSplitOptions.None); Dictionary<bool, bool> Rho_SubFolder_Pass = new Dictionary<bool, bool>(); Rho_SubFolder_Pass.Add(true, true); try { //bool FIleExists= Rho_SubFolder_Pass[strFolders[1].Contains(localFolder.Path.ToString())]; string[] StrSubFolders = strFolders[0].Split('/'); foreach (string Path in StrSubFolders) { try { bool BlankFolder = Rho_SubFolder_Pass[!string.IsNullOrEmpty(Path)]; var subfolders = await localFolder.GetFoldersAsync(); foreach (StorageFolder appFolder in subfolders) { try { bool status = Rho_SubFolder_Pass[appFolder.Name.Contains(Path)]; localFolder = appFolder; } catch (Exception ex) { } } } catch (Exception ex) { } } } catch (Exception ex) { } string[] picList = Directory.GetFiles(localFolder.Path); try { bool image = Rho_SubFolder_Pass[fileName.Contains(".jpg")]; fileName = fileName.Replace(".jpg", FileNameSuffix + ".jpg"); } catch (Exception ex) { fileName = fileName + FileNameSuffix; } foreach (string DeleteFile in picList) { try { bool fileexist = Rho_SubFolder_Pass[DeleteFile.Contains(FileNameSuffix)]; File.Delete(DeleteFile); } catch (Exception ex) { } } StorageFile storageFile = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); Task<Stream> outputStreamTask = storageFile.OpenStreamForWriteAsync(); Stream outputStream = outputStreamTask.Result; var bitmap = new BitmapImage(); /*bitmap.SetSource(file); var wb = new WriteableBitmap(bitmap); wb.SaveJpeg(outputStream, wb.PixelWidth, wb.PixelHeight, 0, 100); outputStream.Close();*/ TakePicture_output["imageUri"] = "\\" + storageFile.Name; TakePicture_output["image_uri"] = "\\" + storageFile.Name; StoreTakePictureResult.set(TakePicture_output); } #endregion } #region Singleton class /// <summary> /// Singleton class /// </summary> public class CameraSingleton : CameraSingletonBase { /// <summary> /// Initialize DataURI and Image types. /// </summary> public CameraSingleton() : base() { CRhoRuntime.getInstance().logEvent("Camera class-->CameraSingleton"); } /// <summary> /// Get the list of supported Camera /// </summary> /// <param name="oResult"></param> public override void enumerate(IMethodResult oResult) { Camera.deb("Singleton enumeration"); CRhoRuntime.getInstance().logEvent("Camera class-->enumerate"); List<string> availabeCameras = null; try { availabeCameras = Camera.initCameraIDs().Keys.ToList(); }catch(Exception e) { availabeCameras = new List<string>(); } oResult.set(availabeCameras); Camera.deb("Singleton enumeration end"); } /// <summary> /// Get whether the supplied camera type is supported or not. /// </summary> /// <param name="cameraType">type of camera supported (back or front)</param> /// <param name="oResult"></param> public override void getCameraByType(string cameraType, IMethodResult oResult) { CRhoRuntime.getInstance().logEvent("Camera class-->getCameraByType"); oResult.set(Camera.initCameraIDs().ContainsKey(cameraType)); } private static async Task choosePictureAsync(IReadOnlyDictionary<string, string> propertyMap, IMethodResult oResult) { CRhoRuntime.getInstance().logEvent("Camera class-->choosePicture"); Dictionary<string, string> m_choosePicture_output = new Dictionary<string, string>(); try { var picker = new FileOpenPicker(); picker.ViewMode = PickerViewMode.Thumbnail; picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; picker.FileTypeFilter.Add(".jpg"); picker.FileTypeFilter.Add(".jpeg"); picker.FileTypeFilter.Add(".png"); StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read)) { BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream); SoftwareBitmap image = await decoder.GetSoftwareBitmapAsync(); string format = file.FileType; m_choosePicture_output["status"] = CameraBase.STATUS_OK; m_choosePicture_output["imageHeight"] = image.PixelHeight.ToString(); m_choosePicture_output["imageWidth"] = image.PixelWidth.ToString(); m_choosePicture_output["imageFormat"] = format; m_choosePicture_output["imagePath"] = file.Path; m_choosePicture_output["image_height"] = image.PixelHeight.ToString(); m_choosePicture_output["image_width"] = image.PixelWidth.ToString(); m_choosePicture_output["image_format"] = format; m_choosePicture_output["image_path"] = file.Path; Uri imageUri = new Uri(file.Path); m_choosePicture_output["image_uri"] = imageUri.AbsoluteUri; m_choosePicture_output["imageUri"] = imageUri.AbsoluteUri; } } else { m_choosePicture_output.Add("status", CameraBase.STATUS_CANCELLED); } } catch (Exception ex) { m_choosePicture_output = new Dictionary<string, string>(); CRhoRuntime.getInstance().logEvent("Camera class-->choosePicture-->Exception" + ex.ToString()); m_choosePicture_output["status"] = "error"; m_choosePicture_output["message"] = ex.Message; oResult.set(m_choosePicture_output); } finally { Task.Run(() => oResult.set(m_choosePicture_output)); } } /// <summary> /// Choose the Pictures from the shown list. /// </summary> /// <param name="propertyMap">supports only outputformat.</param> /// <param name="oResult"></param> public override void choosePicture(IReadOnlyDictionary<string, string> propertyMap, IMethodResult oResult) { CRhoRuntime.getInstance().logEvent("Camera class--> choosePicture"); dispatchInvoke(delegate () { Task task = choosePictureAsync(propertyMap, oResult); }); CRhoRuntime.getInstance().logEvent("Camera class--> End choosePicture"); } public async Task<string> copyImageToDeviceGalleryAsync(string pathToImage, IMethodResult oResult) { StorageFile file = await StorageFile.GetFileFromPathAsync(pathToImage); var copied = await file.CopyAsync(ApplicationData.Current.LocalFolder); deb("Image has been taken to file path: " + copied.Path); return copied.Path; } public override void copyImageToDeviceGallery(string pathToImage, IMethodResult oResult) { Dictionary<string, string> copyPictureOutput = new Dictionary<string, string>(); try { Task<string> task = copyImageToDeviceGalleryAsync(pathToImage, oResult); try { task.Start(); } catch (Exception ex) { } try { if (task.Status == TaskStatus.Running) {task.Wait(); }} catch (Exception ex) {} string result = task.Result; if (result != null) { copyPictureOutput["status"] = CameraBase.STATUS_OK; copyPictureOutput["pathToImage"] = result; }else{ throw new Exception("Can't copy picture for some reasons"); } } catch (Exception ex) { CRhoRuntime.getInstance().logEvent("Camera class-->copyImageToDeviceGallery-->Exception" + ex.ToString()); copyPictureOutput = new Dictionary<string, string>(); copyPictureOutput["status"] = "error"; copyPictureOutput["message"] = ex.Message; oResult.set(copyPictureOutput); } finally { Task.Run(() => oResult.set(copyPictureOutput)); } } } public class CameraFactory : CameraFactoryBase { } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ApiManagement { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Azure.OData; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// LoggerOperations operations. /// </summary> internal partial class LoggerOperations : IServiceOperations<ApiManagementClient>, ILoggerOperations { /// <summary> /// Initializes a new instance of the LoggerOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal LoggerOperations(ApiManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the ApiManagementClient /// </summary> public ApiManagementClient Client { get; private set; } /// <summary> /// Lists a collection of loggers in the specified service instance. /// <see href="https://docs.microsoft.com/en-us/azure/api-management/api-management-howto-log-event-hubs" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<LoggerContract>>> ListByServiceWithHttpMessagesAsync(string resourceGroupName, string serviceName, ODataQuery<LoggerContract> odataQuery = default(ODataQuery<LoggerContract>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (serviceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "serviceName"); } if (serviceName != null) { if (serviceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "serviceName", 50); } if (serviceName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "serviceName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(serviceName, "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$")) { throw new ValidationException(ValidationRules.Pattern, "serviceName", "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"); } } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByService", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/loggers").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<LoggerContract>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<LoggerContract>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets the details of the logger specified by its identifier. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='loggerid'> /// Logger identifier. Must be unique in the API Management service instance. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<LoggerContract,LoggerGetHeaders>> GetWithHttpMessagesAsync(string resourceGroupName, string serviceName, string loggerid, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (serviceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "serviceName"); } if (serviceName != null) { if (serviceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "serviceName", 50); } if (serviceName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "serviceName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(serviceName, "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$")) { throw new ValidationException(ValidationRules.Pattern, "serviceName", "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"); } } if (loggerid == null) { throw new ValidationException(ValidationRules.CannotBeNull, "loggerid"); } if (loggerid != null) { if (loggerid.Length > 256) { throw new ValidationException(ValidationRules.MaxLength, "loggerid", 256); } if (!System.Text.RegularExpressions.Regex.IsMatch(loggerid, "^[^*#&+:<>?]+$")) { throw new ValidationException(ValidationRules.Pattern, "loggerid", "^[^*#&+:<>?]+$"); } } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("loggerid", loggerid); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/loggers/{loggerid}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName)); _url = _url.Replace("{loggerid}", System.Uri.EscapeDataString(loggerid)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<LoggerContract,LoggerGetHeaders>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<LoggerContract>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<LoggerGetHeaders>(JsonSerializer.Create(Client.DeserializationSettings)); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or Updates a logger. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='loggerid'> /// Logger identifier. Must be unique in the API Management service instance. /// </param> /// <param name='parameters'> /// Create parameters. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<LoggerContract>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serviceName, string loggerid, LoggerContract parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (serviceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "serviceName"); } if (serviceName != null) { if (serviceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "serviceName", 50); } if (serviceName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "serviceName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(serviceName, "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$")) { throw new ValidationException(ValidationRules.Pattern, "serviceName", "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"); } } if (loggerid == null) { throw new ValidationException(ValidationRules.CannotBeNull, "loggerid"); } if (loggerid != null) { if (loggerid.Length > 256) { throw new ValidationException(ValidationRules.MaxLength, "loggerid", 256); } if (!System.Text.RegularExpressions.Regex.IsMatch(loggerid, "^[^*#&+:<>?]+$")) { throw new ValidationException(ValidationRules.Pattern, "loggerid", "^[^*#&+:<>?]+$"); } } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (parameters == null) { parameters = new LoggerContract(); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("loggerid", loggerid); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/loggers/{loggerid}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName)); _url = _url.Replace("{loggerid}", System.Uri.EscapeDataString(loggerid)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201 && (int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<LoggerContract>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<LoggerContract>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<LoggerContract>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Updates an existing logger. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='loggerid'> /// Logger identifier. Must be unique in the API Management service instance. /// </param> /// <param name='parameters'> /// Update parameters. /// </param> /// <param name='ifMatch'> /// The entity state (Etag) version of the logger to update. A value of "*" can /// be used for If-Match to unconditionally apply the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> UpdateWithHttpMessagesAsync(string resourceGroupName, string serviceName, string loggerid, LoggerUpdateContract parameters, string ifMatch, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (serviceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "serviceName"); } if (serviceName != null) { if (serviceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "serviceName", 50); } if (serviceName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "serviceName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(serviceName, "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$")) { throw new ValidationException(ValidationRules.Pattern, "serviceName", "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"); } } if (loggerid == null) { throw new ValidationException(ValidationRules.CannotBeNull, "loggerid"); } if (loggerid != null) { if (loggerid.Length > 256) { throw new ValidationException(ValidationRules.MaxLength, "loggerid", 256); } if (!System.Text.RegularExpressions.Regex.IsMatch(loggerid, "^[^*#&+:<>?]+$")) { throw new ValidationException(ValidationRules.Pattern, "loggerid", "^[^*#&+:<>?]+$"); } } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (ifMatch == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ifMatch"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("loggerid", loggerid); tracingParameters.Add("parameters", parameters); tracingParameters.Add("ifMatch", ifMatch); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/loggers/{loggerid}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName)); _url = _url.Replace("{loggerid}", System.Uri.EscapeDataString(loggerid)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (ifMatch != null) { if (_httpRequest.Headers.Contains("If-Match")) { _httpRequest.Headers.Remove("If-Match"); } _httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes the specified logger. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='loggerid'> /// Logger identifier. Must be unique in the API Management service instance. /// </param> /// <param name='ifMatch'> /// The entity state (Etag) version of the logger to delete. A value of "*" can /// be used for If-Match to unconditionally apply the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string serviceName, string loggerid, string ifMatch, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (serviceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "serviceName"); } if (serviceName != null) { if (serviceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "serviceName", 50); } if (serviceName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "serviceName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(serviceName, "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$")) { throw new ValidationException(ValidationRules.Pattern, "serviceName", "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"); } } if (loggerid == null) { throw new ValidationException(ValidationRules.CannotBeNull, "loggerid"); } if (loggerid != null) { if (loggerid.Length > 256) { throw new ValidationException(ValidationRules.MaxLength, "loggerid", 256); } if (!System.Text.RegularExpressions.Regex.IsMatch(loggerid, "^[^*#&+:<>?]+$")) { throw new ValidationException(ValidationRules.Pattern, "loggerid", "^[^*#&+:<>?]+$"); } } if (ifMatch == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ifMatch"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("loggerid", loggerid); tracingParameters.Add("ifMatch", ifMatch); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/loggers/{loggerid}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName)); _url = _url.Replace("{loggerid}", System.Uri.EscapeDataString(loggerid)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (ifMatch != null) { if (_httpRequest.Headers.Contains("If-Match")) { _httpRequest.Headers.Remove("If-Match"); } _httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists a collection of loggers in the specified service instance. /// <see href="https://docs.microsoft.com/en-us/azure/api-management/api-management-howto-log-event-hubs" /> /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<LoggerContract>>> ListByServiceNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByServiceNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<LoggerContract>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<LoggerContract>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //////////////////////////////////////////////////////////////////////////// // // // Purpose: This class defines behaviors specific to a writing system. // A writing system is the collection of scripts and // orthographic rules required to represent a language as text. // // //////////////////////////////////////////////////////////////////////////// using System; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.Serialization; namespace System.Globalization { [Serializable] public class StringInfo { [OptionalField(VersionAdded = 2)] private string _str; [NonSerialized] private int[] _indexes; // Legacy constructor public StringInfo() : this("") { } // Primary, useful constructor public StringInfo(string value) { this.String = value; } [OnDeserializing] private void OnDeserializing(StreamingContext ctx) { _str = String.Empty; } [OnDeserialized] private void OnDeserialized(StreamingContext ctx) { if (_str.Length == 0) { _indexes = null; } } public override bool Equals(Object value) { StringInfo that = value as StringInfo; if (that != null) { return (_str.Equals(that._str)); } return (false); } public override int GetHashCode() { return _str.GetHashCode(); } // Our zero-based array of index values into the string. Initialize if // our private array is not yet, in fact, initialized. private int[] Indexes { get { if ((null == _indexes) && (0 < this.String.Length)) { _indexes = StringInfo.ParseCombiningCharacters(this.String); } return (_indexes); } } public string String { get { return (_str); } set { if (null == value) { throw new ArgumentNullException(nameof(String), SR.ArgumentNull_String); } Contract.EndContractBlock(); _str = value; _indexes = null; } } public int LengthInTextElements { get { if (null == this.Indexes) { // Indexes not initialized, so assume length zero return (0); } return (this.Indexes.Length); } } public string SubstringByTextElements(int startingTextElement) { // If the string is empty, no sense going further. if (null == this.Indexes) { // Just decide which error to give depending on the param they gave us.... if (startingTextElement < 0) { throw new ArgumentOutOfRangeException(nameof(startingTextElement), SR.ArgumentOutOfRange_NeedPosNum); } else { throw new ArgumentOutOfRangeException(nameof(startingTextElement), SR.Arg_ArgumentOutOfRangeException); } } return (SubstringByTextElements(startingTextElement, Indexes.Length - startingTextElement)); } public string SubstringByTextElements(int startingTextElement, int lengthInTextElements) { if (startingTextElement < 0) { throw new ArgumentOutOfRangeException(nameof(startingTextElement), SR.ArgumentOutOfRange_NeedPosNum); } if (this.String.Length == 0 || startingTextElement >= Indexes.Length) { throw new ArgumentOutOfRangeException(nameof(startingTextElement), SR.Arg_ArgumentOutOfRangeException); } if (lengthInTextElements < 0) { throw new ArgumentOutOfRangeException(nameof(lengthInTextElements), SR.ArgumentOutOfRange_NeedPosNum); } if (startingTextElement > Indexes.Length - lengthInTextElements) { throw new ArgumentOutOfRangeException(nameof(lengthInTextElements), SR.Arg_ArgumentOutOfRangeException); } int start = Indexes[startingTextElement]; if (startingTextElement + lengthInTextElements == Indexes.Length) { // We are at the last text element in the string and because of that // must handle the call differently. return (this.String.Substring(start)); } else { return (this.String.Substring(start, (Indexes[lengthInTextElements + startingTextElement] - start))); } } public static string GetNextTextElement(string str) { return (GetNextTextElement(str, 0)); } //////////////////////////////////////////////////////////////////////// // // Get the code point count of the current text element. // // A combining class is defined as: // A character/surrogate that has the following Unicode category: // * NonSpacingMark (e.g. U+0300 COMBINING GRAVE ACCENT) // * SpacingCombiningMark (e.g. U+ 0903 DEVANGARI SIGN VISARGA) // * EnclosingMark (e.g. U+20DD COMBINING ENCLOSING CIRCLE) // // In the context of GetNextTextElement() and ParseCombiningCharacters(), a text element is defined as: // // 1. If a character/surrogate is in the following category, it is a text element. // It can NOT further combine with characters in the combinging class to form a text element. // * one of the Unicode category in the combinging class // * UnicodeCategory.Format // * UnicodeCateogry.Control // * UnicodeCategory.OtherNotAssigned // 2. Otherwise, the character/surrogate can be combined with characters in the combinging class to form a text element. // // Return: // The length of the current text element // // Parameters: // String str // index The starting index // len The total length of str (to define the upper boundary) // ucCurrent The Unicode category pointed by Index. It will be updated to the uc of next character if this is not the last text element. // currentCharCount The char count of an abstract char pointed by Index. It will be updated to the char count of next abstract character if this is not the last text element. // //////////////////////////////////////////////////////////////////////// internal static int GetCurrentTextElementLen(string str, int index, int len, ref UnicodeCategory ucCurrent, ref int currentCharCount) { Debug.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len); Debug.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len); if (index + currentCharCount == len) { // This is the last character/surrogate in the string. return (currentCharCount); } // Call an internal GetUnicodeCategory, which will tell us both the unicode category, and also tell us if it is a surrogate pair or not. int nextCharCount; UnicodeCategory ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index + currentCharCount, out nextCharCount); if (CharUnicodeInfo.IsCombiningCategory(ucNext)) { // The next element is a combining class. // Check if the current text element to see if it is a valid base category (i.e. it should not be a combining category, // not a format character, and not a control character). if (CharUnicodeInfo.IsCombiningCategory(ucCurrent) || (ucCurrent == UnicodeCategory.Format) || (ucCurrent == UnicodeCategory.Control) || (ucCurrent == UnicodeCategory.OtherNotAssigned) || (ucCurrent == UnicodeCategory.Surrogate)) // An unpair high surrogate or low surrogate { // Will fall thru and return the currentCharCount } else { int startIndex = index; // Remember the current index. // We have a valid base characters, and we have a character (or surrogate) that is combining. // Check if there are more combining characters to follow. // Check if the next character is a nonspacing character. index += currentCharCount + nextCharCount; while (index < len) { ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out nextCharCount); if (!CharUnicodeInfo.IsCombiningCategory(ucNext)) { ucCurrent = ucNext; currentCharCount = nextCharCount; break; } index += nextCharCount; } return (index - startIndex); } } // The return value will be the currentCharCount. int ret = currentCharCount; ucCurrent = ucNext; // Update currentCharCount. currentCharCount = nextCharCount; return (ret); } // Returns the str containing the next text element in str starting at // index index. If index is not supplied, then it will start at the beginning // of str. It recognizes a base character plus one or more combining // characters or a properly formed surrogate pair as a text element. See also // the ParseCombiningCharacters() and the ParseSurrogates() methods. public static string GetNextTextElement(string str, int index) { // // Validate parameters. // if (str == null) { throw new ArgumentNullException(nameof(str)); } Contract.EndContractBlock(); int len = str.Length; if (index < 0 || index >= len) { if (index == len) { return (String.Empty); } throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); } int charLen; UnicodeCategory uc = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out charLen); return (str.Substring(index, GetCurrentTextElementLen(str, index, len, ref uc, ref charLen))); } public static TextElementEnumerator GetTextElementEnumerator(string str) { return (GetTextElementEnumerator(str, 0)); } public static TextElementEnumerator GetTextElementEnumerator(string str, int index) { // // Validate parameters. // if (str == null) { throw new ArgumentNullException(nameof(str)); } Contract.EndContractBlock(); int len = str.Length; if (index < 0 || (index > len)) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); } return (new TextElementEnumerator(str, index, len)); } /* * Returns the indices of each base character or properly formed surrogate pair * within the str. It recognizes a base character plus one or more combining * characters or a properly formed surrogate pair as a text element and returns * the index of the base character or high surrogate. Each index is the * beginning of a text element within a str. The length of each element is * easily computed as the difference between successive indices. The length of * the array will always be less than or equal to the length of the str. For * example, given the str \u4f00\u302a\ud800\udc00\u4f01, this method would * return the indices: 0, 2, 4. */ public static int[] ParseCombiningCharacters(string str) { if (str == null) { throw new ArgumentNullException(nameof(str)); } Contract.EndContractBlock(); int len = str.Length; int[] result = new int[len]; if (len == 0) { return (result); } int resultCount = 0; int i = 0; int currentCharLen; UnicodeCategory currentCategory = CharUnicodeInfo.InternalGetUnicodeCategory(str, 0, out currentCharLen); while (i < len) { result[resultCount++] = i; i += GetCurrentTextElementLen(str, i, len, ref currentCategory, ref currentCharLen); } if (resultCount < len) { int[] returnArray = new int[resultCount]; Array.Copy(result, returnArray, resultCount); return (returnArray); } return (result); } } }