context
stringlengths
2.52k
185k
gt
stringclasses
1 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 openvpn.api.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; } } }
// // Encog(tm) Core v3.3 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using Encog.MathUtil.Randomize; using Encog.MathUtil.RBF; using Encog.ML; using Encog.ML.Data; using Encog.ML.Data.Basic; using Encog.Neural.Flat; using Encog.Neural.Networks; using Encog.Util; using Encog.Util.Simple; namespace Encog.Neural.RBF { /// <summary> /// RBF neural network. /// </summary> [Serializable] public class RBFNetwork : BasicML, IMLError, IMLRegression, IContainsFlat { /// <summary> /// The underlying flat network. /// </summary> /// private readonly FlatNetworkRBF _flat; /// <summary> /// Construct RBF network. /// </summary> /// public RBFNetwork() { _flat = new FlatNetworkRBF(); } /// <summary> /// Construct RBF network. /// </summary> /// /// <param name="inputCount">The input count.</param> /// <param name="hiddenCount">The hidden count.</param> /// <param name="outputCount">The output count.</param> /// <param name="t">The RBF type.</param> public RBFNetwork(int inputCount, int hiddenCount, int outputCount, RBFEnum t) { if (hiddenCount == 0) { throw new NeuralNetworkError( "RBF network cannot have zero hidden neurons."); } var rbf = new IRadialBasisFunction[hiddenCount]; // Set the standard RBF neuron width. // Literature seems to suggest this is a good default value. double volumeNeuronWidth = 2.0d/hiddenCount; _flat = new FlatNetworkRBF(inputCount, rbf.Length, outputCount, rbf); try { // try this SetRBFCentersAndWidthsEqualSpacing(-1, 1, t, volumeNeuronWidth, false); } catch (EncogError) { // if we have the wrong number of hidden neurons, try this RandomizeRBFCentersAndWidths(-1, 1, t); } } /// <summary> /// Construct RBF network. /// </summary> /// /// <param name="inputCount">The input count.</param> /// <param name="outputCount">The output count.</param> /// <param name="rbf">The RBF type.</param> public RBFNetwork(int inputCount, int outputCount, IRadialBasisFunction[] rbf) { _flat = new FlatNetworkRBF(inputCount, rbf.Length, outputCount, rbf) {RBF = rbf}; } /// <summary> /// Set the RBF's. /// </summary> public IRadialBasisFunction[] RBF { get { return _flat.RBF; } set { _flat.RBF = value; } } #region ContainsFlat Members /// <inheritdoc/> public FlatNetwork Flat { get { return _flat; } } #endregion #region MLError Members /// <summary> /// Calculate the error for this neural network. /// </summary> /// /// <param name="data">The training set.</param> /// <returns>The error percentage.</returns> public double CalculateError(IMLDataSet data) { return EncogUtility.CalculateRegressionError(this, data); } #endregion #region MLRegression Members /// <inheritdoc/> public IMLData Compute(IMLData input) { var output = new double[OutputCount]; _flat.Compute(input, output); return new BasicMLData(output, false); } /// <inheritdoc/> public virtual int InputCount { get { return _flat.InputCount; } } /// <inheritdoc/> public virtual int OutputCount { get { return _flat.OutputCount; } } #endregion /// <summary> /// Set the RBF components to random values. /// </summary> /// /// <param name="min">Minimum random value.</param> /// <param name="max">Max random value.</param> /// <param name="t">The type of RBF to use.</param> public void RandomizeRBFCentersAndWidths(double min, double max, RBFEnum t) { int dimensions = InputCount; var centers = new double[dimensions]; for (int i = 0; i < dimensions; i++) { centers[i] = RangeRandomizer.Randomize(min, max); } for (int i = 0; i < _flat.RBF.Length; i++) { SetRBFFunction(i, t, centers, RangeRandomizer.Randomize(min, max)); } } /// <summary> /// Array containing center position. Row n contains centers for neuron n. /// Row n contains x elements for x number of dimensions. /// </summary> /// /// <param name="centers">The centers.</param> /// <param name="widths"></param> /// <param name="t">The RBF Function to use for this layer.</param> public void SetRBFCentersAndWidths(double[][] centers, double[] widths, RBFEnum t) { for (int i = 0; i < _flat.RBF.Length; i++) { SetRBFFunction(i, t, centers[i], widths[i]); } } /// <summary> /// Equally spaces all hidden neurons within the n dimensional variable /// space. /// </summary> /// /// <param name="minPosition">The minimum position neurons should be centered. Typically 0.</param> /// <param name="maxPosition">The maximum position neurons should be centered. Typically 1</param> /// <param name="t">The RBF type.</param> /// <param name="volumeNeuronRBFWidth">The neuron width of neurons within the mesh.</param> /// <param name="useWideEdgeRBFs">Enables wider RBF's around the boundary of the neuron mesh.</param> public void SetRBFCentersAndWidthsEqualSpacing( double minPosition, double maxPosition, RBFEnum t, double volumeNeuronRBFWidth, bool useWideEdgeRBFs) { int totalNumHiddenNeurons = _flat.RBF.Length; int dimensions = InputCount; double disMinMaxPosition = Math.Abs(maxPosition - minPosition); // Check to make sure we have the correct number of neurons for the // provided dimensions var expectedSideLength = (int) Math.Pow(totalNumHiddenNeurons, 1.0d/dimensions); double cmp = Math.Pow(totalNumHiddenNeurons, 1.0d/dimensions); if (expectedSideLength != cmp) { throw new NeuralNetworkError( "Total number of RBF neurons must be some integer to the power of 'dimensions'.\n" + Format.FormatDouble(expectedSideLength, 5) + " <> " + Format.FormatDouble(cmp, 5)); } double edgeNeuronRBFWidth = 2.5d*volumeNeuronRBFWidth; var centers = new double[totalNumHiddenNeurons][]; var widths = new double[totalNumHiddenNeurons]; for (int i = 0; i < totalNumHiddenNeurons; i++) { centers[i] = new double[dimensions]; int sideLength = expectedSideLength; // Evenly distribute the volume neurons. int temp = i; // First determine the centers for (int j = dimensions; j > 0; j--) { // i + j * sidelength + k * sidelength ^2 + ... l * sidelength ^ // n // i - neuron number in x direction, i.e. 0,1,2,3 // j - neuron number in y direction, i.e. 0,1,2,3 // Following example assumes sidelength of 4 // e.g Neuron 5 - x position is (int)5/4 * 0.33 = 0.33 // then take modulus of 5%4 = 1 // Neuron 5 - y position is (int)1/1 * 0.33 = 0.33 centers[i][j - 1] = ((int) (temp/Math.Pow(sideLength, j - 1))*(disMinMaxPosition/(sideLength - 1))) + minPosition; temp = temp%(int) (Math.Pow(sideLength, j - 1)); } // Now set the widths bool contains = false; for (int z = 0; z < centers[0].Length; z++) { if ((centers[i][z] == 1.0d) || (centers[i][z] == 0.0d)) { contains = true; } } if (contains && useWideEdgeRBFs) { widths[i] = edgeNeuronRBFWidth; } else { widths[i] = volumeNeuronRBFWidth; } } SetRBFCentersAndWidths(centers, widths, t); } /// <summary> /// Set an RBF function. /// </summary> /// /// <param name="index">The index to set.</param> /// <param name="t">The function type.</param> /// <param name="centers">The centers.</param> /// <param name="width">The width.</param> public void SetRBFFunction(int index, RBFEnum t, double[] centers, double width) { if (t == RBFEnum.Gaussian) { _flat.RBF[index] = new GaussianFunction(0.5d, centers, width); } else if (t == RBFEnum.Multiquadric) { _flat.RBF[index] = new MultiquadricFunction(0.5d, centers, width); } else if (t == RBFEnum.InverseMultiquadric) { _flat.RBF[index] = new InverseMultiquadricFunction(0.5d, centers, width); } } /// <inheritdoc/> public override void UpdateProperties() { // unneeded } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.Text; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { internal interface ICodeModelService : ICodeModelNavigationPointService { /// <summary> /// Retrieves the Option nodes (i.e. VB Option statements) parented /// by the given node. /// </summary> IEnumerable<SyntaxNode> GetOptionNodes(SyntaxNode parent); /// <summary> /// Retrieves the import nodes (e.g. using/Import directives) parented /// by the given node. /// </summary> IEnumerable<SyntaxNode> GetImportNodes(SyntaxNode parent); /// <summary> /// Retrieves the attributes parented or owned by the given node. /// </summary> IEnumerable<SyntaxNode> GetAttributeNodes(SyntaxNode parent); /// <summary> /// Retrieves the attribute arguments parented by the given node. /// </summary> IEnumerable<SyntaxNode> GetAttributeArgumentNodes(SyntaxNode parent); /// <summary> /// Retrieves the Inherits nodes (i.e. VB Inherits statements) parented /// or owned by the given node. /// </summary> IEnumerable<SyntaxNode> GetInheritsNodes(SyntaxNode parent); /// <summary> /// Retrieves the Implements nodes (i.e. VB Implements statements) parented /// or owned by the given node. /// </summary> IEnumerable<SyntaxNode> GetImplementsNodes(SyntaxNode parent); /// <summary> /// Retrieves the members of a specified <paramref name="container"/> node. The members that are /// returned can be controlled by passing various parameters. /// </summary> /// <param name="container">The <see cref="SyntaxNode"/> from which to retrieve members.</param> /// <param name="includeSelf">If true, the container is returned as well.</param> /// <param name="recursive">If true, members are recursed to return descendent members as well /// as immediate children. For example, a namespace would return the namespaces and types within. /// However, if <paramref name="recursive"/> is true, members with the namespaces and types would /// also be returned.</param> /// <param name="logicalFields">If true, field declarations are broken into their respective declarators. /// For example, the field "int x, y" would return two declarators, one for x and one for y in place /// of the field.</param> /// <param name="onlySupportedNodes">If true, only members supported by Code Model are returned.</param> IEnumerable<SyntaxNode> GetMemberNodes(SyntaxNode container, bool includeSelf, bool recursive, bool logicalFields, bool onlySupportedNodes); IEnumerable<SyntaxNode> GetLogicalSupportedMemberNodes(SyntaxNode container); SyntaxNodeKey GetNodeKey(SyntaxNode node); SyntaxNodeKey TryGetNodeKey(SyntaxNode node); SyntaxNode LookupNode(SyntaxNodeKey nodeKey, SyntaxTree syntaxTree); bool TryLookupNode(SyntaxNodeKey nodeKey, SyntaxTree syntaxTree, out SyntaxNode node); bool MatchesScope(SyntaxNode node, EnvDTE.vsCMElement scope); string Language { get; } string AssemblyAttributeString { get; } /// <summary> /// Do not use this method directly! Instead, go through <see cref="FileCodeModel.GetOrCreateCodeElement{T}(SyntaxNode)"/> /// </summary> EnvDTE.CodeElement CreateInternalCodeElement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node); EnvDTE.CodeElement CreateExternalCodeElement(CodeModelState state, ProjectId projectId, ISymbol symbol); EnvDTE.CodeElement CreateUnknownCodeElement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node); EnvDTE.CodeElement CreateUnknownRootNamespaceCodeElement(CodeModelState state, FileCodeModel fileCodeModel); EnvDTE.CodeElement CreateCodeType(CodeModelState state, ProjectId projectId, ITypeSymbol typeSymbol); /// <summary> /// Used by RootCodeModel.CreateCodeTypeRef to create an EnvDTE.CodeTypeRef. /// </summary> EnvDTE.CodeTypeRef CreateCodeTypeRef(CodeModelState state, ProjectId projectId, object type); EnvDTE.vsCMTypeRef GetTypeKindForCodeTypeRef(ITypeSymbol typeSymbol); string GetAsFullNameForCodeTypeRef(ITypeSymbol typeSymbol); string GetAsStringForCodeTypeRef(ITypeSymbol typeSymbol); bool IsParameterNode(SyntaxNode node); bool IsAttributeNode(SyntaxNode node); bool IsAttributeArgumentNode(SyntaxNode node); bool IsOptionNode(SyntaxNode node); bool IsImportNode(SyntaxNode node); ISymbol ResolveSymbol(Workspace workspace, ProjectId projectId, SymbolKey symbolId); string GetUnescapedName(string name); /// <summary> /// Retrieves the value to be returned from the EnvDTE.CodeElement.Name property. /// </summary> string GetName(SyntaxNode node); SyntaxNode GetNodeWithName(SyntaxNode node); SyntaxNode SetName(SyntaxNode node, string name); /// <summary> /// Retrieves the value to be returned from the EnvDTE.CodeElement.FullName property. /// </summary> string GetFullName(SyntaxNode node, SemanticModel semanticModel); /// <summary> /// Given a name, attempts to convert it to a fully qualified name. /// </summary> string GetFullyQualifiedName(string name, int position, SemanticModel semanticModel); void Rename(ISymbol symbol, string newName, Solution solution); /// <summary> /// Returns true if the given <paramref name="symbol"/> can be used to create an external code element; otherwise, false. /// </summary> bool IsValidExternalSymbol(ISymbol symbol); /// <summary> /// Returns the value to be returned from <see cref="EnvDTE.CodeElement.Name"/> for external code elements. /// </summary> string GetExternalSymbolName(ISymbol symbol); /// <summary> /// Retrieves the value to be returned from <see cref="EnvDTE.CodeElement.FullName"/> for external code elements. /// </summary> string GetExternalSymbolFullName(ISymbol symbol); SyntaxNode GetNodeWithModifiers(SyntaxNode node); SyntaxNode GetNodeWithType(SyntaxNode node); SyntaxNode GetNodeWithInitializer(SyntaxNode node); EnvDTE.vsCMAccess GetAccess(ISymbol symbol); EnvDTE.vsCMAccess GetAccess(SyntaxNode node); SyntaxNode SetAccess(SyntaxNode node, EnvDTE.vsCMAccess access); EnvDTE.vsCMElement GetElementKind(SyntaxNode node); bool IsAccessorNode(SyntaxNode node); MethodKind GetAccessorKind(SyntaxNode node); bool TryGetAccessorNode(SyntaxNode parentNode, MethodKind kind, out SyntaxNode accessorNode); bool TryGetParameterNode(SyntaxNode parentNode, string name, out SyntaxNode parameterNode); bool TryGetImportNode(SyntaxNode parentNode, string dottedName, out SyntaxNode importNode); bool TryGetOptionNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode optionNode); bool TryGetInheritsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode inheritsNode); bool TryGetImplementsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode implementsNode); bool TryGetAttributeNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode attributeNode); bool TryGetAttributeArgumentNode(SyntaxNode attributeNode, int index, out SyntaxNode attributeArgumentNode); void GetOptionNameAndOrdinal(SyntaxNode parentNode, SyntaxNode optionNode, out string name, out int ordinal); void GetInheritsNamespaceAndOrdinal(SyntaxNode parentNode, SyntaxNode inheritsNode, out string namespaceName, out int ordinal); void GetImplementsNamespaceAndOrdinal(SyntaxNode parentNode, SyntaxNode implementsNode, out string namespaceName, out int ordinal); void GetAttributeArgumentParentAndIndex(SyntaxNode attributeArgumentNode, out SyntaxNode attributeNode, out int index); void GetAttributeNameAndOrdinal(SyntaxNode parentNode, SyntaxNode attributeNode, out string name, out int ordinal); SyntaxNode GetAttributeTargetNode(SyntaxNode attributeNode); string GetAttributeTarget(SyntaxNode attributeNode); string GetAttributeValue(SyntaxNode attributeNode); SyntaxNode SetAttributeTarget(SyntaxNode attributeNode, string value); SyntaxNode SetAttributeValue(SyntaxNode attributeNode, string value); /// <summary> /// Given a node, finds the related node that holds on to the attribute information. /// Generally, this will be an ancestor node. For example, given a C# VariableDeclarator, /// looks up the syntax tree to find the FieldDeclaration. /// </summary> SyntaxNode GetNodeWithAttributes(SyntaxNode node); /// <summary> /// Given node for an attribute, returns a node that can represent the parent. /// For example, an attribute on a C# field cannot use the FieldDeclaration (as it is /// not keyed) but instead must use one of the FieldDeclaration's VariableDeclarators. /// </summary> SyntaxNode GetEffectiveParentForAttribute(SyntaxNode node); SyntaxNode CreateAttributeNode(string name, string value, string target = null); SyntaxNode CreateAttributeArgumentNode(string name, string value); SyntaxNode CreateImportNode(string name, string alias = null); SyntaxNode CreateParameterNode(string name, string type); string GetAttributeArgumentValue(SyntaxNode attributeArgumentNode); string GetImportAlias(SyntaxNode node); string GetImportNamespaceOrType(SyntaxNode node); string GetParameterName(SyntaxNode node); string GetParameterFullName(SyntaxNode node); EnvDTE80.vsCMParameterKind GetParameterKind(SyntaxNode node); SyntaxNode SetParameterKind(SyntaxNode node, EnvDTE80.vsCMParameterKind kind); IEnumerable<SyntaxNode> GetParameterNodes(SyntaxNode parent); EnvDTE.vsCMFunction ValidateFunctionKind(SyntaxNode containerNode, EnvDTE.vsCMFunction kind, string name); bool SupportsEventThrower { get; } bool GetCanOverride(SyntaxNode memberNode); SyntaxNode SetCanOverride(SyntaxNode memberNode, bool value); EnvDTE80.vsCMClassKind GetClassKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol); SyntaxNode SetClassKind(SyntaxNode typeNode, EnvDTE80.vsCMClassKind kind); string GetComment(SyntaxNode node); SyntaxNode SetComment(SyntaxNode node, string value); EnvDTE80.vsCMConstKind GetConstKind(SyntaxNode variableNode); SyntaxNode SetConstKind(SyntaxNode variableNode, EnvDTE80.vsCMConstKind kind); EnvDTE80.vsCMDataTypeKind GetDataTypeKind(SyntaxNode typeNode, INamedTypeSymbol symbol); SyntaxNode SetDataTypeKind(SyntaxNode typeNode, EnvDTE80.vsCMDataTypeKind kind); string GetDocComment(SyntaxNode node); SyntaxNode SetDocComment(SyntaxNode node, string value); EnvDTE.vsCMFunction GetFunctionKind(IMethodSymbol symbol); EnvDTE80.vsCMInheritanceKind GetInheritanceKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol); SyntaxNode SetInheritanceKind(SyntaxNode node, EnvDTE80.vsCMInheritanceKind kind); bool GetIsAbstract(SyntaxNode memberNode, ISymbol symbol); SyntaxNode SetIsAbstract(SyntaxNode memberNode, bool value); bool GetIsConstant(SyntaxNode memberNode); SyntaxNode SetIsConstant(SyntaxNode memberNode, bool value); bool GetIsDefault(SyntaxNode propertyNode); SyntaxNode SetIsDefault(SyntaxNode propertyNode, bool value); bool GetIsGeneric(SyntaxNode memberNode); bool GetIsPropertyStyleEvent(SyntaxNode eventNode); bool GetIsShared(SyntaxNode memberNode, ISymbol symbol); SyntaxNode SetIsShared(SyntaxNode memberNode, bool value); bool GetMustImplement(SyntaxNode memberNode); SyntaxNode SetMustImplement(SyntaxNode memberNode, bool value); EnvDTE80.vsCMOverrideKind GetOverrideKind(SyntaxNode memberNode); SyntaxNode SetOverrideKind(SyntaxNode memberNode, EnvDTE80.vsCMOverrideKind kind); EnvDTE80.vsCMPropertyKind GetReadWrite(SyntaxNode memberNode); SyntaxNode SetType(SyntaxNode node, ITypeSymbol typeSymbol); Document Delete(Document document, SyntaxNode node); string GetMethodXml(SyntaxNode node, SemanticModel semanticModel); string GetInitExpression(SyntaxNode node); SyntaxNode AddInitExpression(SyntaxNode node, string value); CodeGenerationDestination GetDestination(SyntaxNode containerNode); /// <summary> /// Retrieves the Accessibility for an EnvDTE.vsCMAccess. If the specified value is /// EnvDTE.vsCMAccess.vsCMAccessDefault, then the SymbolKind and CodeGenerationDestination hints /// will be used to retrieve the correct Accessibility for the current language. /// </summary> Accessibility GetAccessibility(EnvDTE.vsCMAccess access, SymbolKind targetSymbolKind, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified); bool GetWithEvents(EnvDTE.vsCMAccess access); /// <summary> /// Given an "type" argument received from a CodeModel client, converts it to an ITypeSymbol. Note that /// this parameter is a VARIANT and could be an EnvDTE.vsCMTypeRef, a string representing a fully-qualified /// type name, or an EnvDTE.CodeTypeRef. /// </summary> ITypeSymbol GetTypeSymbol(object type, SemanticModel semanticModel, int position); ITypeSymbol GetTypeSymbolFromFullName(string fullName, Compilation compilation); SyntaxNode CreateReturnDefaultValueStatement(ITypeSymbol type); int PositionVariantToAttributeInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel); int PositionVariantToMemberInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel); int PositionVariantToAttributeArgumentInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel); int PositionVariantToImportInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel); int PositionVariantToParameterInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel); SyntaxNode InsertAttribute( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode attributeNode, CancellationToken cancellationToken, out Document newDocument); SyntaxNode InsertAttributeArgument( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode attributeArgumentNode, CancellationToken cancellationToken, out Document newDocument); SyntaxNode InsertImport( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode importNode, CancellationToken cancellationToken, out Document newDocument); SyntaxNode InsertMember( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode newMemberNode, CancellationToken cancellationToken, out Document newDocument); SyntaxNode InsertParameter( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode parameterNode, CancellationToken cancellationToken, out Document newDocument); Document UpdateNode( Document document, SyntaxNode node, SyntaxNode newNode, CancellationToken cancellationToken); Queue<CodeModelEvent> CollectCodeModelEvents(SyntaxTree oldTree, SyntaxTree newTree); bool IsNamespace(SyntaxNode node); bool IsType(SyntaxNode node); IList<string> GetHandledEventNames(SyntaxNode method, SemanticModel semanticModel); bool HandlesEvent(string eventName, SyntaxNode method, SemanticModel semanticModel); Document AddHandlesClause(Document document, string eventName, SyntaxNode method, CancellationToken cancellationToken); Document RemoveHandlesClause(Document document, string eventName, SyntaxNode method, CancellationToken cancellationToken); string[] GetFunctionExtenderNames(); object GetFunctionExtender(string name, SyntaxNode node, ISymbol symbol); string[] GetPropertyExtenderNames(); object GetPropertyExtender(string name, SyntaxNode node, ISymbol symbol); string[] GetExternalTypeExtenderNames(); object GetExternalTypeExtender(string name, string externalLocation); string[] GetTypeExtenderNames(); object GetTypeExtender(string name, AbstractCodeType codeType); bool IsValidBaseType(SyntaxNode node, ITypeSymbol typeSymbol); SyntaxNode AddBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position); SyntaxNode RemoveBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel); bool IsValidInterfaceType(SyntaxNode node, ITypeSymbol typeSymbol); SyntaxNode AddImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position); SyntaxNode RemoveImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel); string GetPrototype(SyntaxNode node, ISymbol symbol, PrototypeFlags flags); void AttachFormatTrackingToBuffer(ITextBuffer buffer); void DetachFormatTrackingToBuffer(ITextBuffer buffer); void EnsureBufferFormatted(ITextBuffer buffer); } }
// // https://github.com/ServiceStack/ServiceStack.Text // ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers. // // Authors: // Demis Bellot ([email protected]) // // Copyright 2012 ServiceStack Ltd. // // Licensed under the same terms of ServiceStack: new BSD license. // using System; using System.Globalization; using System.IO; using ServiceStack.Text.Common; using ServiceStack.Text.Json; namespace ServiceStack.Text.Jsv { internal class JsvTypeSerializer : ITypeSerializer { public static ITypeSerializer Instance = new JsvTypeSerializer(); public bool IncludeNullValues { get { return false; } //Doesn't support null values, treated as "null" string literal } public string TypeAttrInObject { get { return JsConfig.JsvTypeAttrInObject; } } internal static string GetTypeAttrInObject(string typeAttr) { return string.Format("{{{0}:", typeAttr); } public WriteObjectDelegate GetWriteFn<T>() { return JsvWriter<T>.WriteFn(); } public WriteObjectDelegate GetWriteFn(Type type) { return JsvWriter.GetWriteFn(type); } static readonly TypeInfo DefaultTypeInfo = new TypeInfo { EncodeMapKey = false }; public TypeInfo GetTypeInfo(Type type) { return DefaultTypeInfo; } public void WriteRawString(TextWriter writer, string value) { writer.Write(value.EncodeJsv()); } public void WritePropertyName(TextWriter writer, string value) { writer.Write(value); } public void WriteBuiltIn(TextWriter writer, object value) { writer.Write(value); } public void WriteObjectString(TextWriter writer, object value) { if (value != null) { writer.Write(value.ToString().EncodeJsv()); } } public void WriteException(TextWriter writer, object value) { writer.Write(((Exception)value).Message.EncodeJsv()); } public void WriteString(TextWriter writer, string value) { writer.Write(value.EncodeJsv()); } public void WriteFormattableObjectString(TextWriter writer, object value) { var f = (IFormattable)value; writer.Write(f.ToString(null,CultureInfo.InvariantCulture).EncodeJsv()); } public void WriteDateTime(TextWriter writer, object oDateTime) { writer.Write(DateTimeSerializer.ToShortestXsdDateTimeString((DateTime)oDateTime)); } public void WriteNullableDateTime(TextWriter writer, object dateTime) { if (dateTime == null) return; writer.Write(DateTimeSerializer.ToShortestXsdDateTimeString((DateTime)dateTime)); } public void WriteDateTimeOffset(TextWriter writer, object oDateTimeOffset) { writer.Write(((DateTimeOffset) oDateTimeOffset).ToString("o")); } public void WriteNullableDateTimeOffset(TextWriter writer, object dateTimeOffset) { if (dateTimeOffset == null) return; this.WriteDateTimeOffset(writer, dateTimeOffset); } public void WriteTimeSpan(TextWriter writer, object oTimeSpan) { writer.Write(DateTimeSerializer.ToXsdTimeSpanString((TimeSpan)oTimeSpan)); } public void WriteNullableTimeSpan(TextWriter writer, object oTimeSpan) { if (oTimeSpan == null) return; writer.Write(DateTimeSerializer.ToXsdTimeSpanString((TimeSpan?)oTimeSpan)); } public void WriteGuid(TextWriter writer, object oValue) { writer.Write(((Guid)oValue).ToString("N")); } public void WriteNullableGuid(TextWriter writer, object oValue) { if (oValue == null) return; writer.Write(((Guid)oValue).ToString("N")); } public void WriteBytes(TextWriter writer, object oByteValue) { if (oByteValue == null) return; writer.Write(Convert.ToBase64String((byte[])oByteValue)); } public void WriteChar(TextWriter writer, object charValue) { if (charValue == null) return; writer.Write((char)charValue); } public void WriteByte(TextWriter writer, object byteValue) { if (byteValue == null) return; writer.Write((byte)byteValue); } public void WriteInt16(TextWriter writer, object intValue) { if (intValue == null) return; writer.Write((short)intValue); } public void WriteUInt16(TextWriter writer, object intValue) { if (intValue == null) return; writer.Write((ushort)intValue); } public void WriteInt32(TextWriter writer, object intValue) { if (intValue == null) return; writer.Write((int)intValue); } public void WriteUInt32(TextWriter writer, object uintValue) { if (uintValue == null) return; writer.Write((uint)uintValue); } public void WriteUInt64(TextWriter writer, object ulongValue) { if (ulongValue == null) return; writer.Write((ulong)ulongValue); } public void WriteInt64(TextWriter writer, object longValue) { if (longValue == null) return; writer.Write((long)longValue); } public void WriteBool(TextWriter writer, object boolValue) { if (boolValue == null) return; writer.Write((bool)boolValue); } public void WriteFloat(TextWriter writer, object floatValue) { if (floatValue == null) return; var floatVal = (float)floatValue; if (Equals(floatVal, float.MaxValue) || Equals(floatVal, float.MinValue)) writer.Write(floatVal.ToString("r", CultureInfo.InvariantCulture)); else writer.Write(floatVal.ToString(CultureInfo.InvariantCulture)); } public void WriteDouble(TextWriter writer, object doubleValue) { if (doubleValue == null) return; var doubleVal = (double)doubleValue; if (Equals(doubleVal, double.MaxValue) || Equals(doubleVal, double.MinValue)) writer.Write(doubleVal.ToString("r", CultureInfo.InvariantCulture)); else writer.Write(doubleVal.ToString(CultureInfo.InvariantCulture)); } public void WriteDecimal(TextWriter writer, object decimalValue) { if (decimalValue == null) return; writer.Write(((decimal)decimalValue).ToString(CultureInfo.InvariantCulture)); } public void WriteEnum(TextWriter writer, object enumValue) { if (enumValue == null) return; if (JsConfig.TreatEnumAsInteger) JsWriter.WriteEnumFlags(writer, enumValue); else writer.Write(enumValue.ToString()); } public void WriteEnumFlags(TextWriter writer, object enumFlagValue) { JsWriter.WriteEnumFlags(writer, enumFlagValue); } public void WriteLinqBinary(TextWriter writer, object linqBinaryValue) { #if !MONOTOUCH && !SILVERLIGHT && !XBOX && !ANDROID WriteRawString(writer, Convert.ToBase64String(((System.Data.Linq.Binary)linqBinaryValue).ToArray())); #endif } public object EncodeMapKey(object value) { return value; } public ParseStringDelegate GetParseFn<T>() { return JsvReader.Instance.GetParseFn<T>(); } public ParseStringDelegate GetParseFn(Type type) { return JsvReader.GetParseFn(type); } public string UnescapeSafeString(string value) { return value.FromCsvField(); } public string ParseRawString(string value) { return value; } public string ParseString(string value) { return value.FromCsvField(); } public string UnescapeString(string value) { return value.FromCsvField(); } public string EatTypeValue(string value, ref int i) { return EatValue(value, ref i); } public bool EatMapStartChar(string value, ref int i) { var success = value[i] == JsWriter.MapStartChar; if (success) i++; return success; } public string EatMapKey(string value, ref int i) { var tokenStartPos = i; var valueLength = value.Length; var valueChar = value[tokenStartPos]; switch (valueChar) { case JsWriter.QuoteChar: while (++i < valueLength) { valueChar = value[i]; if (valueChar != JsWriter.QuoteChar) continue; var isLiteralQuote = i + 1 < valueLength && value[i + 1] == JsWriter.QuoteChar; i++; //skip quote if (!isLiteralQuote) break; } return value.Substring(tokenStartPos, i - tokenStartPos); //Is Type/Map, i.e. {...} case JsWriter.MapStartChar: var endsToEat = 1; var withinQuotes = false; while (++i < valueLength && endsToEat > 0) { valueChar = value[i]; if (valueChar == JsWriter.QuoteChar) withinQuotes = !withinQuotes; if (withinQuotes) continue; if (valueChar == JsWriter.MapStartChar) endsToEat++; if (valueChar == JsWriter.MapEndChar) endsToEat--; } return value.Substring(tokenStartPos, i - tokenStartPos); } while (value[++i] != JsWriter.MapKeySeperator) { } return value.Substring(tokenStartPos, i - tokenStartPos); } public bool EatMapKeySeperator(string value, ref int i) { return value[i++] == JsWriter.MapKeySeperator; } public bool EatItemSeperatorOrMapEndChar(string value, ref int i) { if (i == value.Length) return false; var success = value[i] == JsWriter.ItemSeperator || value[i] == JsWriter.MapEndChar; i++; return success; } public void EatWhitespace(string value, ref int i) { } public string EatValue(string value, ref int i) { var tokenStartPos = i; var valueLength = value.Length; if (i == valueLength) return null; var valueChar = value[i]; var withinQuotes = false; var endsToEat = 1; switch (valueChar) { //If we are at the end, return. case JsWriter.ItemSeperator: case JsWriter.MapEndChar: return null; //Is Within Quotes, i.e. "..." case JsWriter.QuoteChar: while (++i < valueLength) { valueChar = value[i]; if (valueChar != JsWriter.QuoteChar) continue; var isLiteralQuote = i + 1 < valueLength && value[i + 1] == JsWriter.QuoteChar; i++; //skip quote if (!isLiteralQuote) break; } return value.Substring(tokenStartPos, i - tokenStartPos); //Is Type/Map, i.e. {...} case JsWriter.MapStartChar: while (++i < valueLength && endsToEat > 0) { valueChar = value[i]; if (valueChar == JsWriter.QuoteChar) withinQuotes = !withinQuotes; if (withinQuotes) continue; if (valueChar == JsWriter.MapStartChar) endsToEat++; if (valueChar == JsWriter.MapEndChar) endsToEat--; } return value.Substring(tokenStartPos, i - tokenStartPos); //Is List, i.e. [...] case JsWriter.ListStartChar: while (++i < valueLength && endsToEat > 0) { valueChar = value[i]; if (valueChar == JsWriter.QuoteChar) withinQuotes = !withinQuotes; if (withinQuotes) continue; if (valueChar == JsWriter.ListStartChar) endsToEat++; if (valueChar == JsWriter.ListEndChar) endsToEat--; } return value.Substring(tokenStartPos, i - tokenStartPos); } //Is Value while (++i < valueLength) { valueChar = value[i]; if (valueChar == JsWriter.ItemSeperator || valueChar == JsWriter.MapEndChar) { break; } } return value.Substring(tokenStartPos, i - tokenStartPos); } } }
/* ** $Id: lapi.c,v 2.55.1.5 2008/07/04 18:41:18 roberto Exp $ ** Lua API ** See Copyright Notice in lua.h */ using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.IO; namespace SharpLua { using lu_mem = System.UInt32; using TValue = Lua.lua_TValue; using StkId = Lua.lua_TValue; using lua_Integer = System.Int32; using lua_Number = System.Double; using ptrdiff_t = System.Int32; using ZIO = Lua.Zio; public partial class Lua { public const string lua_ident = "$Lua: " + LUA_RELEASE + " " + LUA_COPYRIGHT + " $\n" + "$Authors: " + LUA_AUTHORS + " $\n" + "$URL: www.lua.org $\n"; public static void api_checknelems(LuaState L, int n) { api_check(L, n <= L.top - L.base_); } public static void api_checkvalidindex(LuaState L, StkId i) { api_check(L, i != luaO_nilobject); } public static void api_incr_top(LuaState L) { api_check(L, L.top < L.ci.top); StkId.inc(ref L.top); } public static TValue index2adr(LuaState L, int idx) { if (idx > 0) { TValue o = L.base_ + (idx - 1); api_check(L, idx <= L.ci.top - L.base_); if (o >= L.top) return luaO_nilobject; else return o; } else if (idx > LUA_REGISTRYINDEX) { api_check(L, idx != 0 && -idx <= L.top - L.base_); return L.top + idx; } else switch (idx) { /* pseudo-indices */ case LUA_REGISTRYINDEX: return registry(L); case LUA_ENVIRONINDEX: { Closure func = curr_func(L); sethvalue(L, L.env, func.c.env); return L.env; } case LUA_GLOBALSINDEX: return gt(L); default: { Closure func = curr_func(L); idx = LUA_GLOBALSINDEX - idx; return (idx <= func.c.nupvalues) ? func.c.upvalue[idx - 1] : (TValue)luaO_nilobject; } } } internal static Table getcurrenv(LuaState L) { if (L.ci == L.base_ci[0]) /* no enclosing function? */ return hvalue(gt(L)); /* use global table as environment */ else { Closure func = curr_func(L); return func.c.env; } } public static void luaA_pushobject(LuaState L, TValue o) { setobj2s(L, L.top, o); api_incr_top(L); } public static int lua_checkstack(LuaState L, int size) { int res = 1; lua_lock(L); if (size > LUAI_MAXCSTACK || (L.top - L.base_ + size) > LUAI_MAXCSTACK) res = 0; /* stack overflow */ else if (size > 0) { luaD_checkstack(L, size); if (L.ci.top < L.top + size) L.ci.top = L.top + size; } lua_unlock(L); return res; } public static void lua_xmove(LuaState from, LuaState to, int n) { int i; if (from == to) return; lua_lock(to); api_checknelems(from, n); api_check(from, G(from) == G(to)); api_check(from, to.ci.top - to.top >= n); from.top -= n; for (i = 0; i < n; i++) { setobj2s(to, StkId.inc(ref to.top), from.top + i); } lua_unlock(to); } public static void lua_setlevel(LuaState from, LuaState to) { to.nCcalls = from.nCcalls; } public static lua_CFunction lua_atpanic(LuaState L, lua_CFunction panicf) { lua_CFunction old; lua_lock(L); old = G(L).panic; G(L).panic = panicf; lua_unlock(L); return old; } public static LuaState lua_newthread(LuaState L) { LuaState L1; lua_lock(L); luaC_checkGC(L); L1 = luaE_newthread(L); setthvalue(L, L.top, L1); api_incr_top(L); lua_unlock(L); luai_userstatethread(L, L1); return L1; } /* ** basic stack manipulation */ public static int lua_gettop(LuaState L) { return cast_int(L.top - L.base_); } public static void lua_settop(LuaState L, int idx) { lua_lock(L); if (idx >= 0) { api_check(L, idx <= L.stack_last - L.base_); while (L.top < L.base_ + idx) setnilvalue(StkId.inc(ref L.top)); L.top = L.base_ + idx; } else { api_check(L, -(idx + 1) <= (L.top - L.base_)); L.top += idx + 1; /* `subtract' index (index is negative) */ } lua_unlock(L); } public static void lua_remove(LuaState L, int idx) { StkId p; lua_lock(L); p = index2adr(L, idx); api_checkvalidindex(L, p); while ((p = p[1]) < L.top) setobjs2s(L, p - 1, p); StkId.dec(ref L.top); lua_unlock(L); } public static void lua_insert(LuaState L, int idx) { StkId p; StkId q; lua_lock(L); p = index2adr(L, idx); api_checkvalidindex(L, p); for (q = L.top; q > p; StkId.dec(ref q)) setobjs2s(L, q, q - 1); setobjs2s(L, p, L.top); lua_unlock(L); } public static void lua_replace(LuaState L, int idx) { StkId o; lua_lock(L); /* explicit test for incompatible code */ if (idx == LUA_ENVIRONINDEX && L.ci == L.base_ci[0]) luaG_runerror(L, "no calling environment"); api_checknelems(L, 1); o = index2adr(L, idx); api_checkvalidindex(L, o); if (idx == LUA_ENVIRONINDEX) { Closure func = curr_func(L); api_check(L, ttistable(L.top - 1)); func.c.env = hvalue(L.top - 1); luaC_barrier(L, func, L.top - 1); } else { setobj(L, o, L.top - 1); if (idx < LUA_GLOBALSINDEX) /* function upvalue? */ luaC_barrier(L, curr_func(L), L.top - 1); } StkId.dec(ref L.top); lua_unlock(L); } public static void lua_pushvalue(LuaState L, int idx) { lua_lock(L); setobj2s(L, L.top, index2adr(L, idx)); api_incr_top(L); lua_unlock(L); } /* ** access functions (stack . C) */ public static int lua_type(LuaState L, int idx) { StkId o = index2adr(L, idx); return (o == luaO_nilobject) ? LUA_TNONE : ttype(o); } public static CharPtr lua_typename(LuaState L, int t) { //UNUSED(L); return (t == LUA_TNONE) ? "no value" : luaT_typenames[t].ToString(); } public static bool lua_iscfunction(LuaState L, int idx) { StkId o = index2adr(L, idx); return iscfunction(o); } public static int lua_isnumber(LuaState L, int idx) { TValue n = new TValue(); TValue o = index2adr(L, idx); return tonumber(ref o, n); } public static int lua_isstring(LuaState L, int idx) { int t = lua_type(L, idx); return (t == LUA_TSTRING || t == LUA_TNUMBER) ? 1 : 0; } public static int lua_isuserdata(LuaState L, int idx) { TValue o = index2adr(L, idx); return (ttisuserdata(o) || ttislightuserdata(o)) ? 1 : 0; } public static int lua_rawequal(LuaState L, int index1, int index2) { StkId o1 = index2adr(L, index1); StkId o2 = index2adr(L, index2); return (o1 == luaO_nilobject || o2 == luaO_nilobject) ? 0 : luaO_rawequalObj(o1, o2); } public static int lua_equal(LuaState L, int index1, int index2) { StkId o1, o2; int i; lua_lock(L); /* may call tag method */ o1 = index2adr(L, index1); o2 = index2adr(L, index2); i = (o1 == luaO_nilobject || o2 == luaO_nilobject) ? 0 : equalobj(L, o1, o2); lua_unlock(L); return i; } public static int lua_lessthan(LuaState L, int index1, int index2) { StkId o1, o2; int i; lua_lock(L); /* may call tag method */ o1 = index2adr(L, index1); o2 = index2adr(L, index2); i = (o1 == luaO_nilobject || o2 == luaO_nilobject) ? 0 : luaV_lessthan(L, o1, o2); lua_unlock(L); return i; } public static lua_Number lua_tonumber(LuaState L, int idx) { TValue n = new TValue(); TValue o = index2adr(L, idx); if (tonumber(ref o, n) != 0) return nvalue(o); else return 0; } public static lua_Integer lua_tointeger(LuaState L, int idx) { TValue n = new TValue(); TValue o = index2adr(L, idx); if (tonumber(ref o, n) != 0) { lua_Integer res; lua_Number num = nvalue(o); lua_number2integer(out res, num); return res; } else return 0; } public static int lua_toboolean(LuaState L, int idx) { TValue o = index2adr(L, idx); return (l_isfalse(o) == 0) ? 1 : 0; } public static CharPtr lua_tolstring(LuaState L, int idx, out uint len) { StkId o = index2adr(L, idx); if (!ttisstring(o)) { lua_lock(L); /* `luaV_tostring' may create a new string */ if (luaV_tostring(L, o) == 0) { /* conversion failed? */ len = 0; lua_unlock(L); return null; } luaC_checkGC(L); o = index2adr(L, idx); /* previous call may reallocate the stack */ lua_unlock(L); } len = tsvalue(o).len; return svalue(o); } public static uint lua_objlen(LuaState L, int idx) { StkId o = index2adr(L, idx); switch (ttype(o)) { case LUA_TSTRING: return tsvalue(o).len; case LUA_TUSERDATA: return uvalue(o).len; case LUA_TTABLE: // Table now respects __len metamethod Table h = hvalue(o); TValue tm = fasttm(L, h.metatable, TMS.TM_LEN); if (tm != null) //return call_binTM(L, o, luaO_nilobject, ra, TMS.TM_LEN); throw new NotImplementedException(); else return (uint)luaH_getn(hvalue(o)); case LUA_TNUMBER: { uint l; lua_lock(L); /* 'luaV_tostring' may create a new string */ l = (luaV_tostring(L, o) != 0 ? tsvalue(o).len : 0); lua_unlock(L); return l; } default: return 0; } } public static lua_CFunction lua_tocfunction(LuaState L, int idx) { StkId o = index2adr(L, idx); return (!iscfunction(o)) ? null : clvalue(o).c.f; } public static object lua_touserdata(LuaState L, int idx) { StkId o = index2adr(L, idx); switch (ttype(o)) { case LUA_TUSERDATA: return (rawuvalue(o).user_data); case LUA_TLIGHTUSERDATA: return pvalue(o); default: return null; } } public static LuaState lua_tothread(LuaState L, int idx) { StkId o = index2adr(L, idx); return (!ttisthread(o)) ? null : thvalue(o); } public static object lua_topointer(LuaState L, int idx) { StkId o = index2adr(L, idx); switch (ttype(o)) { case LUA_TTABLE: return hvalue(o); case LUA_TFUNCTION: return clvalue(o); case LUA_TTHREAD: return thvalue(o); case LUA_TUSERDATA: case LUA_TLIGHTUSERDATA: return lua_touserdata(L, idx); default: return null; } } /* ** push functions (C . stack) */ public static void lua_pushnil(LuaState L) { lua_lock(L); setnilvalue(L.top); api_incr_top(L); lua_unlock(L); } public static void lua_pushnumber(LuaState L, lua_Number n) { lua_lock(L); setnvalue(L.top, n); api_incr_top(L); lua_unlock(L); } public static void lua_pushinteger(LuaState L, lua_Integer n) { lua_lock(L); setnvalue(L.top, cast_num(n)); api_incr_top(L); lua_unlock(L); } public static void lua_pushlstring(LuaState L, CharPtr s, uint len) { lua_lock(L); luaC_checkGC(L); setsvalue2s(L, L.top, luaS_newlstr(L, s, len)); api_incr_top(L); lua_unlock(L); } public static void lua_pushstring(LuaState L, CharPtr s) { if (s == null) lua_pushnil(L); else lua_pushlstring(L, s, (uint)strlen(s)); } public static CharPtr lua_pushvfstring(LuaState L, CharPtr fmt, object[] argp) { CharPtr ret; lua_lock(L); luaC_checkGC(L); ret = luaO_pushvfstring(L, fmt, argp); lua_unlock(L); return ret; } public static CharPtr lua_pushfstring(LuaState L, CharPtr fmt) { CharPtr ret; lua_lock(L); luaC_checkGC(L); ret = luaO_pushvfstring(L, fmt, null); lua_unlock(L); return ret; } public static CharPtr lua_pushfstring(LuaState L, CharPtr fmt, params object[] p) { CharPtr ret; lua_lock(L); luaC_checkGC(L); ret = luaO_pushvfstring(L, fmt, p); lua_unlock(L); return ret; } public static void lua_pushcclosure(LuaState L, lua_CFunction fn, int n) { Closure cl; lua_lock(L); luaC_checkGC(L); api_checknelems(L, n); cl = luaF_newCclosure(L, n, getcurrenv(L)); cl.c.f = fn; L.top -= n; while (n-- != 0) setobj2n(L, cl.c.upvalue[n], L.top + n); setclvalue(L, L.top, cl); lua_assert(iswhite(obj2gco(cl))); api_incr_top(L); lua_unlock(L); } public static void lua_pushboolean(LuaState L, int b) { lua_lock(L); setbvalue(L.top, (b != 0) ? 1 : 0); /* ensure that true is 1 */ api_incr_top(L); lua_unlock(L); } public static void lua_pushlightuserdata(LuaState L, object p) { lua_lock(L); setpvalue(L.top, p); api_incr_top(L); lua_unlock(L); } public static int lua_pushthread(LuaState L) { lua_lock(L); setthvalue(L, L.top, L); api_incr_top(L); lua_unlock(L); return (G(L).mainthread == L) ? 1 : 0; } /* ** get functions (Lua . stack) */ public static void lua_gettable(LuaState L, int idx) { StkId t; lua_lock(L); t = index2adr(L, idx); api_checkvalidindex(L, t); luaV_gettable(L, t, L.top - 1, L.top - 1); lua_unlock(L); } public static void lua_getfield(LuaState L, int idx, CharPtr k) { StkId t; TValue key = new TValue(); lua_lock(L); t = index2adr(L, idx); api_checkvalidindex(L, t); setsvalue(L, key, luaS_new(L, k)); luaV_gettable(L, t, key, L.top); api_incr_top(L); lua_unlock(L); } public static void lua_rawget(LuaState L, int idx) { StkId t; lua_lock(L); t = index2adr(L, idx); api_check(L, ttistable(t)); setobj2s(L, L.top - 1, luaH_get(hvalue(t), L.top - 1)); lua_unlock(L); } public static void lua_rawgeti(LuaState L, int idx, int n) { StkId o; lua_lock(L); o = index2adr(L, idx); api_check(L, ttistable(o)); setobj2s(L, L.top, luaH_getnum(hvalue(o), n)); api_incr_top(L); lua_unlock(L); } public static void lua_createtable(LuaState L, int narray, int nrec) { lua_lock(L); luaC_checkGC(L); sethvalue(L, L.top, luaH_new(L, narray, nrec)); api_incr_top(L); lua_unlock(L); } public static int lua_getmetatable(LuaState L, int objindex) { TValue obj; Table mt = null; int res; lua_lock(L); obj = index2adr(L, objindex); switch (ttype(obj)) { case LUA_TTABLE: mt = hvalue(obj).metatable; break; case LUA_TUSERDATA: mt = uvalue(obj).metatable; break; default: mt = G(L).mt[ttype(obj)]; break; } if (mt == null) res = 0; else { sethvalue(L, L.top, mt); api_incr_top(L); res = 1; } lua_unlock(L); return res; } public static void lua_getfenv(LuaState L, int idx) { StkId o; lua_lock(L); o = index2adr(L, idx); api_checkvalidindex(L, o); switch (ttype(o)) { case LUA_TFUNCTION: sethvalue(L, L.top, clvalue(o).c.env); break; case LUA_TUSERDATA: sethvalue(L, L.top, uvalue(o).env); break; case LUA_TTHREAD: setobj2s(L, L.top, gt(thvalue(o))); break; default: setnilvalue(L.top); break; } api_incr_top(L); lua_unlock(L); } /* ** set functions (stack . Lua) */ public static void lua_settable(LuaState L, int idx) { StkId t; lua_lock(L); api_checknelems(L, 2); t = index2adr(L, idx); api_checkvalidindex(L, t); luaV_settable(L, t, L.top - 2, L.top - 1); L.top -= 2; /* pop index and value */ lua_unlock(L); } public static void lua_setfield(LuaState L, int idx, CharPtr k) { StkId t; TValue key = new TValue(); lua_lock(L); api_checknelems(L, 1); t = index2adr(L, idx); api_checkvalidindex(L, t); setsvalue(L, key, luaS_new(L, k)); luaV_settable(L, t, key, L.top - 1); StkId.dec(ref L.top); /* pop value */ lua_unlock(L); } public static void lua_rawset(LuaState L, int idx) { StkId t; lua_lock(L); api_checknelems(L, 2); t = index2adr(L, idx); api_check(L, ttistable(t)); setobj2t(L, luaH_set(L, hvalue(t), L.top - 2), L.top - 1); luaC_barriert(L, hvalue(t), L.top - 1); L.top -= 2; lua_unlock(L); } public static void lua_rawseti(LuaState L, int idx, int n) { StkId o; lua_lock(L); api_checknelems(L, 1); o = index2adr(L, idx); api_check(L, ttistable(o)); setobj2t(L, luaH_setnum(L, hvalue(o), n), L.top - 1); luaC_barriert(L, hvalue(o), L.top - 1); StkId.dec(ref L.top); lua_unlock(L); } public static int lua_setmetatable(LuaState L, int objindex) { TValue obj; Table mt; lua_lock(L); api_checknelems(L, 1); obj = index2adr(L, objindex); api_checkvalidindex(L, obj); if (ttisnil(L.top - 1)) mt = null; else { api_check(L, ttistable(L.top - 1)); mt = hvalue(L.top - 1); } switch (ttype(obj)) { case LUA_TTABLE: { hvalue(obj).metatable = mt; if (mt != null) luaC_objbarriert(L, hvalue(obj), mt); break; } case LUA_TUSERDATA: { uvalue(obj).metatable = mt; if (mt != null) luaC_objbarrier(L, rawuvalue(obj), mt); break; } default: { G(L).mt[ttype(obj)] = mt; break; } } StkId.dec(ref L.top); lua_unlock(L); return 1; } public static int lua_setfenv(LuaState L, int idx) { StkId o; int res = 1; lua_lock(L); api_checknelems(L, 1); o = index2adr(L, idx); api_checkvalidindex(L, o); api_check(L, ttistable(L.top - 1)); switch (ttype(o)) { case LUA_TFUNCTION: clvalue(o).c.env = hvalue(L.top - 1); break; case LUA_TUSERDATA: uvalue(o).env = hvalue(L.top - 1); break; case LUA_TTHREAD: sethvalue(L, gt(thvalue(o)), hvalue(L.top - 1)); break; default: res = 0; break; } if (res != 0) luaC_objbarrier(L, gcvalue(o), hvalue(L.top - 1)); StkId.dec(ref L.top); lua_unlock(L); return res; } /* ** `load' and `call' functions (run Lua code) */ public static void adjustresults(LuaState L, int nres) { if (nres == LUA_MULTRET && L.top >= L.ci.top) L.ci.top = L.top; } public static void checkresults(LuaState L, int na, int nr) { api_check(L, (nr) == LUA_MULTRET || (L.ci.top - L.top >= (nr) - (na))); } public static void lua_call(LuaState L, int nargs, int nresults) { StkId func; lua_lock(L); api_checknelems(L, nargs + 1); checkresults(L, nargs, nresults); func = L.top - (nargs + 1); luaD_call(L, func, nresults); adjustresults(L, nresults); lua_unlock(L); } /* ** Execute a protected call. */ public class CallS { /* data to `f_call' */ public StkId func; public int nresults; }; static void f_call(LuaState L, object ud) { CallS c = ud as CallS; luaD_call(L, c.func, c.nresults); } public static int lua_pcall(LuaState L, int nargs, int nresults, int errfunc) { CallS c = new CallS(); int status; ptrdiff_t func; lua_lock(L); api_checknelems(L, nargs + 1); checkresults(L, nargs, nresults); if (errfunc == 0) func = 0; else { StkId o = index2adr(L, errfunc); api_checkvalidindex(L, o); func = savestack(L, o); } c.func = L.top - (nargs + 1); /* function to be called */ c.nresults = nresults; status = luaD_pcall(L, f_call, c, savestack(L, c.func), func); adjustresults(L, nresults); lua_unlock(L); return status; } /* ** Execute a protected C call. */ public class CCallS { /* data to `f_Ccall' */ public lua_CFunction func; public object ud; }; static void f_Ccall(LuaState L, object ud) { CCallS c = ud as CCallS; Closure cl; cl = luaF_newCclosure(L, 0, getcurrenv(L)); cl.c.f = c.func; setclvalue(L, L.top, cl); /* push function */ api_incr_top(L); setpvalue(L.top, c.ud); /* push only argument */ api_incr_top(L); luaD_call(L, L.top - 2, 0); } public static int lua_cpcall(LuaState L, lua_CFunction func, object ud) { CCallS c = new CCallS(); int status; lua_lock(L); c.func = func; c.ud = ud; status = luaD_pcall(L, f_Ccall, c, savestack(L, L.top), 0); lua_unlock(L); return status; } /// <summary> /// Wraps a lua_Reader and its associated data object to provide a read-ahead ("peek") ability. /// </summary> class PeekableLuaReader { readonly lua_Reader inner; readonly object inner_data; CharPtr readahead_buffer; uint readahead_buffer_size; public PeekableLuaReader(lua_Reader inner, object inner_data) { this.inner = inner; this.inner_data = inner_data; } public CharPtr lua_Reader(LuaState L, object ud, out uint sz) { CharPtr ret = lua_ReaderImpl(L, ud, out sz); //Debug.Print("PeekableLuaReader::lua_Reader() returning sz = {0}, buffer = {1}", // sz, // (ret == null) ? "null" : // string.Concat("'", ret.ToStringDebug(), "'") // ); return ret; } CharPtr lua_ReaderImpl(LuaState L, object ud, out uint sz) { if (readahead_buffer != null && readahead_buffer_size != 0) { CharPtr tmp = readahead_buffer; sz = readahead_buffer_size; readahead_buffer = null; return tmp; } return inner(L, inner_data, out sz); } static readonly CharPtr empty_buffer = new CharPtr(new char[1]); public int peek(LuaState L, object ud) { if (readahead_buffer == null) { readahead_buffer = inner(L, inner_data, out readahead_buffer_size); if (readahead_buffer == null) { readahead_buffer = empty_buffer; readahead_buffer_size = 0; } } if (readahead_buffer_size == 0) return -1; // EOF return readahead_buffer[0]; } } class CharPtrLuaReader { CharPtr buffer; uint size; public CharPtrLuaReader(CharPtr buffer, int size) { if (size < 0) throw new ArgumentException("size must be >= 0!"); this.buffer = buffer; this.size = (uint)size; } public CharPtr lua_Reader(LuaState L, object ud, out uint sz) { CharPtr old_buffer = buffer; sz = size; buffer = null; size = 0; return old_buffer; } } #if OVERRIDE_LOAD /// <summary> /// Performs SharpLua-specific preprocessing magic for lua_load() /// </summary> /// <param name="reader">Original lua_Reader.</param> /// <param name="data">Data object for the original lua_Reader</param> static void SharpLua_OverrideLoad(LuaState L, ref lua_Reader reader, ref object data) { // Wrap our reader in a PeekableLuaReader. PeekableLuaReader plr = new PeekableLuaReader(reader, data); reader = plr.lua_Reader; data = plr; // Look ahead to see if it's something we're interested in. int peek_char = plr.peek(L, plr); if (peek_char == LUA_SIGNATURE[0]) return; // if it's empty, or there's no binary value, there's no work to be done. // Okay, we are. Read the whole thing into memory RIGHT NOW char[] cur_buffer = null; int cur_buffer_size = 0; CharPtr next_data; uint _next_data_size; while ( (next_data = reader(L, data, out _next_data_size)) != null ) { int next_data_size = checked((int) _next_data_size); if (next_data_size == 0) continue; char[] new_buffer = new char[cur_buffer_size + next_data_size + 1]; if (cur_buffer_size > 0) { Array.Copy(cur_buffer, 0, new_buffer, 0, cur_buffer_size); } Array.Copy(next_data.chars, next_data.index, new_buffer, cur_buffer_size, next_data_size); cur_buffer = new_buffer; cur_buffer_size = cur_buffer.Length - 1; } Lexer l = new Lexer(); TokenReader tr = l.Lex(new CharPtr(cur_buffer)); Parser p = new Parser(tr); Ast.Chunk c = p.Parse(); Visitors.LuaCompatibleOutput lco = new Visitors.LuaCompatibleOutput(); string s = lco.Format(c); CharPtr s_buf = new CharPtr(s); // Replace the provided lua_Reader with one that reads out of the CharPtrLuaReader. CharPtrLuaReader cplr = new CharPtrLuaReader(s_buf, s.Length); reader = cplr.lua_Reader; data = cplr; } #endif public static int lua_load(LuaState L, lua_Reader reader, object data, CharPtr chunkname) { ZIO z = new ZIO(); int status; lua_lock(L); if (chunkname == null) chunkname = "?"; #if OVERRIDE_LOAD //#if false // SharpLua_OverrideLoad(L, ref reader, ref data); #endif luaZ_init(L, z, reader, data); status = luaD_protectedparser(L, z, chunkname); lua_unlock(L); if (data is LoadF) { LoadF f = data as LoadF; if (f.f != null) { f.f.Close(); } } return status; } public static int lua_dump(LuaState L, lua_Writer writer, object data) { int status; TValue o; lua_lock(L); api_checknelems(L, 1); o = L.top - 1; if (isLfunction(o)) status = luaU_dump(L, clvalue(o).l.p, writer, data, 0); else status = 1; lua_unlock(L); return status; } public static int lua_status(LuaState L) { return L.status; } /* ** Garbage-collection function */ public static int lua_gc(LuaState L, int what, int data) { int res = 0; GlobalState g; lua_lock(L); g = G(L); switch (what) { case LUA_GCSTOP: { g.GCthreshold = MAX_LUMEM; break; } case LUA_GCRESTART: { g.GCthreshold = g.totalbytes; break; } case LUA_GCCOLLECT: { luaC_fullgc(L); break; } case LUA_GCCOUNT: { /* GC values are expressed in Kbytes: #bytes/2^10 */ res = cast_int(g.totalbytes >> 10); break; } case LUA_GCCOUNTB: { res = cast_int(g.totalbytes & 0x3ff); break; } case LUA_GCSTEP: { lu_mem a = ((lu_mem)data << 10); if (a <= g.totalbytes) g.GCthreshold = (uint)(g.totalbytes - a); else g.GCthreshold = 0; while (g.GCthreshold <= g.totalbytes) { luaC_step(L); if (g.gcstate == GCSpause) { /* end of cycle? */ res = 1; /* signal it */ break; } } break; } case LUA_GCSETPAUSE: { res = g.gcpause; g.gcpause = data; break; } case LUA_GCSETSTEPMUL: { res = g.gcstepmul; g.gcstepmul = data; break; } default: res = -1; /* invalid option */ break; } lua_unlock(L); return res; } /* ** miscellaneous functions */ public static int lua_error(LuaState L) { lua_lock(L); api_checknelems(L, 1); luaG_errormsg(L); lua_unlock(L); return 0; /* to avoid warnings */ } public static int lua_next(LuaState L, int idx) { StkId t; int more; lua_lock(L); t = index2adr(L, idx); api_check(L, ttistable(t)); more = luaH_next(L, hvalue(t), L.top - 1); if (more != 0) { api_incr_top(L); } else /* no more elements */ StkId.dec(ref L.top); /* remove key */ lua_unlock(L); return more; } public static void lua_concat(LuaState L, int n) { lua_lock(L); api_checknelems(L, n); if (n >= 2) { luaC_checkGC(L); luaV_concat(L, n, cast_int(L.top - L.base_) - 1); L.top -= (n - 1); } else if (n == 0) { /* push empty string */ setsvalue2s(L, L.top, luaS_newlstr(L, "", 0)); api_incr_top(L); } /* else n == 1; nothing to do */ lua_unlock(L); } public static lua_Alloc lua_getallocf(LuaState L, ref object ud) { lua_Alloc f; lua_lock(L); if (ud != null) ud = G(L).ud; f = G(L).frealloc; lua_unlock(L); return f; } public static void lua_setallocf(LuaState L, lua_Alloc f, object ud) { lua_lock(L); G(L).ud = ud; G(L).frealloc = f; lua_unlock(L); } public static object lua_newuserdata(LuaState L, uint size) { Udata u; lua_lock(L); luaC_checkGC(L); u = luaS_newudata(L, size, getcurrenv(L)); setuvalue(L, L.top, u); api_incr_top(L); lua_unlock(L); return u.user_data; } // this one is used internally only internal static object lua_newuserdata(LuaState L, Type t) { Udata u; lua_lock(L); luaC_checkGC(L); u = luaS_newudata(L, t, getcurrenv(L)); setuvalue(L, L.top, u); api_incr_top(L); lua_unlock(L); return u.user_data; } static CharPtr aux_upvalue(StkId fi, int n, ref TValue val) { Closure f; if (!ttisfunction(fi)) return null; f = clvalue(fi); if (f.c.isC != 0) { if (!(1 <= n && n <= f.c.nupvalues)) return null; val = f.c.upvalue[n - 1]; return ""; } else { Proto p = f.l.p; if (!(1 <= n && n <= p.sizeupvalues)) return null; val = f.l.upvals[n - 1].v; return getstr(p.upvalues[n - 1]); } } public static CharPtr lua_getupvalue(LuaState L, int funcindex, int n) { CharPtr name; TValue val = new TValue(); lua_lock(L); name = aux_upvalue(index2adr(L, funcindex), n, ref val); if (name != null) { setobj2s(L, L.top, val); api_incr_top(L); } lua_unlock(L); return name; } public static CharPtr lua_setupvalue(LuaState L, int funcindex, int n) { CharPtr name; TValue val = new TValue(); StkId fi; lua_lock(L); fi = index2adr(L, funcindex); api_checknelems(L, 1); name = aux_upvalue(fi, n, ref val); if (name != null) { StkId.dec(ref L.top); setobj(L, val, L.top); luaC_barrier(L, clvalue(fi), L.top); } lua_unlock(L); return name; } } }
using UnityEngine; namespace Sabresaurus.SabreCSG { public static class MathHelper { public static float InverseLerpNoClamp(float from, float to, float value) { if (from < to) { value -= from; value /= to - from; return value; } else { return 1f - (value - to) / (from - to); } } public static Vector3 VectorInDirection(Vector3 sourceVector, Vector3 direction) { return direction * Vector3.Dot(sourceVector, direction); } public static Vector3 ClosestPointOnPlane(Vector3 point, Plane plane) { float signedDistance = plane.GetDistanceToPoint(point); return point - plane.normal * signedDistance; } // From http://answers.unity3d.com/questions/344630/how-would-i-find-the-closest-vector3-point-to-a-gi.html public static float DistanceToRay(Vector3 X0, Ray ray) { Vector3 X1 = ray.origin; // get the definition of a line from the ray Vector3 X2 = ray.origin + ray.direction; Vector3 X0X1 = (X0 - X1); Vector3 X0X2 = (X0 - X2); return (Vector3.Cross(X0X1, X0X2).magnitude / (X1 - X2).magnitude); // magic } // From: http://wiki.unity3d.com/index.php/3d_Math_functions // Two non-parallel lines which may or may not touch each other have a point on each line which are closest // to each other. This function finds those two points. If the lines are not parallel, the function // outputs true, otherwise false. public static bool ClosestPointsOnTwoLines(out Vector3 closestPointLine1, out Vector3 closestPointLine2, Vector3 linePoint1, Vector3 lineVec1, Vector3 linePoint2, Vector3 lineVec2) { closestPointLine1 = Vector3.zero; closestPointLine2 = Vector3.zero; float a = Vector3.Dot(lineVec1, lineVec1); float b = Vector3.Dot(lineVec1, lineVec2); float e = Vector3.Dot(lineVec2, lineVec2); float d = (a * e) - (b * b); //lines are not parallel if (d != 0.0f) { Vector3 r = linePoint1 - linePoint2; float c = Vector3.Dot(lineVec1, r); float f = Vector3.Dot(lineVec2, r); float s = (b * f - c * e) / d; float t = (a * f - c * b) / d; closestPointLine1 = linePoint1 + lineVec1 * Mathf.Clamp01(s); closestPointLine2 = linePoint2 + lineVec2 * Mathf.Clamp01(t); return true; } else { return false; } } // From: http://wiki.unity3d.com/index.php/3d_Math_functions //This function finds out on which side of a line segment the point is located. //The point is assumed to be on a line created by linePoint1 and linePoint2. If the point is not on //the line segment, project it on the line using ProjectPointOnLine() first. //Returns 0 if point is on the line segment. //Returns 1 if point is outside of the line segment and located on the side of linePoint1. //Returns 2 if point is outside of the line segment and located on the side of linePoint2. public static int PointOnWhichSideOfLineSegment(Vector3 linePoint1, Vector3 linePoint2, Vector3 point){ Vector3 lineVec = linePoint2 - linePoint1; Vector3 pointVec = point - linePoint1; float dot = Vector3.Dot(pointVec, lineVec); //point is on side of linePoint2, compared to linePoint1 if(dot > 0){ //point is on the line segment if(pointVec.magnitude <= lineVec.magnitude){ return 0; } //point is not on the line segment and it is on the side of linePoint2 else{ return 2; } } //Point is not on side of linePoint2, compared to linePoint1. //Point is not on the line segment and it is on the side of linePoint1. else{ return 1; } } // From: http://wiki.unity3d.com/index.php/3d_Math_functions //This function returns a point which is a projection from a point to a line. //The line is regarded infinite. If the line is finite, use ProjectPointOnLineSegment() instead. public static Vector3 ProjectPointOnLine(Vector3 linePoint, Vector3 lineVec, Vector3 point){ //get vector from point on line to point in space Vector3 linePointToPoint = point - linePoint; float t = Vector3.Dot(linePointToPoint, lineVec); return linePoint + lineVec * t; } // From: http://wiki.unity3d.com/index.php/3d_Math_functions //This function returns a point which is a projection from a point to a line segment. //If the projected point lies outside of the line segment, the projected point will //be clamped to the appropriate line edge. //If the line is infinite instead of a segment, use ProjectPointOnLine() instead. public static Vector3 ProjectPointOnLineSegment(Vector3 linePoint1, Vector3 linePoint2, Vector3 point){ Vector3 vector = linePoint2 - linePoint1; Vector3 projectedPoint = ProjectPointOnLine(linePoint1, vector.normalized, point); int side = PointOnWhichSideOfLineSegment(linePoint1, linePoint2, projectedPoint); //The projected point is on the line segment if(side == 0){ return projectedPoint; } if(side == 1){ return linePoint1; } if(side == 2){ return linePoint2; } //output is invalid return Vector3.zero; } public static Vector3 ClosestPointOnLine(Ray ray, Vector3 lineStart, Vector3 lineEnd) { Vector3 rayStart = ray.origin; Vector3 rayDirection = ray.direction * 10000; // Outputs Vector3 closestPointLine1; Vector3 closestPointLine2; MathHelper.ClosestPointsOnTwoLines(out closestPointLine1, out closestPointLine2, rayStart, rayDirection, lineStart, lineEnd - lineStart); // Only interested in the closest point on the line (lineStart -> lineEnd), not the ray return closestPointLine1; } public static float RoundFloat(float value, float gridScale) { float reciprocal = 1f / gridScale; return gridScale * Mathf.Round(reciprocal * value); } public static Vector3 RoundVector3(Vector3 vector) { vector.x = Mathf.Round(vector.x); vector.y = Mathf.Round(vector.y); vector.z = Mathf.Round(vector.z); return vector; } public static Vector3 RoundVector3(Vector3 vector, float gridScale) { // By dividing the source value by the scale, rounding it, then rescaling it, we calculate the rounding float reciprocal = 1f / gridScale; vector.x = gridScale * Mathf.Round(reciprocal * vector.x); vector.y = gridScale * Mathf.Round(reciprocal * vector.y); vector.z = gridScale * Mathf.Round(reciprocal * vector.z); return vector; } public static Vector2 RoundVector2(Vector3 vector) { vector.x = Mathf.Round(vector.x); vector.y = Mathf.Round(vector.y); return vector; } public static Vector2 RoundVector2(Vector2 vector, float gridScale) { // By dividing the source value by the scale, rounding it, then rescaling it, we calculate the rounding float reciprocal = 1f / gridScale; vector.x = gridScale * Mathf.Round(reciprocal * vector.x); vector.y = gridScale * Mathf.Round(reciprocal * vector.y); return vector; } public static Vector3 VectorAbs(Vector3 vector) { vector.x = Mathf.Abs(vector.x); vector.y = Mathf.Abs(vector.y); vector.z = Mathf.Abs(vector.z); return vector; } public static int Wrap(int i, int range) { if (i < 0) { i = range - 1; } if (i >= range) { i = 0; } return i; } public static float Wrap(float i, float range) { if (i < 0) { i = range - 1; } if (i >= range) { i = 0; } return i; } public static float WrapAngle(float angle) { while(angle > 180) { angle -= 360; } while(angle <= -180) { angle += 360; } return angle; } const float EPSILON_LOWER = 0.001f; public static bool PlaneEqualsLooser(Plane plane1, Plane plane2) { if( Mathf.Abs(plane1.distance - plane2.distance) < EPSILON_LOWER && Mathf.Abs(plane1.normal.x - plane2.normal.x) < EPSILON_LOWER && Mathf.Abs(plane1.normal.y - plane2.normal.y) < EPSILON_LOWER && Mathf.Abs(plane1.normal.z - plane2.normal.z) < EPSILON_LOWER) { return true; } else { return false; } } public static bool IsVectorInteger(Vector3 vector) { if(vector.x % 1f != 0 || vector.y % 1f != 0 || vector.z % 1f != 0) { return false; } else { return true; } } public static bool IsVectorOnGrid(Vector3 position, Vector3 mask, float gridScale) { if(mask.x != 0) { if(position.x % gridScale != 0) { return false; } } if(mask.y != 0) { if(position.y % gridScale != 0) { return false; } } if(mask.z != 0) { if(position.z % gridScale != 0) { return false; } } return true; } } }
using GTANetworkAPI; using Newtonsoft.Json.Linq; //Disapproved by god himself //Just use the API functions, you have nothing else to worry about //Things to note //More things like vehicle mods will be added in the next version /* API FUNCTIONS: public static void SetVehicleWindowState(Vehicle veh, WindowID window, WindowState state) public static WindowState GetVehicleWindowState(Vehicle veh, WindowID window) public static void SetVehicleWheelState(Vehicle veh, WheelID wheel, WheelState state) public static WheelState GetVehicleWheelState(Vehicle veh, WheelID wheel) public static void SetVehicleDirt(Vehicle veh, float dirt) public static float GetVehicleDirt(Vehicle veh) public static void SetDoorState(Vehicle veh, DoorID door, DoorState state) public static DoorState GetDoorState(Vehicle veh, DoorID door) public static void SetEngineState(Vehicle veh, bool status) public static bool GetEngineState(Vehicle veh) public static void SetLockStatus(Vehicle veh, bool status) public static bool GetLockState(Vehicle veh) */ namespace VehicleSync { //Enums for ease of use public enum WindowID { WindowFrontRight, WindowFrontLeft, WindowRearRight, WindowRearLeft } public enum WindowState { WindowFixed, WindowDown, WindowBroken } public enum DoorID { DoorFrontLeft, DoorFrontRight, DoorRearLeft, DoorRearRight, DoorHood, DoorTrunk } public enum DoorState { DoorClosed, DoorOpen, DoorBroken, } public enum WheelID { Wheel0, Wheel1, Wheel2, Wheel3, Wheel4, Wheel5, Wheel6, Wheel7, Wheel8, Wheel9 } public enum WheelState { WheelFixed, WheelBurst, WheelOnRim, } public class VehicleStreaming : Script { //This is the data object which will be synced to vehicles public class VehicleSyncData { //Used to bypass some streaming bugs public Vector3 Position { get; set; } = new Vector3(); public Vector3 Rotation { get; set; } = new Vector3(); //Basics public float Dirt { get; set; } = 0.0f; public bool Locked { get; set; } = true; public bool Engine { get; set; } = false; //(Not synced) public float BodyHealth { get; set; } = 1000.0f; public float EngineHealth { get; set; } = 1000.0f; //Doors 0-7 (0 = closed, 1 = open, 2 = broken) (This uses enums so don't worry about it) public int[] Door { get; set; } = new int[8] { 0, 0, 0, 0, 0, 0, 0, 0 }; //Windows (0 = up, 1 = down, 2 = smashed) (This uses enums so don't worry about it) public int[] Window { get; set; } = new int[4] { 0, 0, 0, 0 }; //Wheels 0-7, 45/47 (0 = fixed, 1 = flat, 2 = missing) (This uses enums so don't worry about it) public int[] Wheel { get; set; } = new int[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; } //API functions for people to use public static void SetVehicleWindowState(Vehicle veh, WindowID window, WindowState state) { VehicleSyncData data = GetVehicleSyncData(veh); if (data == default(VehicleSyncData)) //If data doesn't exist create a new one. This is the process for all API functions data = new VehicleSyncData(); data.Window[(int)window] = (int)state; UpdateVehicleSyncData(veh, data); NAPI.ClientEvent.TriggerClientEventInDimension(veh.Dimension, "VehStream_SetVehicleWindowStatus_Single", veh.Handle, (int)window, (int)state); } public static WindowState GetVehicleWindowState(Vehicle veh, WindowID window) { VehicleSyncData data = GetVehicleSyncData(veh); if (data == default(VehicleSyncData)) { data = new VehicleSyncData(); UpdateVehicleSyncData(veh, data); } return (WindowState)data.Window[(int)window]; } public static void SetVehicleWheelState(Vehicle veh, WheelID wheel, WheelState state) { VehicleSyncData data = GetVehicleSyncData(veh); if (data == default(VehicleSyncData)) data = new VehicleSyncData(); data.Wheel[(int)wheel] = (int)state; UpdateVehicleSyncData(veh, data); NAPI.ClientEvent.TriggerClientEventInDimension(veh.Dimension, "VehStream_SetVehicleWheelStatus_Single", veh.Handle, (int)wheel, (int)state); } public static WheelState GetVehicleWheelState(Vehicle veh, WheelID wheel) { VehicleSyncData data = GetVehicleSyncData(veh); if (data == default(VehicleSyncData)) { data = new VehicleSyncData(); UpdateVehicleSyncData(veh, data); } return (WheelState)data.Wheel[(int)wheel]; } public static void SetVehicleDirt(Vehicle veh, float dirt) { VehicleSyncData data = GetVehicleSyncData(veh); if (data == default(VehicleSyncData)) data = new VehicleSyncData(); data.Dirt = dirt; UpdateVehicleSyncData(veh, data); NAPI.ClientEvent.TriggerClientEventInDimension(veh.Dimension, "VehStream_SetVehicleDirtLevel", veh.Handle, dirt); } public static float GetVehicleDirt(Vehicle veh) { VehicleSyncData data = GetVehicleSyncData(veh); if (data == default(VehicleSyncData)) { data = new VehicleSyncData(); UpdateVehicleSyncData(veh, data); } return data.Dirt; } public static void SetDoorState(Vehicle veh, DoorID door, DoorState state) { VehicleSyncData data = GetVehicleSyncData(veh); if (data == default(VehicleSyncData)) data = new VehicleSyncData(); data.Door[(int)door] = (int)state; UpdateVehicleSyncData(veh, data); NAPI.ClientEvent.TriggerClientEventInDimension(veh.Dimension, "VehStream_SetVehicleDoorStatus_Single", veh, (int)door, (int)state); } public static DoorState GetDoorState(Vehicle veh, DoorID door) { VehicleSyncData data = GetVehicleSyncData(veh); if (data == default(VehicleSyncData)) { data = new VehicleSyncData(); UpdateVehicleSyncData(veh, data); } return (DoorState)data.Door[(int)door]; } public static void SetEngineState(Vehicle veh, bool status) { VehicleSyncData data = GetVehicleSyncData(veh); if (data == default(VehicleSyncData)) data = new VehicleSyncData(); data.Engine = status; UpdateVehicleSyncData(veh, data); NAPI.ClientEvent.TriggerClientEventInDimension(veh.Dimension, "VehStream_SetEngineStatus", veh, status); } public static bool GetEngineState(Vehicle veh) { VehicleSyncData data = GetVehicleSyncData(veh); if (data == default(VehicleSyncData)) { data = new VehicleSyncData(); UpdateVehicleSyncData(veh, data); } return data.Engine; } public static void SetLockStatus(Vehicle veh, bool status) { VehicleSyncData data = GetVehicleSyncData(veh); if (data == default(VehicleSyncData)) data = new VehicleSyncData(); data.Locked = status; UpdateVehicleSyncData(veh, data); NAPI.ClientEvent.TriggerClientEventInDimension(veh.Dimension, "VehStream_SetLockStatus", veh, status); } public static bool GetLockState(Vehicle veh) { VehicleSyncData data = GetVehicleSyncData(veh); if (data == default(VehicleSyncData)) { data = new VehicleSyncData(); UpdateVehicleSyncData(veh, data); } return data.Locked; } //Used internally only but publicly available in case any of you need it public static VehicleSyncData GetVehicleSyncData(Vehicle veh) { if (veh != null) { if (NAPI.Entity.DoesEntityExist(veh)) { if (NAPI.Data.HasEntitySharedData(veh.Handle, "VehicleSyncData")) { //API converts class objects to JObject so we have to change it back JObject obj = NAPI.Data.GetEntitySharedData(veh.Handle, "VehicleSyncData"); return obj.ToObject<VehicleSyncData>(); } } } return default(VehicleSyncData); //null } //Used internally only but publicly available in case any of you need it public static bool UpdateVehicleSyncData(Vehicle veh, VehicleSyncData data) { if (veh != null) { if (NAPI.Entity.DoesEntityExist(veh)) { if (data != null) { data.Position = veh.Position; data.Rotation = veh.Rotation; NAPI.Data.SetEntitySharedData(veh, "VehicleSyncData", data); return true; } } } return false; } //Called from the client to sync dirt level [RemoteEvent("VehStream_SetDirtLevel")] public void VehStreamSetDirtLevel(Client player, Vehicle veh, float dirt) { VehicleSyncData data = GetVehicleSyncData(veh); if (data == default(VehicleSyncData)) data = new VehicleSyncData(); data.Dirt = dirt; UpdateVehicleSyncData(veh, data); //Re-distribute the goods NAPI.ClientEvent.TriggerClientEventInDimension(veh.Dimension, "VehStream_SetVehicleDirtLevel", veh.Handle, dirt); } //Called from the client to sync door data [RemoteEvent("VehStream_SetDoorData")] public void VehStreamSetDoorData(Client player, Vehicle veh, int door1state, int door2state, int door3state, int door4state, int door5state, int door6state, int door7state, int door8state) { VehicleSyncData data = GetVehicleSyncData(veh); if (data == default(VehicleSyncData)) data = new VehicleSyncData(); data.Door[0] = door1state; data.Door[1] = door2state; data.Door[2] = door3state; data.Door[3] = door4state; data.Door[4] = door5state; data.Door[5] = door6state; data.Door[6] = door7state; data.Door[7] = door8state; UpdateVehicleSyncData(veh, data); //Re-distribute the goods NAPI.ClientEvent.TriggerClientEventInDimension(veh.Dimension, "VehStream_SetVehicleDoorStatus", veh.Handle, door1state, door2state, door3state, door4state, door5state, door6state, door7state, door8state); } //Called from the client to sync window data [RemoteEvent("VehStream_SetWindowData")] public void VehStreamSetWindowData(Client player, Vehicle veh, int window1state, int window2state, int window3state, int window4state) { VehicleSyncData data = GetVehicleSyncData(veh); if (data == default(VehicleSyncData)) data = new VehicleSyncData(); data.Window[0] = window1state; data.Window[1] = window2state; data.Window[2] = window3state; data.Window[3] = window4state; UpdateVehicleSyncData(veh, data); //Re-distribute the goods NAPI.ClientEvent.TriggerClientEventInDimension(veh.Dimension, "VehStream_SetVehicleWindowStatus", veh.Handle, window1state, window2state, window3state, window4state); } //Called from the client to sync wheel data [RemoteEvent("VehStream_SetWheelData")] public void VehStreamSetWheelData(Client player, Vehicle veh, int wheel1state, int wheel2state, int wheel3state, int wheel4state, int wheel5state, int wheel6state, int wheel7state, int wheel8state, int wheel9state, int wheel10state) { VehicleSyncData data = GetVehicleSyncData(veh); if (data == default(VehicleSyncData)) data = new VehicleSyncData(); data.Wheel[0] = wheel1state; data.Wheel[1] = wheel2state; data.Wheel[2] = wheel3state; data.Wheel[3] = wheel4state; data.Wheel[4] = wheel5state; data.Wheel[5] = wheel6state; data.Wheel[6] = wheel7state; data.Wheel[7] = wheel8state; data.Wheel[8] = wheel9state; data.Wheel[9] = wheel10state; UpdateVehicleSyncData(veh, data); //Re-distribute the goods NAPI.ClientEvent.TriggerClientEventInDimension(veh.Dimension, "VehStream_SetVehicleWheelStatus", veh.Handle, wheel1state, wheel2state, wheel3state, wheel4state, wheel5state, wheel6state, wheel7state, wheel8state, wheel9state, wheel10state); } //Other events [ServerEvent(Event.PlayerEnterVehicleAttempt)] public void VehStreamEnterAttempt(Client player, Vehicle veh, sbyte seat) { VehicleSyncData data = GetVehicleSyncData(veh); if (data == default(VehicleSyncData)) data = new VehicleSyncData(); UpdateVehicleSyncData(veh, data); NAPI.ClientEvent.TriggerClientEvent(player, "VehStream_PlayerEnterVehicleAttempt", veh, seat); } [ServerEvent(Event.PlayerExitVehicleAttempt)] public void VehStreamExitAttempt(Client player, Vehicle veh) { VehicleSyncData data = GetVehicleSyncData(veh); if (data == default(VehicleSyncData)) data = new VehicleSyncData(); data.Position = veh.Position; data.Rotation = veh.Rotation; UpdateVehicleSyncData(veh, data); NAPI.ClientEvent.TriggerClientEvent(player, "VehStream_PlayerExitVehicleAttempt", veh); } [ServerEvent(Event.PlayerExitVehicle)] public void VehStreamExit(Client player, Vehicle veh) { VehicleSyncData data = GetVehicleSyncData(veh); if (data == default(VehicleSyncData)) data = new VehicleSyncData(); data.Position = veh.Position; data.Rotation = veh.Rotation; UpdateVehicleSyncData(veh, data); NAPI.ClientEvent.TriggerClientEvent(player, "VehStream_PlayerExitVehicle", veh); } [ServerEvent(Event.PlayerEnterVehicle)] public void VehStreamEnter(Client player, Vehicle veh, sbyte seat) { VehicleSyncData data = GetVehicleSyncData(veh); if (data == default(VehicleSyncData)) data = new VehicleSyncData(); UpdateVehicleSyncData(veh, data); NAPI.ClientEvent.TriggerClientEvent(player, "VehStream_PlayerEnterVehicle", veh, seat); } [ServerEvent(Event.VehicleDamage)] public void VehDamage(Vehicle veh, float bodyHealthLoss, float engineHealthLoss) { VehicleSyncData data = GetVehicleSyncData(veh); if (data == default(VehicleSyncData)) data = new VehicleSyncData(); data.BodyHealth -= bodyHealthLoss; data.EngineHealth -= engineHealthLoss; UpdateVehicleSyncData(veh, data); if (NAPI.Vehicle.GetVehicleDriver(veh) != default(Client)) //Doesn't work? NAPI.ClientEvent.TriggerClientEvent(NAPI.Vehicle.GetVehicleDriver(veh), "VehStream_PlayerExitVehicleAttempt", veh); } [ServerEvent(Event.VehicleDoorBreak)] public void VehDoorBreak(Vehicle veh, int index) { VehicleSyncData data = GetVehicleSyncData(veh); if (data == default(VehicleSyncData)) data = new VehicleSyncData(); data.Door[index] = 2; UpdateVehicleSyncData(veh, data); NAPI.ClientEvent.TriggerClientEventInDimension(veh.Dimension, "VehStream_SetVehicleDoorStatus", veh.Handle, data.Door[0], data.Door[1], data.Door[2], data.Door[3], data.Door[4], data.Door[5], data.Door[6], data.Door[7]); } } }
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2009 Oracle. All rights reserved. * */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using System.Xml; using NUnit.Framework; using BerkeleyDB; namespace CsharpAPITest { [TestFixture] public class DatabaseExceptionTest { [Test] public void TestDB_REP_DUPMASTER() { DatabaseException.ThrowException(ErrorCodes.DB_REP_DUPMASTER); } [Test] public void TestDB_REP_HOLDELECTION() { DatabaseException.ThrowException(ErrorCodes.DB_REP_HOLDELECTION); } [Test] public void TestDB_REP_IGNORE() { DatabaseException.ThrowException(ErrorCodes.DB_REP_IGNORE); } [Test] public void TestDB_REP_ISPERM() { DatabaseException.ThrowException(ErrorCodes.DB_REP_ISPERM); } [Test] public void TestDB_REP_JOIN_FAILURE() { DatabaseException.ThrowException(ErrorCodes.DB_REP_JOIN_FAILURE); } [Test] public void TestDB_REP_NEWSITE() { DatabaseException.ThrowException(ErrorCodes.DB_REP_NEWSITE); } [Test] public void TestDB_REP_NOTPERM() { DatabaseException.ThrowException(ErrorCodes.DB_REP_NOTPERM); } [Test] public void TestDeadlockException() { try { DatabaseException.ThrowException(ErrorCodes.DB_LOCK_DEADLOCK); } catch (DeadlockException e) { Assert.AreEqual(ErrorCodes.DB_LOCK_DEADLOCK, e.ErrorCode); } } [Test] public void TestForeignConflictException() { try { DatabaseException.ThrowException(ErrorCodes.DB_FOREIGN_CONFLICT); } catch (ForeignConflictException e) { Assert.AreEqual(ErrorCodes.DB_FOREIGN_CONFLICT, e.ErrorCode); } } [Test] public void TestKeyEmptyException() { try { DatabaseException.ThrowException(ErrorCodes.DB_KEYEMPTY); } catch (KeyEmptyException e) { Assert.AreEqual(ErrorCodes.DB_KEYEMPTY, e.ErrorCode); } } [Test] public void TestKeyExistException() { try { DatabaseException.ThrowException(ErrorCodes.DB_KEYEXIST); } catch (KeyExistException e) { Assert.AreEqual(ErrorCodes.DB_KEYEXIST, e.ErrorCode); } } [Test] public void TestLeaseExpiredException() { try { DatabaseException.ThrowException(ErrorCodes.DB_REP_LEASE_EXPIRED); } catch (LeaseExpiredException e) { Assert.AreEqual(ErrorCodes.DB_REP_LEASE_EXPIRED, e.ErrorCode); } } [Test] public void TestLockNotGrantedException() { try { DatabaseException.ThrowException(ErrorCodes.DB_LOCK_NOTGRANTED); } catch (LockNotGrantedException e) { Assert.AreEqual(ErrorCodes.DB_LOCK_NOTGRANTED, e.ErrorCode); } } [Test] public void TestNotFoundException() { try { DatabaseException.ThrowException(ErrorCodes.DB_NOTFOUND); } catch (NotFoundException e) { Assert.AreEqual(ErrorCodes.DB_NOTFOUND, e.ErrorCode); } } [Test] public void TestOldVersionException() { try { DatabaseException.ThrowException(ErrorCodes.DB_OLD_VERSION); } catch (OldVersionException e) { Assert.AreEqual(ErrorCodes.DB_OLD_VERSION, e.ErrorCode); } } [Test] public void TestPageNotFoundException() { try { DatabaseException.ThrowException(ErrorCodes.DB_PAGE_NOTFOUND); } catch (PageNotFoundException e) { Assert.AreEqual(ErrorCodes.DB_PAGE_NOTFOUND, e.ErrorCode); } } [Test] public void TestRunRecoveryException() { try { DatabaseException.ThrowException(ErrorCodes.DB_RUNRECOVERY); } catch (RunRecoveryException e) { Assert.AreEqual(ErrorCodes.DB_RUNRECOVERY, e.ErrorCode); } } [Test] public void TestVerificationException() { try { DatabaseException.ThrowException(ErrorCodes.DB_VERIFY_BAD); } catch (VerificationException e) { Assert.AreEqual(ErrorCodes.DB_VERIFY_BAD, e.ErrorCode); } } [Test] public void TestVersionMismatchException() { try { DatabaseException.ThrowException(ErrorCodes.DB_VERSION_MISMATCH); } catch (VersionMismatchException e) { Assert.AreEqual(ErrorCodes.DB_VERSION_MISMATCH, e.ErrorCode); } } } }
#if ENABLE_PLAYFABADMIN_API using PlayFab.AdminModels; namespace PlayFab.Events { public partial class PlayFabEvents { public event PlayFabRequestEvent<CreatePlayerSharedSecretRequest> OnAdminCreatePlayerSharedSecretRequestEvent; public event PlayFabResultEvent<CreatePlayerSharedSecretResult> OnAdminCreatePlayerSharedSecretResultEvent; public event PlayFabRequestEvent<DeletePlayerSharedSecretRequest> OnAdminDeletePlayerSharedSecretRequestEvent; public event PlayFabResultEvent<DeletePlayerSharedSecretResult> OnAdminDeletePlayerSharedSecretResultEvent; public event PlayFabRequestEvent<GetPlayerSharedSecretsRequest> OnAdminGetPlayerSharedSecretsRequestEvent; public event PlayFabResultEvent<GetPlayerSharedSecretsResult> OnAdminGetPlayerSharedSecretsResultEvent; public event PlayFabRequestEvent<GetPolicyRequest> OnAdminGetPolicyRequestEvent; public event PlayFabResultEvent<GetPolicyResponse> OnAdminGetPolicyResultEvent; public event PlayFabRequestEvent<SetPlayerSecretRequest> OnAdminSetPlayerSecretRequestEvent; public event PlayFabResultEvent<SetPlayerSecretResult> OnAdminSetPlayerSecretResultEvent; public event PlayFabRequestEvent<UpdatePlayerSharedSecretRequest> OnAdminUpdatePlayerSharedSecretRequestEvent; public event PlayFabResultEvent<UpdatePlayerSharedSecretResult> OnAdminUpdatePlayerSharedSecretResultEvent; public event PlayFabRequestEvent<UpdatePolicyRequest> OnAdminUpdatePolicyRequestEvent; public event PlayFabResultEvent<UpdatePolicyResponse> OnAdminUpdatePolicyResultEvent; public event PlayFabRequestEvent<BanUsersRequest> OnAdminBanUsersRequestEvent; public event PlayFabResultEvent<BanUsersResult> OnAdminBanUsersResultEvent; public event PlayFabRequestEvent<LookupUserAccountInfoRequest> OnAdminGetUserAccountInfoRequestEvent; public event PlayFabResultEvent<LookupUserAccountInfoResult> OnAdminGetUserAccountInfoResultEvent; public event PlayFabRequestEvent<GetUserBansRequest> OnAdminGetUserBansRequestEvent; public event PlayFabResultEvent<GetUserBansResult> OnAdminGetUserBansResultEvent; public event PlayFabRequestEvent<ResetUsersRequest> OnAdminResetUsersRequestEvent; public event PlayFabResultEvent<BlankResult> OnAdminResetUsersResultEvent; public event PlayFabRequestEvent<RevokeAllBansForUserRequest> OnAdminRevokeAllBansForUserRequestEvent; public event PlayFabResultEvent<RevokeAllBansForUserResult> OnAdminRevokeAllBansForUserResultEvent; public event PlayFabRequestEvent<RevokeBansRequest> OnAdminRevokeBansRequestEvent; public event PlayFabResultEvent<RevokeBansResult> OnAdminRevokeBansResultEvent; public event PlayFabRequestEvent<SendAccountRecoveryEmailRequest> OnAdminSendAccountRecoveryEmailRequestEvent; public event PlayFabResultEvent<SendAccountRecoveryEmailResult> OnAdminSendAccountRecoveryEmailResultEvent; public event PlayFabRequestEvent<UpdateBansRequest> OnAdminUpdateBansRequestEvent; public event PlayFabResultEvent<UpdateBansResult> OnAdminUpdateBansResultEvent; public event PlayFabRequestEvent<UpdateUserTitleDisplayNameRequest> OnAdminUpdateUserTitleDisplayNameRequestEvent; public event PlayFabResultEvent<UpdateUserTitleDisplayNameResult> OnAdminUpdateUserTitleDisplayNameResultEvent; public event PlayFabRequestEvent<CreatePlayerStatisticDefinitionRequest> OnAdminCreatePlayerStatisticDefinitionRequestEvent; public event PlayFabResultEvent<CreatePlayerStatisticDefinitionResult> OnAdminCreatePlayerStatisticDefinitionResultEvent; public event PlayFabRequestEvent<DeleteUsersRequest> OnAdminDeleteUsersRequestEvent; public event PlayFabResultEvent<DeleteUsersResult> OnAdminDeleteUsersResultEvent; public event PlayFabRequestEvent<GetDataReportRequest> OnAdminGetDataReportRequestEvent; public event PlayFabResultEvent<GetDataReportResult> OnAdminGetDataReportResultEvent; public event PlayFabRequestEvent<GetPlayerStatisticDefinitionsRequest> OnAdminGetPlayerStatisticDefinitionsRequestEvent; public event PlayFabResultEvent<GetPlayerStatisticDefinitionsResult> OnAdminGetPlayerStatisticDefinitionsResultEvent; public event PlayFabRequestEvent<GetPlayerStatisticVersionsRequest> OnAdminGetPlayerStatisticVersionsRequestEvent; public event PlayFabResultEvent<GetPlayerStatisticVersionsResult> OnAdminGetPlayerStatisticVersionsResultEvent; public event PlayFabRequestEvent<GetUserDataRequest> OnAdminGetUserDataRequestEvent; public event PlayFabResultEvent<GetUserDataResult> OnAdminGetUserDataResultEvent; public event PlayFabRequestEvent<GetUserDataRequest> OnAdminGetUserInternalDataRequestEvent; public event PlayFabResultEvent<GetUserDataResult> OnAdminGetUserInternalDataResultEvent; public event PlayFabRequestEvent<GetUserDataRequest> OnAdminGetUserPublisherDataRequestEvent; public event PlayFabResultEvent<GetUserDataResult> OnAdminGetUserPublisherDataResultEvent; public event PlayFabRequestEvent<GetUserDataRequest> OnAdminGetUserPublisherInternalDataRequestEvent; public event PlayFabResultEvent<GetUserDataResult> OnAdminGetUserPublisherInternalDataResultEvent; public event PlayFabRequestEvent<GetUserDataRequest> OnAdminGetUserPublisherReadOnlyDataRequestEvent; public event PlayFabResultEvent<GetUserDataResult> OnAdminGetUserPublisherReadOnlyDataResultEvent; public event PlayFabRequestEvent<GetUserDataRequest> OnAdminGetUserReadOnlyDataRequestEvent; public event PlayFabResultEvent<GetUserDataResult> OnAdminGetUserReadOnlyDataResultEvent; public event PlayFabRequestEvent<IncrementPlayerStatisticVersionRequest> OnAdminIncrementPlayerStatisticVersionRequestEvent; public event PlayFabResultEvent<IncrementPlayerStatisticVersionResult> OnAdminIncrementPlayerStatisticVersionResultEvent; public event PlayFabRequestEvent<RefundPurchaseRequest> OnAdminRefundPurchaseRequestEvent; public event PlayFabResultEvent<RefundPurchaseResponse> OnAdminRefundPurchaseResultEvent; public event PlayFabRequestEvent<ResetUserStatisticsRequest> OnAdminResetUserStatisticsRequestEvent; public event PlayFabResultEvent<ResetUserStatisticsResult> OnAdminResetUserStatisticsResultEvent; public event PlayFabRequestEvent<ResolvePurchaseDisputeRequest> OnAdminResolvePurchaseDisputeRequestEvent; public event PlayFabResultEvent<ResolvePurchaseDisputeResponse> OnAdminResolvePurchaseDisputeResultEvent; public event PlayFabRequestEvent<UpdatePlayerStatisticDefinitionRequest> OnAdminUpdatePlayerStatisticDefinitionRequestEvent; public event PlayFabResultEvent<UpdatePlayerStatisticDefinitionResult> OnAdminUpdatePlayerStatisticDefinitionResultEvent; public event PlayFabRequestEvent<UpdateUserDataRequest> OnAdminUpdateUserDataRequestEvent; public event PlayFabResultEvent<UpdateUserDataResult> OnAdminUpdateUserDataResultEvent; public event PlayFabRequestEvent<UpdateUserInternalDataRequest> OnAdminUpdateUserInternalDataRequestEvent; public event PlayFabResultEvent<UpdateUserDataResult> OnAdminUpdateUserInternalDataResultEvent; public event PlayFabRequestEvent<UpdateUserDataRequest> OnAdminUpdateUserPublisherDataRequestEvent; public event PlayFabResultEvent<UpdateUserDataResult> OnAdminUpdateUserPublisherDataResultEvent; public event PlayFabRequestEvent<UpdateUserInternalDataRequest> OnAdminUpdateUserPublisherInternalDataRequestEvent; public event PlayFabResultEvent<UpdateUserDataResult> OnAdminUpdateUserPublisherInternalDataResultEvent; public event PlayFabRequestEvent<UpdateUserDataRequest> OnAdminUpdateUserPublisherReadOnlyDataRequestEvent; public event PlayFabResultEvent<UpdateUserDataResult> OnAdminUpdateUserPublisherReadOnlyDataResultEvent; public event PlayFabRequestEvent<UpdateUserDataRequest> OnAdminUpdateUserReadOnlyDataRequestEvent; public event PlayFabResultEvent<UpdateUserDataResult> OnAdminUpdateUserReadOnlyDataResultEvent; public event PlayFabRequestEvent<AddNewsRequest> OnAdminAddNewsRequestEvent; public event PlayFabResultEvent<AddNewsResult> OnAdminAddNewsResultEvent; public event PlayFabRequestEvent<AddVirtualCurrencyTypesRequest> OnAdminAddVirtualCurrencyTypesRequestEvent; public event PlayFabResultEvent<BlankResult> OnAdminAddVirtualCurrencyTypesResultEvent; public event PlayFabRequestEvent<DeleteStoreRequest> OnAdminDeleteStoreRequestEvent; public event PlayFabResultEvent<DeleteStoreResult> OnAdminDeleteStoreResultEvent; public event PlayFabRequestEvent<GetCatalogItemsRequest> OnAdminGetCatalogItemsRequestEvent; public event PlayFabResultEvent<GetCatalogItemsResult> OnAdminGetCatalogItemsResultEvent; public event PlayFabRequestEvent<GetPublisherDataRequest> OnAdminGetPublisherDataRequestEvent; public event PlayFabResultEvent<GetPublisherDataResult> OnAdminGetPublisherDataResultEvent; public event PlayFabRequestEvent<GetRandomResultTablesRequest> OnAdminGetRandomResultTablesRequestEvent; public event PlayFabResultEvent<GetRandomResultTablesResult> OnAdminGetRandomResultTablesResultEvent; public event PlayFabRequestEvent<GetStoreItemsRequest> OnAdminGetStoreItemsRequestEvent; public event PlayFabResultEvent<GetStoreItemsResult> OnAdminGetStoreItemsResultEvent; public event PlayFabRequestEvent<GetTitleDataRequest> OnAdminGetTitleDataRequestEvent; public event PlayFabResultEvent<GetTitleDataResult> OnAdminGetTitleDataResultEvent; public event PlayFabRequestEvent<GetTitleDataRequest> OnAdminGetTitleInternalDataRequestEvent; public event PlayFabResultEvent<GetTitleDataResult> OnAdminGetTitleInternalDataResultEvent; public event PlayFabRequestEvent<ListVirtualCurrencyTypesRequest> OnAdminListVirtualCurrencyTypesRequestEvent; public event PlayFabResultEvent<ListVirtualCurrencyTypesResult> OnAdminListVirtualCurrencyTypesResultEvent; public event PlayFabRequestEvent<RemoveVirtualCurrencyTypesRequest> OnAdminRemoveVirtualCurrencyTypesRequestEvent; public event PlayFabResultEvent<BlankResult> OnAdminRemoveVirtualCurrencyTypesResultEvent; public event PlayFabRequestEvent<UpdateCatalogItemsRequest> OnAdminSetCatalogItemsRequestEvent; public event PlayFabResultEvent<UpdateCatalogItemsResult> OnAdminSetCatalogItemsResultEvent; public event PlayFabRequestEvent<UpdateStoreItemsRequest> OnAdminSetStoreItemsRequestEvent; public event PlayFabResultEvent<UpdateStoreItemsResult> OnAdminSetStoreItemsResultEvent; public event PlayFabRequestEvent<SetTitleDataRequest> OnAdminSetTitleDataRequestEvent; public event PlayFabResultEvent<SetTitleDataResult> OnAdminSetTitleDataResultEvent; public event PlayFabRequestEvent<SetTitleDataRequest> OnAdminSetTitleInternalDataRequestEvent; public event PlayFabResultEvent<SetTitleDataResult> OnAdminSetTitleInternalDataResultEvent; public event PlayFabRequestEvent<SetupPushNotificationRequest> OnAdminSetupPushNotificationRequestEvent; public event PlayFabResultEvent<SetupPushNotificationResult> OnAdminSetupPushNotificationResultEvent; public event PlayFabRequestEvent<UpdateCatalogItemsRequest> OnAdminUpdateCatalogItemsRequestEvent; public event PlayFabResultEvent<UpdateCatalogItemsResult> OnAdminUpdateCatalogItemsResultEvent; public event PlayFabRequestEvent<UpdateRandomResultTablesRequest> OnAdminUpdateRandomResultTablesRequestEvent; public event PlayFabResultEvent<UpdateRandomResultTablesResult> OnAdminUpdateRandomResultTablesResultEvent; public event PlayFabRequestEvent<UpdateStoreItemsRequest> OnAdminUpdateStoreItemsRequestEvent; public event PlayFabResultEvent<UpdateStoreItemsResult> OnAdminUpdateStoreItemsResultEvent; public event PlayFabRequestEvent<AddUserVirtualCurrencyRequest> OnAdminAddUserVirtualCurrencyRequestEvent; public event PlayFabResultEvent<ModifyUserVirtualCurrencyResult> OnAdminAddUserVirtualCurrencyResultEvent; public event PlayFabRequestEvent<GetUserInventoryRequest> OnAdminGetUserInventoryRequestEvent; public event PlayFabResultEvent<GetUserInventoryResult> OnAdminGetUserInventoryResultEvent; public event PlayFabRequestEvent<GrantItemsToUsersRequest> OnAdminGrantItemsToUsersRequestEvent; public event PlayFabResultEvent<GrantItemsToUsersResult> OnAdminGrantItemsToUsersResultEvent; public event PlayFabRequestEvent<RevokeInventoryItemRequest> OnAdminRevokeInventoryItemRequestEvent; public event PlayFabResultEvent<RevokeInventoryResult> OnAdminRevokeInventoryItemResultEvent; public event PlayFabRequestEvent<SubtractUserVirtualCurrencyRequest> OnAdminSubtractUserVirtualCurrencyRequestEvent; public event PlayFabResultEvent<ModifyUserVirtualCurrencyResult> OnAdminSubtractUserVirtualCurrencyResultEvent; public event PlayFabRequestEvent<GetMatchmakerGameInfoRequest> OnAdminGetMatchmakerGameInfoRequestEvent; public event PlayFabResultEvent<GetMatchmakerGameInfoResult> OnAdminGetMatchmakerGameInfoResultEvent; public event PlayFabRequestEvent<GetMatchmakerGameModesRequest> OnAdminGetMatchmakerGameModesRequestEvent; public event PlayFabResultEvent<GetMatchmakerGameModesResult> OnAdminGetMatchmakerGameModesResultEvent; public event PlayFabRequestEvent<ModifyMatchmakerGameModesRequest> OnAdminModifyMatchmakerGameModesRequestEvent; public event PlayFabResultEvent<ModifyMatchmakerGameModesResult> OnAdminModifyMatchmakerGameModesResultEvent; public event PlayFabRequestEvent<AddServerBuildRequest> OnAdminAddServerBuildRequestEvent; public event PlayFabResultEvent<AddServerBuildResult> OnAdminAddServerBuildResultEvent; public event PlayFabRequestEvent<GetServerBuildInfoRequest> OnAdminGetServerBuildInfoRequestEvent; public event PlayFabResultEvent<GetServerBuildInfoResult> OnAdminGetServerBuildInfoResultEvent; public event PlayFabRequestEvent<GetServerBuildUploadURLRequest> OnAdminGetServerBuildUploadUrlRequestEvent; public event PlayFabResultEvent<GetServerBuildUploadURLResult> OnAdminGetServerBuildUploadUrlResultEvent; public event PlayFabRequestEvent<ListBuildsRequest> OnAdminListServerBuildsRequestEvent; public event PlayFabResultEvent<ListBuildsResult> OnAdminListServerBuildsResultEvent; public event PlayFabRequestEvent<ModifyServerBuildRequest> OnAdminModifyServerBuildRequestEvent; public event PlayFabResultEvent<ModifyServerBuildResult> OnAdminModifyServerBuildResultEvent; public event PlayFabRequestEvent<RemoveServerBuildRequest> OnAdminRemoveServerBuildRequestEvent; public event PlayFabResultEvent<RemoveServerBuildResult> OnAdminRemoveServerBuildResultEvent; public event PlayFabRequestEvent<SetPublisherDataRequest> OnAdminSetPublisherDataRequestEvent; public event PlayFabResultEvent<SetPublisherDataResult> OnAdminSetPublisherDataResultEvent; public event PlayFabRequestEvent<GetCloudScriptRevisionRequest> OnAdminGetCloudScriptRevisionRequestEvent; public event PlayFabResultEvent<GetCloudScriptRevisionResult> OnAdminGetCloudScriptRevisionResultEvent; public event PlayFabRequestEvent<GetCloudScriptVersionsRequest> OnAdminGetCloudScriptVersionsRequestEvent; public event PlayFabResultEvent<GetCloudScriptVersionsResult> OnAdminGetCloudScriptVersionsResultEvent; public event PlayFabRequestEvent<SetPublishedRevisionRequest> OnAdminSetPublishedRevisionRequestEvent; public event PlayFabResultEvent<SetPublishedRevisionResult> OnAdminSetPublishedRevisionResultEvent; public event PlayFabRequestEvent<UpdateCloudScriptRequest> OnAdminUpdateCloudScriptRequestEvent; public event PlayFabResultEvent<UpdateCloudScriptResult> OnAdminUpdateCloudScriptResultEvent; public event PlayFabRequestEvent<DeleteContentRequest> OnAdminDeleteContentRequestEvent; public event PlayFabResultEvent<BlankResult> OnAdminDeleteContentResultEvent; public event PlayFabRequestEvent<GetContentListRequest> OnAdminGetContentListRequestEvent; public event PlayFabResultEvent<GetContentListResult> OnAdminGetContentListResultEvent; public event PlayFabRequestEvent<GetContentUploadUrlRequest> OnAdminGetContentUploadUrlRequestEvent; public event PlayFabResultEvent<GetContentUploadUrlResult> OnAdminGetContentUploadUrlResultEvent; public event PlayFabRequestEvent<ResetCharacterStatisticsRequest> OnAdminResetCharacterStatisticsRequestEvent; public event PlayFabResultEvent<ResetCharacterStatisticsResult> OnAdminResetCharacterStatisticsResultEvent; public event PlayFabRequestEvent<AddPlayerTagRequest> OnAdminAddPlayerTagRequestEvent; public event PlayFabResultEvent<AddPlayerTagResult> OnAdminAddPlayerTagResultEvent; public event PlayFabRequestEvent<GetAllActionGroupsRequest> OnAdminGetAllActionGroupsRequestEvent; public event PlayFabResultEvent<GetAllActionGroupsResult> OnAdminGetAllActionGroupsResultEvent; public event PlayFabRequestEvent<GetAllSegmentsRequest> OnAdminGetAllSegmentsRequestEvent; public event PlayFabResultEvent<GetAllSegmentsResult> OnAdminGetAllSegmentsResultEvent; public event PlayFabRequestEvent<GetPlayersSegmentsRequest> OnAdminGetPlayerSegmentsRequestEvent; public event PlayFabResultEvent<GetPlayerSegmentsResult> OnAdminGetPlayerSegmentsResultEvent; public event PlayFabRequestEvent<GetPlayersInSegmentRequest> OnAdminGetPlayersInSegmentRequestEvent; public event PlayFabResultEvent<GetPlayersInSegmentResult> OnAdminGetPlayersInSegmentResultEvent; public event PlayFabRequestEvent<GetPlayerTagsRequest> OnAdminGetPlayerTagsRequestEvent; public event PlayFabResultEvent<GetPlayerTagsResult> OnAdminGetPlayerTagsResultEvent; public event PlayFabRequestEvent<RemovePlayerTagRequest> OnAdminRemovePlayerTagRequestEvent; public event PlayFabResultEvent<RemovePlayerTagResult> OnAdminRemovePlayerTagResultEvent; public event PlayFabRequestEvent<AbortTaskInstanceRequest> OnAdminAbortTaskInstanceRequestEvent; public event PlayFabResultEvent<EmptyResult> OnAdminAbortTaskInstanceResultEvent; public event PlayFabRequestEvent<CreateActionsOnPlayerSegmentTaskRequest> OnAdminCreateActionsOnPlayersInSegmentTaskRequestEvent; public event PlayFabResultEvent<CreateTaskResult> OnAdminCreateActionsOnPlayersInSegmentTaskResultEvent; public event PlayFabRequestEvent<CreateCloudScriptTaskRequest> OnAdminCreateCloudScriptTaskRequestEvent; public event PlayFabResultEvent<CreateTaskResult> OnAdminCreateCloudScriptTaskResultEvent; public event PlayFabRequestEvent<DeleteTaskRequest> OnAdminDeleteTaskRequestEvent; public event PlayFabResultEvent<EmptyResult> OnAdminDeleteTaskResultEvent; public event PlayFabRequestEvent<GetTaskInstanceRequest> OnAdminGetActionsOnPlayersInSegmentTaskInstanceRequestEvent; public event PlayFabResultEvent<GetActionsOnPlayersInSegmentTaskInstanceResult> OnAdminGetActionsOnPlayersInSegmentTaskInstanceResultEvent; public event PlayFabRequestEvent<GetTaskInstanceRequest> OnAdminGetCloudScriptTaskInstanceRequestEvent; public event PlayFabResultEvent<GetCloudScriptTaskInstanceResult> OnAdminGetCloudScriptTaskInstanceResultEvent; public event PlayFabRequestEvent<GetTaskInstancesRequest> OnAdminGetTaskInstancesRequestEvent; public event PlayFabResultEvent<GetTaskInstancesResult> OnAdminGetTaskInstancesResultEvent; public event PlayFabRequestEvent<GetTasksRequest> OnAdminGetTasksRequestEvent; public event PlayFabResultEvent<GetTasksResult> OnAdminGetTasksResultEvent; public event PlayFabRequestEvent<RunTaskRequest> OnAdminRunTaskRequestEvent; public event PlayFabResultEvent<RunTaskResult> OnAdminRunTaskResultEvent; public event PlayFabRequestEvent<UpdateTaskRequest> OnAdminUpdateTaskRequestEvent; public event PlayFabResultEvent<EmptyResult> OnAdminUpdateTaskResultEvent; } } #endif
// // Copyright (C) Microsoft. All rights reserved. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Management.Automation; using System.Management.Automation.Remoting; using System.Threading; namespace Microsoft.PowerShell.Commands { /// <summary> /// This cmdlet suspends the jobs that are Job2. Errors are added for each Job that is not Job2. /// </summary> #if !CORECLR [SuppressMessage("Microsoft.PowerShell", "PS1012:CallShouldProcessOnlyIfDeclaringSupport")] [Cmdlet(VerbsLifecycle.Suspend, "Job", SupportsShouldProcess = true, DefaultParameterSetName = JobCmdletBase.SessionIdParameterSet, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=210613")] [OutputType(typeof(Job))] #endif public class SuspendJobCommand : JobCmdletBase, IDisposable { #region Parameters /// <summary> /// Specifies the Jobs objects which need to be /// suspended /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = JobParameterSet)] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public Job[] Job { get { return _jobs; } set { _jobs = value; } } private Job[] _jobs; /// <summary> /// /// </summary> public override String[] Command { get { return null; } } /// <summary> /// If state of the job is running , this will forcefully suspend it. /// </summary> [Parameter(ParameterSetName = RemoveJobCommand.InstanceIdParameterSet)] [Parameter(ParameterSetName = RemoveJobCommand.JobParameterSet)] [Parameter(ParameterSetName = RemoveJobCommand.NameParameterSet)] [Parameter(ParameterSetName = RemoveJobCommand.SessionIdParameterSet)] [Parameter(ParameterSetName = RemoveJobCommand.FilterParameterSet)] [Parameter(ParameterSetName = RemoveJobCommand.StateParameterSet)] [Alias("F")] public SwitchParameter Force { get { return _force; } set { _force = value; } } private bool _force = false; /// <summary> /// /// </summary> [Parameter()] public SwitchParameter Wait { get { return _wait; } set { _wait = value; } } private bool _wait = false; #endregion Parameters #region Overrides /// <summary> /// Suspend the Job. /// </summary> protected override void ProcessRecord() { //List of jobs to suspend List<Job> jobsToSuspend = null; switch (ParameterSetName) { case NameParameterSet: { jobsToSuspend = FindJobsMatchingByName(true, false, true, false); } break; case InstanceIdParameterSet: { jobsToSuspend = FindJobsMatchingByInstanceId(true, false, true, false); } break; case SessionIdParameterSet: { jobsToSuspend = FindJobsMatchingBySessionId(true, false, true, false); } break; case StateParameterSet: { jobsToSuspend = FindJobsMatchingByState(false); } break; case FilterParameterSet: { jobsToSuspend = FindJobsMatchingByFilter(false); } break; default: { jobsToSuspend = CopyJobsToList(_jobs, false, false); } break; } _allJobsToSuspend.AddRange(jobsToSuspend); foreach (Job job in jobsToSuspend) { var job2 = job as Job2; // If the job is not Job2, the suspend operation is not supported. if (job2 == null) { WriteError( new ErrorRecord( PSTraceSource.NewNotSupportedException(RemotingErrorIdStrings.JobSuspendNotSupported, job.Id), "Job2OperationNotSupportedOnJob", ErrorCategory.InvalidType, (object)job)); continue; } string targetString = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemovePSJobWhatIfTarget, job.Command, job.Id); if (ShouldProcess(targetString, VerbsLifecycle.Suspend)) { if (_wait) { _cleanUpActions.Add(job2, HandleSuspendJobCompleted); } else { if (job2.IsFinishedState(job2.JobStateInfo.State) || job2.JobStateInfo.State == JobState.Stopping) { _warnInvalidState = true; continue; } if (job2.JobStateInfo.State == JobState.Suspending || job2.JobStateInfo.State == JobState.Suspended) continue; job2.StateChanged += noWait_Job2_StateChanged; } job2.SuspendJobCompleted += HandleSuspendJobCompleted; lock (_syncObject) { if (!_pendingJobs.Contains(job2.InstanceId)) { _pendingJobs.Add(job2.InstanceId); } } // there could be possiblility that the job gets completed befor or after the // subscribing to nowait_job2_statechanged event so checking it again. if (!_wait && (job2.IsFinishedState(job2.JobStateInfo.State) || job2.JobStateInfo.State == JobState.Suspending || job2.JobStateInfo.State == JobState.Suspended)) { this.ProcessExecutionErrorsAndReleaseWaitHandle(job2); } job2.SuspendJobAsync(_force, RemotingErrorIdStrings.ForceSuspendJob); } } } private bool _warnInvalidState = false; private readonly HashSet<Guid> _pendingJobs = new HashSet<Guid>(); private readonly ManualResetEvent _waitForJobs = new ManualResetEvent(false); private readonly Dictionary<Job2, EventHandler<AsyncCompletedEventArgs>> _cleanUpActions = new Dictionary<Job2, EventHandler<AsyncCompletedEventArgs>>(); private readonly List<ErrorRecord> _errorsToWrite = new List<ErrorRecord>(); private readonly List<Job> _allJobsToSuspend = new List<Job>(); private readonly object _syncObject = new object(); private bool _needToCheckForWaitingJobs; private void noWait_Job2_StateChanged(object sender, JobStateEventArgs e) { Job job = sender as Job; switch (e.JobStateInfo.State) { case JobState.Completed: case JobState.Stopped: case JobState.Failed: case JobState.Suspended: case JobState.Suspending: this.ProcessExecutionErrorsAndReleaseWaitHandle(job); break; } } private void HandleSuspendJobCompleted(object sender, AsyncCompletedEventArgs eventArgs) { Job job = sender as Job; if (eventArgs.Error != null && eventArgs.Error is InvalidJobStateException) { _warnInvalidState = true; } this.ProcessExecutionErrorsAndReleaseWaitHandle(job); } private void ProcessExecutionErrorsAndReleaseWaitHandle(Job job) { bool releaseWait = false; lock (_syncObject) { if (_pendingJobs.Contains(job.InstanceId)) { _pendingJobs.Remove(job.InstanceId); } else { // there could be a possiblity of race condiftion where this fucntion is getting called twice // so if job doesn't present in the _pendingJobs then just return return; } if (_needToCheckForWaitingJobs && _pendingJobs.Count == 0) releaseWait = true; } if (!_wait) { job.StateChanged -= noWait_Job2_StateChanged; Job2 job2 = job as Job2; if (job2 != null) job2.SuspendJobCompleted -= HandleSuspendJobCompleted; } var parentJob = job as ContainerParentJob; if (parentJob != null && parentJob.ExecutionError.Count > 0) { foreach ( var e in parentJob.ExecutionError.Where(e => e.FullyQualifiedErrorId == "ContainerParentJobSuspendAsyncError") ) { if (e.Exception is InvalidJobStateException) { // if any errors were invalid job state exceptions, warn the user. // This is to support Get-Job | Resume-Job scenarios when many jobs // are Completed, etc. _warnInvalidState = true; } else { _errorsToWrite.Add(e); } } } // end processing has been called // set waithandle if this is the last one if (releaseWait) _waitForJobs.Set(); } /// <summary> /// End Processing. /// </summary> protected override void EndProcessing() { bool haveToWait = false; lock (_syncObject) { _needToCheckForWaitingJobs = true; if (_pendingJobs.Count > 0) haveToWait = true; } if (haveToWait) _waitForJobs.WaitOne(); if (_warnInvalidState) WriteWarning(RemotingErrorIdStrings.SuspendJobInvalidJobState); foreach (var e in _errorsToWrite) WriteError(e); foreach (var j in _allJobsToSuspend) WriteObject(j); base.EndProcessing(); } /// <summary> /// /// </summary> protected override void StopProcessing() { _waitForJobs.Set(); } #endregion Overrides #region Dispose /// <summary> /// /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// /// </summary> /// <param name="disposing"></param> protected void Dispose(bool disposing) { if (!disposing) return; foreach (var pair in _cleanUpActions) { pair.Key.SuspendJobCompleted -= pair.Value; } _waitForJobs.Dispose(); } #endregion Dispose } }
using System; using System.Drawing; using System.Windows.Forms; using System.Diagnostics; using System.Xml; using Microsoft.Win32; using System.IO; namespace RatioMaster_source { public partial class MainForm : Form { public static bool _24h_format_enabled = false; readonly RMCollection<RM> data = new RMCollection<RM>(); // RM current; int items = 0; // RM current; int allit = 0; bool trayIconBaloonIsUp = false; private VersionChecker versionChecker = new VersionChecker(""); internal NewVersionForm verform = new NewVersionForm(); string Log = ""; internal MainForm() { InitializeComponent(); Text = "RatioMaster.NET " + VersionChecker.PublicVersion; } private void newToolStripMenuItem_Click(object sender, EventArgs e) { Add(""); } private void MainForm_Load(object sender, EventArgs e) { versionChecker = new VersionChecker(Log); if (versionChecker.CheckNewVersion()) verform.ShowDialog(); txtVersion.Text = VersionChecker.PublicVersion; txtRemote.Text = versionChecker.RemoteVersion; txtLocal.Text = VersionChecker.LocalVersion; txtReleaseDate.Text = VersionChecker.ReleaseDate; Log += versionChecker.Log; // lblSize.Text = this.Width + "x" + this.Height; LoadSettings(); // trayIcon.Text += versionChecker.PublicVersion; // trayIcon.BalloonTipTitle += " " + versionChecker.PublicVersion; Add(""); lblIp.Text = Functions.GetIp(); tab_TabIndexChanged(null, null); } private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { AboutForm About = new AboutForm(VersionChecker.PublicVersion); About.ShowDialog(); } private void winRestore() { if (WindowState == FormWindowState.Minimized) { Show(); WindowState = FormWindowState.Normal; trayIcon.Visible = false; } // Activate the form. Activate(); Focus(); } private void MainForm_Move(object sender, EventArgs e) { if (this == null) { // This happen on create. return; } // If we are minimizing the form then hide it so it doesn't show up on the task bar if (WindowState == FormWindowState.Minimized && chkMinimize.Checked) { Hide(); trayIcon.Visible = true; } else { // any other windows state show it. Show(); } // lblLocation.Text = this.Location.X + "x" + this.Location.Y; } private void Exit() { if (GetTabType(tab.SelectedTab) == TabType.RatioMaster) SaveSettings((RM)tab.SelectedTab.Controls[0]); foreach (TabPage tabb in tab.TabPages) { if (GetTabType(tabb) == TabType.RatioMaster) ((RM)tabb.Controls[0]).StopButton_Click(null, null); } Application.Exit(); Process.GetCurrentProcess().Kill(); } private static TabType GetTabType(TabPage page) { // string name = page.Controls[0].ToString(); return TabType.RatioMaster; } #region Tray items private void trayIcon_MouseDoubleClick(object sender, MouseEventArgs e) { if (e.Button != MouseButtons.Right) { winRestore(); } } private void restoreToolStripMenuItem_Click(object sender, EventArgs e) { winRestore(); } private void trayIcon_MouseMove(object sender, MouseEventArgs e) { if (checkShowTrayBaloon.Checked && trayIconBaloonIsUp == false) { trayIcon.BalloonTipText = ""; foreach (TabPage tabb in tab.TabPages) { try { if (GetTabType(tabb) == TabType.RatioMaster) trayIcon.BalloonTipText += tabb.Text + " - " + ((RM)tabb.Controls[0]).currentTorrentFile.Name + "\n"; } catch { trayIcon.BalloonTipText += tabb.Text + " - Not opened!" + "\n"; } } trayIcon.ShowBalloonTip(0); } } private void goToProgramSiteToolStripMenuItem_Click(object sender, EventArgs e) { Process.Start(Links.ProgramPage); } private void toolStripMenuItem4_Click(object sender, EventArgs e) { Exit(); } private void trayIcon_BalloonTipClicked(object sender, EventArgs e) { trayIconBaloonIsUp = false; } private void trayIcon_BalloonTipClosed(object sender, EventArgs e) { trayIconBaloonIsUp = false; } private void trayIcon_BalloonTipShown(object sender, EventArgs e) { trayIconBaloonIsUp = true; } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { Exit(); } #endregion #region Tabs private void EditCurrent(string FileName) { ((RM)tab.SelectedTab.Controls[0]).loadTorrentFileInfo(FileName); } private void Add(string FileName) { items++; allit++; RM rm1 = new RM(); data.Add(rm1); // current = rm1; TabPage page1 = new TabPage("RM " + allit.ToString()); page1.Name = "RM" + items.ToString(); page1.Controls.Add(rm1); // page1.Enter += new EventHandler(this.TabPage_Enter); // page1.BorderStyle = BorderStyle.FixedSingle; // page1.BackColor = Color.White; tab.Controls.Add(page1); tab.SelectedTab = page1; lblTabs.Text = allit.ToString(); if (FileName != "") { ((RM)tab.SelectedTab.Controls[0]).loadTorrentFileInfo(FileName); } page1.ToolTipText = "Double click to rename this tab"; tab.ShowToolTips = true; } private void Remove() { if (tab.TabPages.Count < 2) return; int last = tab.SelectedIndex; if (GetTabType(tab.SelectedTab) == TabType.RatioMaster) { ((RM)tab.SelectedTab.Controls[0]).StopButton_Click(null, null); allit--; } tab.TabPages.Remove(tab.SelectedTab); tab.SelectedIndex = last; lblTabs.Text = allit.ToString(); } private void RenameTabs() { int curr = 0; foreach (TabPage thetab in tab.TabPages) { if (thetab.Text.IndexOf("RM ") > -1) { curr++; thetab.Text = "RM " + curr; } } } private void renameCurrentToolStripMenuItem_Click(object sender, EventArgs e) { Prompt prompt = new Prompt("Please select new tab name", "Type new tab name:", tab.SelectedTab.Text); if (prompt.ShowDialog() == DialogResult.OK) tab.SelectedTab.Text = prompt.Result; } private void renameCurrentTab_MouseDoubleClick(object sender, MouseEventArgs e) { Prompt prompt = new Prompt("Please select new tab name", "Type new tab name:", tab.SelectedTab.Text); if (prompt.ShowDialog() == DialogResult.OK) tab.SelectedTab.Text = prompt.Result; } private void removeCurrentToolStripMenuItem_Click(object sender, EventArgs e) { Remove(); RenameTabs(); } #endregion private void MainForm_Resize(object sender, EventArgs e) { tab.Size = new Size(Width - 8, Height - 80); // lblSize.Text = this.Width + "x" + this.Height; } private void goToProgramPageToolStripMenuItem_Click(object sender, EventArgs e) { Process.Start(Links.ProgramPage); } private void goToGitHubPageToolStripMenuItem_Click(object sender, EventArgs e) { Process.Start(Links.GitHubPage); } private void goToAuthorPageToolStripMenuItem_Click(object sender, EventArgs e) { Process.Start(Links.AuthorPage); } private void jOINToOurForumPleaseToolStripMenuItem_Click(object sender, EventArgs e) { Process.Start(Links.PayPal); } private void lblCodedBy_Click(object sender, EventArgs e) { Process.Start(Links.AuthorPage); } private void LoadSettings() { RegistryKey reg = Registry.CurrentUser.OpenSubKey("Software\\RatioMaster.NET", true); if (reg == null) { // The key doesn't exist; create it / open it Registry.CurrentUser.CreateSubKey("Software\\RatioMaster.NET"); return; } try { checkShowTrayBaloon.Checked = ItoB((int)reg.GetValue("BallonTip", false)); chkMinimize.Checked = ItoB((int)reg.GetValue("MinimizeToTray", true)); closeToTrayToolStripMenuItem.Checked = ItoB((int)reg.GetValue("CloseToTray", true)); } catch { } } private void SaveSettings(RM RMdata) { try { RegistryKey reg = Registry.CurrentUser.OpenSubKey("Software\\RatioMaster.NET", true); if (reg == null) { // The key doesn't exist; create it / open it reg = Registry.CurrentUser.CreateSubKey("Software\\RatioMaster.NET"); } reg.SetValue("Version", VersionChecker.PublicVersion, RegistryValueKind.String); reg.SetValue("NewValues", BtoI(RMdata.chkNewValues.Checked), RegistryValueKind.DWord); reg.SetValue("BallonTip", BtoI(checkShowTrayBaloon.Checked), RegistryValueKind.DWord); reg.SetValue("MinimizeToTray", BtoI(chkMinimize.Checked), RegistryValueKind.DWord); reg.SetValue("CloseToTray", BtoI(closeToTrayToolStripMenuItem.Checked), RegistryValueKind.DWord); reg.SetValue("Client", RMdata.cmbClient.SelectedItem, RegistryValueKind.String); reg.SetValue("ClientVersion", RMdata.cmbVersion.SelectedItem, RegistryValueKind.String); reg.SetValue("UploadRate", RMdata.uploadRate.Text, RegistryValueKind.String); reg.SetValue("DownloadRate", RMdata.downloadRate.Text, RegistryValueKind.String); reg.SetValue("Interval", RMdata.interval.Text, RegistryValueKind.String); reg.SetValue("fileSize", RMdata.fileSize.Text, RegistryValueKind.String); reg.SetValue("Directory", RMdata.DefaultDirectory, RegistryValueKind.String); reg.SetValue("TCPlistener", BtoI(RMdata.checkTCPListen.Checked), RegistryValueKind.DWord); reg.SetValue("ScrapeInfo", BtoI(RMdata.checkRequestScrap.Checked), RegistryValueKind.DWord); reg.SetValue("EnableLog", BtoI(RMdata.checkLogEnabled.Checked), RegistryValueKind.DWord); // Radnom value reg.SetValue("GetRandUp", BtoI(RMdata.chkRandUP.Checked), RegistryValueKind.DWord); reg.SetValue("GetRandDown", BtoI(RMdata.chkRandDown.Checked), RegistryValueKind.DWord); reg.SetValue("MinRandUp", RMdata.txtRandUpMin.Text, RegistryValueKind.String); reg.SetValue("MaxRandUp", RMdata.txtRandUpMax.Text, RegistryValueKind.String); reg.SetValue("MinRandDown", RMdata.txtRandDownMin.Text, RegistryValueKind.String); reg.SetValue("MaxRandDown", RMdata.txtRandDownMax.Text, RegistryValueKind.String); // Custom values reg.SetValue("CustomKey", RMdata.customKey.Text, RegistryValueKind.String); reg.SetValue("CustomPeerID", RMdata.customPeerID.Text, RegistryValueKind.String); reg.SetValue("CustomPeers", RMdata.customPeersNum.Text, RegistryValueKind.String); reg.SetValue("CustomPort", RMdata.customPort.Text, RegistryValueKind.String); // Stop after... reg.SetValue("StopWhen", RMdata.cmbStopAfter.SelectedItem, RegistryValueKind.String); reg.SetValue("StopAfter", RMdata.txtStopValue.Text, RegistryValueKind.String); // Proxy reg.SetValue("ProxyType", RMdata.comboProxyType.SelectedItem, RegistryValueKind.String); reg.SetValue("ProxyAdress", RMdata.textProxyHost.Text, RegistryValueKind.String); reg.SetValue("ProxyUser", RMdata.textProxyUser.Text, RegistryValueKind.String); reg.SetValue("ProxyPass", RMdata.textProxyPass.Text, RegistryValueKind.String); reg.SetValue("ProxyPort", RMdata.textProxyPort.Text, RegistryValueKind.String); // Radnom value on next reg.SetValue("GetRandUpNext", BtoI(RMdata.checkRandomUpload.Checked), RegistryValueKind.DWord); reg.SetValue("GetRandDownNext", BtoI(RMdata.checkRandomDownload.Checked), RegistryValueKind.DWord); reg.SetValue("MinRandUpNext", RMdata.RandomUploadFrom.Text, RegistryValueKind.String); reg.SetValue("MaxRandUpNext", RMdata.RandomUploadTo.Text, RegistryValueKind.String); reg.SetValue("MinRandDownNext", RMdata.RandomDownloadFrom.Text, RegistryValueKind.String); reg.SetValue("MaxRandDownNext", RMdata.RandomDownloadTo.Text, RegistryValueKind.String); reg.SetValue("IgnoreFailureReason", BtoI(RMdata.checkIgnoreFailureReason.Checked), RegistryValueKind.DWord); } catch (Exception e) { Log += "Error in SetSettings(): " + e.Message + "\n"; } } internal static Int64 parseValidInt64(string str, Int64 defVal) { try { return Int64.Parse(str); } catch (Exception) { return defVal; } } internal static int ParseValidInt(string str, int defVal) { try { return int.Parse(str); } catch (Exception) { return defVal; } } internal static int BtoI(bool b) { if (b) return 1; else return 0; } internal static bool ItoB(int param) { if (param == 0) return false; if (param == 1) return true; return true; } internal void MainForm_FormClosing(object sender, FormClosingEventArgs e) { if (closeToTrayToolStripMenuItem.Checked && chkMinimize.Checked) { e.Cancel = true; WindowState = FormWindowState.Minimized; Hide(); trayIcon.Visible = true; } else Exit(); } internal void aboutToolStripMenuItem1_Click(object sender, EventArgs e) { AboutForm About = new AboutForm(VersionChecker.PublicVersion); About.ShowDialog(); } private void startToolStripMenuItem_Click(object sender, EventArgs e) { if (GetTabType(tab.SelectedTab) == TabType.RatioMaster) ((RM)tab.SelectedTab.Controls[0]).StartButton_Click(null, null); } private void manualUpdateToolStripMenuItem_Click(object sender, EventArgs e) { if (GetTabType(tab.SelectedTab) == TabType.RatioMaster) ((RM)tab.SelectedTab.Controls[0]).manualUpdateButton_Click(null, null); } private void stopToolStripMenuItem_Click(object sender, EventArgs e) { if (GetTabType(tab.SelectedTab) == TabType.RatioMaster) ((RM)tab.SelectedTab.Controls[0]).StopButton_Click(null, null); } #region Sessions bool startthem = false; bool stopthem = false; private static void AppendItem(XmlDocument aXmlDoc, XmlElement aXmlElement, string Value, string Name) { XmlElement itemElement = aXmlDoc.CreateElement(Name); itemElement.InnerText = Value; aXmlElement.AppendChild(itemElement); } private static void NewMainItem(XmlDocument aXmlDoc, XmlElement aXmlElement, RM data, string name) { AppendItem(aXmlDoc, aXmlElement, name, "Name"); if (data.currentTorrent.filename != null) AppendItem(aXmlDoc, aXmlElement, data.currentTorrent.filename, "Address"); else AppendItem(aXmlDoc, aXmlElement, data.torrentFile.Text, "Address"); AppendItem(aXmlDoc, aXmlElement, data.trackerAddress.Text, "Tracker"); AppendItem(aXmlDoc, aXmlElement, data.uploadRate.Text, "UploadSpeed"); AppendItem(aXmlDoc, aXmlElement, data.chkRandUP.Checked.ToString(), "UploadRandom"); AppendItem(aXmlDoc, aXmlElement, data.txtRandUpMin.Text, "UploadRandMin"); AppendItem(aXmlDoc, aXmlElement, data.txtRandUpMax.Text, "UploadRandMax"); AppendItem(aXmlDoc, aXmlElement, data.downloadRate.Text, "DownloadSpeed"); AppendItem(aXmlDoc, aXmlElement, data.chkRandDown.Checked.ToString(), "DownloadRandom"); AppendItem(aXmlDoc, aXmlElement, data.txtRandDownMin.Text, "DownloadRandMin"); AppendItem(aXmlDoc, aXmlElement, data.txtRandDownMax.Text, "DownloadRandMax"); AppendItem(aXmlDoc, aXmlElement, data.cmbClient.SelectedItem.ToString(), "Client"); AppendItem(aXmlDoc, aXmlElement, data.cmbVersion.SelectedItem.ToString(), "Version"); AppendItem(aXmlDoc, aXmlElement, data.fileSize.Text, "Finished"); AppendItem(aXmlDoc, aXmlElement, data.cmbStopAfter.SelectedItem.ToString(), "StopType"); AppendItem(aXmlDoc, aXmlElement, data.txtStopValue.Text, "StopValue"); AppendItem(aXmlDoc, aXmlElement, data.customPort.Text, "Port"); AppendItem(aXmlDoc, aXmlElement, data.checkTCPListen.Checked.ToString(), "UseTCP"); AppendItem(aXmlDoc, aXmlElement, data.checkRequestScrap.Checked.ToString(), "UseScrape"); AppendItem(aXmlDoc, aXmlElement, data.comboProxyType.SelectedItem.ToString(), "ProxyType"); AppendItem(aXmlDoc, aXmlElement, data.textProxyUser.Text, "ProxyUser"); AppendItem(aXmlDoc, aXmlElement, data.textProxyPass.Text, "ProxyPass"); AppendItem(aXmlDoc, aXmlElement, data.textProxyHost.Text, "ProxyHost"); AppendItem(aXmlDoc, aXmlElement, data.textProxyPort.Text, "ProxyPort"); AppendItem(aXmlDoc, aXmlElement, data.checkRandomUpload.Checked.ToString(), "NextUpdateUpload"); AppendItem(aXmlDoc, aXmlElement, data.RandomUploadFrom.Text, "NextUpdateUploadFrom"); AppendItem(aXmlDoc, aXmlElement, data.RandomUploadTo.Text, "NextUpdateUploadTo"); AppendItem(aXmlDoc, aXmlElement, data.checkRandomDownload.Checked.ToString(), "NextUpdateDownload"); AppendItem(aXmlDoc, aXmlElement, data.RandomDownloadFrom.Text, "NextUpdateDownloadFrom"); AppendItem(aXmlDoc, aXmlElement, data.RandomDownloadTo.Text, "NextUpdateDownloadTo"); AppendItem(aXmlDoc, aXmlElement, data.checkIgnoreFailureReason.Checked.ToString(), "IgnoreFailureReason"); } private void saveCurrentSessionToolStripMenuItem_Click(object sender, EventArgs e) { stopthem = true; saveSession.ShowDialog(); } private void loadSessionToolStripMenuItem_Click(object sender, EventArgs e) { startthem = false; loadSession.ShowDialog(); } private void loadSessionAndStartToolStripMenuItem_Click(object sender, EventArgs e) { startthem = true; loadSession.ShowDialog(); } private void saveCurrentSessionToolStripMenuItem1_Click(object sender, EventArgs e) { stopthem = false; saveSession.ShowDialog(); } private void SaveSession(string Path) { XmlDocument doc = new XmlDocument(); XmlElement main = doc.CreateElement("main"); doc.AppendChild(main); foreach (TabPage tabb in tab.TabPages) { if (GetTabType(tabb) == TabType.RatioMaster) { if (stopthem) ((RM)tabb.Controls[0]).StopButton_Click(null, null); XmlElement child = doc.CreateElement("RatioMaster"); main.AppendChild(child); NewMainItem(doc, child, (RM)tabb.Controls[0], tabb.Text); } } doc.Save(Path); } private void LoadSession(string Path) { XmlDocument doc = new XmlDocument(); doc.Load(Path); XmlNode root = doc.DocumentElement; foreach (XmlNode node in root.ChildNodes) { Add(""); tab.SelectedTab.Text = node["Name"].InnerText; ((RM)tab.SelectedTab.Controls[0]).torrentFile.Text = node["Address"].InnerText; ((RM)tab.SelectedTab.Controls[0]).openFileDialog1.FileName = node["Address"].InnerText; ((RM)tab.SelectedTab.Controls[0]).openFileDialog1_FileOk(null, null); ((RM)tab.SelectedTab.Controls[0]).trackerAddress.Text = node["Tracker"].InnerText; ((RM)tab.SelectedTab.Controls[0]).uploadRate.Text = node["UploadSpeed"].InnerText; ((RM)tab.SelectedTab.Controls[0]).txtRandUpMin.Text = node["UploadRandMin"].InnerText; ((RM)tab.SelectedTab.Controls[0]).txtRandUpMax.Text = node["UploadRandMax"].InnerText; ((RM)tab.SelectedTab.Controls[0]).downloadRate.Text = node["DownloadSpeed"].InnerText; ((RM)tab.SelectedTab.Controls[0]).txtRandDownMin.Text = node["DownloadRandMin"].InnerText; ((RM)tab.SelectedTab.Controls[0]).txtRandDownMax.Text = node["DownloadRandMax"].InnerText; ((RM)tab.SelectedTab.Controls[0]).chkRandUP.Checked = bool.Parse(node["UploadRandom"].InnerText); ((RM)tab.SelectedTab.Controls[0]).chkRandDown.Checked = bool.Parse(node["DownloadRandom"].InnerText); ((RM)tab.SelectedTab.Controls[0]).cmbClient.SelectedItem = node["Client"].InnerText; ((RM)tab.SelectedTab.Controls[0]).cmbVersion.SelectedItem = node["Version"].InnerText; ((RM)tab.SelectedTab.Controls[0]).fileSize.Text = node["Finished"].InnerText; ((RM)tab.SelectedTab.Controls[0]).cmbStopAfter.SelectedItem = node["StopType"].InnerText; ((RM)tab.SelectedTab.Controls[0]).txtStopValue.Text = node["StopValue"].InnerText; ((RM)tab.SelectedTab.Controls[0]).customPort.Text = node["Port"].InnerText; ((RM)tab.SelectedTab.Controls[0]).checkTCPListen.Checked = bool.Parse(node["UseTCP"].InnerText); ((RM)tab.SelectedTab.Controls[0]).checkRequestScrap.Checked = bool.Parse(node["UseScrape"].InnerText); ((RM)tab.SelectedTab.Controls[0]).comboProxyType.SelectedItem = node["ProxyType"].InnerText; ((RM)tab.SelectedTab.Controls[0]).textProxyUser.Text = node["ProxyUser"].InnerText; ((RM)tab.SelectedTab.Controls[0]).textProxyPass.Text = node["ProxyPass"].InnerText; ((RM)tab.SelectedTab.Controls[0]).textProxyHost.Text = node["ProxyHost"].InnerText; ((RM)tab.SelectedTab.Controls[0]).textProxyPort.Text = node["ProxyPort"].InnerText; ((RM)tab.SelectedTab.Controls[0]).checkRandomUpload.Checked = bool.Parse(node["NextUpdateUpload"].InnerText); ((RM)tab.SelectedTab.Controls[0]).checkRandomDownload.Checked = bool.Parse(node["NextUpdateDownload"].InnerText); ((RM)tab.SelectedTab.Controls[0]).RandomUploadFrom.Text = node["NextUpdateUploadFrom"].InnerText; ((RM)tab.SelectedTab.Controls[0]).RandomUploadTo.Text = node["NextUpdateUploadTo"].InnerText; ((RM)tab.SelectedTab.Controls[0]).RandomDownloadFrom.Text = node["NextUpdateDownloadFrom"].InnerText; ((RM)tab.SelectedTab.Controls[0]).RandomDownloadTo.Text = node["NextUpdateDownloadTo"].InnerText; ((RM)tab.SelectedTab.Controls[0]).checkIgnoreFailureReason.Checked = bool.Parse(node["IgnoreFailureReason"].InnerText); if (startthem) ((RM)tab.SelectedTab.Controls[0]).StartButton_Click(null, null); } RenameTabs(); } private void saveSession_FileOk(object sender, System.ComponentModel.CancelEventArgs e) { SaveSession(saveSession.FileName); } private void loadSession_FileOk(object sender, System.ComponentModel.CancelEventArgs e) { LoadSession(loadSession.FileName); } #endregion #region All RatioMasters menu private void startToolStripMenuItem1_Click(object sender, EventArgs e) { foreach (TabPage tabb in tab.TabPages) { if (GetTabType(tabb) == TabType.RatioMaster) ((RM)tabb.Controls[0]).StartButton_Click(null, null); } } private void stopToolStripMenuItem1_Click(object sender, EventArgs e) { foreach (TabPage tabb in tab.TabPages) { if (GetTabType(tabb) == TabType.RatioMaster) ((RM)tabb.Controls[0]).StopButton_Click(null, null); } } private void updateToolStripMenuItem_Click(object sender, EventArgs e) { foreach (TabPage tabb in tab.TabPages) { if (GetTabType(tabb) == TabType.RatioMaster) ((RM)tabb.Controls[0]).manualUpdateButton_Click(null, null); } } private void clearAllLogsToolStripMenuItem_Click(object sender, EventArgs e) { foreach (TabPage tabb in tab.TabPages) { if (GetTabType(tabb) == TabType.RatioMaster) ((RM)tabb.Controls[0]).clearLogButton_Click(null, null); } } private void setUploadSpeedToToolStripMenuItem_Click(object sender, EventArgs e) { Prompt prompt = new Prompt("Please type valid integer value", "Type new upload speed for all tabs:", "100"); if (prompt.ShowDialog() == DialogResult.OK) { int value; try { value = int.Parse(prompt.Result); } catch { MessageBox.Show("Invalid value!\nTry again!", "Error"); return; } foreach (TabPage tabb in tab.TabPages) { if (GetTabType(tabb) == TabType.RatioMaster) ((RM)tabb.Controls[0]).updateTextBox(((RM)tabb.Controls[0]).uploadRate, value.ToString()); } } } private void setDownloadSpeedToToolStripMenuItem_Click(object sender, EventArgs e) { Prompt prompt = new Prompt("Please type valid integer value", "Type new download speed for all tabs:", "100"); if (prompt.ShowDialog() == DialogResult.OK) { int value; try { value = int.Parse(prompt.Result); } catch { MessageBox.Show("Invalid value!\nTry again!", "Error"); return; } foreach (TabPage tabb in tab.TabPages) { if (GetTabType(tabb) == TabType.RatioMaster) ((RM)tabb.Controls[0]).updateTextBox(((RM)tabb.Controls[0]).downloadRate, value.ToString()); } } } #endregion private void saveSettingsFromCurrentTabToolStripMenuItem_Click(object sender, EventArgs e) { if (GetTabType(tab.SelectedTab) == TabType.RatioMaster) SaveSettings((RM)tab.SelectedTab.Controls[0]); } private void tab_TabIndexChanged(object sender, EventArgs e) { /* if (GetTabType(tab.SelectedTab) == TabType.RatioMaster) { currentToolStripMenuItem.Enabled = true; allRatioMastersToolStripMenuItem.Enabled = true; saveSettingsFromCurrentTabToolStripMenuItem.Enabled = true; newToolStripMenuItem.Enabled = true; browserToolStripMenuItem.Enabled = false; } else if (GetTabType(tab.SelectedTab) == TabType.Browser) { currentToolStripMenuItem.Enabled = false; allRatioMastersToolStripMenuItem.Enabled = false; saveSettingsFromCurrentTabToolStripMenuItem.Enabled = false; newToolStripMenuItem.Enabled = false; browserToolStripMenuItem.Enabled = true; } */ } private static string GetFileExtenstion(string File) { FileInfo info = new FileInfo(File); return info.Extension; } private void MainForm_DragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop, false)) { e.Effect = DragDropEffects.All; } } private void MainForm_DragDrop(object sender, DragEventArgs e) { foreach (string fileName in (string[])e.Data.GetData(DataFormats.FileDrop)) { // MessageBox.Show(fileName + "\n" + GetFileExtenstion(fileName), "Debug"); if (GetFileExtenstion(fileName) == ".torrent") { if (MessageBox.Show("You have successfuly loaded this torrent file:\n" + fileName + "\nDo you want to load this torrent file in a new tab?", "File loaded!", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes) Add(fileName); else EditCurrent(fileName); } else if (GetFileExtenstion(fileName) == ".session") { MessageBox.Show("You have successfuly loaded this session file:\n" + fileName, "File loaded!"); startthem = false; LoadSession(fileName); } } } private void enable24hformat_Click(object sender, EventArgs e) { _24h_format_enabled = enable24hformat.Checked; } } internal enum TabType { RatioMaster = 1, Unknown = 3, } }
using System.Collections; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; #if NETFX_CORE using System.Collections.Generic; using Windows.UI.Notifications; using XboxLiveIntegration; #endif namespace Complete { public class GameManager : MonoBehaviour { public int m_NumRoundsToWin = 3; // The number of rounds a single player has to win to win the game. private bool isTrytoSilentSignin = true; public float m_StartDelay = 3f; // The delay between the start of RoundStarting and RoundPlaying phases. public float m_EndDelay = 3f; // The delay between the end of RoundPlaying and RoundEnding phases. public CameraControl m_CameraControl; // Reference to the CameraControl script for control during different phases. public Text m_MessageText; // Reference to the overlay Text to display winning text, etc. public GameObject m_TankPrefab; // Reference to the prefab the players will control. public TankManager[] m_Tanks; // A collection of managers for enabling and disabling different aspects of the tanks. private int m_RoundNumber; // Which round the game is currently on. private WaitForSeconds m_StartWait; // Used to have a delay whilst the round starts. private WaitForSeconds m_EndWait; // Used to have a delay whilst the round or game ends. private TankManager m_RoundWinner; // Reference to the winner of the current round. Used to make an announcement of who won. private TankManager m_GameWinner; // Reference to the winner of the game. Used to make an announcement of who won. private void Start() { // Create the delays so they only have to be made once. m_StartWait = new WaitForSeconds(m_StartDelay); m_EndWait = new WaitForSeconds(m_EndDelay); SpawnAllTanks(); SetCameraTargets(); // Once the tanks have been created and the camera is using them as targets, start the game. StartCoroutine(GameLoop()); } #if NETFX_CORE GUIStyle m_guiStyle = new GUIStyle(); string m_logText = string.Empty; List<string> m_logLines = new List<string>(); #region Xbox Live private IEnumerator SignInSilent() { var liveResource = XboxLiveIntegration.LiveResources.GetInstance(); yield return new WaitForSeconds(1f); if (liveResource.IsSignedIn) { var msg = $"You're signed in, gametag: {liveResource.User.Gamertag}"; LogLine(msg); ShowToastNotification("Xbox Live", msg); } } /// <summary> /// Xbox Live Sign in with UI /// </summary> void SignIn() { try { var liveResource = XboxLiveIntegration.LiveResources.GetInstance(); liveResource.SignIn(); if (liveResource.IsSignedIn) { LogLine($"You're signed in, gametag: {liveResource.User.Gamertag}"); } } catch (System.Exception ex) { LogLine("SignIn failed: " + ex.ToString()); } } /// <summary> /// Xbox Live Switch Account /// </summary> void SwitchAccount() { try { var liveResource = XboxLiveIntegration.LiveResources.GetInstance(); liveResource.SwitchAccount(); if (liveResource.IsSignedIn) { LogLine($"You're signed in, gametag: {liveResource.User.Gamertag}"); } } catch (System.Exception ex) { LogLine("SignIn failed: " + ex.ToString()); } } /// <summary> /// Unlock First Win Achievement /// </summary> /// <param name="totalWinCount">TotalWinCount</param> void UnlockFirstWinAchievement(int totalWinCount) { var liveResource = XboxLiveIntegration.LiveResources.GetInstance(); var measurements = new Windows.Foundation.Collections.PropertySet(); measurements.Add("TotalWinCount", totalWinCount); var dimensions = new Windows.Foundation.Collections.PropertySet(); dimensions.Add("UserId", liveResource.User.XboxUserId); AchievementManager.GetInstance().WriteGameEvent("TotalDataUpdate", dimensions, measurements); System.Diagnostics.Debug.WriteLine("Wrote game event: TotalDataUpdate"); } /// <summary> /// Get Xbox Live Achievement by Id /// </summary> /// <param name="id"></param> async void GetAchievementById(int id) { var ach = await AchievementManager.GetInstance().GetAchievement(id.ToString()); if (ach.ProgressState == Microsoft.Xbox.Services.Achievements.AchievementProgressState.Achieved) { var msg = $"You achieved {ach.Name}"; System.Diagnostics.Debug.WriteLine(msg); LogLine(msg); ShowToastNotification("Xbox Live Achievement", msg); } } /// <summary> /// Get Xbox Live Leaderboard by Leaderboard name /// </summary> /// <param name="name"></param> async void GetLeaderboardByName(string name) { var result = await LeaderboardManager.GetInstance().GetLeaderboardAsync(name); } IEnumerator ExecuteAfterTime(float time) { yield return new WaitForSeconds(time); GetAchievementById(1); } #endregion #region UI private void DrawTextWithShadow(float x, float y, float width, float height, string text) { m_guiStyle.fontSize = 14; m_guiStyle.normal.textColor = Color.black; GUI.Label(new UnityEngine.Rect(x, y, height, height), text, m_guiStyle); m_guiStyle.normal.textColor = Color.white; GUI.Label(new UnityEngine.Rect(x - 1, y - 1, width, height), text, m_guiStyle); } public void LogLine(string line) { lock (m_logText) { if (m_logLines.Count > 5) { m_logLines.RemoveAt(0); } m_logLines.Add($"{System.DateTime.Now} - {line}"); m_logText = string.Empty; foreach (string s in m_logLines) { m_logText += "\n"; m_logText += s; } } } public void OnGUI() { lock (m_logText) { DrawTextWithShadow(10, 50, 800, 500, m_logText); } if (GUI.Button(new Rect(10, 10, 100, 30), "Sign-in")) { SignIn(); } if (GUI.Button(new Rect(120, 10, 100, 30), "Change Users")) { SwitchAccount(); } if (GUI.Button(new Rect(230, 10, 100, 30), "Quit")) { UnityEngine.Application.Quit(); } } #endregion #region ToastNotificationHelper private void ShowToastNotification(string title, string stringContent) { ToastNotifier ToastNotifier = ToastNotificationManager.CreateToastNotifier(); Windows.Data.Xml.Dom.XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02); Windows.Data.Xml.Dom.XmlNodeList toastNodeList = toastXml.GetElementsByTagName("text"); toastNodeList.Item(0).AppendChild(toastXml.CreateTextNode(title)); toastNodeList.Item(1).AppendChild(toastXml.CreateTextNode(stringContent)); Windows.Data.Xml.Dom.IXmlNode toastNode = toastXml.SelectSingleNode("/toast"); Windows.Data.Xml.Dom.XmlElement audio = toastXml.CreateElement("audio"); audio.SetAttribute("src", "ms-winsoundevent:Notification.SMS"); ToastNotification toast = new ToastNotification(toastXml); toast.ExpirationTime = System.DateTime.Now.AddSeconds(10); ToastNotifier.Show(toast); } #endregion private void Update() { if (Input.GetKeyDown("t") || Input.GetKeyDown("joystick button 2")) { this.SignIn(); } if (Input.GetKeyDown("y") || Input.GetKeyDown("joystick button 3")) { this.SwitchAccount(); } if (Input.GetKey("escape") || Input.GetKeyDown("joystick button 6")) UnityEngine.Application.Quit(); } #endif private void SpawnAllTanks() { // For all the tanks... for (int i = 0; i < m_Tanks.Length; i++) { // ... create them, set their player number and references needed for control. m_Tanks[i].m_Instance = Instantiate(m_TankPrefab, m_Tanks[i].m_SpawnPoint.position, m_Tanks[i].m_SpawnPoint.rotation) as GameObject; m_Tanks[i].m_PlayerNumber = i + 1; m_Tanks[i].Setup(); } } private void SetCameraTargets() { // Create a collection of transforms the same size as the number of tanks. Transform[] targets = new Transform[m_Tanks.Length]; // For each of these transforms... for (int i = 0; i < targets.Length; i++) { // ... set it to the appropriate tank transform. targets[i] = m_Tanks[i].m_Instance.transform; } // These are the targets the camera should follow. m_CameraControl.m_Targets = targets; } // This is called from start and will run each phase of the game one after another. private IEnumerator GameLoop() { // Start off by running the 'RoundStarting' coroutine but don't return until it's finished. yield return StartCoroutine(RoundStarting()); #if NETFX_CORE #region Silently sign in if (isTrytoSilentSignin) { isTrytoSilentSignin = false; yield return StartCoroutine(SignInSilent()); } #endregion #endif // Once the 'RoundStarting' coroutine is finished, run the 'RoundPlaying' coroutine but don't return until it's finished. yield return StartCoroutine(RoundPlaying()); // Once execution has returned here, run the 'RoundEnding' coroutine, again don't return until it's finished. yield return StartCoroutine(RoundEnding()); // This code is not run until 'RoundEnding' has finished. At which point, check if a game winner has been found. if (m_GameWinner != null) { isTrytoSilentSignin = true; // If there is a game winner, restart the level. SceneManager.LoadScene(0); } else { // If there isn't a winner yet, restart this coroutine so the loop continues. // Note that this coroutine doesn't yield. This means that the current version of the GameLoop will end. StartCoroutine(GameLoop()); } } private IEnumerator RoundStarting() { // As soon as the round starts reset the tanks and make sure they can't move. ResetAllTanks(); DisableTankControl(); // Snap the camera's zoom and position to something appropriate for the reset tanks. m_CameraControl.SetStartPositionAndSize(); // Increment the round number and display text showing the players what round it is. m_RoundNumber++; m_MessageText.text = "ROUND " + m_RoundNumber; // Wait for the specified length of time until yielding control back to the game loop. yield return m_StartWait; } private IEnumerator RoundPlaying() { // As soon as the round begins playing let the players control the tanks. EnableTankControl(); // Clear the text from the screen. m_MessageText.text = string.Empty; // While there is not one tank left... while (!OneTankLeft()) { // ... return on the next frame. yield return null; } } private IEnumerator RoundEnding() { // Stop tanks from moving. DisableTankControl(); // Clear the winner from the previous round. m_RoundWinner = null; // See if there is a winner now the round is over. m_RoundWinner = GetRoundWinner(); // If there is a winner, increment their score. if (m_RoundWinner != null) m_RoundWinner.m_Wins++; // Now the winner's score has been incremented, see if someone has one the game. m_GameWinner = GetGameWinner(); // Get a message based on the scores and whether or not there is a game winner and display it. string message = EndMessage(); m_MessageText.text = message; #if NETFX_CORE if(message.Contains("WINS THE GAME")) yield return new WaitForSeconds(2); #endif // Wait for the specified length of time until yielding control back to the game loop. yield return m_EndWait; } // This is used to check if there is one or fewer tanks remaining and thus the round should end. private bool OneTankLeft() { // Start the count of tanks left at zero. int numTanksLeft = 0; // Go through all the tanks... for (int i = 0; i < m_Tanks.Length; i++) { // ... and if they are active, increment the counter. if (m_Tanks[i].m_Instance.activeSelf) numTanksLeft++; } // If there are one or fewer tanks remaining return true, otherwise return false. return numTanksLeft <= 1; } // This function is to find out if there is a winner of the round. // This function is called with the assumption that 1 or fewer tanks are currently active. private TankManager GetRoundWinner() { // Go through all the tanks... for (int i = 0; i < m_Tanks.Length; i++) { // ... and if one of them is active, it is the winner so return it. if (m_Tanks[i].m_Instance.activeSelf) return m_Tanks[i]; } // If none of the tanks are active it is a draw so return null. return null; } // This function is to find out if there is a winner of the game. private TankManager GetGameWinner() { // Go through all the tanks... for (int i = 0; i < m_Tanks.Length; i++) { // ... and if one of them has enough rounds to win the game, return it. if (m_Tanks[i].m_Wins == m_NumRoundsToWin) { #if NETFX_CORE var liveResource = XboxLiveIntegration.LiveResources.GetInstance(); if (liveResource.IsSignedIn) this.UnlockFirstWinAchievement(1); else LogLine("Please sign in to Xbox Live first"); if (liveResource.IsSignedIn) { StartCoroutine(ExecuteAfterTime(2)); } #endif return m_Tanks[i]; } } // If no tanks have enough rounds to win, return null. return null; } // Returns a string message to display at the end of each round. private string EndMessage() { // By default when a round ends there are no winners so the default end message is a draw. string message = "DRAW!"; // If there is a winner then change the message to reflect that. if (m_RoundWinner != null) message = m_RoundWinner.m_ColoredPlayerText + " WINS THE ROUND!"; // Add some line breaks after the initial message. message += "\n\n\n\n"; // Go through all the tanks and add each of their scores to the message. for (int i = 0; i < m_Tanks.Length; i++) { message += m_Tanks[i].m_ColoredPlayerText + ": " + m_Tanks[i].m_Wins + " WINS\n"; } // If there is a game winner, change the entire message to reflect that. if (m_GameWinner != null) message = m_GameWinner.m_ColoredPlayerText + " WINS THE GAME!"; return message; } // This function is used to turn all the tanks back on and reset their positions and properties. private void ResetAllTanks() { for (int i = 0; i < m_Tanks.Length; i++) { m_Tanks[i].Reset(); } } private void EnableTankControl() { for (int i = 0; i < m_Tanks.Length; i++) { m_Tanks[i].EnableControl(); } } private void DisableTankControl() { for (int i = 0; i < m_Tanks.Length; i++) { m_Tanks[i].DisableControl(); } } } }
using YAF.Lucene.Net.Support; using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Text; namespace YAF.Lucene.Net.Util { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// Represents <see cref="T:long[]"/>, as a slice (offset + length) into an /// existing <see cref="T:long[]"/>. The <see cref="Int64s"/> member should never be <c>null</c>; use /// <see cref="EMPTY_INT64S"/> if necessary. /// <para/> /// NOTE: This was LongsRef in Lucene /// <para/> /// @lucene.internal /// </summary> #if FEATURE_SERIALIZABLE [Serializable] #endif public sealed class Int64sRef : IComparable<Int64sRef> #if FEATURE_CLONEABLE , System.ICloneable #endif { /// <summary> /// An empty <see cref="long"/> array for convenience /// <para/> /// NOTE: This was EMPTY_LONGS in Lucene /// </summary> public static readonly long[] EMPTY_INT64S = new long[0]; /// <summary> /// The contents of the <see cref="Int64sRef"/>. Should never be <c>null</c>. /// <para/> /// NOTE: This was longs (field) in Lucene /// </summary> [WritableArray] [SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")] public long[] Int64s { get { return longs; } set { if (value == null) { throw new ArgumentNullException("value"); } longs = value; } } private long[] longs; /// <summary> /// Offset of first valid long. </summary> public int Offset { get; set; } /// <summary> /// Length of used longs. </summary> public int Length { get; set; } /// <summary> /// Create a <see cref="Int64sRef"/> with <see cref="EMPTY_INT64S"/> </summary> public Int64sRef() { longs = EMPTY_INT64S; } /// <summary> /// Create a <see cref="Int64sRef"/> pointing to a new array of size <paramref name="capacity"/>. /// Offset and length will both be zero. /// </summary> public Int64sRef(int capacity) { longs = new long[capacity]; } /// <summary> /// This instance will directly reference <paramref name="longs"/> w/o making a copy. /// <paramref name="longs"/> should not be <c>null</c>. /// </summary> public Int64sRef(long[] longs, int offset, int length) { this.longs = longs; this.Offset = offset; this.Length = length; Debug.Assert(IsValid()); } /// <summary> /// Returns a shallow clone of this instance (the underlying <see cref="long"/>s are /// <b>not</b> copied and will be shared by both the returned object and this /// object. /// </summary> /// <seealso cref="DeepCopyOf(Int64sRef)"/> public object Clone() { return new Int64sRef(longs, Offset, Length); } public override int GetHashCode() { const int prime = 31; int result = 0; long end = Offset + Length; for (int i = Offset; i < end; i++) { result = prime * result + (int)(longs[i] ^ ((long)((ulong)longs[i] >> 32))); } return result; } public override bool Equals(object other) { if (other == null) { return false; } if (other is Int64sRef) { return this.Int64sEquals((Int64sRef)other); } return false; } /// <summary> /// NOTE: This was longsEquals() in Lucene /// </summary> public bool Int64sEquals(Int64sRef other) { if (Length == other.Length) { int otherUpto = other.Offset; long[] otherInts = other.longs; long end = Offset + Length; for (int upto = Offset; upto < end; upto++, otherUpto++) { if (longs[upto] != otherInts[otherUpto]) { return false; } } return true; } else { return false; } } /// <summary> /// Signed <see cref="int"/> order comparison </summary> public int CompareTo(Int64sRef other) { if (this == other) { return 0; } long[] aInts = this.longs; int aUpto = this.Offset; long[] bInts = other.longs; int bUpto = other.Offset; long aStop = aUpto + Math.Min(this.Length, other.Length); while (aUpto < aStop) { long aInt = aInts[aUpto++]; long bInt = bInts[bUpto++]; if (aInt > bInt) { return 1; } else if (aInt < bInt) { return -1; } } // One is a prefix of the other, or, they are equal: return this.Length - other.Length; } /// <summary> /// NOTE: This was copyLongs() in Lucene /// </summary> public void CopyInt64s(Int64sRef other) { if (longs.Length - Offset < other.Length) { longs = new long[other.Length]; Offset = 0; } Array.Copy(other.longs, other.Offset, longs, Offset, other.Length); Length = other.Length; } /// <summary> /// Used to grow the reference array. /// <para/> /// In general this should not be used as it does not take the offset into account. /// <para/> /// @lucene.internal /// </summary> public void Grow(int newLength) { Debug.Assert(Offset == 0); if (longs.Length < newLength) { longs = ArrayUtil.Grow(longs, newLength); } } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append('['); long end = Offset + Length; for (int i = Offset; i < end; i++) { if (i > Offset) { sb.Append(' '); } sb.Append(longs[i].ToString("x")); } sb.Append(']'); return sb.ToString(); } /// <summary> /// Creates a new <see cref="Int64sRef"/> that points to a copy of the <see cref="long"/>s from /// <paramref name="other"/>. /// <para/> /// The returned <see cref="Int64sRef"/> will have a length of <c>other.Length</c> /// and an offset of zero. /// </summary> public static Int64sRef DeepCopyOf(Int64sRef other) { Int64sRef clone = new Int64sRef(); clone.CopyInt64s(other); return clone; } /// <summary> /// Performs internal consistency checks. /// Always returns <c>true</c> (or throws <see cref="InvalidOperationException"/>) /// </summary> public bool IsValid() { if (longs == null) { throw new InvalidOperationException("longs is null"); } if (Length < 0) { throw new InvalidOperationException("length is negative: " + Length); } if (Length > longs.Length) { throw new InvalidOperationException("length is out of bounds: " + Length + ",longs.length=" + longs.Length); } if (Offset < 0) { throw new InvalidOperationException("offset is negative: " + Offset); } if (Offset > longs.Length) { throw new InvalidOperationException("offset out of bounds: " + Offset + ",longs.length=" + longs.Length); } if (Offset + Length < 0) { throw new InvalidOperationException("offset+length is negative: offset=" + Offset + ",length=" + Length); } if (Offset + Length > longs.Length) { throw new InvalidOperationException("offset+length out of bounds: offset=" + Offset + ",length=" + Length + ",longs.length=" + longs.Length); } return true; } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Student Access Restrictions Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class STARDataSet : EduHubDataSet<STAR> { /// <inheritdoc /> public override string Name { get { return "STAR"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal STARDataSet(EduHubContext Context) : base(Context) { Index_SKEY = new Lazy<Dictionary<string, IReadOnlyList<STAR>>>(() => this.ToGroupedDictionary(i => i.SKEY)); Index_TID = new Lazy<Dictionary<int, STAR>>(() => this.ToDictionary(i => i.TID)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="STAR" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="STAR" /> fields for each CSV column header</returns> internal override Action<STAR, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<STAR, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "TID": mapper[i] = (e, v) => e.TID = int.Parse(v); break; case "SKEY": mapper[i] = (e, v) => e.SKEY = v; break; case "ACCESS_TYPE": mapper[i] = (e, v) => e.ACCESS_TYPE = v; break; case "RESTRICTION": mapper[i] = (e, v) => e.RESTRICTION = v; break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="STAR" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="STAR" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="STAR" /> entities</param> /// <returns>A merged <see cref="IEnumerable{STAR}"/> of entities</returns> internal override IEnumerable<STAR> ApplyDeltaEntities(IEnumerable<STAR> Entities, List<STAR> DeltaEntities) { HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.SKEY; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_TID.Remove(entity.TID); if (entity.SKEY.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<Dictionary<string, IReadOnlyList<STAR>>> Index_SKEY; private Lazy<Dictionary<int, STAR>> Index_TID; #endregion #region Index Methods /// <summary> /// Find STAR by SKEY field /// </summary> /// <param name="SKEY">SKEY value used to find STAR</param> /// <returns>List of related STAR entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<STAR> FindBySKEY(string SKEY) { return Index_SKEY.Value[SKEY]; } /// <summary> /// Attempt to find STAR by SKEY field /// </summary> /// <param name="SKEY">SKEY value used to find STAR</param> /// <param name="Value">List of related STAR entities</param> /// <returns>True if the list of related STAR entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindBySKEY(string SKEY, out IReadOnlyList<STAR> Value) { return Index_SKEY.Value.TryGetValue(SKEY, out Value); } /// <summary> /// Attempt to find STAR by SKEY field /// </summary> /// <param name="SKEY">SKEY value used to find STAR</param> /// <returns>List of related STAR entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<STAR> TryFindBySKEY(string SKEY) { IReadOnlyList<STAR> value; if (Index_SKEY.Value.TryGetValue(SKEY, out value)) { return value; } else { return null; } } /// <summary> /// Find STAR by TID field /// </summary> /// <param name="TID">TID value used to find STAR</param> /// <returns>Related STAR entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public STAR FindByTID(int TID) { return Index_TID.Value[TID]; } /// <summary> /// Attempt to find STAR by TID field /// </summary> /// <param name="TID">TID value used to find STAR</param> /// <param name="Value">Related STAR entity</param> /// <returns>True if the related STAR entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByTID(int TID, out STAR Value) { return Index_TID.Value.TryGetValue(TID, out Value); } /// <summary> /// Attempt to find STAR by TID field /// </summary> /// <param name="TID">TID value used to find STAR</param> /// <returns>Related STAR entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public STAR TryFindByTID(int TID) { STAR value; if (Index_TID.Value.TryGetValue(TID, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a STAR table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[STAR]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[STAR]( [TID] int IDENTITY NOT NULL, [SKEY] varchar(10) NOT NULL, [ACCESS_TYPE] varchar(30) NULL, [RESTRICTION] varchar(MAX) NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [STAR_Index_TID] PRIMARY KEY NONCLUSTERED ( [TID] ASC ) ); CREATE CLUSTERED INDEX [STAR_Index_SKEY] ON [dbo].[STAR] ( [SKEY] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STAR]') AND name = N'STAR_Index_TID') ALTER INDEX [STAR_Index_TID] ON [dbo].[STAR] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STAR]') AND name = N'STAR_Index_TID') ALTER INDEX [STAR_Index_TID] ON [dbo].[STAR] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="STAR"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="STAR"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<STAR> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<int> Index_TID = new List<int>(); foreach (var entity in Entities) { Index_TID.Add(entity.TID); } builder.AppendLine("DELETE [dbo].[STAR] WHERE"); // Index_TID builder.Append("[TID] IN ("); for (int index = 0; index < Index_TID.Count; index++) { if (index != 0) builder.Append(", "); // TID var parameterTID = $"@p{parameterIndex++}"; builder.Append(parameterTID); command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the STAR data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the STAR data set</returns> public override EduHubDataSetDataReader<STAR> GetDataSetDataReader() { return new STARDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the STAR data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the STAR data set</returns> public override EduHubDataSetDataReader<STAR> GetDataSetDataReader(List<STAR> Entities) { return new STARDataReader(new EduHubDataSetLoadedReader<STAR>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class STARDataReader : EduHubDataSetDataReader<STAR> { public STARDataReader(IEduHubDataSetReader<STAR> Reader) : base (Reader) { } public override int FieldCount { get { return 7; } } public override object GetValue(int i) { switch (i) { case 0: // TID return Current.TID; case 1: // SKEY return Current.SKEY; case 2: // ACCESS_TYPE return Current.ACCESS_TYPE; case 3: // RESTRICTION return Current.RESTRICTION; case 4: // LW_DATE return Current.LW_DATE; case 5: // LW_TIME return Current.LW_TIME; case 6: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 2: // ACCESS_TYPE return Current.ACCESS_TYPE == null; case 3: // RESTRICTION return Current.RESTRICTION == null; case 4: // LW_DATE return Current.LW_DATE == null; case 5: // LW_TIME return Current.LW_TIME == null; case 6: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // TID return "TID"; case 1: // SKEY return "SKEY"; case 2: // ACCESS_TYPE return "ACCESS_TYPE"; case 3: // RESTRICTION return "RESTRICTION"; case 4: // LW_DATE return "LW_DATE"; case 5: // LW_TIME return "LW_TIME"; case 6: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "TID": return 0; case "SKEY": return 1; case "ACCESS_TYPE": return 2; case "RESTRICTION": return 3; case "LW_DATE": return 4; case "LW_TIME": return 5; case "LW_USER": return 6; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
using GuiLabs.Canvas.DrawStyle; using System.Drawing; namespace GuiLabs.Editor.Xml { public class XmlStyleFactory : StyleFactory { public XmlStyleFactory() { #region Colors Color lightGray = Color.FromArgb(250, 250, 250); Color niceGray = Color.FromArgb(246, 243, 243); Color classBack = lightGray; Color methodBack = lightGray; Color memberBack = Color.GhostWhite; Color namespaceBack = lightGray; Color propertyBack = lightGray; Color grayFrame = Color.Black;// Color.Gainsboro; Color deselectedFrame = Color.Transparent; // Color.Gainsboro; //Color controlStructure = Color.White; //Color controlStructure = Color.FromArgb(250, 250, 250); Color controlStructure = lightGray; Color typeName = Color.FromArgb(43, 145, 175); #endregion AddStyle(StyleNames.Transparent, Color.Transparent, Color.Transparent); AddAlias(StyleNames.TransparentSel, StyleNames.Transparent); #region Types AddStyle( StyleNames.TypeName, Color.Transparent, Color.Transparent, typeName//, "Consolas", 11, FontStyle.Regular ); AddAlias( StyleNames.TypeNameSel, StyleNames.TypeName); AddStyle("ClassBlock", //Color.Lavender, deselectedFrame, classBack); AddStyle("ClassBlock_selected", grayFrame, classBack); AddAliasAndSelected("StructBlock", "ClassBlock"); AddAliasAndSelected("InterfaceBlock", "ClassBlock"); AddAliasAndSelected("EnumBlock", "ClassBlock"); #endregion #region Namespace AddStyle("NodeBlock", //Color.PeachPuff, deselectedFrame, namespaceBack); AddStyle("NodeBlock_selected", grayFrame, namespaceBack); AddStyle("UsingBlock", deselectedFrame, lightGray); AddStyle("UsingBlock_selected", grayFrame, lightGray); #endregion #region Members AddStyle("MethodBlock", //Color.PaleGreen, deselectedFrame, methodBack); AddStyle("MethodBlock_selected", grayFrame, methodBack); AddStyle("FieldBlock", Color.Transparent, Color.Transparent); AddStyle("FieldBlock_selected", grayFrame, memberBack); AddStyle("PropertyBlock", //Color.PaleGreen, deselectedFrame, propertyBack); AddStyle("PropertyBlock_selected", grayFrame, propertyBack); AddStyle("PropertyAccessorBlock", //Color.PaleGreen, deselectedFrame, propertyBack); AddStyle("PropertyAccessorBlock_selected", grayFrame, propertyBack); AddAliasAndSelected("InterfaceAccessorsBlock", "FieldBlock"); #endregion AddAliasAndSelected("DelegateBlock", "FieldBlock"); #region Method AddStyle("ControlStructureBlock", //Color.PaleGreen, deselectedFrame, controlStructure); AddStyle("ControlStructureBlock_selected", grayFrame, controlStructure); #endregion #region Text //ShapeStyle s = new ShapeStyle(); //s.Name = "GuiLabs.Editor.CSharp.ModifierLabelBlock_selected"; //s.FontStyleInfo = // GuiLabs.Canvas.Renderer.RendererSingleton.StyleFactory.ProduceNewFontStyleInfo( // "Lucida Console", // 14, // FontStyle.Regular); //s.LineColor = Color.BlueViolet; //Add(s); AddStyle("TextBoxBlock", Color.Transparent, Color.Transparent); AddStyle("TextBoxBlock_selected", Color.Transparent, Color.Transparent); AddStyle("MemberNameBlock", Color.Transparent, Color.Transparent, Color.Black, "Courier New", 10, FontStyle.Bold); AddStyle("MemberNameBlock_selected", Color.PaleGoldenrod, Color.LightYellow, Color.Black, "Courier New", 10, FontStyle.Bold); AddStyle("ButtonBlock", Color.DarkRed, Color.Linen, Color.PeachPuff, FillMode.VerticalGradient); AddStyle("ButtonBlock_selected", Color.DarkRed, Color.Linen, Color.SandyBrown, FillMode.VerticalGradient); AddStyle("EmptyBlock", Color.Transparent, Color.Transparent); AddStyle("EmptyBlock_selected", Color.Transparent, Color.Transparent); AddStyle("EmptyBlock_validated", Color.OrangeRed, Color.FloralWhite); AddStyle("LabelBlock", Color.Transparent, Color.Transparent); AddStyle("LabelBlock_selected", Color.Transparent, Color.Transparent); AddStyle("SpaceBlock", Color.Transparent, Color.Transparent); AddStyle("SpaceBlock_selected", Color.DarkBlue, Color.LightCyan); AddStyle("TextLine", Color.Transparent, Color.Transparent); AddStyle("TextLine_selected", Color.LightGray, Color.LightYellow); //Color.Transparent, //Color.Transparent); AddStyle("StatementLine", Color.Transparent, Color.Transparent); AddStyle("StatementLine_selected", Color.LightGray, Color.LightYellow); AddStyle("KeywordLabel", Color.Transparent, Color.Transparent, Color.Blue); AddStyle("KeywordLabel_selected", Color.Blue, Color.LightCyan, Color.Blue); AddStyle("OneWordStatement", Color.Transparent, Color.Transparent); AddStyle("OneWordStatement_selected", Color.Gray, Color.Yellow); AddAliasAndSelected("ExpressionBlock", "TextLine"); #endregion #region Modifiers AddAliasAndSelected("ModifierSelectionBlock", "KeywordLabel"); AddAliasAndSelected("ModifierSeparatorBlock", "KeywordLabel"); AddStyle("TypeSelection", Color.Transparent, Color.Transparent, typeName); AddStyle("TypeSelection_selected", Color.Blue, Color.LightCyan, typeName); AddAliasAndSelected("InterfacePropertyAccessor", "ModifierSelectionBlock"); #endregion } } public static class StyleNames { public static string sel = "_selected"; public static string val = "_validated"; public static string Transparent = "Transparent"; public static string TransparentSel = Transparent + sel; public static string TypeName = "TypeName"; public static string TypeNameSel = TypeName + sel; } }
#region File Description //----------------------------------------------------------------------------- // Hud.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Content; using RolePlayingGameData; #endregion namespace RolePlaying { /// <summary> /// Displays each player's basic statistics and the combat action menu. /// </summary> class Hud { private ScreenManager screenManager; public static float HudHeight;//; = 183 * ScaledVector2.ScaleFactor; private Rectangle firstCombatMenuPosition = Rectangle.Empty; private float heightInterval = 65f * ScaledVector2.ScaleFactor; public static bool IsActive { get; set; } #region Graphics Data private Texture2D backgroundHudTexture; private Texture2D topHudTexture; private Texture2D combatPopupTexture; private Texture2D activeCharInfoTexture; private Texture2D inActiveCharInfoTexture; private Texture2D cantUseCharInfoTexture; private Texture2D selectionBracketTexture; private Texture2D menuTexture; private Texture2D statsTexture; private Texture2D deadPortraitTexture; private Texture2D charSelFadeLeftTexture; private Texture2D charSelFadeRightTexture; private Texture2D charSelArrowLeftTexture; private Texture2D charSelArrowRightTexture; private Texture2D actionTexture; private Texture2D yButtonTexture; private Texture2D startButtonTexture; private Vector2 topHudPosition = ScaledVector2.GetScaledVector(353f, 30f); private Vector2 charSelLeftPosition = ScaledVector2.GetScaledVector(70f, 600f); private Vector2 charSelRightPosition = ScaledVector2.GetScaledVector(1170f, 600f); private Vector2 yButtonPosition = ScaledVector2.GetScaledVector(0f, 560f + 70f); private Vector2 startButtonPosition = ScaledVector2.GetScaledVector(0f, 560f + 35f); private Vector2 yTextPosition = ScaledVector2.GetScaledVector(0f, 560f + 130f); private Vector2 startTextPosition = ScaledVector2.GetScaledVector(0f, 560f + 70f); private Vector2 actionTextPosition = ScaledVector2.GetScaledVector(640f, 55f); private Vector2 backgroundHudPosition;// = ScaledVector2.GetScaledVector(0f, 525f); private Vector2 portraitPosition = ScaledVector2.GetScaledVector(640f, 55f); private Vector2 startingInfoPosition;// = ScaledVector2.GetScaledVector(0f, 550f); private Vector2 namePosition; private Vector2 levelPosition; private Vector2 detailPosition; private readonly Color activeNameColor = new Color(200, 200, 200); private readonly Color inActiveNameColor = new Color(100, 100, 100); private readonly Color nonSelColor = new Color(86, 26, 5); private readonly Color selColor = new Color(229, 206, 144); #endregion #region Action Text /// <summary> /// The text that is shown in the action bar at the top of the combat screen. /// </summary> private string actionText = String.Empty; /// <summary> /// The text that is shown in the action bar at the top of the combat screen. /// </summary> public string ActionText { get { return actionText; } set { actionText = value; } } #endregion #region Initialization /// <summary> /// Creates a new Hud object using the given ScreenManager. /// </summary> public Hud(ScreenManager screenManager) { // check the parameter if (screenManager == null) { throw new ArgumentNullException("screenManager"); } this.screenManager = screenManager; IsActive = true; } /// <summary> /// Load the graphics content from the content manager. /// </summary> public void LoadContent() { ContentManager content = (screenManager.Game as RolePlayingGame).StaticContent; backgroundHudTexture = content.Load<Texture2D>(@"Textures\HUD\HudBkgd"); topHudTexture = content.Load<Texture2D>(@"Textures\HUD\CombatStateInfoStrip"); activeCharInfoTexture = content.Load<Texture2D>(@"Textures\HUD\PlankActive"); inActiveCharInfoTexture = content.Load<Texture2D>(@"Textures\HUD\PlankInActive"); cantUseCharInfoTexture = content.Load<Texture2D>(@"Textures\HUD\PlankCantUse"); selectionBracketTexture = content.Load<Texture2D>(@"Textures\HUD\SelectionBrackets"); deadPortraitTexture = content.Load<Texture2D>(@"Textures\Characters\Portraits\Tombstone"); combatPopupTexture = content.Load<Texture2D>(@"Textures\HUD\CombatPopup"); charSelFadeLeftTexture = content.Load<Texture2D>(@"Textures\Buttons\CharSelectFadeLeft"); charSelFadeRightTexture = content.Load<Texture2D>(@"Textures\Buttons\CharSelectFadeRight"); charSelArrowLeftTexture = content.Load<Texture2D>(@"Textures\Buttons\CharSelectHlLeft"); charSelArrowRightTexture = content.Load<Texture2D>(@"Textures\Buttons\CharSelectHlRight"); actionTexture = content.Load<Texture2D>(@"Textures\HUD\HudSelectButton"); yButtonTexture = content.Load<Texture2D>(@"Textures\Buttons\rpgbtn"); startButtonTexture = content.Load<Texture2D>(@"Textures\Buttons\StartButton"); menuTexture = content.Load<Texture2D>(@"Textures\HUD\Menu"); statsTexture = content.Load<Texture2D>(@"Textures\HUD\Stats"); HudHeight = backgroundHudTexture.Height * ScaledVector2.DrawFactor; backgroundHudPosition = new Vector2(0, screenManager.GraphicsDevice.Viewport.Height - HudHeight); startingInfoPosition = new Vector2(backgroundHudPosition.X, backgroundHudPosition.Y + 30); } #endregion public void HandleInput() { if (!CombatEngine.IsActive) { if (InputManager.IsButtonClicked(new Rectangle ((int)yButtonPosition.X, (int)yButtonPosition.Y, yButtonTexture.Width , yButtonTexture.Height))) { if (StatClicked != null) { StatClicked(this, EventArgs.Empty); } } } } public event EventHandler StatClicked; #region Drawing /// <summary> /// Draw the screen. /// </summary> public void Draw() { if (!Hud.IsActive) { return; } SpriteBatch spriteBatch = screenManager.SpriteBatch; spriteBatch.Begin(); startingInfoPosition.X = 640f * ScaledVector2.ScaleFactor; startingInfoPosition.X -= (Session.Party.Players.Count / 2 * 200f) * ScaledVector2.ScaleFactor; if (Session.Party.Players.Count % 2 != 0) { startingInfoPosition.X -= 100f * ScaledVector2.ScaleFactor; } spriteBatch.Draw(backgroundHudTexture, backgroundHudPosition,null, Color.White,0f, Vector2.Zero, ScaledVector2.DrawFactor , SpriteEffects.None, 0f); if (CombatEngine.IsActive) { DrawForCombat(); } else { DrawForNonCombat(); } spriteBatch.End(); } public static Dictionary<CombatantPlayer, Vector2> PlayerPositionMapping = new Dictionary<CombatantPlayer, Vector2>(); /// <summary> /// Draws HUD for Combat Mode /// </summary> private void DrawForCombat() { SpriteBatch spriteBatch = screenManager.SpriteBatch; Vector2 position = startingInfoPosition; Hud.PlayerPositionMapping.Clear(); foreach (CombatantPlayer combatantPlayer in CombatEngine.Players) { Hud.PlayerPositionMapping.Add(combatantPlayer , position); DrawCombatPlayerDetails(combatantPlayer, position); position.X += activeCharInfoTexture.Width * ScaledVector2.DrawFactor - 6f * ScaledVector2.ScaleFactor; } charSelLeftPosition.X = startingInfoPosition.X - 5f * ScaledVector2.ScaleFactor - charSelArrowLeftTexture.Width * ScaledVector2.DrawFactor; charSelRightPosition.X = position.X + 5f * ScaledVector2.ScaleFactor; // Draw character Selection Arrows if (CombatEngine.IsPlayersTurn) { spriteBatch.Draw(charSelArrowLeftTexture, charSelLeftPosition,null,Color.White,0f, Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f); spriteBatch.Draw(charSelArrowRightTexture, charSelRightPosition,null,Color.White,0f, Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f); } else { spriteBatch.Draw(charSelFadeLeftTexture, charSelLeftPosition,null,Color.White,0f, Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f); spriteBatch.Draw(charSelFadeRightTexture, charSelRightPosition, null,Color.White,0f, Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f); } if (actionText.Length > 0) { spriteBatch.Draw(topHudTexture, topHudPosition,null, Color.White,0f, Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f); // Draw Action Text Fonts.DrawCenteredText(spriteBatch, Fonts.PlayerStatisticsFont, actionText, actionTextPosition, Color.Black); } } /// <summary> /// Draws HUD for non Combat Mode /// </summary> private void DrawForNonCombat() { SpriteBatch spriteBatch = screenManager.SpriteBatch; Vector2 position = startingInfoPosition; foreach (Player player in Session.Party.Players) { DrawNonCombatPlayerDetails(player, position); position.X += (inActiveCharInfoTexture.Width * ScaledVector2.DrawFactor) - 6f * ScaledVector2.ScaleFactor; } yTextPosition.X = position.X + 115f * ScaledVector2.ScaleFactor; yButtonPosition.X = position.X + 120f * ScaledVector2.ScaleFactor; spriteBatch.Draw(yButtonTexture, yButtonPosition,null, Color.White,0f, Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f); Vector2 statePosition = new Vector2( yButtonPosition.X + yButtonTexture.Width * 2f / 2 - statsTexture.Width * 2 / 2, yButtonPosition.Y + yButtonTexture.Height * 2f / 2 - statsTexture.Height * 2 / 2); // Draw Select Button spriteBatch.Draw(statsTexture, statePosition - new Vector2(26,10), null, Color.White, 0f, Vector2.Zero, new Vector2(2f, ScaledVector2.DrawFactor), SpriteEffects.None, 0f); startTextPosition.X = startingInfoPosition.X - (startButtonTexture.Width * ScaledVector2.DrawFactor) - 25f * ScaledVector2.ScaleFactor; startButtonPosition.X = startingInfoPosition.X - (startButtonTexture.Width * ScaledVector2.DrawFactor) - 10f * ScaledVector2.ScaleFactor; } enum PlankState { Active, InActive, CantUse, } /// <summary> /// Draws Player Details /// </summary> /// <param name="playerIndex">Index of player details to draw</param> /// <param name="position">Position where to draw</param> private void DrawCombatPlayerDetails(CombatantPlayer player, Vector2 position) { SpriteBatch spriteBatch = screenManager.SpriteBatch; PlankState plankState; bool isPortraitActive = false; bool isCharDead = false; Color color; portraitPosition.X = position.X + 7f * ScaledVector2.ScaleFactor; portraitPosition.Y = position.Y + 7f * ScaledVector2.ScaleFactor; namePosition.X = position.X + 84f * ScaledVector2.ScaleFactor; namePosition.Y = position.Y + 12f * ScaledVector2.ScaleFactor; levelPosition.X = position.X + 84f * ScaledVector2.ScaleFactor; levelPosition.Y = position.Y + 39f * ScaledVector2.ScaleFactor; detailPosition.X = position.X + 25f * ScaledVector2.ScaleFactor; detailPosition.Y = position.Y + 66f * ScaledVector2.ScaleFactor; position.X -= 2 * ScaledVector2.ScaleFactor; position.Y -= 4 * ScaledVector2.ScaleFactor; if (player.IsTurnTaken) { plankState = PlankState.CantUse; isPortraitActive = false; } else { plankState = PlankState.InActive; isPortraitActive = true; } if (((CombatEngine.HighlightedCombatant == player) && !player.IsTurnTaken) || (CombatEngine.PrimaryTargetedCombatant == player) || (CombatEngine.SecondaryTargetedCombatants.Contains(player))) { plankState = PlankState.Active; } if (player.IsDeadOrDying) { isCharDead = true; isPortraitActive = false; plankState = PlankState.CantUse; } // Draw Info Slab if (plankState == PlankState.Active) { color = activeNameColor; spriteBatch.Draw(activeCharInfoTexture, position,null, Color.White,0f, Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f); // Draw Brackets if ((CombatEngine.HighlightedCombatant == player) && !player.IsTurnTaken) { spriteBatch.Draw(selectionBracketTexture, position,null, Color.White,0f, Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f); } if (isPortraitActive && (CombatEngine.HighlightedCombatant == player) && (CombatEngine.HighlightedCombatant.CombatAction == null) && !CombatEngine.IsDelaying) { position.X += (activeCharInfoTexture.Width * ScaledVector2.DrawFactor ) / 2; position.X -= (combatPopupTexture.Width * ScaledVector2.DrawFactor) / 2; position.Y -= (combatPopupTexture.Height * ScaledVector2.DrawFactor); // Draw Action DrawActionsMenu(position); } } else if (plankState == PlankState.InActive) { color = inActiveNameColor; spriteBatch.Draw(inActiveCharInfoTexture, position,null, Color.White,0f, Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f); } else { color = Color.Black; spriteBatch.Draw(cantUseCharInfoTexture, position,null, Color.White,0f, Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f); } if (isCharDead) { spriteBatch.Draw(deadPortraitTexture, portraitPosition,null, Color.White,0f, Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f); } else { // Draw Player Portrait DrawPortrait(player.Player, portraitPosition, plankState); } // Draw Player Name spriteBatch.DrawString(Fonts.PlayerStatisticsFont, player.Player.Name, namePosition, color); color = Color.Black; // Draw Player Details spriteBatch.DrawString(Fonts.HudDetailFont, "Lvl: " + player.Player.CharacterLevel, levelPosition, color); spriteBatch.DrawString(Fonts.HudDetailFont, "HP: " + player.Statistics.HealthPoints + "/" + player.Player.CharacterStatistics.HealthPoints, detailPosition, color); detailPosition.Y += 30f * ScaledVector2.ScaleFactor; spriteBatch.DrawString(Fonts.HudDetailFont, "MP: " + player.Statistics.MagicPoints + "/" + player.Player.CharacterStatistics.MagicPoints, detailPosition, color); } /// <summary> /// Draws Player Details /// </summary> /// <param name="playerIndex">Index of player details to draw</param> /// <param name="position">Position where to draw</param> private void DrawNonCombatPlayerDetails(Player player, Vector2 position) { SpriteBatch spriteBatch = screenManager.SpriteBatch; PlankState plankState; bool isCharDead = false; Color color; portraitPosition.X = position.X + 7f * ScaledVector2.ScaleFactor; portraitPosition.Y = position.Y + 7f * ScaledVector2.ScaleFactor; namePosition.X = position.X + 84f * ScaledVector2.ScaleFactor; namePosition.Y = position.Y + 12f * ScaledVector2.ScaleFactor; levelPosition.X = position.X + 84f * ScaledVector2.ScaleFactor; levelPosition.Y = position.Y + 39f * ScaledVector2.ScaleFactor; detailPosition.X = position.X + 25f * ScaledVector2.ScaleFactor; detailPosition.Y = position.Y + 66f * ScaledVector2.ScaleFactor; position.X -= 2 * ScaledVector2.ScaleFactor; position.Y -= 4 * ScaledVector2.ScaleFactor; plankState = PlankState.Active; // Draw Info Slab if (plankState == PlankState.Active) { color = activeNameColor; spriteBatch.Draw(activeCharInfoTexture, position,null, Color.White,0f, Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f); } else if (plankState == PlankState.InActive) { color = inActiveNameColor; spriteBatch.Draw(inActiveCharInfoTexture, position,null, Color.White,0f, Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f); } else { color = Color.Black; spriteBatch.Draw(cantUseCharInfoTexture, position,null, Color.White,0f, Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f); } if (isCharDead) { spriteBatch.Draw(deadPortraitTexture, portraitPosition,null, Color.White,0f, Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f); } else { // Draw Player Portrait DrawPortrait(player, portraitPosition, plankState); } // Draw Player Name spriteBatch.DrawString(Fonts.PlayerStatisticsFont, player.Name, namePosition, color); color = Color.Black; // Draw Player Details spriteBatch.DrawString(Fonts.HudDetailFont, "Lvl: " + player.CharacterLevel, levelPosition, color); spriteBatch.DrawString(Fonts.HudDetailFont, "HP: " + player.CurrentStatistics.HealthPoints + "/" + player.CharacterStatistics.HealthPoints, detailPosition, color); detailPosition.Y += 30f * ScaledVector2.ScaleFactor; spriteBatch.DrawString(Fonts.HudDetailFont, "MP: " + player.CurrentStatistics.MagicPoints + "/" + player.CharacterStatistics.MagicPoints, detailPosition, color); } /// <summary> /// Draw the portrait of the given player at the given position. /// </summary> private void DrawPortrait(Player player, Vector2 position, PlankState plankState) { switch (plankState) { case PlankState.Active: screenManager.SpriteBatch.Draw(player.ActivePortraitTexture, position,null, Color.White,0f, Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f); break; case PlankState.InActive: screenManager.SpriteBatch.Draw(player.InactivePortraitTexture, position,null, Color.White,0f, Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f); break; case PlankState.CantUse: screenManager.SpriteBatch.Draw(player.UnselectablePortraitTexture, position,null, Color.White,0f, Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f); break; } } #endregion #region Combat Action Menu /// <summary> /// The list of entries in the combat action menu. /// </summary> private string[] actionList = new string[5] { "Attack", "Spell", "Item", "Defend", "Flee", }; /// <summary> /// The currently highlighted item. /// </summary> private int highlightedAction = 0; /// <summary> /// Handle user input to the actions menu. /// </summary> public void UpdateActionsMenu() { bool isMenuItemPressed = false; if (firstCombatMenuPosition != Rectangle.Empty) { int x = firstCombatMenuPosition.X; for (int playerCount = 0; playerCount < CombatEngine.Players.Count; playerCount++) { for (int actionIndex = 0; actionIndex < actionList.Length; actionIndex++) { float yPosition = firstCombatMenuPosition.Y; if (actionIndex + 1 > 1) { yPosition = yPosition + (heightInterval * actionIndex + 1); } Rectangle currentActionPosition = new Rectangle(x, (int)yPosition, (int)(firstCombatMenuPosition.Width * ScaledVector2.ScaleFactor), (int)(firstCombatMenuPosition.Height * ScaledVector2.ScaleFactor)); if (InputManager.IsButtonClicked(currentActionPosition)) { highlightedAction = actionIndex; isMenuItemPressed = true; break; } } x += (int)(activeCharInfoTexture.Width * ScaledVector2.DrawFactor - 6f * ScaledVector2.ScaleFactor); } } // select an action if (isMenuItemPressed) { switch (actionList[highlightedAction]) { case "Attack": { ActionText = "Performing a Melee Attack"; CombatEngine.HighlightedCombatant.CombatAction = new MeleeCombatAction(CombatEngine.HighlightedCombatant); CombatEngine.HighlightedCombatant.CombatAction.Target = CombatEngine.FirstEnemyTarget; } break; case "Spell": { SpellbookScreen spellbookScreen = new SpellbookScreen( CombatEngine.HighlightedCombatant.Character, CombatEngine.HighlightedCombatant.Statistics); spellbookScreen.SpellSelected += new SpellbookScreen.SpellSelectedHandler( spellbookScreen_SpellSelected); Session.ScreenManager.AddScreen(spellbookScreen); } break; case "Item": { InventoryScreen inventoryScreen = new InventoryScreen(true); inventoryScreen.GearSelected += new InventoryScreen.GearSelectedHandler( inventoryScreen_GearSelected); Session.ScreenManager.AddScreen(inventoryScreen); } break; case "Defend": { ActionText = "Defending"; CombatEngine.HighlightedCombatant.CombatAction = new DefendCombatAction( CombatEngine.HighlightedCombatant); CombatEngine.HighlightedCombatant.CombatAction.Start(); } break; case "Flee": CombatEngine.AttemptFlee(); break; } return; } } /// <summary> /// Recieves the spell from the Spellbook screen and casts it. /// </summary> void spellbookScreen_SpellSelected(Spell spell) { if (spell != null) { ActionText = "Casting " + spell.Name; CombatEngine.HighlightedCombatant.CombatAction = new SpellCombatAction(CombatEngine.HighlightedCombatant, spell); if (spell.IsOffensive) { CombatEngine.HighlightedCombatant.CombatAction.Target = CombatEngine.FirstEnemyTarget; } else { CombatEngine.HighlightedCombatant.CombatAction.Target = CombatEngine.HighlightedCombatant; } } } /// <summary> /// Receives the item back from the Inventory screen and uses it. /// </summary> void inventoryScreen_GearSelected(Gear gear) { Item item = gear as Item; if (item != null) { ActionText = "Using " + item.Name; CombatEngine.HighlightedCombatant.CombatAction = new ItemCombatAction(CombatEngine.HighlightedCombatant, item); if (item.IsOffensive) { CombatEngine.HighlightedCombatant.CombatAction.Target = CombatEngine.FirstEnemyTarget; } else { CombatEngine.HighlightedCombatant.CombatAction.Target = CombatEngine.HighlightedCombatant; } } } /// <summary> /// Draws the combat action menu. /// </summary> /// <param name="position">The position of the menu.</param> private void DrawActionsMenu(Vector2 position) { ActionText = "Choose an Action"; SpriteBatch spriteBatch = screenManager.SpriteBatch; Vector2 arrowPosition; //position.Y = position.Y - combatPopupTexture.Height; spriteBatch.Draw(combatPopupTexture,position,null, Color.White,0f, Vector2.Zero,ScaledVector2.DrawFactor ,SpriteEffects.None,0f); position.Y += 18f * ScaledVector2.ScaleFactor; arrowPosition = position; arrowPosition.X += 4f * ScaledVector2.ScaleFactor; arrowPosition.Y += 2f * ScaledVector2.ScaleFactor; arrowPosition.Y += heightInterval * (int)highlightedAction; spriteBatch.Draw(actionTexture, arrowPosition,null, Color.White,0f, Vector2.Zero, ScaledVector2.DrawFactor * 2f, SpriteEffects.None, 0f); position.Y += 4f * ScaledVector2.ScaleFactor; position.X += 50f * ScaledVector2.ScaleFactor; if(firstCombatMenuPosition == Rectangle.Empty) { firstCombatMenuPosition = new Rectangle((int)position.X , (int)position.Y, (int)(actionTexture.Width * ScaledVector2.DrawFactor), (int)heightInterval); } position.X += 18; // Draw Action Text for (int i = 0; i < actionList.Length; i++) { spriteBatch.DrawString(Fonts.GearInfoFont, actionList[i], position, i == highlightedAction ? selColor : nonSelColor,0f,Vector2.Zero,1.75f,SpriteEffects.None,0f); position.Y += heightInterval; } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using Rudine.Web.Util; namespace Rudine.Util.Types { internal class CompositeSignature : IEquatable<CompositeSignature> { internal readonly Type[] _SourceTypes; internal readonly string[] _PropertyNameExclutions; internal readonly Type _BaseType; internal readonly bool _PrettyNames; internal readonly CompositeProperty[] _ClassProperties; internal readonly string _FullName; private Dictionary<string, Type> _MergedProperties; private int _HashCode; public Dictionary<string, Type> MergedProperties { get { if (_MergedProperties == null) ConsolidateProperties(); return _MergedProperties; } } public CompositeSignature(Type[] sourceTypes = null, string[] propertyNameExclutions = null, Type baseType = null, bool prettyNames = true, CompositeProperty[] ClassProperties = null) { if (ClassProperties == null) ClassProperties = new CompositeProperty[] { }; if (propertyNameExclutions == null) propertyNameExclutions = new string[] { }; if (sourceTypes == null) sourceTypes = new Type[] { }; else if (baseType == null) baseType = DefaultBaseType(sourceTypes); if (baseType != null) propertyNameExclutions = baseType .GetProperties() .Select(p => p.Name) .Union(propertyNameExclutions) .ToArray(); _SourceTypes = sourceTypes; _PropertyNameExclutions = propertyNameExclutions; _BaseType = baseType; _PrettyNames = prettyNames; _ClassProperties = ClassProperties; } private void ConsolidateProperties(bool calcMergedProperties = true) { Dictionary<string, Type> _mergedProperties = new Dictionary<string, Type>(); Dictionary<string, int> _mergedPropertyHashes = new Dictionary<string, int> { { "Base_Type", _BaseType == null ? 0 : new CompositeSignature(new[] { _BaseType }, null, null, false).GetHashCode() } }; var PropertiesByName = FilterInvalidProperties(_SourceTypes, _PropertyNameExclutions, _PrettyNames) .Select(p => new CompositeProperty(p.Name, p.PropertyType)) .Union(_ClassProperties) .Select(classproperty => new { MergeName = _PrettyNames ? pretty(classproperty.Name) : classproperty.Name, SourceName = classproperty.Name, SourceType = classproperty.PropertyType, PrincipleType = classproperty.PropertyType.GetPrincipleType() }) .Select(SourceProperty => new { SourceProperty, MergeFactors = new { isCollection = SourceProperty.SourceType.isCollection(), SourceProperty.PrincipleType.IsEnum, IsPrimitive = SourceProperty.PrincipleType.isSimple(), SourceProperty.SourceType.IsArray } }) .GroupBy(m => m.SourceProperty.MergeName) .ToDictionary(m => m.Key); // do simple value/quazi-value type properties first // notice there is no OrderBy as we want to maintain the original layout of the properties as long as possible // only when the _hashcode is calculated do we ignore order foreach (string MergeName in PropertiesByName.Keys) { if (1 != PropertiesByName[MergeName].Select(m => m.MergeFactors.isCollection.GetHashCode() ^ m.MergeFactors.IsEnum.GetHashCode() ^ m.MergeFactors.IsPrimitive.GetHashCode() ^ m.MergeFactors.IsArray.GetHashCode() ).Distinct().Count()) throw new Exception(String.Format("{0} as the target Name for a new PropertyType can't be created. Merging between collection, enum & primitive (vs non) Types is not supported", MergeName)); var MergeFactors = PropertiesByName[MergeName].Select(m => m.MergeFactors).First(); if (MergeFactors.IsPrimitive) { foreach (var _ClassProperty in PropertiesByName[MergeName]) { // handle normal numeric, byte, string & datetime types Type typeA = _ClassProperty.SourceProperty.SourceType; Type typeB = _mergedProperties.ContainsKey(MergeName) ? _mergedProperties[MergeName] : _ClassProperty.SourceProperty.SourceType; Type typeC = ImplicitTypeConversionExtension.TypeLcd(typeA.GetPrincipleType(), typeB.GetPrincipleType()); // there are many situations that will yield a nullable if (typeC == typeof(string)) _mergedProperties[MergeName] = typeC; else if (typeC == typeof(byte[])) _mergedProperties[MergeName] = typeC; else if (Nullable.GetUnderlyingType(typeA) != null || Nullable.GetUnderlyingType(typeB) != null) _mergedProperties[MergeName] = typeof(Nullable<>).MakeGenericType(typeC); else if (_SourceTypes.Any() && PropertiesByName[MergeName].Count() != _SourceTypes.Count()) _mergedProperties[MergeName] = typeof(Nullable<>).MakeGenericType(typeC); else _mergedProperties[MergeName] = typeC; } _mergedPropertyHashes[MergeName] = _mergedProperties[MergeName].GetHashCode(); } else if (MergeFactors.IsEnum) { //TODO:Check for enum item collision & apply merging of multiple enum type when everything is OK _mergedProperties[MergeName] = PropertiesByName[MergeName].Select(m => m.SourceProperty.SourceType).First(); _mergedPropertyHashes[MergeName] = _mergedProperties[MergeName].GetHashCode(); } else { Type[] dstTypes = PropertiesByName[MergeName].Select(m => m.SourceProperty.PrincipleType).ToArray(); // create the CompositeType that represents the new property's Type only if it's specifically asked for if (calcMergedProperties) { _mergedProperties[MergeName] = new CompositeType( DefaultNamespace(dstTypes), DefaultClassName(dstTypes, _PrettyNames), dstTypes, null, _PropertyNameExclutions, _PrettyNames); if (MergeFactors.isCollection) _mergedProperties[MergeName] = typeof(List<>).MakeGenericType(_mergedProperties[MergeName]); } _mergedPropertyHashes[MergeName] = new CompositeSignature(dstTypes, _PropertyNameExclutions, null, _PrettyNames).GetHashCode(); } } _HashCode = 0; foreach (int HashCode in _mergedPropertyHashes.OrderBy(m => m.Key).Select(m1 => m1.Key.GetHashCode() ^ m1.Value)) _HashCode ^= HashCode; if (calcMergedProperties) _MergedProperties = _mergedProperties; } private static CompositeProperty[] FilterInvalidProperties(Type[] sourceTypes, string[] PropertyNameExclutions, bool prettyNames, string[] targetPropertyNames = null, CompositeProperty[] ClassPropertyInclusions = null) { return sourceTypes .SelectMany(t => t .GetProperties() .Where(_PropertyInfo => _PropertyInfo.PropertyType.IsSerializable && _PropertyInfo.CanRead && _PropertyInfo.CanWrite)) .Select(p => new CompositeProperty(p.Name, p.PropertyType)) .Union(ClassPropertyInclusions ?? new CompositeProperty[] { }) .Where(ClassProperty => (prettyNames ? !PropertyNameExclutions.Any(Name => pretty(Name) == pretty(ClassProperty)) : !PropertyNameExclutions.Any(Name => Name == ClassProperty.Name)) && (targetPropertyNames == null || targetPropertyNames.Length == 0 || (prettyNames ? targetPropertyNames.Any(Name => pretty(Name) == pretty(ClassProperty)) : targetPropertyNames.Any(Name => Name == ClassProperty.Name)))) .Distinct() .ToArray(); } private static readonly Dictionary<string, string> _prettyDictionary = new Dictionary<string, string>(); private static string pretty(string name) => _prettyDictionary.ContainsKey(name) ? _prettyDictionary[name] : (_prettyDictionary[name] = StringTransform.PrettyMsSqlIdent(name)); private static string pretty(CompositeProperty _ClassProperty) => pretty(_ClassProperty.Name); internal string DefaultClassName(Type[] sourceTypes, bool prettyNames = true) => string.Join("_", sourceTypes .Select(t => prettyNames ? pretty(t.Name) : t.Name) .Distinct() .OrderBy(s => s)); public static Type DefaultBaseType(Type[] sourceTypes) { IEnumerable<Type> _BaseTypes = sourceTypes .Select(t => t.BaseType) .Where(BaseType => BaseType != typeof(object) && BaseType != typeof(Object)) .Distinct(); return _BaseTypes.Count() == 1 ? _BaseTypes.First() : null; } public static string DefaultNamespace(Type[] sourceTypes) => string.Join(".", sourceTypes.Select(t => t.Namespace).Distinct().ToArray()); public override int GetHashCode() { if (_HashCode == 0) ConsolidateProperties(false); return _HashCode; } public override bool Equals(object obj) => obj is CompositeSignature ? Equals((CompositeSignature) obj) : false; public bool Equals(CompositeSignature other) => GetHashCode().Equals(other.GetHashCode()); } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Media; using System.Windows.Media.Imaging; using BuildVision.Contracts; using BuildVision.UI.Modelss; using BuildVision.UI.Helpers; using BuildVision.UI.Extensions; using BuildVision.UI.Common.Logging; using BuildVision.UI.Models; using BuildVision.UI.Settings.Models.Columns; using BuildVision.UI.Settings.Models.Sorting; using BuildVision.UI.Settings.Models; namespace BuildVision.UI.DataGrid { public static class ColumnsManager { private static List<string> _nonSortableColumns = new List<string> { nameof(ProjectItem.StateBitmap) }; private static List<string> _nonGroupableColumns = new List<string> { nameof(ProjectItem.StateBitmap), nameof(ProjectItem.BuildStartTime), nameof(ProjectItem.BuildFinishTime), nameof(ProjectItem.BuildElapsedTime), nameof(ProjectItem.BuildOrder), }; private static readonly Type _itemRowType = typeof(ProjectItem); public static string GetInitialColumnHeader(GridColumnSettings gridColumnSettings) { try { var attr = GetPropertyAttribute<GridColumnAttribute>(gridColumnSettings.PropertyNameId); return (attr != null) ? attr.Header : null; } catch (PropertyNotFoundException) { return null; } } public static object GetColumnExampleValue(GridColumnSettings gridColumnSettings) { try { var attr = GetPropertyAttribute<GridColumnAttribute>(gridColumnSettings.PropertyNameId); return attr?.ExampleValue; } catch (PropertyNotFoundException) { return null; } } public static bool ColumnIsSortable(string propertyName) { if (_nonSortableColumns.Contains(propertyName)) return false; return true; } public static bool ColumnIsGroupable(GridColumnSettings gridColumnSettings) { if (_nonGroupableColumns.Contains(gridColumnSettings.PropertyNameId)) return false; return true; } public static void GenerateColumns(ObservableCollection<DataGridColumn> columns, GridSettings gridSettings) { try { try { columns.Clear(); } catch (ArgumentOutOfRangeException) { // DataGrid or DataGridColumn issue? // Saving VisualStudio|Options|BuildVision settings causes ArgumentOutOfRangeException (DisplayIndex) // at columns.Clear if BuildVision toolwindow was hidden since VisualStudio start (only in this case). // For the second time without any errors. columns.Clear(); } var tmpColumnsList = new List<DataGridColumn>(); foreach (PropertyInfo property in GetItemProperties()) { GridColumnAttribute columnConfiguration = property.GetCustomAttribute<GridColumnAttribute>(); if (columnConfiguration == null) continue; string propertyName = property.Name; GridColumnSettings columnSettings; if (gridSettings.Columns[propertyName] != null) { columnSettings = gridSettings.Columns[propertyName]; } else { columnSettings = new GridColumnSettings( propertyName, columnConfiguration.Header, columnConfiguration.Visible, columnConfiguration.DisplayIndex, columnConfiguration.Width, columnConfiguration.ValueStringFormat); gridSettings.Columns.Add(columnSettings); } DataGridBoundColumn column = CreateColumn(property); InitColumn(column, columnConfiguration, columnSettings, gridSettings.Sort); tmpColumnsList.Add(column); } tmpColumnsList.Sort((col1, col2) => col1.DisplayIndex.CompareTo(col2.DisplayIndex)); for (int i = 0; i < tmpColumnsList.Count; i++) { var column = tmpColumnsList[i]; // We aren't able to afford coincidence of indexes, otherwise UI will hang. column.DisplayIndex = i; columns.Add(column); } } catch (Exception ex) { ex.TraceUnknownException(); } } public static void SyncColumnSettings(ObservableCollection<DataGridColumn> columns, GridSettings gridSettings) { try { foreach (DataGridBoundColumn column in columns.OfType<DataGridBoundColumn>()) { string propertyName = column.GetBindedProperty(); GridColumnSettings columnSettings = gridSettings.Columns[propertyName]; if (columnSettings == null) continue; columnSettings.Visible = (column.Visibility == Visibility.Visible); columnSettings.DisplayIndex = column.DisplayIndex; columnSettings.Width = column.Width.IsAuto ? double.NaN : column.ActualWidth; } } catch (Exception ex) { ex.TraceUnknownException(); } } public static string GetBindedProperty(this DataGridColumn column) { var boundColumn = column as DataGridBoundColumn; if (boundColumn == null) return string.Empty; var binding = boundColumn.Binding as Binding; if (binding == null) return string.Empty; return binding.Path.Path; } private static PropertyInfo[] GetItemProperties() { return _itemRowType.GetProperties(); } private static T GetPropertyAttribute<T>(string propertyName) where T : Attribute { var propertyInfo = _itemRowType.GetProperty(propertyName); if (propertyInfo == null) { var ex = new PropertyNotFoundException(propertyName, _itemRowType); ex.Trace("Unable to find attribute by property."); throw ex; } T attribute = propertyInfo.GetCustomAttribute<T>(); return attribute; } private static DataGridBoundColumn CreateColumn(PropertyInfo property) { DataGridBoundColumn column; column = CreateColumnForProperty(property); column.CanUserSort = ColumnIsSortable(property.Name); column.Binding = new Binding(property.Name); return column; } private static DataGridBoundColumn CreateColumnForProperty(PropertyInfo property) { DataGridBoundColumn column; if (property.PropertyType == typeof(BitmapSource) || property.PropertyType == typeof(ImageSource)) column = new DataGridImageColumn(); else if (property.PropertyType == typeof(ControlTemplate)) column = new DataGridContentControlColumn(); else if (property.PropertyType == typeof(bool)) column = new DataGridCheckBoxColumn(); else column = new DataGridTextColumn(); return column; } private static void InitColumn(DataGridBoundColumn column, GridColumnAttribute columnConfiguration, GridColumnSettings columnSettings, SortDescription sortDescription) { if (string.IsNullOrEmpty(columnConfiguration.ImageKey)) { column.Header = columnSettings.Header; } else if (columnConfiguration.ImageKey == GridColumnAttribute.EmptyHeaderImageKey) { column.Header = null; } else { const int ImgHeight = 14; const int ImgWidth = 14; if (string.IsNullOrEmpty(columnConfiguration.ImageDictionaryUri)) { var imgRes = Resources.ResourceManager.GetObject(columnConfiguration.ImageKey); var img = (System.Drawing.Bitmap)imgRes; column.Header = new Image { Source = img.ToMediaBitmap(), Width = ImgWidth, Height = ImgHeight, Stretch = Stretch.Uniform, Tag = columnSettings.Header }; } else { var controlTemplate = VectorResources.TryGet(columnConfiguration.ImageDictionaryUri, columnConfiguration.ImageKey); column.Header = new ContentControl { Template = controlTemplate, Width = ImgWidth, Height = ImgHeight, ClipToBounds = true, Tag = columnSettings.Header }; } } column.Visibility = columnSettings.Visible ? Visibility.Visible : Visibility.Collapsed; if (columnSettings.DisplayIndex != -1) column.DisplayIndex = columnSettings.DisplayIndex; if (!double.IsNaN(columnSettings.Width)) column.Width = new DataGridLength(columnSettings.Width); if (columnSettings.ValueStringFormat != null) column.Binding.StringFormat = columnSettings.ValueStringFormat; if (column.GetBindedProperty() == sortDescription.Property) column.SortDirection = sortDescription.Order.ToSystem(); string columnName = columnSettings.Header; if (string.IsNullOrEmpty(columnName)) columnName = columnConfiguration.Header; column.SetValue(DataGridColumnExtensions.NameProperty, columnName); } } }
namespace QI4N.Framework.Reflection { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Threading; using Reflection; public class ProxyTypeBuilder { private readonly IList<FieldBuilder> fieldBuilders = new List<FieldBuilder>(); private readonly IDictionary<Type, Type[]> interfaceToMixinMap = new Dictionary<Type, Type[]>(); private AssemblyBuilder assemblyBuilder; private Type compositeType; private Type[] interfaces; private TypeBuilder typeBuilder; public Type BuildProxyType(Type compositeType) { this.compositeType = compositeType; this.CreateInterfaceList(); this.CreateAssemblyBuilder(); this.CreateTypeBuilder(); this.CreateMixinList(); this.CreateMixinFields(); foreach (Type type in this.interfaces) { foreach (MethodInfo method in type.GetAllMethods()) { this.CreateMethod(method); } } this.CreateDefaultCtor(); Type proxyType = this.typeBuilder.CreateType(); return proxyType; } private static void CreateDelegatedMixinMethod(MethodInfo method, ILGenerator generator, FieldBuilder fieldBuilder) { //delegate calls to fieldbuilder generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldfld, fieldBuilder); ParameterInfo[] paramArray = method.GetParameters(); int paramCount = paramArray.Length; for (int i = 0; i < paramCount; i++) { generator.Emit(OpCodes.Ldarg, i + 1); } generator.Emit(OpCodes.Callvirt, method); generator.Emit(OpCodes.Ret); } private static void CreateInvocationHandlerMethod(MethodInfo method, ILGenerator generator, FieldBuilder fieldBuilder) { MethodInfo invokeMethod = typeof(InvocationHandler).GetMethod("Invoke"); MethodInfo getFromCacheMethod = typeof(MethodInfoCache).GetMethod("GetMethod"); int methodId = MethodInfoCache.AddMethod(method); ParameterInfo[] paramInfos = method.GetParameters(); IEnumerable<Type> paramTypes = paramInfos.Select(p => p.ParameterType); int paramCount = method.GetParameters().Length; // Build parameter object array LocalBuilder paramArray = generator.DeclareLocal(typeof(object[])); generator.Emit(OpCodes.Ldc_I4_S, paramCount); generator.Emit(OpCodes.Newarr, typeof(object)); generator.Emit(OpCodes.Stloc, paramArray); //--- int j = 0; //Fill parameter object array foreach (Type parameterType in paramTypes) { //load arr generator.Emit(OpCodes.Ldloc, paramArray); //load index generator.Emit(OpCodes.Ldc_I4, j); //load arg generator.Emit(OpCodes.Ldarg, j + 1); //box if needed if (parameterType.IsByRef) { generator.Emit(OpCodes.Ldind_Ref); Type t = parameterType.GetElementType(); if (t.IsValueType) { generator.Emit(OpCodes.Box, t); } } else if (parameterType.IsValueType) { generator.Emit(OpCodes.Box, parameterType); } generator.Emit(OpCodes.Stelem_Ref); j++; } //This . generator.Emit(OpCodes.Ldarg_0); //Mixin . generator.Emit(OpCodes.Ldfld, fieldBuilder); // param 1 = this generator.Emit(OpCodes.Ldarg_0); // param 2 = methodinfo generator.Emit(OpCodes.Ldc_I4, methodId); generator.Emit(OpCodes.Call, getFromCacheMethod); // param 3 = parameter array generator.Emit(OpCodes.Ldloc, paramArray); //call this.mixin.invoke(this,methodinfo,paramArray); generator.Emit(OpCodes.Callvirt, invokeMethod); if (method.ReturnType == typeof(void)) { generator.Emit(OpCodes.Pop); } else if (method.ReturnType.IsValueType) { generator.Emit(OpCodes.Unbox, method.ReturnType); generator.Emit(OpCodes.Ldobj, method.ReturnType); } generator.Emit(OpCodes.Ret); } private static void CreateNoOpMethod(MethodInfo method, ILGenerator generator) { if (method.ReturnType != typeof(void)) { LocalBuilder local = generator.DeclareLocal(method.ReturnType); local.SetLocalSymInfo("FakeReturn"); generator.Emit(OpCodes.Ldloc, local); } generator.Emit(OpCodes.Ret); } private void CreateAssemblyBuilder() { AppDomain domain = Thread.GetDomain(); var assemblyName = new AssemblyName { Name = Guid.NewGuid().ToString(), Version = new Version(1, 0, 0, 0) }; this.assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); } private void CreateDefaultCtor() { ConstructorBuilder ctorBuilder = this.typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[] { }); ILGenerator generator = ctorBuilder.GetILGenerator(); foreach (FieldBuilder field in this.fieldBuilders) { ConstructorInfo ctor = field.FieldType.GetConstructor(new Type[] { }); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Newobj, ctor); generator.Emit(OpCodes.Stfld, field); } generator.Emit(OpCodes.Ret); } private void CreateInterfaceList() { Type[] all = this.compositeType.GetAllInterfaces().ToArray(); this.interfaces = all; } private void CreateMethod(MethodInfo method) { MethodBuilder methodBuilder = this.typeBuilder.GetMethodOverrideBuilder(method); ILGenerator generator = methodBuilder.GetILGenerator(); FieldBuilder fieldBuilder = this.GetDelegatingFieldBuilder(method); //If possible, delegate call to mixin implementation if (fieldBuilder != null) { CreateDelegatedMixinMethod(method, generator, fieldBuilder); return; } fieldBuilder = this.GetInterceptorFieldBuilder(method); //If possible, delegate call to mixin interceptor if (fieldBuilder != null) { CreateInvocationHandlerMethod(method, generator, fieldBuilder); return; } //else just No Op it CreateNoOpMethod(method, generator); } private void CreateMixinFields() { foreach (Type interfaceType in this.interfaceToMixinMap.Keys) { foreach (Type mixinType in this.interfaceToMixinMap[interfaceType]) { Type fieldType = mixinType; string mixinFieldName = string.Format("field {0}", fieldType.GetTypeName()); //TODO: ensure unique name FieldBuilder mixinFieldBuilder = this.typeBuilder.DefineField(mixinFieldName, fieldType, FieldAttributes.Public); this.fieldBuilders.Add(mixinFieldBuilder); } } } private void CreateMixinList() { foreach (Type interfaceType in this.interfaces) { IEnumerable<Type> mixins = from attribute in interfaceType.GetCustomAttributes(typeof(MixinsAttribute), true).Cast<MixinsAttribute>() from mixinType in attribute.MixinTypes select mixinType; var genericMixins = new List<Type>(); foreach (Type mixinType in mixins) { Type genericType = mixinType; //handle generic type mixins if (mixinType.IsGenericTypeDefinition) { Type[] generics = interfaceType.GetGenericArguments(); genericType = mixinType.MakeGenericType(generics); } genericMixins.Add(genericType); } this.interfaceToMixinMap.Add(interfaceType, genericMixins.ToArray()); } } private void CreateTypeBuilder() { const string moduleName = "Alsing.Proxy"; const string nameSpace = "Alsing.Proxy"; string typeName = string.Format("{0}.{1}", nameSpace, this.compositeType.GetTypeName()); ModuleBuilder moduleBuilder = this.assemblyBuilder.DefineDynamicModule(moduleName, true); const TypeAttributes typeAttributes = TypeAttributes.Class | TypeAttributes.Public; this.typeBuilder = moduleBuilder.DefineType(typeName, typeAttributes, typeof(object), this.interfaces); } private FieldBuilder GetDelegatingFieldBuilder(MethodInfo method) { FieldBuilder fieldBuilder = (from fb in this.fieldBuilders from i in fb.FieldType.GetInterfaces() where i == method.DeclaringType select fb).FirstOrDefault(); return fieldBuilder; } private FieldBuilder GetInterceptorFieldBuilder(MethodInfo method) { FieldBuilder fieldBuilder = (from fb in this.fieldBuilders where typeof(InvocationHandler).IsAssignableFrom(fb.FieldType) from a in fb.FieldType.GetCustomAttributes(typeof(AppliesToAttribute), true).Cast<AppliesToAttribute>() from t in a.AppliesToTypes let f = Activator.CreateInstance(t, null) as AppliesToFilter where f.AppliesTo(method, fb.FieldType, this.compositeType, null) select fb).FirstOrDefault(); return fieldBuilder; } } }
// Copyright (c) "Neo4j" // Neo4j Sweden AB [http://neo4j.com] // // This file is part of Neo4j. // // 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.Linq; using System.Reactive; using System.Reactive.Linq; using System.Threading.Tasks; using FluentAssertions; using Moq; using Neo4j.Driver.Internal; using Neo4j.Driver.Tests; using Xunit; using Xunit.Abstractions; using static Microsoft.Reactive.Testing.ReactiveAssert; using static Neo4j.Driver.Tests.Assertions; namespace Neo4j.Driver.Reactive.Internal { public static class InternalRxSessionTests { public class Run : AbstractRxTest { [Fact] public void ShouldReturnInternalRxResult() { var rxSession = new InternalRxSession(Mock.Of<IInternalAsyncSession>(), Mock.Of<IRxRetryLogic>()); rxSession.Run("RETURN 1").Should().BeOfType<RxResult>(); } [Fact] public void ShouldInvokeSessionRunAsyncOnKeys() { VerifyLazyRunAsync(r => r.Keys().WaitForCompletion()); } [Fact] public void ShouldInvokeSessionRunAsyncOnRecords() { VerifyLazyRunAsync(r => r.Records().WaitForCompletion()); } [Fact] public void ShouldInvokeSessionRunAsyncOnSummary() { VerifyLazyRunAsync(r => r.Consume().WaitForCompletion()); } [Fact] public void ShouldInvokeSessionRunAsyncOnlyOnce() { VerifyLazyRunAsync(r => { r.Keys().WaitForCompletion(); r.Records().WaitForCompletion(); r.Consume().WaitForCompletion(); }); } private static void VerifyLazyRunAsync(Action<IRxResult> action) { var asyncSession = new Mock<IInternalAsyncSession>(); asyncSession.Setup(x => x.RunAsync(It.IsAny<Query>(), It.IsAny<Action<TransactionConfigBuilder>>(), It.IsAny<bool>())) .ReturnsAsync(new ListBasedRecordCursor(new[] {"x"}, Enumerable.Empty<IRecord>, Mock.Of<IResultSummary>)); var session = new InternalRxSession(asyncSession.Object, Mock.Of<IRxRetryLogic>()); var result = session.Run("RETURN 1"); asyncSession.Verify( x => x.RunAsync(It.IsAny<Query>(), It.IsAny<Action<TransactionConfigBuilder>>(), It.IsAny<bool>()), Times.Never); action(result); asyncSession.Verify( x => x.RunAsync(It.IsAny<Query>(), It.IsAny<Action<TransactionConfigBuilder>>(), It.IsAny<bool>()), Times.Once); } } public class BeginTransaction : AbstractRxTest { [Fact] public void ShouldReturnObservable() { var session = new Mock<IInternalAsyncSession>(); session.Setup(x => x.BeginTransactionAsync(It.IsAny<Action<TransactionConfigBuilder>>(), It.IsAny<bool>())) .ReturnsAsync(Mock.Of<IInternalAsyncTransaction>()); var rxSession = new InternalRxSession(session.Object, Mock.Of<IRxRetryLogic>()); rxSession.BeginTransaction().WaitForCompletion() .AssertEqual( OnNext(0, Matches<IRxTransaction>(t => t.Should().BeOfType<InternalRxTransaction>())), OnCompleted<IRxTransaction>(0)); session.Verify(x => x.BeginTransactionAsync(It.IsAny<Action<TransactionConfigBuilder>>(), It.IsAny<bool>()), Times.Once); } } public class TransactionFunctions : AbstractRxTest { [Theory] [MemberData(nameof(AccessModes))] public void ShouldBeginTransactionAndCommit(AccessMode mode) { var rxSession = CreateSession(mode, null, out var session, out var txc); rxSession .RunTransaction(mode, t => Observable.Return(1), null) .WaitForCompletion() .AssertEqual( OnNext(0, 1), OnCompleted<int>(0)); session.Verify(x => x.BeginTransactionAsync(mode, null, false), Times.Once); session.VerifyNoOtherCalls(); txc.Verify(x => x.CommitAsync(), Times.Once); txc.VerifyGet(x => x.IsOpen); txc.VerifyNoOtherCalls(); } [Theory] [MemberData(nameof(AccessModes))] public void ShouldBeginTransactionAndRollback(AccessMode mode) { var error = new ClientException(); var rxSession = CreateSession(mode, null, out var session, out var txc); rxSession .RunTransaction(mode, t => Observable.Throw<int>(error), null) .WaitForCompletion() .AssertEqual( OnError<int>(0, error)); session.Verify(x => x.BeginTransactionAsync(mode, null,false), Times.Once); session.VerifyNoOtherCalls(); txc.Verify(x => x.RollbackAsync(), Times.Once); txc.VerifyGet(x => x.IsOpen); txc.VerifyNoOtherCalls(); } [Theory] [MemberData(nameof(AccessModes))] public void ShouldBeginTransactionAndRollbackOnSynchronousException(AccessMode mode) { var error = new ClientException(); var rxSession = CreateSession(mode, null, out var session, out var txc); rxSession .RunTransaction<int>(mode, t => throw error, null) .WaitForCompletion() .AssertEqual( OnError<int>(0, error)); session.Verify(x => x.BeginTransactionAsync(mode, null,false), Times.Once); session.VerifyNoOtherCalls(); txc.Verify(x => x.RollbackAsync(), Times.Once); txc.VerifyGet(x => x.IsOpen); txc.VerifyNoOtherCalls(); } private static InternalRxSession CreateSession(AccessMode mode, Action<TransactionConfigBuilder> action, out Mock<IInternalAsyncSession> session, out Mock<IInternalAsyncTransaction> txc) { var isOpen = true; txc = new Mock<IInternalAsyncTransaction>(); txc.Setup(x => x.CommitAsync()).Returns(Task.CompletedTask).Callback(() => isOpen = false); txc.Setup(x => x.RollbackAsync()).Returns(Task.CompletedTask).Callback(() => isOpen = false); txc.SetupGet(x => x.IsOpen).Returns(() => isOpen); session = new Mock<IInternalAsyncSession>(); session.Setup(x => x.BeginTransactionAsync(mode, action, false)).ReturnsAsync(txc.Object); return new InternalRxSession(session.Object, new SingleRetryLogic()); } public static TheoryData<AccessMode> AccessModes() { return new TheoryData<AccessMode> { AccessMode.Read, AccessMode.Write }; } private class SingleRetryLogic : IRxRetryLogic { public IObservable<T> Retry<T>(IObservable<T> work) { return work; } } } public class Close : AbstractRxTest { [Fact] public void ShouldInvokeSessionCloseAsync() { var asyncSession = new Mock<IInternalAsyncSession>(); var rxSession = new InternalRxSession(asyncSession.Object, Mock.Of<IRxRetryLogic>()); var close = rxSession.Close<Unit>(); asyncSession.Verify(x => x.CloseAsync(), Times.Never); close.WaitForCompletion(); asyncSession.Verify(x => x.CloseAsync(), Times.Once); } } public class LastBookmark { [Fact] public void ShouldDelegateToAsyncSession() { var asyncSession = new Mock<IInternalAsyncSession>(); var rxSession = new InternalRxSession(asyncSession.Object, Mock.Of<IRxRetryLogic>()); var bookmark = rxSession.LastBookmark; asyncSession.Verify(x => x.LastBookmark, Times.Once); } } public class SessionConfig { [Fact] public void ShouldDelegateToAsyncSession() { var asyncSession = new Mock<IInternalAsyncSession>(); var rxSession = new InternalRxSession(asyncSession.Object, Mock.Of<IRxRetryLogic>()); var bookmark = rxSession.SessionConfig; asyncSession.Verify(x => x.SessionConfig, Times.Once); } } } }
#if !NOT_UNITY3D using System; using System.Collections.Generic; using System.Linq; using ModestTree; using ModestTree.Util; using UnityEngine; using UnityEngine.Serialization; using UnityEngine.SceneManagement; using Zenject.Internal; namespace Zenject { public class SceneContext : Context { public static Action<DiContainer> ExtraBindingsInstallMethod; public static DiContainer ParentContainer; [FormerlySerializedAs("ParentNewObjectsUnderRoot")] [Tooltip("When true, objects that are created at runtime will be parented to the SceneContext")] [SerializeField] bool _parentNewObjectsUnderRoot = false; [Tooltip("Optional contract names for this SceneContext, allowing contexts in subsequently loaded scenes to depend on it and be parented to it, and also for previously loaded decorators to be included")] [SerializeField] List<string> _contractNames = new List<string>(); [Tooltip("Optional contract name of a SceneContext in a previously loaded scene that this context depends on and to which it must be parented")] [SerializeField] string _parentContractName; [Tooltip("When false, wait until run method is explicitly called. Otherwise run on awake")] [SerializeField] bool _autoRun = true; DiContainer _container; readonly List<object> _dependencyRoots = new List<object>(); readonly List<SceneDecoratorContext> _decoratorContexts = new List<SceneDecoratorContext>(); bool _hasInstalled; bool _hasResolved; static bool _staticAutoRun = true; public override DiContainer Container { get { return _container; } } public bool IsValidating { get { #if UNITY_EDITOR return ProjectContext.Instance.Container.IsValidating; #else return false; #endif } } public IEnumerable<string> ContractNames { get { return _contractNames; } set { _contractNames.Clear(); _contractNames.AddRange(value); } } public string ParentContractName { get { return _parentContractName; } set { _parentContractName = value; } } public bool ParentNewObjectsUnderRoot { get { return _parentNewObjectsUnderRoot; } set { _parentNewObjectsUnderRoot = value; } } public void Awake() { // We always want to initialize ProjectContext as early as possible ProjectContext.Instance.EnsureIsInitialized(); if (_staticAutoRun && _autoRun) { Run(); } else { // True should always be default _staticAutoRun = true; } } #if UNITY_EDITOR public void Validate() { Assert.That(IsValidating); Install(); Resolve(); _container.ValidateValidatables(); } #endif public void Run() { Assert.That(!IsValidating); Install(); Resolve(); } public override IEnumerable<GameObject> GetRootGameObjects() { return ZenUtilInternal.GetRootGameObjects(gameObject.scene); } DiContainer GetParentContainer() { if (string.IsNullOrEmpty(_parentContractName)) { if (ParentContainer != null) { var tempParentContainer = ParentContainer; // Always reset after using it - it is only used to pass the reference // between scenes via ZenjectSceneLoader ParentContainer = null; return tempParentContainer; } return ProjectContext.Instance.Container; } Assert.IsNull(ParentContainer, "Scene cannot have both a parent scene context name set and also an explicit parent container given"); var sceneContexts = UnityUtil.AllLoadedScenes .Except(gameObject.scene) .SelectMany(scene => scene.GetRootGameObjects()) .SelectMany(root => root.GetComponentsInChildren<SceneContext>()) .Where(sceneContext => sceneContext.ContractNames.Contains(_parentContractName)) .ToList(); Assert.That(sceneContexts.Any(), () => string.Format( "SceneContext on object {0} of scene {1} requires contract {2}, but none of the loaded SceneContexts implements that contract.", gameObject.name, gameObject.scene.name, _parentContractName)); Assert.That(sceneContexts.Count == 1, () => string.Format( "SceneContext on object {0} of scene {1} requires a single implementation of contract {2}, but multiple were found.", gameObject.name, gameObject.scene.name, _parentContractName)); return sceneContexts.Single().Container; } List<SceneDecoratorContext> LookupDecoratorContexts() { if (_contractNames.IsEmpty()) { return new List<SceneDecoratorContext>(); } return UnityUtil.AllLoadedScenes .Except(gameObject.scene) .SelectMany(scene => scene.GetRootGameObjects()) .SelectMany(root => root.GetComponentsInChildren<SceneDecoratorContext>()) .Where(decoratorContext => _contractNames.Contains(decoratorContext.DecoratedContractName)) .ToList(); } public void Install() { #if !UNITY_EDITOR Assert.That(!IsValidating); #endif Assert.That(!_hasInstalled); _hasInstalled = true; Assert.IsNull(_container); _container = GetParentContainer().CreateSubContainer(); Assert.That(_decoratorContexts.IsEmpty()); _decoratorContexts.AddRange(LookupDecoratorContexts()); Log.Debug("SceneContext: Running installers..."); if (_parentNewObjectsUnderRoot) { _container.DefaultParent = this.transform; } else { // This is necessary otherwise we inherit the project root DefaultParent _container.DefaultParent = null; } // Record all the injectable components in the scene BEFORE installing the installers // This is nice for cases where the user calls InstantiatePrefab<>, etc. in their installer // so that it doesn't inject on the game object twice // InitialComponentsInjecter will also guarantee that any component that is injected into // another component has itself been injected foreach (var instance in GetInjectableMonoBehaviours().Cast<object>()) { _container.QueueForInject(instance); } foreach (var decoratorContext in _decoratorContexts) { decoratorContext.Initialize(_container); } _container.IsInstalling = true; try { InstallBindings(); } finally { _container.IsInstalling = false; } } public void Resolve() { Log.Debug("SceneContext: Injecting components in the scene..."); Assert.That(_hasInstalled); Assert.That(!_hasResolved); _hasResolved = true; Log.Debug("SceneContext: Resolving all..."); Assert.That(_dependencyRoots.IsEmpty()); _dependencyRoots.AddRange(_container.ResolveDependencyRoots()); _container.FlushInjectQueue(); Log.Debug("SceneContext: Initialized successfully"); } void InstallBindings() { _container.Bind(typeof(Context), typeof(SceneContext)).To<SceneContext>().FromInstance(this); foreach (var decoratorContext in _decoratorContexts) { decoratorContext.InstallDecoratorSceneBindings(); } InstallSceneBindings(); _container.Bind<SceneKernel>().FromNewComponentOn(this.gameObject).AsSingle().NonLazy(); _container.Bind<ZenjectSceneLoader>().AsSingle(); if (ExtraBindingsInstallMethod != null) { ExtraBindingsInstallMethod(_container); // Reset extra bindings for next time we change scenes ExtraBindingsInstallMethod = null; } // Always install the installers last so they can be injected with // everything above foreach (var decoratorContext in _decoratorContexts) { decoratorContext.InstallDecoratorInstallers(); } InstallInstallers(); foreach (var decoratorContext in _decoratorContexts) { decoratorContext.InstallLateDecoratorInstallers(); } } protected override IEnumerable<MonoBehaviour> GetInjectableMonoBehaviours() { return ZenUtilInternal.GetInjectableMonoBehaviours(this.gameObject.scene); } // These methods can be used for cases where you need to create the SceneContext entirely in code // Note that if you use these methods that you have to call Run() yourself // This is useful because it allows you to create a SceneContext and configure it how you want // and add what installers you want before kicking off the Install/Resolve public static SceneContext Create() { return CreateComponent( new GameObject("SceneContext")); } public static SceneContext CreateComponent(GameObject gameObject) { _staticAutoRun = false; var result = gameObject.AddComponent<SceneContext>(); Assert.That(_staticAutoRun); // Should be reset return result; } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void TestCInt32() { var test = new BooleanBinaryOpTest__TestCInt32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Avx.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class BooleanBinaryOpTest__TestCInt32 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(Int32[] inArray1, Int32[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Int32> _fld1; public Vector256<Int32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); return testStruct; } public void RunStructFldScenario(BooleanBinaryOpTest__TestCInt32 testClass) { var result = Avx.TestC(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } public void RunStructFldScenario_Load(BooleanBinaryOpTest__TestCInt32 testClass) { fixed (Vector256<Int32>* pFld1 = &_fld1) fixed (Vector256<Int32>* pFld2 = &_fld2) { var result = Avx.TestC( Avx.LoadVector256((Int32*)(pFld1)), Avx.LoadVector256((Int32*)(pFld2)) ); testClass.ValidateResult(_fld1, _fld2, result); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector256<Int32> _clsVar1; private static Vector256<Int32> _clsVar2; private Vector256<Int32> _fld1; private Vector256<Int32> _fld2; private DataTable _dataTable; static BooleanBinaryOpTest__TestCInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); } public BooleanBinaryOpTest__TestCInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, _data2, LargestVectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx.TestC( Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx.TestC( Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx.TestC( Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx).GetMethod(nameof(Avx.TestC), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx).GetMethod(nameof(Avx.TestC), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) }) .Invoke(null, new object[] { Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx).GetMethod(nameof(Avx.TestC), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx.TestC( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<Int32>* pClsVar1 = &_clsVar1) fixed (Vector256<Int32>* pClsVar2 = &_clsVar2) { var result = Avx.TestC( Avx.LoadVector256((Int32*)(pClsVar1)), Avx.LoadVector256((Int32*)(pClsVar2)) ); ValidateResult(_clsVar1, _clsVar2, result); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr); var result = Avx.TestC(op1, op2); ValidateResult(op1, op2, result); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)); var result = Avx.TestC(op1, op2); ValidateResult(op1, op2, result); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)); var result = Avx.TestC(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new BooleanBinaryOpTest__TestCInt32(); var result = Avx.TestC(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new BooleanBinaryOpTest__TestCInt32(); fixed (Vector256<Int32>* pFld1 = &test._fld1) fixed (Vector256<Int32>* pFld2 = &test._fld2) { var result = Avx.TestC( Avx.LoadVector256((Int32*)(pFld1)), Avx.LoadVector256((Int32*)(pFld2)) ); ValidateResult(test._fld1, test._fld2, result); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx.TestC(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<Int32>* pFld1 = &_fld1) fixed (Vector256<Int32>* pFld2 = &_fld2) { var result = Avx.TestC( Avx.LoadVector256((Int32*)(pFld1)), Avx.LoadVector256((Int32*)(pFld2)) ); ValidateResult(_fld1, _fld2, result); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx.TestC(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Avx.TestC( Avx.LoadVector256((Int32*)(&test._fld1)), Avx.LoadVector256((Int32*)(&test._fld2)) ); ValidateResult(test._fld1, test._fld2, result); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Int32> op1, Vector256<Int32> op2, bool result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int32>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Int32[] left, Int32[] right, bool result, [CallerMemberName] string method = "") { bool succeeded = true; var expectedResult = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult &= ((~left[i] & right[i]) == 0); } succeeded = (expectedResult == result); if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.TestC)}<Int32>(Vector256<Int32>, Vector256<Int32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Copyright (C) 2015-2021 The Neo Project. // // The neo is free software distributed under the MIT software license, // see the accompanying file LICENSE in the main directory of the // project or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without // modifications are permitted. using Neo.Cryptography; using Neo.Cryptography.ECC; using Neo.IO; using Neo.IO.Json; using Neo.Ledger; using Neo.Persistence; using Neo.SmartContract; using Neo.SmartContract.Native; using Neo.VM; using Neo.VM.Types; using Neo.Wallets; using System; using System.Collections.Generic; using System.IO; using System.Linq; using static Neo.SmartContract.Helper; using Array = Neo.VM.Types.Array; namespace Neo.Network.P2P.Payloads { /// <summary> /// Represents a transaction. /// </summary> public class Transaction : IEquatable<Transaction>, IInventory, IInteroperable { /// <summary> /// The maximum size of a transaction. /// </summary> public const int MaxTransactionSize = 102400; /// <summary> /// The maximum number of attributes that can be contained within a transaction. /// </summary> public const int MaxTransactionAttributes = 16; private byte version; private uint nonce; private long sysfee; private long netfee; private uint validUntilBlock; private Signer[] _signers; private TransactionAttribute[] attributes; private byte[] script; private Witness[] witnesses; /// <summary> /// The size of a transaction header. /// </summary> public const int HeaderSize = sizeof(byte) + //Version sizeof(uint) + //Nonce sizeof(long) + //SystemFee sizeof(long) + //NetworkFee sizeof(uint); //ValidUntilBlock private Dictionary<Type, TransactionAttribute[]> _attributesCache; /// <summary> /// The attributes of the transaction. /// </summary> public TransactionAttribute[] Attributes { get => attributes; set { attributes = value; _attributesCache = null; _hash = null; _size = 0; } } /// <summary> /// The <see cref="NetworkFee"/> for the transaction divided by its <see cref="Size"/>. /// </summary> public long FeePerByte => NetworkFee / Size; private UInt256 _hash = null; public UInt256 Hash { get { if (_hash == null) { _hash = this.CalculateHash(); } return _hash; } } InventoryType IInventory.InventoryType => InventoryType.TX; /// <summary> /// The network fee of the transaction. /// </summary> public long NetworkFee //Distributed to consensus nodes. { get => netfee; set { netfee = value; _hash = null; } } /// <summary> /// The nonce of the transaction. /// </summary> public uint Nonce { get => nonce; set { nonce = value; _hash = null; } } /// <summary> /// The script of the transaction. /// </summary> public byte[] Script { get => script; set { script = value; _hash = null; _size = 0; } } /// <summary> /// The sender is the first signer of the transaction, regardless of its <see cref="WitnessScope"/>. /// </summary> /// <remarks>Note: The sender will pay the fees of the transaction.</remarks> public UInt160 Sender => _signers[0].Account; /// <summary> /// The signers of the transaction. /// </summary> public Signer[] Signers { get => _signers; set { _signers = value; _hash = null; _size = 0; } } private int _size; public int Size { get { if (_size == 0) { _size = HeaderSize + Signers.GetVarSize() + // Signers Attributes.GetVarSize() + // Attributes Script.GetVarSize() + // Script Witnesses.GetVarSize(); // Witnesses } return _size; } } /// <summary> /// The system fee of the transaction. /// </summary> public long SystemFee //Fee to be burned. { get => sysfee; set { sysfee = value; _hash = null; } } /// <summary> /// Indicates that the transaction is only valid before this block height. /// </summary> public uint ValidUntilBlock { get => validUntilBlock; set { validUntilBlock = value; _hash = null; } } /// <summary> /// The version of the transaction. /// </summary> public byte Version { get => version; set { version = value; _hash = null; } } public Witness[] Witnesses { get => witnesses; set { witnesses = value; _size = 0; } } void ISerializable.Deserialize(BinaryReader reader) { int startPosition = -1; if (reader.BaseStream.CanSeek) startPosition = (int)reader.BaseStream.Position; DeserializeUnsigned(reader); Witnesses = reader.ReadSerializableArray<Witness>(Signers.Length); if (Witnesses.Length != Signers.Length) throw new FormatException(); if (startPosition >= 0) _size = (int)reader.BaseStream.Position - startPosition; } private static IEnumerable<TransactionAttribute> DeserializeAttributes(BinaryReader reader, int maxCount) { int count = (int)reader.ReadVarInt((ulong)maxCount); HashSet<TransactionAttributeType> hashset = new(); while (count-- > 0) { TransactionAttribute attribute = TransactionAttribute.DeserializeFrom(reader); if (!attribute.AllowMultiple && !hashset.Add(attribute.Type)) throw new FormatException(); yield return attribute; } } private static IEnumerable<Signer> DeserializeSigners(BinaryReader reader, int maxCount) { int count = (int)reader.ReadVarInt((ulong)maxCount); if (count == 0) throw new FormatException(); HashSet<UInt160> hashset = new(); for (int i = 0; i < count; i++) { Signer signer = reader.ReadSerializable<Signer>(); if (!hashset.Add(signer.Account)) throw new FormatException(); yield return signer; } } public void DeserializeUnsigned(BinaryReader reader) { Version = reader.ReadByte(); if (Version > 0) throw new FormatException(); Nonce = reader.ReadUInt32(); SystemFee = reader.ReadInt64(); if (SystemFee < 0) throw new FormatException(); NetworkFee = reader.ReadInt64(); if (NetworkFee < 0) throw new FormatException(); if (SystemFee + NetworkFee < SystemFee) throw new FormatException(); ValidUntilBlock = reader.ReadUInt32(); Signers = DeserializeSigners(reader, MaxTransactionAttributes).ToArray(); Attributes = DeserializeAttributes(reader, MaxTransactionAttributes - Signers.Length).ToArray(); Script = reader.ReadVarBytes(ushort.MaxValue); if (Script.Length == 0) throw new FormatException(); } public bool Equals(Transaction other) { if (other is null) return false; if (ReferenceEquals(this, other)) return true; return Hash.Equals(other.Hash); } public override bool Equals(object obj) { return Equals(obj as Transaction); } void IInteroperable.FromStackItem(StackItem stackItem) { throw new NotSupportedException(); } /// <summary> /// Gets the attribute of the specified type. /// </summary> /// <typeparam name="T">The type of the attribute.</typeparam> /// <returns>The first attribute of this type. Or <see langword="null"/> if there is no attribute of this type.</returns> public T GetAttribute<T>() where T : TransactionAttribute { return GetAttributes<T>().FirstOrDefault(); } /// <summary> /// Gets all attributes of the specified type. /// </summary> /// <typeparam name="T">The type of the attributes.</typeparam> /// <returns>All the attributes of this type.</returns> public IEnumerable<T> GetAttributes<T>() where T : TransactionAttribute { _attributesCache ??= attributes.GroupBy(p => p.GetType()).ToDictionary(p => p.Key, p => p.ToArray()); if (_attributesCache.TryGetValue(typeof(T), out var result)) return result.OfType<T>(); return Enumerable.Empty<T>(); } public override int GetHashCode() { return Hash.GetHashCode(); } public UInt160[] GetScriptHashesForVerifying(DataCache snapshot) { return Signers.Select(p => p.Account).ToArray(); } void ISerializable.Serialize(BinaryWriter writer) { ((IVerifiable)this).SerializeUnsigned(writer); writer.Write(Witnesses); } void IVerifiable.SerializeUnsigned(BinaryWriter writer) { writer.Write(Version); writer.Write(Nonce); writer.Write(SystemFee); writer.Write(NetworkFee); writer.Write(ValidUntilBlock); writer.Write(Signers); writer.Write(Attributes); writer.WriteVarBytes(Script); } /// <summary> /// Converts the transaction to a JSON object. /// </summary> /// <param name="settings">The <see cref="ProtocolSettings"/> used during the conversion.</param> /// <returns>The transaction represented by a JSON object.</returns> public JObject ToJson(ProtocolSettings settings) { JObject json = new(); json["hash"] = Hash.ToString(); json["size"] = Size; json["version"] = Version; json["nonce"] = Nonce; json["sender"] = Sender.ToAddress(settings.AddressVersion); json["sysfee"] = SystemFee.ToString(); json["netfee"] = NetworkFee.ToString(); json["validuntilblock"] = ValidUntilBlock; json["signers"] = Signers.Select(p => p.ToJson()).ToArray(); json["attributes"] = Attributes.Select(p => p.ToJson()).ToArray(); json["script"] = Convert.ToBase64String(Script); json["witnesses"] = Witnesses.Select(p => p.ToJson()).ToArray(); return json; } /// <summary> /// Verifies the transaction. /// </summary> /// <param name="settings">The <see cref="ProtocolSettings"/> used to verify the transaction.</param> /// <param name="snapshot">The snapshot used to verify the transaction.</param> /// <param name="context">The <see cref="TransactionVerificationContext"/> used to verify the transaction.</param> /// <returns>The result of the verification.</returns> public VerifyResult Verify(ProtocolSettings settings, DataCache snapshot, TransactionVerificationContext context) { VerifyResult result = VerifyStateIndependent(settings); if (result != VerifyResult.Succeed) return result; return VerifyStateDependent(settings, snapshot, context); } /// <summary> /// Verifies the state-dependent part of the transaction. /// </summary> /// <param name="settings">The <see cref="ProtocolSettings"/> used to verify the transaction.</param> /// <param name="snapshot">The snapshot used to verify the transaction.</param> /// <param name="context">The <see cref="TransactionVerificationContext"/> used to verify the transaction.</param> /// <returns>The result of the verification.</returns> public virtual VerifyResult VerifyStateDependent(ProtocolSettings settings, DataCache snapshot, TransactionVerificationContext context) { uint height = NativeContract.Ledger.CurrentIndex(snapshot); if (ValidUntilBlock <= height || ValidUntilBlock > height + settings.MaxValidUntilBlockIncrement) return VerifyResult.Expired; UInt160[] hashes = GetScriptHashesForVerifying(snapshot); foreach (UInt160 hash in hashes) if (NativeContract.Policy.IsBlocked(snapshot, hash)) return VerifyResult.PolicyFail; if (!(context?.CheckTransaction(this, snapshot) ?? true)) return VerifyResult.InsufficientFunds; foreach (TransactionAttribute attribute in Attributes) if (!attribute.Verify(snapshot, this)) return VerifyResult.InvalidAttribute; long net_fee = NetworkFee - Size * NativeContract.Policy.GetFeePerByte(snapshot); if (net_fee < 0) return VerifyResult.InsufficientFunds; if (net_fee > MaxVerificationGas) net_fee = MaxVerificationGas; uint execFeeFactor = NativeContract.Policy.GetExecFeeFactor(snapshot); for (int i = 0; i < hashes.Length; i++) { if (witnesses[i].VerificationScript.IsSignatureContract()) net_fee -= execFeeFactor * SignatureContractCost(); else if (witnesses[i].VerificationScript.IsMultiSigContract(out int m, out int n)) { net_fee -= execFeeFactor * MultiSignatureContractCost(m, n); } else { if (!this.VerifyWitness(settings, snapshot, hashes[i], witnesses[i], net_fee, out long fee)) return VerifyResult.Invalid; net_fee -= fee; } if (net_fee < 0) return VerifyResult.InsufficientFunds; } return VerifyResult.Succeed; } /// <summary> /// Verifies the state-independent part of the transaction. /// </summary> /// <param name="settings">The <see cref="ProtocolSettings"/> used to verify the transaction.</param> /// <returns>The result of the verification.</returns> public virtual VerifyResult VerifyStateIndependent(ProtocolSettings settings) { if (Size > MaxTransactionSize) return VerifyResult.OverSize; try { _ = new Script(Script, true); } catch (BadScriptException) { return VerifyResult.InvalidScript; } UInt160[] hashes = GetScriptHashesForVerifying(null); for (int i = 0; i < hashes.Length; i++) { if (witnesses[i].VerificationScript.IsSignatureContract()) { if (hashes[i] != witnesses[i].ScriptHash) return VerifyResult.Invalid; var pubkey = witnesses[i].VerificationScript.AsSpan(2..35); try { if (!Crypto.VerifySignature(this.GetSignData(settings.Network), witnesses[i].InvocationScript.AsSpan(2), pubkey, ECCurve.Secp256r1)) return VerifyResult.InvalidSignature; } catch { return VerifyResult.Invalid; } } else if (witnesses[i].VerificationScript.IsMultiSigContract(out var m, out ECPoint[] points)) { if (hashes[i] != witnesses[i].ScriptHash) return VerifyResult.Invalid; var signatures = GetMultiSignatures(witnesses[i].InvocationScript); if (signatures.Length != m) return VerifyResult.Invalid; var n = points.Length; var message = this.GetSignData(settings.Network); try { for (int x = 0, y = 0; x < m && y < n;) { if (Crypto.VerifySignature(message, signatures[x], points[y])) x++; y++; if (m - x > n - y) return VerifyResult.InvalidSignature; } } catch { return VerifyResult.Invalid; } } } return VerifyResult.Succeed; } public StackItem ToStackItem(ReferenceCounter referenceCounter) { return new Array(referenceCounter, new StackItem[] { // Computed properties Hash.ToArray(), // Transaction properties (int)Version, Nonce, Sender.ToArray(), SystemFee, NetworkFee, ValidUntilBlock, Script, }); } private static byte[][] GetMultiSignatures(byte[] script) { int i = 0; var signatures = new List<byte[]>(); while (i < script.Length) { if (script[i++] != (byte)OpCode.PUSHDATA1) return null; if (i + 65 > script.Length) return null; if (script[i++] != 64) return null; signatures.Add(script[i..(i + 64)]); i += 64; } return signatures.ToArray(); } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.Json.Serialization; using FluentAssertions; using Microsoft.DotNet.Cli; using Microsoft.DotNet.Cli.CommandLine; using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.Tools; using Microsoft.DotNet.ToolPackage; using Microsoft.DotNet.Tools.Tool.Install; using Microsoft.DotNet.Tools.Tests.ComponentMocks; using Microsoft.DotNet.Tools.Test.Utilities; using Microsoft.DotNet.ShellShim; using Microsoft.Extensions.DependencyModel.Tests; using Microsoft.Extensions.EnvironmentAbstractions; using Xunit; using Parser = Microsoft.DotNet.Cli.Parser; using System.Runtime.InteropServices; using LocalizableStrings = Microsoft.DotNet.Tools.Tool.Install.LocalizableStrings; namespace Microsoft.DotNet.Tests.Commands.Tool { public class ToolInstallGlobalOrToolPathCommandTests { private readonly IFileSystem _fileSystem; private readonly IToolPackageStore _toolPackageStore; private readonly IToolPackageStoreQuery _toolPackageStoreQuery; private readonly CreateShellShimRepository _createShellShimRepository; private readonly CreateToolPackageStoresAndInstaller _createToolPackageStoreAndInstaller; private readonly EnvironmentPathInstructionMock _environmentPathInstructionMock; private readonly AppliedOption _appliedCommand; private readonly ParseResult _parseResult; private readonly BufferedReporter _reporter; private readonly string _temporaryDirectory; private readonly string _pathToPlaceShim; private readonly string _pathToPlacePackages; private const string PackageId = "global.tool.console.demo"; private const string PackageVersion = "1.0.4"; private const string ToolCommandName = "SimulatorCommand"; public ToolInstallGlobalOrToolPathCommandTests() { _reporter = new BufferedReporter(); _fileSystem = new FileSystemMockBuilder().UseCurrentSystemTemporaryDirectory().Build(); _temporaryDirectory = _fileSystem.Directory.CreateTemporaryDirectory().DirectoryPath; _pathToPlaceShim = Path.Combine(_temporaryDirectory, "pathToPlace"); _fileSystem.Directory.CreateDirectory(_pathToPlaceShim); _pathToPlacePackages = _pathToPlaceShim + "Packages"; var toolPackageStoreMock = new ToolPackageStoreMock(new DirectoryPath(_pathToPlacePackages), _fileSystem); _toolPackageStore = toolPackageStoreMock; _toolPackageStoreQuery = toolPackageStoreMock; _createShellShimRepository = (nonGlobalLocation) => new ShellShimRepository( new DirectoryPath(_pathToPlaceShim), fileSystem: _fileSystem, appHostShellShimMaker: new AppHostShellShimMakerMock(_fileSystem), filePermissionSetter: new NoOpFilePermissionSetter()); _environmentPathInstructionMock = new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim); _createToolPackageStoreAndInstaller = (location, forwardArguments) => (_toolPackageStore, _toolPackageStoreQuery, CreateToolPackageInstaller()); ParseResult result = Parser.Instance.Parse($"dotnet tool install -g {PackageId}"); _appliedCommand = result["dotnet"]["tool"]["install"]; var parser = Parser.Instance; _parseResult = parser.ParseFrom("dotnet tool", new[] {"install", "-g", PackageId}); } [Fact] public void WhenRunWithPackageIdItShouldCreateValidShim() { var toolInstallGlobalOrToolPathCommand = new ToolInstallGlobalOrToolPathCommand(_appliedCommand, _parseResult, _createToolPackageStoreAndInstaller, _createShellShimRepository, _environmentPathInstructionMock, _reporter); toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0); // It is hard to simulate shell behavior. Only Assert shim can point to executable dll _fileSystem.File.Exists(ExpectedCommandPath()).Should().BeTrue(); var deserializedFakeShim = JsonSerializer.Parse<AppHostShellShimMakerMock.FakeShim>( _fileSystem.File.ReadAllText(ExpectedCommandPath())); _fileSystem.File.Exists(deserializedFakeShim.ExecutablePath).Should().BeTrue(); } [Fact] public void WhenRunFromToolInstallRedirectCommandWithPackageIdItShouldCreateValidShim() { var toolInstallGlobalOrToolPathCommand = new ToolInstallGlobalOrToolPathCommand(_appliedCommand, _parseResult, _createToolPackageStoreAndInstaller, _createShellShimRepository, _environmentPathInstructionMock, _reporter); var toolInstallCommand = new ToolInstallCommand( _appliedCommand, _parseResult, toolInstallGlobalOrToolPathCommand); toolInstallCommand.Execute().Should().Be(0); _fileSystem.File.Exists(ExpectedCommandPath()).Should().BeTrue(); } [Fact] public void WhenRunWithPackageIdWithSourceItShouldCreateValidShim() { const string sourcePath = "http://mysource.com"; ParseResult result = Parser.Instance.Parse($"dotnet tool install -g {PackageId} --add-source {sourcePath}"); AppliedOption appliedCommand = result["dotnet"]["tool"]["install"]; ParseResult parseResult = Parser.Instance.ParseFrom("dotnet tool", new[] { "install", "-g", PackageId, "--add-source", sourcePath }); var toolToolPackageInstaller = CreateToolPackageInstaller( feeds: new List<MockFeed> { new MockFeed { Type = MockFeedType.ImplicitAdditionalFeed, Uri = sourcePath, Packages = new List<MockFeedPackage> { new MockFeedPackage { PackageId = PackageId, Version = PackageVersion, ToolCommandName = ToolCommandName, } } } }); var toolInstallGlobalOrToolPathCommand = new ToolInstallGlobalOrToolPathCommand(appliedCommand, parseResult, (location, forwardArguments) => (_toolPackageStore, _toolPackageStoreQuery, toolToolPackageInstaller), _createShellShimRepository, _environmentPathInstructionMock, _reporter); toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0); // It is hard to simulate shell behavior. Only Assert shim can point to executable dll _fileSystem.File.Exists(ExpectedCommandPath()) .Should().BeTrue(); var deserializedFakeShim = JsonSerializer.Parse<AppHostShellShimMakerMock.FakeShim>( _fileSystem.File.ReadAllText(ExpectedCommandPath())); _fileSystem.File.Exists(deserializedFakeShim.ExecutablePath).Should().BeTrue(); } [Fact] public void WhenRunWithPackageIdItShouldShowPathInstruction() { var toolInstallGlobalOrToolPathCommand = new ToolInstallGlobalOrToolPathCommand(_appliedCommand, _parseResult, _createToolPackageStoreAndInstaller, _createShellShimRepository, _environmentPathInstructionMock, _reporter); toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0); _reporter.Lines.First().Should().Be(EnvironmentPathInstructionMock.MockInstructionText); } [Fact] public void WhenRunWithPackageIdPackageFormatIsNotFullySupportedItShouldShowPathInstruction() { const string Warning = "WARNING"; var injectedWarnings = new Dictionary<PackageId, IEnumerable<string>>() { [new PackageId(PackageId)] = new List<string>() { Warning } }; var toolPackageInstaller = new ToolPackageInstallerMock( fileSystem: _fileSystem, store: _toolPackageStore, projectRestorer: new ProjectRestorerMock( fileSystem: _fileSystem, reporter: _reporter), warningsMap: injectedWarnings); var toolInstallGlobalOrToolPathCommand = new ToolInstallGlobalOrToolPathCommand( _appliedCommand, _parseResult, (location, forwardArguments) => (_toolPackageStore, _toolPackageStoreQuery, toolPackageInstaller), _createShellShimRepository, _environmentPathInstructionMock, _reporter); toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0); _reporter.Lines.First().Should().Be(Warning.Yellow()); _reporter.Lines.Skip(1).First().Should().Be(EnvironmentPathInstructionMock.MockInstructionText); } [Fact] public void GivenFailedPackageInstallWhenRunWithPackageIdItShouldFail() { const string ErrorMessage = "Simulated error"; var toolPackageInstaller = CreateToolPackageInstaller( installCallback: () => throw new ToolPackageException(ErrorMessage)); var toolInstallGlobalOrToolPathCommand = new ToolInstallGlobalOrToolPathCommand( _appliedCommand, _parseResult, (location, forwardArguments) => (_toolPackageStore, _toolPackageStoreQuery, toolPackageInstaller), _createShellShimRepository, _environmentPathInstructionMock, _reporter); Action a = () => toolInstallGlobalOrToolPathCommand.Execute(); a.ShouldThrow<GracefulException>().And.Message .Should().Contain( ErrorMessage + Environment.NewLine + string.Format(LocalizableStrings.ToolInstallationFailedWithRestoreGuidance, PackageId)); _fileSystem.Directory.Exists(Path.Combine(_pathToPlacePackages, PackageId)).Should().BeFalse(); } [Fact] public void GivenCreateShimItShouldHaveNoBrokenFolderOnDisk() { _fileSystem.File.CreateEmptyFile(ExpectedCommandPath()); // Create conflict shim var toolInstallGlobalOrToolPathCommand = new ToolInstallGlobalOrToolPathCommand( _appliedCommand, _parseResult, _createToolPackageStoreAndInstaller, _createShellShimRepository, _environmentPathInstructionMock, _reporter); Action a = () => toolInstallGlobalOrToolPathCommand.Execute(); a.ShouldThrow<GracefulException>().And.Message .Should().Contain(string.Format( CommonLocalizableStrings.ShellShimConflict, ToolCommandName)); _fileSystem.Directory.Exists(Path.Combine(_pathToPlacePackages, PackageId)).Should().BeFalse(); } [Fact] public void GivenInCorrectToolConfigurationWhenRunWithPackageIdItShouldFail() { var toolPackageInstaller = CreateToolPackageInstaller( installCallback: () => throw new ToolConfigurationException("Simulated error")); var toolInstallGlobalOrToolPathCommand = new ToolInstallGlobalOrToolPathCommand( _appliedCommand, _parseResult, (location, forwardArguments) => (_toolPackageStore, _toolPackageStoreQuery, toolPackageInstaller), _createShellShimRepository, _environmentPathInstructionMock, _reporter); Action a = () => toolInstallGlobalOrToolPathCommand.Execute(); a.ShouldThrow<GracefulException>().And.Message .Should().Contain( string.Format( LocalizableStrings.InvalidToolConfiguration, "Simulated error") + Environment.NewLine + string.Format(LocalizableStrings.ToolInstallationFailedContactAuthor, PackageId) ); } [Fact] public void WhenRunWithPackageIdItShouldShowSuccessMessage() { var toolInstallGlobalOrToolPathCommand = new ToolInstallGlobalOrToolPathCommand( _appliedCommand, _parseResult, _createToolPackageStoreAndInstaller, _createShellShimRepository, new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim, true), _reporter); toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0); _reporter .Lines .Should() .Equal(string.Format( LocalizableStrings.InstallationSucceeded, ToolCommandName, PackageId, PackageVersion).Green()); } [Fact] public void WhenRunWithInvalidVersionItShouldThrow() { const string invalidVersion = "!NotValidVersion!"; ParseResult result = Parser.Instance.Parse($"dotnet tool install -g {PackageId} --version {invalidVersion}"); AppliedOption appliedCommand = result["dotnet"]["tool"]["install"]; var toolInstallGlobalOrToolPathCommand = new ToolInstallGlobalOrToolPathCommand( appliedCommand, result, _createToolPackageStoreAndInstaller, _createShellShimRepository, new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim, true), _reporter); Action action = () => toolInstallGlobalOrToolPathCommand.Execute(); action .ShouldThrow<GracefulException>() .WithMessage(string.Format( LocalizableStrings.InvalidNuGetVersionRange, invalidVersion)); } [Fact] public void WhenRunWithExactVersionItShouldSucceed() { ParseResult result = Parser.Instance.Parse($"dotnet tool install -g {PackageId} --version {PackageVersion}"); AppliedOption appliedCommand = result["dotnet"]["tool"]["install"]; var toolInstallGlobalOrToolPathCommand = new ToolInstallGlobalOrToolPathCommand( appliedCommand, result, _createToolPackageStoreAndInstaller, _createShellShimRepository, new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim, true), _reporter); toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0); _reporter .Lines .Should() .Equal(string.Format( LocalizableStrings.InstallationSucceeded, ToolCommandName, PackageId, PackageVersion).Green()); } [Fact] public void WhenRunWithValidVersionRangeItShouldSucceed() { ParseResult result = Parser.Instance.Parse($"dotnet tool install -g {PackageId} --version [1.0,2.0]"); AppliedOption appliedCommand = result["dotnet"]["tool"]["install"]; var toolInstallGlobalOrToolPathCommand = new ToolInstallGlobalOrToolPathCommand( appliedCommand, result, _createToolPackageStoreAndInstaller, _createShellShimRepository, new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim, true), _reporter); toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0); _reporter .Lines .Should() .Equal(string.Format( LocalizableStrings.InstallationSucceeded, ToolCommandName, PackageId, PackageVersion).Green()); } [Fact] public void WhenRunWithoutAMatchingRangeItShouldFail() { ParseResult result = Parser.Instance.Parse($"dotnet tool install -g {PackageId} --version [5.0,10.0]"); AppliedOption appliedCommand = result["dotnet"]["tool"]["install"]; var toolInstallGlobalOrToolPathCommand = new ToolInstallGlobalOrToolPathCommand( appliedCommand, result, _createToolPackageStoreAndInstaller, _createShellShimRepository, new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim, true), _reporter); Action a = () => toolInstallGlobalOrToolPathCommand.Execute(); a.ShouldThrow<GracefulException>().And.Message .Should().Contain( LocalizableStrings.ToolInstallationRestoreFailed + Environment.NewLine + string.Format(LocalizableStrings.ToolInstallationFailedWithRestoreGuidance, PackageId)); _fileSystem.Directory.Exists(Path.Combine(_pathToPlacePackages, PackageId)).Should().BeFalse(); } [Fact] public void WhenRunWithValidVersionWildcardItShouldSucceed() { ParseResult result = Parser.Instance.Parse($"dotnet tool install -g {PackageId} --version 1.0.*"); AppliedOption appliedCommand = result["dotnet"]["tool"]["install"]; var toolInstallGlobalOrToolPathCommand = new ToolInstallGlobalOrToolPathCommand( appliedCommand, result, _createToolPackageStoreAndInstaller, _createShellShimRepository, new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim, true), _reporter); toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0); _reporter .Lines .Should() .Equal(string.Format( LocalizableStrings.InstallationSucceeded, ToolCommandName, PackageId, PackageVersion).Green()); } [Fact] public void WhenRunWithPackageIdAndBinPathItShouldNoteHaveEnvironmentPathInstruction() { var result = Parser.Instance.Parse($"dotnet tool install --tool-path /tmp/folder {PackageId}"); var appliedCommand = result["dotnet"]["tool"]["install"]; var parser = Parser.Instance; var parseResult = parser.ParseFrom("dotnet tool", new[] {"install", "-g", PackageId}); var toolInstallGlobalOrToolPathCommand = new ToolInstallGlobalOrToolPathCommand(appliedCommand, parseResult, _createToolPackageStoreAndInstaller, _createShellShimRepository, new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim), _reporter); toolInstallGlobalOrToolPathCommand.Execute().Should().Be(0); _reporter.Lines.Should().NotContain(l => l.Contains(EnvironmentPathInstructionMock.MockInstructionText)); } [Fact] public void AndPackagedShimIsProvidedWhenRunWithPackageIdItCreateShimUsingPackagedShim() { var extension = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ".exe" : string.Empty; var prepackagedShimPath = Path.Combine (_temporaryDirectory, ToolCommandName + extension); var tokenToIdentifyPackagedShim = "packagedShim"; _fileSystem.File.WriteAllText(prepackagedShimPath, tokenToIdentifyPackagedShim); var result = Parser.Instance.Parse($"dotnet tool install --tool-path /tmp/folder {PackageId}"); var appliedCommand = result["dotnet"]["tool"]["install"]; var parser = Parser.Instance; var parseResult = parser.ParseFrom("dotnet tool", new[] {"install", "-g", PackageId}); var packagedShimsMap = new Dictionary<PackageId, IReadOnlyList<FilePath>> { [new PackageId(PackageId)] = new[] {new FilePath(prepackagedShimPath)} }; var installCommand = new ToolInstallGlobalOrToolPathCommand(appliedCommand, parseResult, (location, forwardArguments) => (_toolPackageStore, _toolPackageStoreQuery, new ToolPackageInstallerMock( fileSystem: _fileSystem, store: _toolPackageStore, packagedShimsMap: packagedShimsMap, projectRestorer: new ProjectRestorerMock( fileSystem: _fileSystem, reporter: _reporter))), _createShellShimRepository, new EnvironmentPathInstructionMock(_reporter, _pathToPlaceShim), _reporter); installCommand.Execute().Should().Be(0); _fileSystem.File.ReadAllText(ExpectedCommandPath()).Should().Be(tokenToIdentifyPackagedShim); } private IToolPackageInstaller CreateToolPackageInstaller( List<MockFeed> feeds = null, Action installCallback = null) { return new ToolPackageInstallerMock( fileSystem: _fileSystem, store: _toolPackageStore, projectRestorer: new ProjectRestorerMock( fileSystem: _fileSystem, reporter: _reporter, feeds: feeds), installCallback: installCallback); } private string ExpectedCommandPath() { var extension = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ".exe" : string.Empty; return Path.Combine( _pathToPlaceShim, ToolCommandName + extension); } private class NoOpFilePermissionSetter : IFilePermissionSetter { public void SetUserExecutionPermission(string path) { } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Rest.Generator.Ruby.Templates { #line 1 "MethodTemplate.cshtml" using System.Linq; #line default #line hidden #line 2 "MethodTemplate.cshtml" using Microsoft.Rest.Generator.ClientModel #line default #line hidden ; #line 3 "MethodTemplate.cshtml" using Microsoft.Rest.Generator.Ruby.TemplateModels #line default #line hidden ; using System.Threading.Tasks; public class MethodTemplate : Microsoft.Rest.Generator.Template<Microsoft.Rest.Generator.Ruby.MethodTemplateModel> { #line hidden public MethodTemplate() { } #pragma warning disable 1998 public override async Task ExecuteAsync() { WriteLiteral("#\r\n"); #line 7 "MethodTemplate.cshtml" Write(WrapComment("# ", Model.Documentation)); #line default #line hidden WriteLiteral("\r\n"); #line 8 "MethodTemplate.cshtml" foreach (var parameter in Model.Parameters) { #line default #line hidden #line 10 "MethodTemplate.cshtml" Write(WrapComment("# ", string.Format("@param {0} {1}{2}", parameter.Name, parameter.Type.GetYardDocumentation(), parameter.Documentation))); #line default #line hidden WriteLiteral("\r\n"); #line 11 "MethodTemplate.cshtml" } #line default #line hidden #line 12 "MethodTemplate.cshtml" Write(WrapComment("# ", string.Format("@return [{0}] Promise object which allows to get HTTP response.", "Concurrent::Promise"))); #line default #line hidden WriteLiteral("\r\n#\r\ndef "); #line 14 "MethodTemplate.cshtml" Write(Model.Name); #line default #line hidden WriteLiteral("("); #line 14 "MethodTemplate.cshtml" Write(Model.MethodParameterDeclaration); #line default #line hidden WriteLiteral(")\r\n"); #line 15 "MethodTemplate.cshtml" #line default #line hidden #line 15 "MethodTemplate.cshtml" foreach (var parameter in Model.LocalParameters) { if (parameter.IsRequired && parameter.Type.IsNullable()) { #line default #line hidden WriteLiteral(" # fail ArgumentError, \'"); #line 19 "MethodTemplate.cshtml" Write(parameter.Name); #line default #line hidden WriteLiteral(" is nil\' if "); #line 19 "MethodTemplate.cshtml" Write(parameter.Name); #line default #line hidden WriteLiteral(".nil?\r\n \r\n"); #line 21 "MethodTemplate.cshtml" } #line default #line hidden WriteLiteral(" "); #line 22 "MethodTemplate.cshtml" Write(parameter.Type.ValidateType(Model.Scope, parameter.Name)); #line default #line hidden WriteLiteral("\r\n"); #line 23 "MethodTemplate.cshtml" } #line default #line hidden WriteLiteral(" "); #line 24 "MethodTemplate.cshtml" if (Model.LocalParameters.Any(p => p.IsRequired)) { #line default #line hidden #line 26 "MethodTemplate.cshtml" Write(EmptyLine); #line default #line hidden #line 26 "MethodTemplate.cshtml" } #line default #line hidden WriteLiteral("\r\n # Construct URL\r\n path = \""); #line 30 "MethodTemplate.cshtml" Write(Model.Url); #line default #line hidden WriteLiteral("\"\r\n "); #line 31 "MethodTemplate.cshtml" Write(Model.BuildUrl("path", "url")); #line default #line hidden WriteLiteral("\r\n "); #line 32 "MethodTemplate.cshtml" Write(Model.RemoveDuplicateForwardSlashes("url")); #line default #line hidden WriteLiteral("\r\n\r\n "); #line 34 "MethodTemplate.cshtml" Write(EmptyLine); #line default #line hidden WriteLiteral("\r\n # Create HTTP transport objects\r\n http_request = Net::HTTP::"); #line 36 "MethodTemplate.cshtml" Write(Model.HttpMethod.ToString()); #line default #line hidden WriteLiteral(".new(url.request_uri)\r\n\r\n"); #line 38 "MethodTemplate.cshtml" #line default #line hidden #line 38 "MethodTemplate.cshtml" if (Model.Parameters.Any(p => p.Location == ParameterLocation.Header)) { #line default #line hidden #line 40 "MethodTemplate.cshtml" Write(EmptyLine); #line default #line hidden #line 40 "MethodTemplate.cshtml" #line default #line hidden WriteLiteral(" # Set Headers\r\n"); #line 42 "MethodTemplate.cshtml" foreach (var parameter in Model.Parameters.Where(p => p.Location == ParameterLocation.Header)) { #line default #line hidden WriteLiteral(" http_request.add_field(\""); #line 44 "MethodTemplate.cshtml" Write(parameter.SerializedName); #line default #line hidden WriteLiteral("\", "); #line 44 "MethodTemplate.cshtml" Write(parameter.Type.ToString(parameter.Name)); #line default #line hidden WriteLiteral(");\r\n"); #line 45 "MethodTemplate.cshtml" } } #line default #line hidden WriteLiteral("\r\n"); #line 48 "MethodTemplate.cshtml" #line default #line hidden #line 48 "MethodTemplate.cshtml" if (Model.RequestBody != null) { #line default #line hidden #line 50 "MethodTemplate.cshtml" Write(EmptyLine); #line default #line hidden #line 50 "MethodTemplate.cshtml" #line default #line hidden WriteLiteral(" # Serialize Request\r\n http_request.add_field(\'Content-Type\', \'application/json" + "\')\r\n "); #line 53 "MethodTemplate.cshtml" Write(Model.CreateSerializationString(Model.RequestBody.Name, Model.RequestBody.Type, "http_request.body", Settings.Namespace)); #line default #line hidden WriteLiteral("\r\n"); #line 54 "MethodTemplate.cshtml" } #line default #line hidden WriteLiteral("\r\n "); #line 56 "MethodTemplate.cshtml" Write(EmptyLine); #line default #line hidden WriteLiteral("\r\n # Send Request\r\n promise = Concurrent::Promise.new { "); #line 58 "MethodTemplate.cshtml" Write(Model.MakeRequestMethodReference); #line default #line hidden WriteLiteral("(http_request, url) }\r\n\r\n "); #line 60 "MethodTemplate.cshtml" Write(EmptyLine); #line default #line hidden WriteLiteral("\r\n promise = promise.then do |http_response|\r\n status_code = http_response.co" + "de.to_i\r\n response_content = http_response.body\r\n unless ("); #line 64 "MethodTemplate.cshtml" Write(Model.SuccessStatusCodePredicate); #line default #line hidden WriteLiteral(")\r\n"); #line 65 "MethodTemplate.cshtml" #line default #line hidden #line 65 "MethodTemplate.cshtml" if (Model.DefaultResponse != null) { #line default #line hidden WriteLiteral(" error_model = JSON.parse(response_content)\r\n fail ClientRuntime::HttpO" + "perationException.new(http_request, http_response, error_model)\r\n"); #line 69 "MethodTemplate.cshtml" } else { #line default #line hidden WriteLiteral(" fail ClientRuntime::HttpOperationException.new(http_request, http_response)" + "\r\n"); #line 73 "MethodTemplate.cshtml" } #line default #line hidden WriteLiteral(" end\r\n\r\n "); #line 76 "MethodTemplate.cshtml" Write(EmptyLine); #line default #line hidden WriteLiteral("\r\n # Create Result\r\n result = ClientRuntime::HttpOperationResponse.new(http" + "_request, http_response)\r\n\r\n"); #line 80 "MethodTemplate.cshtml" #line default #line hidden #line 80 "MethodTemplate.cshtml" foreach (var responsePair in Model.Responses.Where(r => r.Value != null && r.Value.IsSerializable())) { #line default #line hidden WriteLiteral(" \r\n # Deserialize Response\r\n if status_code == "); #line 84 "MethodTemplate.cshtml" Write(Model.GetStatusCodeReference(responsePair.Key)); #line default #line hidden WriteLiteral("\r\n begin\r\n "); #line 86 "MethodTemplate.cshtml" Write(Model.CreateDeserializationString("response_content", Model.ReturnType, "result.body", Settings.Namespace)); #line default #line hidden WriteLiteral("\r\n rescue Exception => e\r\n fail ClientRuntime::DeserializationError.n" + "ew(\"Error occured in deserializing the response\", e.message, e.backtrace, respon" + "se_content)\r\n end\r\n\r\n result\r\n end\r\n \r\n"); #line 94 "MethodTemplate.cshtml" } #line default #line hidden WriteLiteral("\r\n"); #line 96 "MethodTemplate.cshtml" #line default #line hidden #line 96 "MethodTemplate.cshtml" if (Model.ReturnType != null && Model.DefaultResponse != null && !Model.Responses.Any() && Model.DefaultResponse.IsSerializable()) { #line default #line hidden WriteLiteral(" \r\n begin\r\n "); #line 100 "MethodTemplate.cshtml" Write(Model.CreateDeserializationString("response_content", Model.ReturnType, "result.body", Settings.Namespace)); #line default #line hidden WriteLiteral("\r\n rescue Exception => e\r\n fail ClientRuntime::DeserializationError.new(\"" + "Error occured in deserializing the response\", e.message, e.backtrace, response_c" + "ontent)\r\n end\r\n \r\n result\r\n \r\n"); #line 107 "MethodTemplate.cshtml" } #line default #line hidden WriteLiteral(" end\r\n\r\n "); #line 110 "MethodTemplate.cshtml" Write(EmptyLine); #line default #line hidden WriteLiteral("\r\n promise.execute\r\nend\r\n"); } #pragma warning restore 1998 } }
using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Aardvark.Base { public static partial class Tensor { /// <summary> /// Raw sample access without checks. /// </summary> public static Tup2<long> Index2SamplesRaw(long i, long first, long end, long d) => new Tup2<long>(0L, d); /// <summary> /// Provides sample clamping to the border value. /// </summary> public static Tup2<long>Index2SamplesClamped(long i, long first, long end, long d) { long i0 = i - first; if (i0 < 0) return new Tup2<long>(-i0 * d); long i1 = i - end + 1; if (i1 >= 0) return new Tup2<long>(-i1 * d); return new Tup2<long>(0L, d); } /// <summary> /// Provides cyclic handling within one cycle of the original. /// </summary> public static Tup2<long> Index2SamplesCyclic1(long i, long first, long end, long d) { long i0 = i - first; if (i0 < 0) { var s = (end - first) * d; if (i0 < -1) return new Tup2<long>(s, s + d); return new Tup2<long>(s, d); } long i1 = i - end + 1; if (i1 >= 0) { var s = (first - end) * d; if (i1 >= 1) return new Tup2<long>(s, s + d); return new Tup2<long>(0, s + d); } return new Tup2<long>(0L, d); } /// <summary> /// Raw sample access without checks. /// </summary> public static Tup3<long> Index3SamplesRaw(long i, long first, long end, long d) => new Tup3<long>(-d, 0L, d); /// <summary> /// Provides sample clamping to the border value. /// </summary> public static Tup3<long> Index3SamplesClamped(long i, long first, long end, long d) { long i0 = i - first, i1 = i - end + 1; return i0 > 0 ? (i1 < 0 ? new Tup3<long>(-d, 0L, d) : (i1 == 0 ? new Tup3<long>(-d, 0L, 0L) : new Tup3<long>(-i1 * d))) : (i0 == 0 ? (i1 < 0 ? new Tup3<long>(0L, 0L, d) : new Tup3<long>(0L)) : new Tup3<long>(-i0 * d)); } /// <summary> /// Raw sample access without checks. /// </summary> public static Tup4<long> Index4SamplesRaw(long i, long first, long end, long d) => new Tup4<long>(-d, 0L, d, d + d); /// <summary> /// Provides sample clamping to the border value. /// </summary> public static Tup4<long> Index4SamplesClamped (long i, long first, long end, long d) { long i0 = i - first, i1 = i - end + 1; if (i0 < 1) { if (i0 < 0) { if (i0 < -1) return new Tup4<long>(-i0 * d); if (i1 >= -1) return new Tup4<long>(d); return new Tup4<long>(d, d, d, d + d); } if (i1 >= -1) { if (i1 >= 0) return new Tup4<long>(0L); return new Tup4<long>(0L, 0L, d, d); } return new Tup4<long>(0L, 0L, d, d + d); } if (i1 >= -1) { if (i1 >= 0) { if (i1 >= 1) return new Tup4<long>(-i1 * d); return new Tup4<long>(-d, 0L, 0L, 0L); } return new Tup4<long>(-d, 0L, d, d); } return new Tup4<long>(-d, 0L, d, d + d); } /// <summary> /// Provides cyclic handling within one cycle of the original. /// Note that this does not handle regions with less than four /// samples. /// </summary> public static Tup4<long>Index4SamplesCyclic1(long i, long first, long end, long d) { long i0 = i - first, i1 = i - end + 1; if (i0 < 1) { var s = (end - first) * d; if (i0 < -1) { if (i0 < -2) return new Tup4<long>(s - d, s, s + d, s + d + d); return new Tup4<long>(s - d, s, s + d, d + d); } if (i0 < 0) return new Tup4<long>(s - d, s, d, d + d); return new Tup4<long>(s - d, 0L, d, d + d); } if (i1 >= -1) { var s = (first - end) * d; if (i1 >= 1) { if (i1 >= 2) return new Tup4<long>(s - d, s, s + d, s + d + d); return new Tup4<long>(-d, s, s + d, s + d + d); } if (i1 >= 0) return new Tup4<long>(-d, 0L, s + d, s + d + d); return new Tup4<long>(-d, 0L, d, s + d + d); } return new Tup4<long>(-d, 0L, d, d + d); } /// <summary> /// Raw sample access without checks. /// </summary> public static Tup6<long> Index6SamplesRaw(long i, long first, long end, long d) { var d2 = d + d; return new Tup6<long>(-d2, -d, 0L, d, d2, d2 + d); } /// <summary> /// Provides sample clamping to the border value. Note that this /// function currently requires that max - min >= 5! i.e. it /// does not work for too small source tensors. /// </summary> public static Tup5<long> Index5SamplesClamped(long i, long first, long end, long d) { long i0 = i - first, i1 = i - end + 1; long d2 = d + d; if (i0 < 2) { switch (i0) { case 1: return new Tup5<long>(-d, -d, 0L, d, d2); case 0: return new Tup5<long>(0L, 0L, 0L, d, d2); case -1: return new Tup5<long>( d, d, d, d, d2); default: return new Tup5<long>(-i0 * d); } } if (i1 > -2) { switch (i1) { case -1: return new Tup5<long>(-d2, d, 0L, d, d); case 0: return new Tup5<long>(-d2, d, 0L, 0L, 0L); case 1: return new Tup5<long>(-d2, -d, -d, -d, -d); default: return new Tup5<long>(-i1 * d); } } return new Tup5<long>(-d2, -d, 0L, d, d2); } /// <summary> /// Provides sample clamping to the border value. Note that this /// function currently requires that max - min >= 5! i.e. it /// does not work for too small source tensors. /// </summary> public static Tup6<long> Index6SamplesClamped(long i, long first, long end, long d) { long i0 = i - first, i1 = i - end + 1; long d2 = d + d; if (i0 < 2) { switch (i0) { case 1: return new Tup6<long>(-d, -d, 0L, d, d2, d2 + d); case 0: return new Tup6<long>(0L, 0L, 0L, d, d2, d2 + d); case -1: return new Tup6<long>( d, d, d, d, d2, d2 + d); case -2: return new Tup6<long>(d2, d2, d2, d2, d2, d2 + d); default: return new Tup6<long>(-i0 * d); } } if (i1 > -3) { switch (i1) { case -2: return new Tup6<long>(-d2, -d, 0L, d, d2, d2); case -1: return new Tup6<long>(-d2, -d, 0L, d, d, d); case 0: return new Tup6<long>(-d2, -d, 0L, 0L, 0L, 0L); case 1: return new Tup6<long>(-d2, -d, -d, -d, -d, -d); default: return new Tup6<long>(-i1 * d); } } return new Tup6<long>(-d2, -d, 0L, d, d2, d2 + d); } /// <summary> /// Provides sample clamping to the border value. Note that this /// function currently requires that max - min >= 5! i.e. it /// does not work for too small source tensors. /// </summary> public static Tup7<long> Index7SamplesClamped(long i, long first, long end, long d) { long i0 = i - first, i1 = i - end + 1; long d2 = d + d; if (i0 < 3) { switch (i0) { case 2: return new Tup7<long>(-d2, -d2, -d, 0L, d, d2, d2 + d); case 1: return new Tup7<long>( -d, -d, -d, 0L, d, d2, d2 + d); case 0: return new Tup7<long>( 0L, 0L, 0L, 0L, d, d2, d2 + d); case -1: return new Tup7<long>( d, d, d, d, d, d2, d2 + d); case -2: return new Tup7<long>( d2, d2, d2, d2, d2, d2, d2 + d); default: return new Tup7<long>(-i0 * d); } } if (i1 > -3) { switch (i1) { case -2: return new Tup7<long>(-d2 - d, -d2, -d, 0L, d, d2, d2); case -1: return new Tup7<long>(-d2 - d, -d2, -d, 0L, d, d, d); case 0: return new Tup7<long>(-d2 - d, -d2, -d, 0L, 0L, 0L, 0L); case 1: return new Tup7<long>(-d2 - d, -d2, -d, -d, -d, -d, -d); case 2: return new Tup7<long>(-d2 - d, -d2, -d2, -d2, -d2, -d2, -d2); default: return new Tup7<long>(-i1 * d); } } return new Tup7<long>(-d2 - d, -d2, -d, 0L, d, d2, d2 + d); } } /// <summary> /// Generic tensor of elements in r dimensons, each of arbitrary size /// with arbitrary strides in each dimension. All sizes are given as /// r-dimensional array of longs, with the dimensions ordered from /// inner to outer dimension. /// The tensor does not exclusively own its underlying data array, it /// can also serve as a window into other arrays, matrices, volumes, and /// tensors. Operations on tensors are supported by function arguments /// which can be easily exploited by using lambda functions. /// Note: stride is called Delta (or D) within this data structure. /// </summary> /// <typeparam name="T">Element type.</typeparam> public struct Tensor<T> : IValidity, ITensor<T>, IArrayTensorN { private T[] m_data; private long m_origin; private int m_rank; private long[] m_size; private long[] m_delta; #region Constructors public Tensor(long[] size) { m_rank = size.Length; m_size = size.Copy(); long total; m_delta = Tools.DenseDelta(m_size, out total); m_data = new T[total]; m_origin = 0; } public Tensor(int[] size) : this(size.Map(x => (long)x)) { } public Tensor(long[] size, T value) { m_rank = size.Length; m_size = size.Copy(); long total; m_delta = Tools.DenseDelta(m_size, out total); m_data = new T[total]; for (long i = 0; i < total; i++) m_data[i] = value; m_origin = 0; } public Tensor(int[] size, T value) : this(size.Map(x => (long)x), value) { } public Tensor(T[] data, long origin, int[] size) { m_data = data; m_rank = (int)size.Length; m_origin = origin; m_size = size.Map(x => (long)x); long total; m_delta = Tools.DenseDelta(m_size, out total); } public Tensor(T[] data, long origin, long[] size) { m_data = data; m_rank = size.Length; m_origin = origin; m_size = size.Copy(); long total; m_delta = Tools.DenseDelta(size, out total); } public Tensor( T[] data, long origin, long[] size, long[] delta ) { m_data = data; m_rank = size.Length; m_origin = origin; m_size = size.Copy(); m_delta = delta.Copy(); } #endregion #region Properties public bool IsValid { get { return m_data != null; } } public bool IsInvalid { get { return m_data == null; } } /// <summary> /// Underlying data array. Not exclusively owned by the tensor. /// </summary> public T[] Data { get { return m_data; } } /// <summary> /// Origin index in the unerlying data array. /// </summary> public long Origin { get { return m_origin; } set { m_origin = value; } } /// <summary> /// The total number of contravariant and covariant indices. /// </summary> public int Rank { get { return m_rank; } } /// <summary> /// Length is copied out and in, emulating a value property. /// Setting the size property also sets the rank of the tensor. /// </summary> public long[] Size { get { return m_size.Copy(); } set { m_size = value.Copy(); m_rank = m_size.Length; } } public long Count { get { long c = 1; foreach (long len in m_size) c *= len; return c; } } /// <summary> /// Delta is copied out and in, emulating a value property. /// </summary> public long[] Delta { get { return m_delta.Copy(); } set { if (m_delta.Length != m_rank) throw new ArgumentException("delta of wrong rank"); m_delta = value.Copy(); } } public long OriginIndex { get { return m_origin; } set { m_origin = value; } } public long[] SizeArray { get { return Size; } set { Size = value; } } public long[] DeltaArray { get { return Delta; } set { Delta = value; } } public long[] FirstArray { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// <summary> /// Rank /// </summary> public int R { get { return m_rank; } } /// <summary> /// Length /// </summary> public long[] L { get { return m_size; } } /// <summary> /// Delta /// </summary> public long[] D { get { return m_delta; } } /// <summary> /// Yields all elemnts ordered by index. /// </summary> public IEnumerable<T> Elements { get { long i = Origin; var ve = Init(); for (long ee = ve[R - 1]; i != ee; i = Next(i, ref ve)) { for (long e = ve[0], d = D[0]; i != e; i += d) yield return m_data[i]; } } } public Type ArrayType { get { return typeof(T[]); } } public Array Array { get { return m_data; } set { m_data = (T[])value; } } #endregion #region Indexers public T this[Vector<int> vi] { get { return m_data[Index(vi)]; } set { m_data[Index(vi)] = value; } } public T this[Vector<long> vi] { get { return m_data[Index(vi)]; } set { m_data[Index(vi)] = value; } } public T this[params int[] vi] { get { return m_data[Index(vi)]; } set { m_data[Index(vi)] = value; } } public T this[params long[] vi] { get { return m_data[Index(vi)]; } set { m_data[Index(vi)] = value; } } #endregion #region Indexing Helper Methods public long[] Init() { var ve = new long[R]; for (int r = 0; r < R; r++) ve[r] = Origin + DLR(r); return ve; } public long Next(long i, ref long[] ve) { for (int r = 1; r < R; r++) { i += SR(r); if (i == ve[r]) continue; while (--r >= 0) ve[r] = i + DLR(r); break; } return i; } public long Next(long i, ref long[] ve, ref long[] vi) { for (int r = 1; r < R; r++) { i += SR(r); vi[r]++; if (i == ve[r]) continue; while (--r >= 0) { ve[r] = i + DLR(r); vi[r] = 0; } break; } return i; } /// <summary> /// Cummulative delta for all elements in dimension r. /// </summary> public long DLR(int r) { return m_size[r] * m_delta[r]; } /// <summary> /// Skip this many elements in the underlying data array when /// stepping between subtensors of rank r (required: r > 0). /// </summary> public long SR(int r) { return m_delta[r] - m_size[r - 1] * m_delta[r - 1]; } /// <summary> /// Calculate element index for underlying data array. /// </summary> /// <param name="vi"></param> public long Index(Vector<int> vi) { var i = Origin; for (long r = 0; r < R; r++) i += vi[r] * D[r]; return i; } /// <summary> /// Calculate element index for underlying data array. /// </summary> /// <param name="vi"></param> public long Index(Vector<long> vi) { var i = Origin; for (long r = 0; r < R; r++) i += vi[r] * D[r]; return i; } /// <summary> /// Calculate element index for underlying data array. /// </summary> public long Index(params int[] vi) { var i = Origin; for (long r = 0; r < R; r++) i += vi[r] * D[r]; return i; } /// <summary> /// Calculate element index for underlying data array. /// </summary> public long Index(params long[] vi) { var i = Origin; for (long r = 0; r < R; r++) i += vi[r] * D[r]; return i; } #endregion #region Reinterpretation and Parts /// <summary> /// A SubVector does not copy any data, and thus any operations on it /// are reflected in the corresponding part of the parent. /// </summary> public Vector<T> SubVector(long[] origin, long size, long delta) { return new Vector<T>(m_data, Index(origin), size, delta); } /// <summary> /// A SubMatrix does not copy any data, and thus any operations on it /// are reflected in the corresponding part of the parent. /// </summary> public Matrix<T> SubMatrix(long[] origin, V2l size, V2l delta) { return new Matrix<T>(m_data, Index(origin), size, delta); } /// <summary> /// A SubVolume does not copy any data, and thus any operations on it /// are reflected in the corresponding part of the parent. /// </summary> public Volume<T> SubVolume(long[] origin, V3l size, V3l delta) { return new Volume<T>(m_data, Index(origin), size, delta); } /// <summary> /// A SubTensor does not copy any data, and thus any operations on it /// are reflected in the corresponding part of the parent. /// </summary> public Tensor<T> SubTensor(long[] origin, long[] size) { return new Tensor<T>(m_data, Index(origin), size, m_delta); } /// <summary> /// A SubTensor does not copy any data, and thus any operations on it /// are reflected in the corresponding part of the parent. /// </summary> public Tensor<T> SubTensor( long[] origin, long[] size, long[] delta ) { return new Tensor<T>(m_data, Index(origin), size, delta); } #endregion #region Copying /// <summary> /// Elementwise copy. /// </summary> public Tensor<T> Copy() { return new Tensor<T>(L).Set(this); } /// <summary> /// Elementwise copy with function application. /// </summary> public Tensor<Tr> Copy<Tr>(Func<T, Tr> fun) { return new Tensor<Tr>(L).Set(this, fun); } #endregion #region Manipulation Methods public Tensor<T> Set(ITensor<T> t) { var ve = Init(); var vi = new long[R]; long i = Origin; for (long ee = ve[R - 1]; i != ee; i = Next(i, ref ve, ref vi)) { for (long e = ve[0], d = D[0], ix = 0; i != e; i += d, ix++) { vi[0] = ix; m_data[i] = t[vi]; } } return this; } public Tensor<T> Set<T1>(ITensor<T1> t, Func<T1,T> fun) { var ve = Init(); var vi = new long[R]; long i = Origin; for (long ee = ve[R - 1]; i != ee; i = Next(i, ref ve, ref vi)) { for (long e = ve[0], d = D[0], ix = 0; i != e; i += d, ix++) { vi[0] = ix; m_data[i] = fun(t[vi]); } } return this; } /// <summary> /// Set each element to the value of a function of the element coords. /// </summary> /// <returns>this</returns> public Tensor<T> SetByCoord(Func<long[], T> fun) { var ve = Init(); var vi = new long[R]; long i = Origin; for (long ee = ve[R - 1]; i != ee; i = Next(i, ref ve, ref vi)) { for (long e = ve[0], d = D[0], ix = 0; i != e; i += d, ix++) { vi[0] = ix; m_data[i] = fun(vi); } } return this; } public Tensor<T> SetByIndex<T1>(Tensor<T1> t1, Func<long, T> fun) { var ve = Init(); var ve1 = t1.Init(); long i = Origin, i1 = t1.Origin; for (long ee = ve[R - 1]; i != ee; i = Next(i, ref ve), i1 = t1.Next(i1, ref ve1)) { for (long e = ve[0], d = D[0], d1 = t1.D[0]; i != e; i += d, i1 += d1) m_data[i] = fun(i1); } return this; } /// <summary> /// Copy all elements from another tensor. /// </summary> /// <returns>this</returns> public Tensor<T> Set(Tensor<T> t1) { var ve = Init(); var ve1 = t1.Init(); long i = Origin, i1 = t1.Origin; for (long ee = ve[R - 1]; i != ee; i = Next(i, ref ve), i1 = t1.Next(i1, ref ve1)) { for (long e = ve[0], d = D[0], d1 = t1.D[0]; i != e; i += d, i1 += d1) m_data[i] = t1.Data[i1]; } return this; } /// <summary> /// Set the elements of a tensor to the result of a function of /// the elements of the supplied tensor. /// </summary> /// <returns>this</returns> public Tensor<T> Set<T1>(Tensor<T1> t1, Func<T1, T> fun) { var ve = Init(); var ve1 = t1.Init(); long i = Origin, i1 = t1.Origin; for (long ee = ve[R - 1]; i != ee; i = Next(i, ref ve), i1 = t1.Next(i1, ref ve1)) { for (long e = ve[0], d = D[0], d1 = t1.D[0]; i != e; i += d, i1 += d1) m_data[i] = fun(t1.Data[i1]); } return this; } /// <summary> /// Set the elements of a tensor to the result of a function of /// corresponding pairs of elements of the two supplied tensors. /// </summary> /// <returns>this</returns> public Tensor<T> Set<T1, T2>( Tensor<T1> t1, Tensor<T2> t2, Func<T1, T2, T> fun) { var ve = Init(); var ve1 = t1.Init(); var ve2 = t2.Init(); long i = Origin, i1 = t1.Origin, i2 = t2.Origin; for (long ee = ve[R - 1]; i != ee; i = Next(i, ref ve), i1 = t1.Next(i1, ref ve1), i2 = t2.Next(i2, ref ve2)) { for (long e = ve[0], d = D[0], d1 = t1.D[0], d2 = t2.D[0]; i != e; i += d, i1 += d1, i2 += d2) m_data[i] = fun(t1.Data[i1], t2.Data[i2]); } return this; } /// <summary> /// Set the elements of a tensor to the result of a function of /// corresponding triples of elements of the three supplied tensors. /// </summary> /// <returns>this</returns> public Tensor<T> Set<T1, T2, T3>( Tensor<T1> t1, Tensor<T2> t2, Tensor<T3> t3, Func<T1, T2, T3, T> fun) { var ve = Init(); var ve1 = t1.Init(); var ve2 = t2.Init(); var ve3 = t3.Init(); long i = Origin, i1 = t1.Origin, i2 = t2.Origin, i3 = t3.Origin; for (long ee = ve[R - 1]; i != ee; i = Next(i, ref ve), i1 = t1.Next(i1, ref ve1), i2 = t2.Next(i2, ref ve2), i3 = t3.Next(i3, ref ve3)) { for (long e = ve[0], d = D[0], d1 = t1.D[0], d2 = t2.D[0], d3 = t3.D[0]; i != e; i += d, i1 += d1, i2 += d2, i3 += d3) m_data[i] = fun(t1.Data[i1], t2.Data[i2], t3.Data[i3]); } return this; } #endregion #region Creator Functions public static Tensor<T> Create(ITensor<T> t) { return new Tensor<T>(t.Dim).Set(t); } public static Tensor<T> Create<T1>(ITensor<T1> t, Func<T1, T> fun) { return new Tensor<T>(t.Dim).Set(t, fun); } /// <summary> /// Create a new tensor by applying a function to each element of the /// supplied tensor. /// </summary> static Tensor<T> Create<T1>(Tensor<T1> t1, Func<T1, T> fun) { return new Tensor<T>(t1.L).Set(t1, fun); } /// <summary> /// Create a new tensor by applying a function to each corresponding /// pair of elements of the two supplied tensors. /// </summary> static Tensor<T> Create<T1, T2>(Tensor<T1> t1, Tensor<T2> t2, Func<T1, T2, T> fun) { return new Tensor<T>(t1.L).Set(t1, t2, fun); } /// <summary> /// Create a new tensor by applying a function to each corresponding /// triple of elements of the three supplied tensors. /// </summary> static Tensor<T> Create<T1, T2, T3>(Tensor<T1> t1, Tensor<T2> t2, Tensor<T3> t3, Func<T1, T2, T3, T> fun) { return new Tensor<T>(t1.L).Set(t1, t2, t3, fun); } #endregion #region ITensor public long[] Dim { get { return m_size; } } public object GetValue(params long[] v) { return (object)this[v]; } public void SetValue(object value, params long[] v) { this[v] = (T)value; } #endregion } /// <summary> /// Symmetric operations with a scalar or non-tensor result. /// </summary> public static partial class Tensor { #region Scalar Functions public static Ts InnerProduct<T1, T2, Tm, Ts>( Tensor<T1> t1, Tensor<T2> t2, Func<T1, T2, Tm> mulFun, Ts bias, Func<Ts, Tm, Ts> sumFun ) { Ts result = bias; var ve1 = t1.Init(); var ve2 = t2.Init(); long i1 = t1.Origin, i2 = t2.Origin; for (long ee1 = ve1[t1.R - 1]; i1 != ee1; i1 = t1.Next(i1, ref ve1), i2 = t2.Next(i2, ref ve2)) { for (long e1 = ve1[0], d1 = t1.D[0], d2 = t2.D[0]; i1 != e1; i1 += d1, i2 += d2) result = sumFun(result, mulFun(t1.Data[i1], t2.Data[i2])); } return result; } #endregion } public partial struct Matrix<Td> { public TRes Sample4<T1, TRes>( long d0, Tup4<long> d1, Tup4<T1> w, FuncRef1<Td, Td, Td, Td, Tup4<T1>, TRes> smp) => smp(Data[d0 + d1.E0], Data[d0 + d1.E1],Data[d0 + d1.E2], Data[d0 + d1.E3], ref w); } public partial struct Matrix<Td, Tv> { public TRes Sample4<T1, TRes>( long d0, Tup4<long> d1, Tup4<T1> w, FuncRef1<Tv, Tv, Tv, Tv, Tup4<T1>, TRes> smp) => smp(Getter(Data, d0 + d1.E0), Getter(Data, d0 + d1.E1), Getter(Data, d0 + d1.E2), Getter(Data, d0 + d1.E3), ref w); public void SetScaled16InDevelopment<T1, T2, T3>(Matrix<Td, Tv> sourceMat, double xScale, double yScale, double xShift, double yShift, Func<double, Tup4<T1>> xipl, Func<double, Tup4<T2>> yipl, FuncRef1<Tv, Tv, Tv, Tv, Tup4<T1>, T3> xsmp, FuncRef1<T3, T3, T3, T3, Tup4<T2>, Tv> ysmp, Func<long, long, long, long, Tup4<long>> index_min_max_delta_xIndexFun, Func<long, long, long, long, Tup4<long>> index_min_max_delta_yIndexFun) { var dxa = new Tup4<long>[SX]; var wxa = new Tup4<T1>[SX]; long fx = sourceMat.FX, ex = sourceMat.EX, dx1 = sourceMat.DX; for (long tix = 0, tsx = SX; tix < tsx; tix++, xShift += xScale) { double xid = Fun.Floor(xShift); long xi = (long)xid; double xf = xShift - xid; var dx = index_min_max_delta_xIndexFun(xi, fx, ex, dx1); var dxi = xi * dx1; dx.E0 += dxi; dx.E1 += dxi; dx.E2 += dxi; dx.E3 += dxi; dxa[tix] = dx; wxa[tix] = xipl(xf); } var mat = new Matrix<T3>(SX, sourceMat.SY); { var srcdy = sourceMat.DY; var data = mat.Data; long i = mat.FirstIndex; long ys = mat.Info.DSY, yj = mat.Info.JY; long xs = mat.Info.SX; for (long ye = i + ys, y = FY, dy = sourceMat.Origin; i != ye; i += yj, y++, dy += srcdy) for (long xe = i + xs, x = FX; i != xe; i++, x++) data[i] = sourceMat.Sample4(dy, dxa[x], wxa[x], xsmp); } var dya = new Tup4<long>[SY]; var wya = new Tup4<T2>[SY]; long fy = mat.FY, ey = mat.EY, dy1 = mat.DY; for (long tiy = 0, tsy = SY; tiy < tsy; tiy++, yShift += yScale) { double yid = Fun.Floor(yShift); long yi = (long)yid; double yf = yShift - yid; var dy = index_min_max_delta_yIndexFun(yi, fy, ey, dy1); var dyi = yi * dy1; dy.E0 += dyi; dy.E1 += dyi; dy.E2 += dyi; dy.E3 += dyi; dya[tiy] = dy; wya[tiy] = yipl(yf); } { var matdx = mat.DX; var data = Data; long i = FirstIndex; if (Info.DX == 1) { long ys = Info.DSY, yj = Info.JY; long xs = Info.SX; for (long ye = i + ys, y = FY; i != ye; i += yj, y++) { for (long xe = i + xs, x = FX, dx = 0; i != xe; i++, x++, dx += matdx) { Setter(data, i, mat.Sample4(dx, dya[y], wya[y], ysmp)); } } } else if (Info.DY == 1) { long xs = Info.DSX, xj = Info.JXY; long ys = Info.SY; for (long xe = i + xs, x = FX, dx = 0; i != xe; i += xj, x++, dx += matdx) { for (long ye = i + ys, y = FY; i != ye; i++, y++) { Setter(data, i, mat.Sample4(dx, dya[y], wya[y], ysmp)); } } } else { long ys = Info.DSY, yj = Info.JY; long xs = Info.DSX, xj = Info.JX; for (long ye = i + ys, y = FY; i != ye; i += yj, y++) { for (long xe = i + xs, x = FX, dx = 0; i != xe; i += xj, x++, dx += matdx) { Setter(data, i, mat.Sample4(dx, dya[y], wya[y], ysmp)); } } } } } } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.LogReceiverService { using System.Collections.Generic; using System.Linq; using System.Threading; using System; using System.IO; using Xunit; #if WCF_SUPPORTED && !SILVERLIGHT using System.Data; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Description; #endif using System.Xml; using System.Xml.Serialization; using NLog.Layouts; using NLog.LogReceiverService; public class LogReceiverServiceTests : NLogTestBase { private const string logRecieverUrl = "http://localhost:8080/logrecievertest"; [Fact] public void ToLogEventInfoTest() { var events = new NLogEvents { BaseTimeUtc = new DateTime(2010, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).Ticks, ClientName = "foo", LayoutNames = new StringCollection { "foo", "bar", "baz" }, Strings = new StringCollection { "logger1", "logger2", "logger3", "zzz", "message1" }, Events = new[] { new NLogEvent { Id = 1, LevelOrdinal = 2, LoggerOrdinal = 0, TimeDelta = 30000000, MessageOrdinal = 4, Values = "0|1|2" }, new NLogEvent { Id = 2, LevelOrdinal = 3, LoggerOrdinal = 2, MessageOrdinal = 4, TimeDelta = 30050000, Values = "0|1|3", } } }; var converted = events.ToEventInfo(); Assert.Equal(2, converted.Count); Assert.Equal("message1", converted[0].FormattedMessage); Assert.Equal("message1", converted[1].FormattedMessage); Assert.Equal(new DateTime(2010, 1, 1, 0, 0, 3, 0, DateTimeKind.Utc), converted[0].TimeStamp.ToUniversalTime()); Assert.Equal(new DateTime(2010, 1, 1, 0, 0, 3, 5, DateTimeKind.Utc), converted[1].TimeStamp.ToUniversalTime()); Assert.Equal("logger1", converted[0].LoggerName); Assert.Equal("logger3", converted[1].LoggerName); Assert.Equal(LogLevel.Info, converted[0].Level); Assert.Equal(LogLevel.Warn, converted[1].Level); Layout fooLayout = "${event-context:foo}"; Layout barLayout = "${event-context:bar}"; Layout bazLayout = "${event-context:baz}"; Assert.Equal("logger1", fooLayout.Render(converted[0])); Assert.Equal("logger1", fooLayout.Render(converted[1])); Assert.Equal("logger2", barLayout.Render(converted[0])); Assert.Equal("logger2", barLayout.Render(converted[1])); Assert.Equal("logger3", bazLayout.Render(converted[0])); Assert.Equal("zzz", bazLayout.Render(converted[1])); } [Fact] public void NoLayoutsTest() { var events = new NLogEvents { BaseTimeUtc = new DateTime(2010, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).Ticks, ClientName = "foo", LayoutNames = new StringCollection(), Strings = new StringCollection { "logger1", "logger2", "logger3", "zzz", "message1" }, Events = new[] { new NLogEvent { Id = 1, LevelOrdinal = 2, LoggerOrdinal = 0, TimeDelta = 30000000, MessageOrdinal = 4, Values = null, }, new NLogEvent { Id = 2, LevelOrdinal = 3, LoggerOrdinal = 2, MessageOrdinal = 4, TimeDelta = 30050000, Values = null, } } }; var converted = events.ToEventInfo(); Assert.Equal(2, converted.Count); Assert.Equal("message1", converted[0].FormattedMessage); Assert.Equal("message1", converted[1].FormattedMessage); Assert.Equal(new DateTime(2010, 1, 1, 0, 0, 3, 0, DateTimeKind.Utc), converted[0].TimeStamp.ToUniversalTime()); Assert.Equal(new DateTime(2010, 1, 1, 0, 0, 3, 5, DateTimeKind.Utc), converted[1].TimeStamp.ToUniversalTime()); Assert.Equal("logger1", converted[0].LoggerName); Assert.Equal("logger3", converted[1].LoggerName); Assert.Equal(LogLevel.Info, converted[0].Level); Assert.Equal(LogLevel.Warn, converted[1].Level); } #if !SILVERLIGHT /// <summary> /// Ensures that serialization formats of DataContractSerializer and XmlSerializer are the same /// on the same <see cref="NLogEvents"/> object. /// </summary> [Fact] public void CompareSerializationFormats() { var events = new NLogEvents { BaseTimeUtc = DateTime.UtcNow.Ticks, ClientName = "foo", LayoutNames = new StringCollection { "foo", "bar", "baz" }, Strings = new StringCollection { "logger1", "logger2", "logger3" }, Events = new[] { new NLogEvent { Id = 1, LevelOrdinal = 2, LoggerOrdinal = 0, TimeDelta = 34, Values = "1|2|3" }, new NLogEvent { Id = 2, LevelOrdinal = 3, LoggerOrdinal = 2, TimeDelta = 345, Values = "1|2|3", } } }; var serializer1 = new XmlSerializer(typeof(NLogEvents)); var sw1 = new StringWriter(); using (var writer1 = XmlWriter.Create(sw1, new XmlWriterSettings { Indent = true })) { var namespaces = new XmlSerializerNamespaces(); namespaces.Add("i", "http://www.w3.org/2001/XMLSchema-instance"); serializer1.Serialize(writer1, events, namespaces); } var serializer2 = new DataContractSerializer(typeof(NLogEvents)); var sw2 = new StringWriter(); using (var writer2 = XmlWriter.Create(sw2, new XmlWriterSettings { Indent = true })) { serializer2.WriteObject(writer2, events); } var xml1 = sw1.ToString(); var xml2 = sw2.ToString(); Assert.Equal(xml1, xml2); } #endif #if WCF_SUPPORTED && !SILVERLIGHT [Fact] public void RealTestLogReciever_two_way() { RealTestLogReciever(false, false); } [Fact] public void RealTestLogReciever_one_way() { RealTestLogReciever(true, false); } [Fact(Skip = "unit test should listen to non-http for this")] public void RealTestLogReciever_two_way_binary() { RealTestLogReciever(false, true); } [Fact(Skip = "unit test should listen to non-http for this")] public void RealTestLogReciever_one_way_binary() { RealTestLogReciever(true, true); } private void RealTestLogReciever(bool useOneWayContract, bool binaryEncode) { LogManager.Configuration = CreateConfigurationFromString(string.Format(@" <nlog throwExceptions='true'> <targets> <target type='LogReceiverService' name='s1' endpointAddress='{0}' useOneWayContract='{1}' useBinaryEncoding='{2}' includeEventProperties='false'> <!-- <parameter name='key1' layout='testparam1' type='String'/> --> </target> </targets> <rules> <logger name='logger1' minlevel='Trace' writeTo='s1' /> </rules> </nlog>", logRecieverUrl, useOneWayContract.ToString().ToLower(), binaryEncode.ToString().ToLower())); ExecLogRecieverAndCheck(ExecLogging1, CheckRecieved1, 2); } /// <summary> /// Create WCF service, logs and listen to the events /// </summary> /// <param name="logFunc">function for logging the messages</param> /// <param name="logCheckFunc">function for checking the received messsages</param> /// <param name="messageCount">message count for wait for listen and checking</param> public void ExecLogRecieverAndCheck(Action<Logger> logFunc, Action<List<NLogEvents>> logCheckFunc, int messageCount) { Uri baseAddress = new Uri(logRecieverUrl); // Create the ServiceHost. using (ServiceHost host = new ServiceHost(typeof(LogRecieverMock), baseAddress)) { // Enable metadata publishing. ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; #if !MONO smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15; #endif host.Description.Behaviors.Add(smb); // Open the ServiceHost to start listening for messages. Since // no endpoints are explicitly configured, the runtime will create // one endpoint per base address for each service contract implemented // by the service. host.Open(); //wait for 2 events var countdownEvent = new CountdownEvent(messageCount); //reset LogRecieverMock.recievedEvents = new List<NLogEvents>(); LogRecieverMock.CountdownEvent = countdownEvent; var logger1 = LogManager.GetLogger("logger1"); logFunc(logger1); countdownEvent.Wait(20000); //we need some extra time for completion Thread.Sleep(1000); var recieved = LogRecieverMock.recievedEvents; Assert.Equal(messageCount, recieved.Count); logCheckFunc(recieved); // Close the ServiceHost. host.Close(); } } private static void CheckRecieved1(List<NLogEvents> recieved) { //in some case the messages aren't retrieved in the right order when invoked in the same sec. //more important is that both are retrieved with the correct info Assert.Equal(2, recieved.Count); var logmessages = new HashSet<string> {recieved[0].ToEventInfo().First().Message, recieved[1].ToEventInfo().First().Message}; Assert.True(logmessages.Contains("test 1"), "message 1 is missing"); Assert.True(logmessages.Contains("test 2"), "message 2 is missing"); } private static void ExecLogging1(Logger logger) { logger.Info("test 1"); //we wait 10 ms, because after a cold boot, the messages are arrived in the same moment and the order can change. Thread.Sleep(10); logger.Info(new InvalidConstraintException("boo"), "test 2"); } public class LogRecieverMock : ILogReceiverServer, ILogReceiverOneWayServer { public static CountdownEvent CountdownEvent; public static List<NLogEvents> recievedEvents = new List<NLogEvents>(); /// <summary> /// Processes the log messages. /// </summary> /// <param name="events">The events.</param> public void ProcessLogMessages(NLogEvents events) { if (CountdownEvent == null) { throw new Exception("test not prepared well"); } recievedEvents.Add(events); CountdownEvent.Signal(); } } #endif } }
// 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.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Tagging.TagSources; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging { /// <summary> /// <para>The <see cref="ProducerPopulatedTagSource{TTag}"/> is the core part of our asynchronous tagging infrastructure. It's /// the coordinator between <see cref="ITagProducer{TTag}"/>s, <see cref="ITaggerEventSource"/>s, and /// <see cref="ITagger{T}"/>s.</para> /// /// <para>The <see cref="ProducerPopulatedTagSource{TTag}"/> is the type that actually owns the list of cached tags. When an /// <see cref="ITaggerEventSource"/> says tags need to be recomputed, the tag source starts the computation /// and calls the <see cref="ITagProducer{TTag}"/> to build the new list of tags. When that's done, /// the tags are stored in <see cref="_cachedTags"/>. The tagger, when asked for tags from the editor, then returns /// the tags that are stored in <see cref="_cachedTags"/></para> /// /// <para>There is a one-to-many relationship between <see cref="ProducerPopulatedTagSource{TTag}"/>s and <see cref="ITagger{T}"/>s. /// Taggers that tag the buffer and don't care about a view (think classification) have one <see cref="BufferTagSource{TTag}"/> /// per subject buffer, the lifetime management provided by <see cref="AbstractAsynchronousBufferTaggerProvider{TTag}"/>. /// Taggers that tag the buffer and care about the view (think keyword highlighting) have a <see cref="ViewTagSource{TTag}"/> /// per subject buffer/view pair, and the lifetime management for that is provided by a <see cref="AbstractAsynchronousViewTaggerProvider{TTag}"/>. /// Special cases, like reference highlighting (which processes multiple subject buffers at once) have their own /// providers and tag source derivations.</para> /// </summary> /// <typeparam name="TTag">The type of tag.</typeparam> internal abstract partial class ProducerPopulatedTagSource<TTag> : TagSource<TTag> where TTag : ITag { #region Fields that can be accessed from either thread /// <summary> /// Synchronization object for assignments to the <see cref="_cachedTags"/> field. This is only used for /// changes; reads may be done without any locking since the data structure itself is /// immutable. /// </summary> private readonly object _cachedTagsGate = new object(); /// <summary> /// True if edits should cause us to remove tags that intersect with edits. Used to ensure /// that squiggles are removed when the user types over them. /// </summary> private readonly bool _removeTagsThatIntersectEdits; /// <summary> /// The tracking mode we want to use for the tracking spans we create. /// </summary> private readonly SpanTrackingMode _spanTrackingMode; private ImmutableDictionary<ITextBuffer, TagSpanIntervalTree<TTag>> _cachedTags; private bool _computeTagsSynchronouslyIfNoAsynchronousComputationHasCompleted; /// <summary> /// A function that is provided to the producer of this tag source. May be null. In some /// scenarios, such as restoring previous REPL history entries, we want to try to use the /// cached tags we've already computed for the buffer, but those live in a different tag /// source which we need some help to find. /// </summary> private readonly Func<ITextBuffer, ProducerPopulatedTagSource<TTag>> _bufferToRelatedTagSource; private readonly ITagProducer<TTag> _tagProducer; private IEqualityComparer<ITagSpan<TTag>> _lazyTagSpanComparer; /// <summary> /// accumulated text changes since last tag calculation /// </summary> private TextChangeRange? _accumulatedTextChanges; #endregion #region Fields that can only be accessed from the foreground thread /// <summary> /// Our tagger event source that lets us know when we should call into the tag producer for /// new tags. /// </summary> private readonly ITaggerEventSource _eventSource; /// <summary> /// During the time that we are paused from updating the UI, we will use these tags instead. /// </summary> private ImmutableDictionary<ITextBuffer, TagSpanIntervalTree<TTag>> _previousCachedTags; #endregion protected ProducerPopulatedTagSource( ITextBuffer subjectBuffer, ITagProducer<TTag> tagProducer, ITaggerEventSource eventSource, IAsynchronousOperationListener asyncListener, IForegroundNotificationService notificationService, bool removeTagsThatIntersectEdits, SpanTrackingMode spanTrackingMode, Func<ITextBuffer, ProducerPopulatedTagSource<TTag>> bufferToRelatedTagSource = null) : base(subjectBuffer, notificationService, asyncListener) { if (spanTrackingMode == SpanTrackingMode.Custom) { throw new ArgumentException("SpanTrackingMode.Custom not allowed.", "spanTrackingMode"); } _tagProducer = tagProducer; _removeTagsThatIntersectEdits = removeTagsThatIntersectEdits; _spanTrackingMode = spanTrackingMode; _cachedTags = ImmutableDictionary.Create<ITextBuffer, TagSpanIntervalTree<TTag>>(); _eventSource = eventSource; _bufferToRelatedTagSource = bufferToRelatedTagSource; _accumulatedTextChanges = null; AttachEventHandlersAndStart(); } /// <summary> /// Implemented by derived types to return a list of initial snapshot spans to tag. /// </summary> /// <remarks>Called on the foreground thread.</remarks> protected abstract ICollection<SnapshotSpan> GetInitialSpansToTag(); /// <summary> /// Implemented by derived types to return The caret position. /// </summary> /// <remarks>Called on the foreground thread.</remarks> protected abstract SnapshotPoint? GetCaretPoint(); private IEqualityComparer<ITagSpan<TTag>> TagSpanComparer { get { if (_lazyTagSpanComparer == null) { Interlocked.CompareExchange(ref _lazyTagSpanComparer, new TagSpanComparer<TTag>(_tagProducer.TagComparer), null); } return _lazyTagSpanComparer; } } private void AttachEventHandlersAndStart() { this.WorkQueue.AssertIsForeground(); _eventSource.Changed += OnChanged; _eventSource.UIUpdatesResumed += OnUIUpdatesResumed; _eventSource.UIUpdatesPaused += OnUIUpdatesPaused; // Tell the interaction object to start issuing events. _eventSource.Connect(); } protected override void Disconnect() { this.WorkQueue.AssertIsForeground(); base.Disconnect(); // Disconnect from the producer and the event source. _tagProducer.Dispose(); // Tell the interaction object to stop issuing events. _eventSource.Disconnect(); _eventSource.UIUpdatesPaused -= OnUIUpdatesPaused; _eventSource.UIUpdatesResumed -= OnUIUpdatesResumed; _eventSource.Changed -= OnChanged; } private void OnUIUpdatesPaused(object sender, EventArgs e) { this.WorkQueue.AssertIsForeground(); _previousCachedTags = _cachedTags; RaisePaused(); } private void OnUIUpdatesResumed(object sender, EventArgs e) { this.WorkQueue.AssertIsForeground(); _previousCachedTags = null; RaiseResumed(); } private void OnChanged(object sender, TaggerEventArgs e) { using (var token = this.Listener.BeginAsyncOperation("OnChanged")) { // First, cancel any previous requests (either still queued, or started). We no longer // want to continue it if new changes have come in. this.WorkQueue.CancelCurrentWork(); // We don't currently have a request issued to re-compute our tags. Issue it for some // time in the future // If we had a text buffer change, we might be able to do something smarter with the // tags if (e.TextChangeEventArgs != null) { UpdateTagsForTextChange(e.TextChangeEventArgs); AccumulateTextChanges(e.TextChangeEventArgs); } RecalculateTagsOnChanged(e); } } private void AccumulateTextChanges(TextContentChangedEventArgs contentChanged) { var contentChanges = contentChanged.Changes; var count = contentChanges.Count; switch (count) { case 0: return; case 1: // PERF: Optimize for the simple case of typing on a line. { var c = contentChanges[0]; var textChangeRange = new TextChangeRange(new TextSpan(c.OldSpan.Start, c.OldSpan.Length), c.NewLength); lock (_cachedTagsGate) { if (_accumulatedTextChanges == null) { _accumulatedTextChanges = textChangeRange; } else { _accumulatedTextChanges = _accumulatedTextChanges.Accumulate(SpecializedCollections.SingletonEnumerable(textChangeRange)); } } } break; default: var textChangeRanges = new TextChangeRange[count]; for (int i = 0; i < count; i++) { var c = contentChanges[i]; textChangeRanges[i] = new TextChangeRange(new TextSpan(c.OldSpan.Start, c.OldSpan.Length), c.NewLength); } lock (_cachedTagsGate) { _accumulatedTextChanges = _accumulatedTextChanges.Accumulate(textChangeRanges); } break; } } private void UpdateTagsForTextChange(TextContentChangedEventArgs e) { if (!e.Changes.Any()) { return; } // We might be able to steal the cached tags from another tag source if (TryStealTagsFromRelatedTagSource(e)) { return; } var buffer = e.After.TextBuffer; TagSpanIntervalTree<TTag> treeForBuffer; if (!_cachedTags.TryGetValue(buffer, out treeForBuffer)) { return; } if (!_removeTagsThatIntersectEdits) { return; } var tagsToRemove = e.Changes.SelectMany(c => treeForBuffer.GetIntersectingSpans(new SnapshotSpan(e.After, c.NewSpan))); if (!tagsToRemove.Any()) { return; } var allTags = treeForBuffer.GetSpans(e.After).ToList(); var newTreeForBuffer = new TagSpanIntervalTree<TTag>( buffer, treeForBuffer.SpanTrackingMode, allTags.Except(tagsToRemove, this.TagSpanComparer)); UpdateCachedTagsForBuffer(e.After, newTreeForBuffer); } private void UpdateCachedTagsForBuffer(ITextSnapshot snapshot, TagSpanIntervalTree<TTag> newTagsForBuffer) { var oldCachedTags = _cachedTags; lock (_cachedTagsGate) { _cachedTags = _cachedTags.SetItem(snapshot.TextBuffer, newTagsForBuffer); } // Grab our old tags. We might not have any, so in this case we'll just pretend it's // empty TagSpanIntervalTree<TTag> oldCachedTagsForBuffer = null; if (!oldCachedTags.TryGetValue(snapshot.TextBuffer, out oldCachedTagsForBuffer)) { oldCachedTagsForBuffer = new TagSpanIntervalTree<TTag>(snapshot.TextBuffer, _spanTrackingMode); } var difference = ComputeDifference(snapshot, oldCachedTagsForBuffer, newTagsForBuffer); if (difference.Count > 0) { RaiseTagsChanged(snapshot.TextBuffer, difference); } } private bool TryStealTagsFromRelatedTagSource(TextContentChangedEventArgs e) { // see bug 778731 #if INTERACTIVE // If we don't have a way to find the related buffer, we're done immediately if (bufferToRelatedTagSource == null) { return false; } // We can only steal tags if we know where the edit came from, so do we? var editTag = e.EditTag as RestoreHistoryEditTag; if (editTag == null) { return false; } var originalSpan = editTag.OriginalSpan; var relatedTagSource = bufferToRelatedTagSource(originalSpan.Snapshot.TextBuffer); if (relatedTagSource == null) { return false; } // Reading the other tag source's cached tags is safe, since this field is allowed to be // accessed from multiple threads and is immutable. We still need to have a local copy // though to play it safe and be a good citizen (well, as good as a citizen that's about // to steal something can be...) var relatedCachedTags = relatedTagSource.cachedTags; TagSpanIntervalTree<TTag> relatedIntervalTree; if (!relatedCachedTags.TryGetValue(originalSpan.Snapshot.TextBuffer, out relatedIntervalTree)) { return false; } // Excellent! Let's build a new interval tree with these tags mapped to our buffer // instead var tagsForThisBuffer = from tagSpan in relatedIntervalTree.GetSpans(originalSpan.Snapshot) where tagSpan.Span.IntersectsWith(originalSpan) let snapshotSpan = new SnapshotSpan(e.After, tagSpan.SpanStart - originalSpan.Start, tagSpan.Span.Length) select new TagSpan<TTag>(snapshotSpan, tagSpan.Tag); var intervalTreeForThisBuffer = new TagSpanIntervalTree<TTag>(e.After.TextBuffer, relatedIntervalTree.SpanTrackingMode, tagsForThisBuffer); // Update our cached tags UpdateCachedTagsForBuffer(e.After, intervalTreeForThisBuffer); return true; #else return false; #endif } /// <summary> /// Called on the foreground thread. /// </summary> protected override void RecomputeTagsForeground() { this.WorkQueue.AssertIsForeground(); using (Logger.LogBlock(FunctionId.Tagger_TagSource_RecomputeTags, CancellationToken.None)) { // Get the current valid cancellation token for this work. var cancellationToken = this.WorkQueue.CancellationToken; if (cancellationToken.IsCancellationRequested) { return; } var spansToTag = GetSpansAndDocumentsToTag(); var caretPosition = this.GetCaretPoint(); var textChangeRange = _accumulatedTextChanges; this.WorkQueue.EnqueueBackgroundTask( ct => this.RecomputeTagsAsync(caretPosition, textChangeRange, spansToTag, ct), GetType().Name + ".RecomputeTags", cancellationToken); } } protected List<DocumentSnapshotSpan> GetSpansAndDocumentsToTag() { // TODO: Update to tag spans from all related documents. var snapshotToDocumentMap = new Dictionary<ITextSnapshot, Document>(); var spansToTag = this.GetInitialSpansToTag().Select(span => { Document document = null; if (!snapshotToDocumentMap.TryGetValue(span.Snapshot, out document)) { CheckSnapshot(span.Snapshot); document = span.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); snapshotToDocumentMap[span.Snapshot] = document; } // document can be null if the buffer the given span is part of is not part of our workspace. return new DocumentSnapshotSpan(document, span); }).ToList(); return spansToTag; } [Conditional("DEBUG")] private void CheckSnapshot(ITextSnapshot snapshot) { var container = snapshot.TextBuffer.AsTextContainer(); Workspace dummy; if (Workspace.TryGetWorkspace(container, out dummy)) { // if the buffer is part of our workspace, it must be the latest. Contract.Assert(snapshot.Version.Next == null, "should be on latest snapshot"); } } protected ImmutableDictionary<ITextBuffer, TagSpanIntervalTree<TTag>> ConvertToTagTree( IEnumerable<ITagSpan<TTag>> tagSpans, IEnumerable<DocumentSnapshotSpan> spansToCompute = null) { // NOTE: we assume that the following list is already realized and is _not_ lazily // computed. It's not clear what the contract is of this API. // common case where there is only one buffer if (spansToCompute != null && spansToCompute.IsSingle()) { return ConvertToTagTree(tagSpans, spansToCompute.Single().SnapshotSpan); } // heavy generic case var tagsByBuffer = tagSpans.GroupBy(t => t.Span.Snapshot.TextBuffer); var tagsToKeepByBuffer = GetTagsToKeepByBuffer(spansToCompute); var map = ImmutableDictionary<ITextBuffer, TagSpanIntervalTree<TTag>>.Empty; foreach (var tagsInBuffer in tagsByBuffer) { IEnumerable<ITagSpan<TTag>> tags; if (tagsToKeepByBuffer.TryGetValue(tagsInBuffer.Key, out tags)) { tags = tagsInBuffer.Concat(tags); } else { tags = tagsInBuffer; } map = map.Add(tagsInBuffer.Key, new TagSpanIntervalTree<TTag>(tagsInBuffer.Key, _spanTrackingMode, tags)); } foreach (var kv in tagsToKeepByBuffer) { if (!map.ContainsKey(kv.Key) && kv.Value.Any()) { map = map.Add(kv.Key, new TagSpanIntervalTree<TTag>(kv.Key, _spanTrackingMode, kv.Value)); } } return map; } private ImmutableDictionary<ITextBuffer, TagSpanIntervalTree<TTag>> ConvertToTagTree(IEnumerable<ITagSpan<TTag>> tagSpans, SnapshotSpan spanToInvalidate) { var tagsByBuffer = tagSpans.GroupBy(t => t.Span.Snapshot.TextBuffer); var map = ImmutableDictionary<ITextBuffer, TagSpanIntervalTree<TTag>>.Empty; var invalidBuffer = spanToInvalidate.Snapshot.TextBuffer; // These lists only live as long as this method. So it's fine for us to do whatever // we want with them (including mutating them) inside this body. var beforeTagsToKeep = new List<ITagSpan<TTag>>(); var afterTagsToKeep = new List<ITagSpan<TTag>>(); GetTagsToKeep(spanToInvalidate, beforeTagsToKeep, afterTagsToKeep); foreach (var tagsInBuffer in tagsByBuffer) { IEnumerable<ITagSpan<TTag>> tags; if (tagsInBuffer.Key == invalidBuffer) { // Create all the tags for this buffer, using the old tags around the span, // along with all the new tags in the middle. var allTags = beforeTagsToKeep; // Note: we're mutating 'beforeTagsToKeep' here. but that's ok. We won't // use it at all after this. allTags.AddRange(tagsInBuffer); allTags.AddRange(afterTagsToKeep); tags = allTags; } else { tags = tagsInBuffer; } map = map.Add(tagsInBuffer.Key, new TagSpanIntervalTree<TTag>(tagsInBuffer.Key, _spanTrackingMode, tags)); } // Check if we didn't produce any new tags for this buffer. If we didn't, but we did // have old tags before/after the span we tagged, then we want to ensure that we pull // all those old tags forward. if (!map.ContainsKey(invalidBuffer) && (beforeTagsToKeep.Count > 0 || afterTagsToKeep.Count > 0)) { var allTags = beforeTagsToKeep; allTags.AddRange(afterTagsToKeep); map = map.Add(invalidBuffer, new TagSpanIntervalTree<TTag>(invalidBuffer, _spanTrackingMode, allTags)); } return map; } private ImmutableDictionary<ITextBuffer, IEnumerable<ITagSpan<TTag>>> GetTagsToKeepByBuffer(IEnumerable<DocumentSnapshotSpan> spansToCompute) { var map = ImmutableDictionary.Create<ITextBuffer, IEnumerable<ITagSpan<TTag>>>(); if (spansToCompute == null) { return map; } var invalidSpansByBuffer = ImmutableDictionary.CreateRange<ITextBuffer, IEnumerable<SnapshotSpan>>( spansToCompute.Select(t => t.SnapshotSpan).GroupBy(s => s.Snapshot.TextBuffer).Select(g => KeyValuePair.Create(g.Key, g.AsEnumerable()))); foreach (var kv in invalidSpansByBuffer) { TagSpanIntervalTree<TTag> treeForBuffer; if (!_cachedTags.TryGetValue(kv.Key, out treeForBuffer)) { continue; } var invalidSpans = new List<ITagSpan<TTag>>(); foreach (var spanToInvalidate in kv.Value) { invalidSpans.AddRange(treeForBuffer.GetIntersectingSpans(spanToInvalidate)); } map = map.Add(kv.Key, treeForBuffer.GetSpans(kv.Key.CurrentSnapshot).Except(invalidSpans, this.TagSpanComparer)); } return map; } /// <summary> /// Returns all that tags that fully precede 'spanToInvalidate' and all the tags that /// fully follow it. All the tag spans are normalized to the snapshot passed in through /// 'spanToInvalidate'. /// </summary> private void GetTagsToKeep(SnapshotSpan spanToInvalidate, List<ITagSpan<TTag>> beforeTags, List<ITagSpan<TTag>> afterTags) { var fullRefresh = spanToInvalidate.Length == spanToInvalidate.Snapshot.Length; if (fullRefresh) { return; } // we actually have span to invalidate from old tree TagSpanIntervalTree<TTag> treeForBuffer; if (!_cachedTags.TryGetValue(spanToInvalidate.Snapshot.TextBuffer, out treeForBuffer)) { return; } treeForBuffer.GetNonIntersectingSpans(spanToInvalidate, beforeTags, afterTags); } protected virtual async Task RecomputeTagsAsync( SnapshotPoint? caretPosition, TextChangeRange? textChangeRange, IEnumerable<DocumentSnapshotSpan> spansToCompute, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var tagSpans = spansToCompute.IsEmpty() ? SpecializedCollections.EmptyEnumerable<ITagSpan<TTag>>() : await _tagProducer.ProduceTagsAsync(spansToCompute, caretPosition, cancellationToken).ConfigureAwait(false); var map = ConvertToTagTree(tagSpans, spansToCompute); ProcessNewTags(spansToCompute, textChangeRange, map); } protected virtual void ProcessNewTags( IEnumerable<DocumentSnapshotSpan> spansToCompute, TextChangeRange? oldTextChangeRange, ImmutableDictionary<ITextBuffer, TagSpanIntervalTree<TTag>> newTags) { using (Logger.LogBlock(FunctionId.Tagger_TagSource_ProcessNewTags, CancellationToken.None)) { var oldTags = _cachedTags; lock (_cachedTagsGate) { _cachedTags = newTags; // This can have a race, but it is not easy to remove due to our async and cancellation nature. // so here what we do is this, first we see whether the range we used to determine span to recompute is still same, if it is // then we reset the range so that we can start from scratch. if not (if there was another edit while us recomputing but // we didn't get cancelled), then we keep the existing accumulated text changes so that we at least don't miss recomputing // but at the same time, blindly recompute whole file. _accumulatedTextChanges = Nullable.Equals(_accumulatedTextChanges, oldTextChangeRange) ? null : _accumulatedTextChanges; } // Now diff the two resultant sets and fire off the notifications if (!HasTagsChangedListener) { return; } foreach (var latestBuffer in _cachedTags.Keys) { var snapshot = spansToCompute.First(s => s.SnapshotSpan.Snapshot.TextBuffer == latestBuffer).SnapshotSpan.Snapshot; if (oldTags.ContainsKey(latestBuffer)) { var difference = ComputeDifference(snapshot, _cachedTags[latestBuffer], oldTags[latestBuffer]); if (difference.Count > 0) { RaiseTagsChanged(latestBuffer, difference); } } else { // It's a new buffer, so report all spans are changed var allSpans = new NormalizedSnapshotSpanCollection(_cachedTags[latestBuffer].GetSpans(snapshot).Select(t => t.Span)); if (allSpans.Count > 0) { RaiseTagsChanged(latestBuffer, allSpans); } } } foreach (var oldBuffer in oldTags.Keys) { if (!_cachedTags.ContainsKey(oldBuffer)) { // This buffer disappeared, so let's notify that the old tags are gone var allSpans = new NormalizedSnapshotSpanCollection(oldTags[oldBuffer].GetSpans(oldBuffer.CurrentSnapshot).Select(t => t.Span)); if (allSpans.Count > 0) { RaiseTagsChanged(oldBuffer, allSpans); } } } } } private NormalizedSnapshotSpanCollection ComputeDifference( ITextSnapshot snapshot, TagSpanIntervalTree<TTag> latestSpans, TagSpanIntervalTree<TTag> previousSpans) { return new NormalizedSnapshotSpanCollection( Difference(latestSpans.GetSpans(snapshot), previousSpans.GetSpans(snapshot), new DiffSpanComparer(_tagProducer.TagComparer))); } /// <summary> /// Returns the TagSpanIntervalTree containing the tags for the given buffer. If no tags /// exist for the buffer at all, null is returned. /// </summary> public override ITagSpanIntervalTree<TTag> GetTagIntervalTreeForBuffer(ITextBuffer buffer) { this.WorkQueue.AssertIsForeground(); // If we're currently pausing updates to the UI, then just use the tags we had before we // were paused so that nothing changes. var map = _previousCachedTags ?? _cachedTags; TagSpanIntervalTree<TTag> tags; if (!map.TryGetValue(buffer, out tags)) { if (ComputeTagsSynchronouslyIfNoAsynchronousComputationHasCompleted && _previousCachedTags == null) { // We can cancel any background computations currently happening this.WorkQueue.CancelCurrentWork(); var spansToCompute = GetSpansAndDocumentsToTag(); // We shall synchronously compute tags. var producedTags = ConvertToTagTree( _tagProducer.ProduceTagsAsync(spansToCompute, GetCaretPoint(), CancellationToken.None).WaitAndGetResult(CancellationToken.None)); ProcessNewTags(spansToCompute, null, producedTags); producedTags.TryGetValue(buffer, out tags); } } return tags; } public bool ComputeTagsSynchronouslyIfNoAsynchronousComputationHasCompleted { get { return _computeTagsSynchronouslyIfNoAsynchronousComputationHasCompleted; } set { this.WorkQueue.AssertIsForeground(); _computeTagsSynchronouslyIfNoAsynchronousComputationHasCompleted = value; } } private class DiffSpanComparer : IDiffSpanComparer<ITagSpan<TTag>> { private readonly IEqualityComparer<TTag> _comparer; public DiffSpanComparer(IEqualityComparer<TTag> comparer) { _comparer = comparer; } public bool IsDefault(ITagSpan<TTag> tagSpan) { return tagSpan == null; } public SnapshotSpan GetSpan(ITagSpan<TTag> tagSpan) { return tagSpan.Span; } public bool Equals(ITagSpan<TTag> tagSpan1, ITagSpan<TTag> tagSpan2) { return _comparer.Equals(tagSpan1.Tag, tagSpan2.Tag); } } } }
// This file is part of Wintermute Engine // For conditions of distribution and use, see copyright notice in license.txt // http://dead-code.org/redir.php?target=wme using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using DeadCode.WME.Core; using System.IO; namespace DeadCode.WME.Global { public partial class TiledImgEditorForm : FormBase { ////////////////////////////////////////////////////////////////////////// public TiledImgEditorForm() { InitializeComponent(); } private TextBox[] TxtCol; private TextBox[] TxtRow; ////////////////////////////////////////////////////////////////////////// private void OnLoad(object sender, EventArgs e) { this.MinimumSize = this.Size; if (AppMgr != null) LoadLayout(AppMgr.Settings); TxtCol = new TextBox[3]; TxtCol[0] = TxtCol1; TxtCol[1] = TxtCol2; TxtCol[2] = TxtCol3; TxtRow = new TextBox[3]; TxtRow[0] = TxtRow1; TxtRow[1] = TxtRow2; TxtRow[2] = TxtRow3; if (OrigFilename != "" && OrigFilename != null) { LoadFile(OrigFilename); } else Filename = ""; DisplayData(); } ////////////////////////////////////////////////////////////////////////// private void OnFormClosed(object sender, FormClosedEventArgs e) { if (AppMgr != null) SaveLayout(AppMgr.Settings); if (TiledImg != null) TiledImg.Dispose(); } ////////////////////////////////////////////////////////////////////////// private void OnFormClosing(object sender, FormClosingEventArgs e) { e.Cancel = !CanClose(); } private string _OrigFilename; ////////////////////////////////////////////////////////////////////////// public string OrigFilename { get { return _OrigFilename; } set { _OrigFilename = value; } } private WGame _Game; ////////////////////////////////////////////////////////////////////////// public WGame Game { get { return _Game; } set { _Game = value; } } private string _Filename = ""; ////////////////////////////////////////////////////////////////////////// public string Filename { get { return _Filename; } set { _Filename = value; DisplayFilename(); } } private bool _IsDirty = false; ////////////////////////////////////////////////////////////////////////// public bool IsDirty { get { return _IsDirty; } set { _IsDirty = value; DisplayFilename(); } } ////////////////////////////////////////////////////////////////////////// private void DisplayFilename() { string Name = "File name: "; if (Filename != "") Name += Filename; else Name += "untitled"; if (IsDirty) Name += "*"; LabelFilename.Text = Name; } WUITiledImage TiledImg = null; ////////////////////////////////////////////////////////////////////////// private void OnOpenFile(object sender, EventArgs e) { if (!CanClose()) return; string OrigFile = Filename; if (OrigFile != "") OrigFile = Game.MakeAbsolutePath(OrigFile); OpenFileDialog dlg = new OpenFileDialog(); dlg.Filter = "Tiled images (*.image)|*.image|All files (*.*)|*.*"; dlg.RestoreDirectory = true; dlg.CheckFileExists = true; if (File.Exists(OrigFile)) dlg.FileName = OrigFile; if(dlg.ShowDialog()!=DialogResult.OK) return; string NewFile = Game.MakeRelativePath(dlg.FileName); LoadFile(NewFile); DisplayData(); } ////////////////////////////////////////////////////////////////////////// private void LoadFile(string Filename) { WUITiledImage NewImage = new WUITiledImage(Game); if (NewImage.LoadFromFile(Filename)) { if (TiledImg != null) { TiledImg.ClaimOwnership(); TiledImg.Dispose(); } this.TiledImg = NewImage; this.Filename = Filename; this.IsDirty = false; } else MessageBox.Show("Error loading file.", Form.ActiveForm.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); } ////////////////////////////////////////////////////////////////////////// private void DisplayData() { DisplayImage(); LabelDimension.Text = "Size: "; if (PictBox.Image != null) LabelDimension.Text += PictBox.Image.Width.ToString() + "x" + PictBox.Image.Height.ToString(); int[] Cols = GetCols(); int[] Rows = GetRows(); for (int i = 0; i < 3; i++) { if(Cols != null) TxtCol[i].Text = Cols[i].ToString(); else TxtCol[i].Text = ""; if (Rows != null) TxtRow[i].Text = Rows[i].ToString(); else TxtRow[i].Text = ""; } bool RowsValid = true; bool ColsValid = true; if(Cols != null && PictBox.Image != null) { if (Cols[0] + Cols[1] + Cols[2] != PictBox.Image.Width) ColsValid = false; if (Rows[0] + Rows[1] + Rows[2] != PictBox.Image.Height) RowsValid = false; } for (int i = 0; i < 3; i++) { TxtCol[i].BackColor = ColsValid ? SystemColors.Window : Color.Red; TxtCol[i].ForeColor = ColsValid ? SystemColors.WindowText : Color.White; TxtRow[i].BackColor = RowsValid ? SystemColors.Window : Color.Red; TxtRow[i].ForeColor = RowsValid ? SystemColors.WindowText : Color.White; } // enable / disable stuff for (int i = 0; i < 3; i++) { TxtCol[i].Enabled = (TiledImg != null); TxtRow[i].Enabled = (TiledImg != null); } BtnSave.Enabled = (TiledImg != null); BtnSaveAs.Enabled = (TiledImg != null); BtnImage.Enabled = (TiledImg != null); BtnOK.Enabled = (Filename != ""); } ////////////////////////////////////////////////////////////////////////// private void DisplayImage() { if (TiledImg != null) { if (TiledImg.Image != null) PictBox.Image = TiledImg.Image.GetBitmap(); else PictBox.Image = null; } } ////////////////////////////////////////////////////////////////////////// private void OnImagePaint(object sender, PaintEventArgs e) { if(PictBox.Image != null) { int[] Rows = GetRows(); int[] Cols = GetCols(); float ModX = (float)PictBox.ClientSize.Width / (float)PictBox.Image.Width; float ModY = (float)PictBox.ClientSize.Height / (float)PictBox.Image.Height; if(Rows != null) { int CurrY = 0; foreach(int i in Rows) { CurrY += i; e.Graphics.DrawLine(Pens.Red, 0, CurrY * ModY, PictBox.Image.Width * ModX, CurrY * ModY); } } if (Cols != null) { int CurrX = 0; foreach (int i in Cols) { CurrX += i; e.Graphics.DrawLine(Pens.Red, CurrX * ModX, 0, CurrX * ModX, PictBox.Image.Height * ModY); } } } } ////////////////////////////////////////////////////////////////////////// int[] GetCols() { if (TiledImg != null) { int[] Ret = new int[3]; Ret[0] = TiledImg.UpLeft.Right; Ret[1] = TiledImg.UpMiddle.Right - TiledImg.UpMiddle.Left; Ret[2] = TiledImg.UpRight.Right - TiledImg.UpRight.Left; return Ret; } else return null; } ////////////////////////////////////////////////////////////////////////// int[] GetRows() { if (TiledImg != null) { int[] Ret = new int[3]; Ret[0] = TiledImg.UpLeft.Bottom; Ret[1] = TiledImg.MiddleLeft.Bottom - TiledImg.MiddleLeft.Top; Ret[2] = TiledImg.DownLeft.Bottom - TiledImg.DownLeft.Top; return Ret; } else return null; } ////////////////////////////////////////////////////////////////////////// private void OnTxtLeave(object sender, EventArgs e) { if (TiledImg == null) return; TextBox Txt = sender as TextBox; if (Txt == null) return; int Value; if (!int.TryParse(Txt.Text, out Value)) Value = 0; Txt.Text = Value.ToString(); if (UpdateValues()) IsDirty = true; } ////////////////////////////////////////////////////////////////////////// private bool UpdateValues() { if (TiledImg == null) return false; int[] OrigCols = GetCols(); int[] OrigRows = GetRows(); int[] Cols = new int[3]; int[] Rows = new int[3]; bool Changed = false; for(int i=0; i<3; i++) { int.TryParse(TxtCol[i].Text, out Cols[i]); if (Cols[i] != OrigCols[i]) Changed = true; int.TryParse(TxtRow[i].Text, out Rows[i]); if (Rows[i] != OrigRows[i]) Changed = true; } if (!Changed) return false; TiledImg.UpLeft = new Rectangle(0, 0, Cols[0], Rows[0]); TiledImg.UpMiddle = new Rectangle(Cols[0], 0, Cols[1], Rows[0]); TiledImg.UpRight = new Rectangle(Cols[1], 0, Cols[2], Rows[0]); TiledImg.MiddleLeft = new Rectangle(0, Rows[0], Cols[0], Rows[1]); TiledImg.MiddleMiddle = new Rectangle(Cols[0], Rows[0], Cols[1], Rows[1]); TiledImg.MiddleRight = new Rectangle(Cols[1], Rows[0], Cols[2], Rows[1]); TiledImg.DownLeft = new Rectangle(0, Rows[1], Cols[0], Rows[2]); TiledImg.DownMiddle = new Rectangle(Cols[0], Rows[1], Cols[1], Rows[2]); TiledImg.DownRight = new Rectangle(Cols[1], Rows[1], Cols[2], Rows[2]); DisplayData(); return true; } ////////////////////////////////////////////////////////////////////////// private void OnTxtKeyDown(object sender, KeyEventArgs e) { if(e.KeyCode == Keys.Enter) { OnTxtLeave(sender, new EventArgs()); e.Handled = true; } } ////////////////////////////////////////////////////////////////////////// private void OnChooseImage(object sender, EventArgs e) { string OrigFile = null; if (TiledImg != null && TiledImg.Image != null && TiledImg.Image.ImageFilename != null) OrigFile = Game.MakeAbsolutePath(TiledImg.Image.ImageFilename); OpenFileDialog dlg = new OpenFileDialog(); dlg.Filter = "Images (*.png; *.bmp; *.jpg; *.tga)|*.png;*.bmp;*.jpg;*.tga|All files (*.*)|*.*"; dlg.RestoreDirectory = true; dlg.CheckFileExists = true; if (OrigFile != null && File.Exists(OrigFile)) dlg.FileName = OrigFile; if (dlg.ShowDialog() != DialogResult.OK) return; string NewFile = Game.MakeRelativePath(dlg.FileName); WSubFrame NewImg = new WSubFrame(Game); if(NewImg.SetImage(NewFile)) { TiledImg.Image = NewImg; IsDirty = true; DisplayData(); } else { NewImg.Dispose(); MessageBox.Show("Error loading file.", Form.ActiveForm.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); } } ////////////////////////////////////////////////////////////////////////// private void OnNewFile(object sender, EventArgs e) { if (!CanClose()) return; if(TiledImg != null) { TiledImg.ClaimOwnership(); TiledImg.Dispose(); } TiledImg = new WUITiledImage(Game); Filename = ""; IsDirty = true; DisplayData(); } ////////////////////////////////////////////////////////////////////////// private void OnSaveFile(object sender, EventArgs e) { SaveFile(false); } ////////////////////////////////////////////////////////////////////////// private void OnSaveAs(object sender, EventArgs e) { SaveFile(true); } ////////////////////////////////////////////////////////////////////////// private bool SaveFile(bool SaveAs) { if (Filename == "" || Filename == null) SaveAs = true; string NewFileName; if (SaveAs) { SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "Tiles images (*.image)|*.image|All files (*.*)|*.*"; dlg.AddExtension = true; dlg.CheckPathExists = true; dlg.OverwritePrompt = true; dlg.RestoreDirectory = true; if (Filename != null && Filename != "") dlg.FileName = Game.MakeAbsolutePath(Filename); if (dlg.ShowDialog() != DialogResult.OK) return false; NewFileName = dlg.FileName; } else NewFileName = Game.MakeAbsolutePath(Filename); WDynBuffer Buf = new WDynBuffer(Game); TiledImg.SaveAsText(Buf); string FileContent = ""; FileContent += "; generated by WindowEdit\n\n"; FileContent += Buf.Text; Buf.Dispose(); try { using (StreamWriter sw = new StreamWriter(NewFileName, false, Encoding.Default)) { sw.WriteLine(FileContent); } Filename = Game.MakeRelativePath(NewFileName); IsDirty = false; DisplayData(); return true; } catch (Exception e) { MessageBox.Show("Error saving file.\n\n" + e.Message, Form.ActiveForm.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } } ////////////////////////////////////////////////////////////////////////// private bool CanClose() { if (IsDirty) { DialogResult Res = MessageBox.Show("Do you want to save your changes?", Form.ActiveForm.Text, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); switch (Res) { case DialogResult.Yes: return SaveFile(false); case DialogResult.No: return true; default: return false; } } else return true; } } }
//--------------------------------------------------------------------- // <copyright file="EntityModelSchemaGenerator.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- using System.Diagnostics; using System.Collections.Generic; using System.Xml; using System.Data.Common; using System.Data.Common.Utils; using System.Data.Metadata.Edm; using System.Data.Entity.Design.Common; using System.Data.Entity.Design.SsdlGenerator; using System.Reflection; using System.Data.Entity.Design.PluralizationServices; using Microsoft.Build.Utilities; using System.Runtime.Versioning; using System.Linq; namespace System.Data.Entity.Design { /// <summary> /// The class creates a default CCMapping between an EntityContainer in S space /// and an EntityContainer in C space. The Mapping will be created based on the /// declared types of extents. So Inheritance does not work. /// </summary> public sealed class EntityModelSchemaGenerator { private const string ENTITY_CONTAINER_NAME_SUFFIX = "Context"; private const string NAMESPACE_NAME_SUFFIX = "Model"; private const string DEFAULT_NAMESPACE_NAME = "Application"; #region Constructors /// <summary> /// Constructs an EntityModelGenerator /// </summary> /// <param name="storeEntityContainer"></param> public EntityModelSchemaGenerator(EntityContainer storeEntityContainer) { Initialize(storeEntityContainer, null, null, null); } /// <summary> /// Constructs an EntityModelGenerator /// </summary> /// <param name="storeEntityContainer">The Store EntityContainer to create the Model Metadata from.</param> /// <param name="namespaceName">The name to give the namespace. If null, the name of the storeEntityContainer will be used.</param> /// <param name="modelEntityContainerName">The name to give the Model EntityContainer. If null, a modified version of the namespace of the of a type referenced in storeEntityContainer will be used.</param> public EntityModelSchemaGenerator(EntityContainer storeEntityContainer, string namespaceName, string modelEntityContainerName) { EDesignUtil.CheckArgumentNull(namespaceName, "namespaceName"); EDesignUtil.CheckArgumentNull(modelEntityContainerName, "modelEntityContainerName"); Initialize(storeEntityContainer, null, namespaceName, modelEntityContainerName); } /// <summary> /// Constructs an EntityModelGenerator /// </summary> /// <param name="storeItemCollection">The StoreItemCollection that contains an EntityContainer and other items to create the Model Metadata from.</param> /// <param name="namespaceName">The name to give the namespace. If null, the name of the storeEntityContainer will be used.</param> /// <param name="modelEntityContainerName">The name to give the Model EntityContainer. If null, a modified version of the namespace of the of a type referenced in storeEntityContainer will be used.</param> [CLSCompliant(false)] public EntityModelSchemaGenerator(StoreItemCollection storeItemCollection, string namespaceName, string modelEntityContainerName) { EDesignUtil.CheckArgumentNull(storeItemCollection, "storeItemCollection"); EDesignUtil.CheckArgumentNull(namespaceName, "namespaceName"); EDesignUtil.CheckArgumentNull(modelEntityContainerName, "modelEntityContainerName"); var storeContainers = storeItemCollection.GetItems<EntityContainer>().ToArray(); if (storeContainers.Length != 1) { throw EDesignUtil.SingleStoreEntityContainerExpected("storeItemCollection"); } Initialize( storeContainers[0], storeItemCollection.GetItems<EdmFunction>().Where(f => f.IsFromProviderManifest == false && f.IsComposableAttribute == true && f.AggregateAttribute == false), namespaceName, modelEntityContainerName); } private void Initialize(EntityContainer storeEntityContainer, IEnumerable<EdmFunction> storeFunctions, string namespaceName, string modelEntityContainerName) { EDesignUtil.CheckArgumentNull(storeEntityContainer, "storeEntityContainer"); if (!MetadataUtil.IsStoreType(storeEntityContainer)) { throw EDesignUtil.InvalidStoreEntityContainer(storeEntityContainer.Name, "storeEntityContainer"); } if (namespaceName != null) { EDesignUtil.CheckStringArgument(namespaceName, "namespaceName"); string adjustedNamespaceName = CreateValildModelNamespaceName(namespaceName); if (adjustedNamespaceName != namespaceName) { // the user gave us a bad namespace name throw EDesignUtil.InvalidNamespaceNameArgument(namespaceName); } } if (modelEntityContainerName != null) { EDesignUtil.CheckStringArgument(modelEntityContainerName, "modelEntityContainerName"); string adjustedEntityContainerName = CreateModelName(modelEntityContainerName); if (adjustedEntityContainerName != modelEntityContainerName) { throw EDesignUtil.InvalidEntityContainerNameArgument(modelEntityContainerName); } if (modelEntityContainerName == storeEntityContainer.Name) { throw EDesignUtil.DuplicateEntityContainerName(modelEntityContainerName, storeEntityContainer.Name); } } _storeEntityContainer = storeEntityContainer; _storeFunctions = storeFunctions != null ? storeFunctions.ToArray() : null; _namespaceName = namespaceName; _modelEntityContainerName = modelEntityContainerName; this._pluralizationServiceHandler = new EntityDesignPluralizationHandler(null); SetupFields(); } #endregion #region Fields private EntityContainer _storeEntityContainer; private EdmFunction[] _storeFunctions; private EntityContainer _modelEntityContainer = null; private OneToOneMappingSerializer.MappingLookups _mappingLookups = null; string _namespaceName = null; string _modelEntityContainerName = null; private EdmItemCollection _edmItemCollection; private EntityDesignPluralizationHandler _pluralizationServiceHandler = null; private Version _targetEntityFrameworkVersion; private bool _hasAnnotationNamespace; #endregion #region Properties /// <summary> /// Gets the EntityContainer that was created /// </summary> public EntityContainer EntityContainer { get { return _modelEntityContainer; } } /// <summary> /// Gets the EntityContainer that was created /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Edm")] [CLSCompliant(false)] public EdmItemCollection EdmItemCollection { get { return _edmItemCollection; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pluralization")] public PluralizationService PluralizationService { get { Debug.Assert(this._pluralizationServiceHandler != null, "all constructor should call initialize() to set the handler"); return this._pluralizationServiceHandler.Service; } set { this._pluralizationServiceHandler = new EntityDesignPluralizationHandler(value); } } /// <summary> /// Indicates whether foreign key properties should be exposed on entity types. /// </summary> public bool GenerateForeignKeyProperties { get; set; } #endregion #region public methods /// <summary> /// This method reads the s-space metadata objects and creates /// corresponding c-space metadata objects /// </summary> public IList<EdmSchemaError> GenerateMetadata() { // default the newest version _targetEntityFrameworkVersion = EntityFrameworkVersions.Latest; return InternalGenerateMetadata(); } /// <summary> /// This method reads the s-space metadata objects and creates /// corresponding c-space metadata objects /// </summary> public IList<EdmSchemaError> GenerateMetadata(Version targetEntityFrameworkVersion) { EDesignUtil.CheckTargetEntityFrameworkVersionArgument(targetEntityFrameworkVersion, "targetEntityFrameworkVersion"); _targetEntityFrameworkVersion = targetEntityFrameworkVersion; return InternalGenerateMetadata(); } /// <summary> /// Writes the Schema to xml /// </summary> /// <param name="outputFileName">The name of the file to write the xml to.</param> public void WriteModelSchema(string outputFileName) { EDesignUtil.CheckStringArgument(outputFileName, "outputFileName"); CheckValidSchema(); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; using (XmlWriter writer = XmlWriter.Create(outputFileName, settings)) { InternalWriteModelSchema(writer); } } /// <summary> /// Writes the Schema to xml. /// </summary> /// <param name="writer">The XmlWriter to write the xml to.</param> public void WriteModelSchema(XmlWriter writer) { EDesignUtil.CheckArgumentNull(writer, "writer"); CheckValidSchema(); InternalWriteModelSchema(writer); } /// <summary> /// Writes the cs mapping Schema to xml /// </summary> /// <param name="outputFileName">The name of the file to write the xml to.</param> public void WriteStorageMapping(string outputFileName) { EDesignUtil.CheckStringArgument(outputFileName, "outputFileName"); CheckValidSchema(); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; using (XmlWriter writer = XmlWriter.Create(outputFileName, settings)) { InternalWriteStorageMapping(writer); } } /// <summary> /// Writes the Schema to xml. /// </summary> /// <param name="writer">The XmlWriter to write the xml to.</param> public void WriteStorageMapping(XmlWriter writer) { EDesignUtil.CheckArgumentNull(writer, "writer"); CheckValidSchema(); InternalWriteStorageMapping(writer); } #endregion // responsible for holding all the // state for a single execution of the Load // method private class LoadMethodSessionState { public EdmItemCollection EdmItemCollection; public IList<EdmSchemaError> Errors = new List<EdmSchemaError>(); public UniqueIdentifierService UsedGlobalModelTypeNames = new UniqueIdentifierService(false); public UniqueIdentifierService UsedEntityContainerItemNames = new UniqueIdentifierService(false); public Dictionary<EdmProperty, AssociationType> FkProperties = new Dictionary<EdmProperty, AssociationType>(); public Dictionary<EntitySet, OneToOneMappingSerializer.CollapsedEntityAssociationSet> CandidateCollapsedAssociations = new Dictionary<EntitySet, OneToOneMappingSerializer.CollapsedEntityAssociationSet>(); public OneToOneMappingSerializer.MappingLookups MappingLookups = new OneToOneMappingSerializer.MappingLookups(); internal void AddError(string message, ModelBuilderErrorCode errorCode, EdmSchemaErrorSeverity severity, Exception e) { Debug.Assert(message != null, "message parameter is null"); if (null == e) { Errors.Add(new EdmSchemaError(message, (int)errorCode, severity)); } else { Errors.Add(new EdmSchemaError(message, (int)errorCode, severity, e)); } } } [ResourceExposure(ResourceScope.None)] //No resource is exposed. [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] //For EdmItemCollection constructor call. //Since we pass in empty collection for paths, we do not have any resource exposure here. private IList<EdmSchemaError> InternalGenerateMetadata() { if (_modelEntityContainer != null) { _modelEntityContainer = null; _mappingLookups = null; _edmItemCollection = null; } LoadMethodSessionState session = new LoadMethodSessionState(); try { session.EdmItemCollection = new EdmItemCollection(); if (this.GenerateForeignKeyProperties && this._targetEntityFrameworkVersion < EntityFrameworkVersions.Version2) { session.AddError(Strings.UnableToGenerateForeignKeyPropertiesForV1, ModelBuilderErrorCode.UnableToGenerateForeignKeyPropertiesForV1, EdmSchemaErrorSeverity.Error, null); return session.Errors; } List<AssociationSet> storeAssociationSets = new List<AssociationSet>(); CollectAllFkProperties(session); EntityContainer modelEntityContainer = new EntityContainer(_modelEntityContainerName, DataSpace.CSpace); // create the EntityTypes and EntitySets, and save up the AssociationSets for later. foreach (EntitySetBase storeSet in _storeEntityContainer.BaseEntitySets) { switch (storeSet.BuiltInTypeKind) { case BuiltInTypeKind.AssociationSet: // save these, and create them after the EntityTypes and EntitySets have been created string errorMessage; if (this.GenerateForeignKeyProperties || !EntityStoreSchemaGenerator.IsFkPartiallyContainedInPK(((AssociationSet)storeSet).ElementType, out errorMessage)) { storeAssociationSets.Add((AssociationSet)storeSet); } else { session.AddError(errorMessage, ModelBuilderErrorCode.UnsupportedForeinKeyPattern, EdmSchemaErrorSeverity.Error, null); } break; case BuiltInTypeKind.EntitySet: EntitySet set = (EntitySet)storeSet; session.CandidateCollapsedAssociations.Add(set, new OneToOneMappingSerializer.CollapsedEntityAssociationSet(set)); break; default: // error throw EDesignUtil.MissingGenerationPatternForType(storeSet.BuiltInTypeKind); } } foreach (AssociationSet storeAssociationSet in storeAssociationSets) { SaveAssociationForCollapsedAssociationCandidate(session, storeAssociationSet); } Set<AssociationSet> associationSetsFromCollapseCandidateRejects = new Set<AssociationSet>(); IEnumerable<OneToOneMappingSerializer.CollapsedEntityAssociationSet> invalidCandidates = FindAllInvalidCollapsedAssociationCandidates(session); // now that we have gone through all of the association sets, foreach (OneToOneMappingSerializer.CollapsedEntityAssociationSet collapsed in invalidCandidates) { session.CandidateCollapsedAssociations.Remove(collapsed.EntitySet); // just create the entity set and save the association set to be added later EntitySet entitySet = CreateModelEntitySet(session, collapsed.EntitySet); modelEntityContainer.AddEntitySetBase(entitySet); associationSetsFromCollapseCandidateRejects.AddRange(collapsed.AssociationSets); } // create all the associations for the invalid collapsed entity association candidates foreach (AssociationSet storeAssociationSet in (IEnumerable<AssociationSet>)associationSetsFromCollapseCandidateRejects) { if (!IsAssociationPartOfCandidateCollapsedAssociation(session, storeAssociationSet)) { AssociationSet set = CreateModelAssociationSet(session, storeAssociationSet); modelEntityContainer.AddEntitySetBase(set); } } // save the set that needs to be created and mapped session.MappingLookups.CollapsedEntityAssociationSets.AddRange(session.CandidateCollapsedAssociations.Values); // do this in a seperate loop so we are sure all the necessary EntitySets have been created foreach (OneToOneMappingSerializer.CollapsedEntityAssociationSet collapsed in session.MappingLookups.CollapsedEntityAssociationSets) { AssociationSet set = CreateModelAssociationSet(session, collapsed); modelEntityContainer.AddEntitySetBase(set); } if (this._targetEntityFrameworkVersion >= EntityFrameworkVersions.Version2) { Debug.Assert(EntityFrameworkVersions.Latest == EntityFrameworkVersions.Version3, "Did you add a new framework version"); // add LazyLoadingEnabled=true to the EntityContainer MetadataProperty lazyLoadingAttribute = new MetadataProperty( DesignXmlConstants.EdmAnnotationNamespace + ":" + DesignXmlConstants.LazyLoadingEnabled, TypeUsage.CreateStringTypeUsage( PrimitiveType.GetEdmPrimitiveType( PrimitiveTypeKind.String), false, false), true); modelEntityContainer.AddMetadataProperties(new List<MetadataProperty>() { lazyLoadingAttribute }); this._hasAnnotationNamespace = true; } // Map store functions to function imports. MapFunctions(session, modelEntityContainer); if (!EntityStoreSchemaGenerator.HasErrorSeverityErrors(session.Errors)) { // add them to the collection so they will work if someone wants to use the collection foreach (EntityType type in session.MappingLookups.StoreEntityTypeToModelEntityType.Values) { type.SetReadOnly(); session.EdmItemCollection.AddInternal(type); } foreach (AssociationType type in session.MappingLookups.StoreAssociationTypeToModelAssociationType.Values) { type.SetReadOnly(); session.EdmItemCollection.AddInternal(type); } foreach (OneToOneMappingSerializer.CollapsedEntityAssociationSet set in session.MappingLookups.CollapsedEntityAssociationSets) { set.ModelAssociationSet.ElementType.SetReadOnly(); session.EdmItemCollection.AddInternal(set.ModelAssociationSet.ElementType); } modelEntityContainer.SetReadOnly(); session.EdmItemCollection.AddInternal(modelEntityContainer); _modelEntityContainer = modelEntityContainer; _mappingLookups = session.MappingLookups; _edmItemCollection = session.EdmItemCollection; } } catch (Exception e) { if (MetadataUtil.IsCatchableExceptionType(e)) { // an exception in the code is definitely an error string message = EDesignUtil.GetMessagesFromEntireExceptionChain(e); session.AddError(message, ModelBuilderErrorCode.UnknownError, EdmSchemaErrorSeverity.Error, e); } else { throw; } } return session.Errors; } private void InternalWriteModelSchema(XmlWriter writer) { Debug.Assert(writer != null, "writer != null"); Debug.Assert(_edmItemCollection != null, "_edmItemCollection != null"); Debug.Assert(_namespaceName != null, "_namespaceName != null"); Debug.Assert(_targetEntityFrameworkVersion != null, "_targetEntityFrameworkVersion != null"); if (this._hasAnnotationNamespace) { KeyValuePair<string, string> namespacesPrefix = new KeyValuePair<string, string>(DesignXmlConstants.AnnotationPrefix, DesignXmlConstants.EdmAnnotationNamespace); MetadataItemSerializer.WriteXml(writer, _edmItemCollection, _namespaceName, _targetEntityFrameworkVersion, namespacesPrefix); } else { MetadataItemSerializer.WriteXml(writer, _edmItemCollection, _namespaceName, _targetEntityFrameworkVersion); } } private void InternalWriteStorageMapping(XmlWriter writer) { Debug.Assert(writer != null, "writer != null"); Debug.Assert(_mappingLookups != null, "_mappingLookups != null"); Debug.Assert(_storeEntityContainer != null, "_storeEntityContainer != null"); Debug.Assert(_modelEntityContainer != null, "_modelEntityContainer != null"); Debug.Assert(_targetEntityFrameworkVersion != null, "_targetEntityFrameworkVersion != null"); OneToOneMappingSerializer serializer = new OneToOneMappingSerializer(_mappingLookups, _storeEntityContainer, _modelEntityContainer, _targetEntityFrameworkVersion); serializer.WriteXml(writer); } private void MapFunctions(LoadMethodSessionState session, EntityContainer modelEntityContainer) { if (_storeFunctions == null || _storeFunctions.Length == 0 || _targetEntityFrameworkVersion < EntityFrameworkVersions.Version3) { return; } // // Create function imports and appropriate complex types for return parameters and add them to the item collection (session.EdmItemCollection). // Create and add function mappings. // var interestingStoreFunctions = _storeFunctions.Where( f => f.IsComposableAttribute && !f.AggregateAttribute && f.Parameters.All(p => p.Mode == ParameterMode.In)); foreach (var storeFunction in interestingStoreFunctions) { RowType tvfReturnType = TypeHelpers.GetTvfReturnType(storeFunction); if (tvfReturnType == null) { continue; } // Create function import name. string functionImportName = CreateModelName(storeFunction.Name, session.UsedEntityContainerItemNames); // Create function import parameters. UniqueIdentifierService usedParameterNames = new UniqueIdentifierService(false); var parameters = storeFunction.Parameters.Select(p => CreateFunctionImportParameter(p, usedParameterNames)).ToArray(); var failedStoreParameterName = storeFunction.Parameters.Select(p => p.Name).Except(parameters.Select(p => p.Name)).FirstOrDefault(); if (failedStoreParameterName != null) { session.AddError(Strings.UnableToGenerateFunctionImportParameterName(failedStoreParameterName, storeFunction.Identity), ModelBuilderErrorCode.UnableToGenerateFunctionImportParameterName, EdmSchemaErrorSeverity.Warning, null); continue; } // Create new complex type and register it in the item collection. var complexType = CreateModelComplexTypeForTvfResult(session, functionImportName, tvfReturnType); complexType.SetReadOnly(); session.EdmItemCollection.AddInternal(complexType); var collectionType = complexType.GetCollectionType(); collectionType.SetReadOnly(); var returnTypeUsage = TypeUsage.Create(collectionType); // Create function import and register it in the item collection. var functionImport = new EdmFunction(functionImportName, _modelEntityContainerName, DataSpace.CSpace, new EdmFunctionPayload() { Name = functionImportName, NamespaceName = _namespaceName, ReturnParameters = new FunctionParameter[] {new FunctionParameter(EdmConstants.ReturnType, returnTypeUsage, ParameterMode.ReturnValue)}, Parameters = parameters, DataSpace = DataSpace.CSpace, IsComposable = true, IsFunctionImport = true }); functionImport.SetReadOnly(); modelEntityContainer.AddFunctionImport(functionImport); // Add mapping tuple. session.MappingLookups.StoreFunctionToFunctionImport.Add(Tuple.Create(storeFunction, functionImport)); } } private FunctionParameter CreateFunctionImportParameter(FunctionParameter storeParameter, UniqueIdentifierService usedParameterNames) { Debug.Assert(storeParameter.Mode == ParameterMode.In, "Function import mapping is supported only for 'In' parameters."); string name = CreateModelName(storeParameter.Name, usedParameterNames); TypeUsage cspaceTypeUsage = storeParameter.TypeUsage.GetModelTypeUsage(); var modelParameter = new FunctionParameter(name, cspaceTypeUsage, storeParameter.Mode); return modelParameter; } private ComplexType CreateModelComplexTypeForTvfResult(LoadMethodSessionState session, string functionImportName, RowType tvfReturnType) { Debug.Assert(MetadataUtil.IsStoreType(tvfReturnType), "this is not a store type"); // create all the properties List<EdmMember> members = new List<EdmMember>(); UniqueIdentifierService usedPropertyNames = new UniqueIdentifierService(false); string name = CreateModelName(functionImportName + "_Result", session.UsedGlobalModelTypeNames); // Don't want to have a property with the same name as the complex type usedPropertyNames.RegisterUsedIdentifier(name); foreach (EdmProperty storeProperty in tvfReturnType.Properties) { EdmProperty property = CreateModelProperty(session, storeProperty, usedPropertyNames); members.Add(property); } var complexType = new ComplexType(name, _namespaceName, DataSpace.CSpace); foreach (var m in members) { complexType.AddMember(m); } return complexType; } private IEnumerable<OneToOneMappingSerializer.CollapsedEntityAssociationSet> FindAllInvalidCollapsedAssociationCandidates(LoadMethodSessionState session) { Set<OneToOneMappingSerializer.CollapsedEntityAssociationSet> invalid = new Set<OneToOneMappingSerializer.CollapsedEntityAssociationSet>(); Dictionary<EntitySet, OneToOneMappingSerializer.CollapsedEntityAssociationSet> newCandidates = new Dictionary<EntitySet,OneToOneMappingSerializer.CollapsedEntityAssociationSet>(); foreach (OneToOneMappingSerializer.CollapsedEntityAssociationSet collapsed in session.CandidateCollapsedAssociations.Values) { if (!collapsed.MeetsRequirementsForCollapsableAssociation) { invalid.Add(collapsed); } else { newCandidates.Add(collapsed.EntitySet, collapsed); } } foreach (OneToOneMappingSerializer.CollapsedEntityAssociationSet collapsed in newCandidates.Values) { foreach (AssociationSet set in collapsed.AssociationSets) { EntitySet end0Set = set.AssociationSetEnds[0].EntitySet; EntitySet end1Set = set.AssociationSetEnds[1].EntitySet; // if both ends of the association are candidates throw both candidates out // because we can't collapse two entities out // and we don't know which entity we should collapse // so we won't collapse either if (newCandidates.ContainsKey(end0Set) && newCandidates.ContainsKey(end1Set)) { OneToOneMappingSerializer.CollapsedEntityAssociationSet collapsed0 = session.CandidateCollapsedAssociations[end0Set]; OneToOneMappingSerializer.CollapsedEntityAssociationSet collapsed1 = session.CandidateCollapsedAssociations[end1Set]; invalid.Add(collapsed0); invalid.Add(collapsed1); } } } return invalid; } private bool IsAssociationPartOfCandidateCollapsedAssociation(LoadMethodSessionState session, AssociationSet storeAssociationSet) { foreach (AssociationSetEnd end in storeAssociationSet.AssociationSetEnds) { if (session.CandidateCollapsedAssociations.ContainsKey(end.EntitySet)) { return true; } } return false; } private void SaveAssociationForCollapsedAssociationCandidate(LoadMethodSessionState session, AssociationSet storeAssociationSet) { foreach (AssociationSetEnd end in storeAssociationSet.AssociationSetEnds) { OneToOneMappingSerializer.CollapsedEntityAssociationSet collapsed; if (session.CandidateCollapsedAssociations.TryGetValue(end.EntitySet, out collapsed)) { collapsed.AssociationSets.Add(storeAssociationSet); } } } private void CollectAllFkProperties(LoadMethodSessionState session) { foreach (EntitySetBase storeSet in _storeEntityContainer.BaseEntitySets) { if (storeSet.BuiltInTypeKind == BuiltInTypeKind.AssociationSet) { ReferentialConstraint constraint = OneToOneMappingSerializer.GetReferentialConstraint(((AssociationSet)storeSet)); foreach (EdmProperty property in constraint.ToProperties) { if (!session.FkProperties.ContainsKey(property)) { session.FkProperties.Add(property, ((AssociationSet)storeSet).ElementType); } } } } } // Get ModelSchemaNamespace name private void SetupFields() { if( _modelEntityContainerName != null && _namespaceName != null) { return; } string targetSchemaNamespace = null; //Try and get the target schema namespace from one of the types or functions defined in the schema foreach(EntitySetBase type in _storeEntityContainer.BaseEntitySets) { targetSchemaNamespace = type.ElementType.NamespaceName; break; } if (string.IsNullOrEmpty(targetSchemaNamespace)) { // the default targetSchemaNamespace = DEFAULT_NAMESPACE_NAME; } if(_namespaceName == null) { // if the schema namespace has 'Target' then replace it with '.Model int index = targetSchemaNamespace.IndexOf("Target", StringComparison.OrdinalIgnoreCase); if (index > 0) { _namespaceName = CreateValildModelNamespaceName(targetSchemaNamespace.Substring(0, index) + NAMESPACE_NAME_SUFFIX); } else { // else just append .Model to the name _namespaceName = CreateValildModelNamespaceName(targetSchemaNamespace + NAMESPACE_NAME_SUFFIX); } } if(_modelEntityContainerName == null) { // get default container name int dotIndex = targetSchemaNamespace.IndexOf('.'); if (dotIndex > 0) { _modelEntityContainerName = CreateModelName(targetSchemaNamespace.Substring(0, dotIndex) + ENTITY_CONTAINER_NAME_SUFFIX); } else { _modelEntityContainerName = CreateModelName(targetSchemaNamespace + ENTITY_CONTAINER_NAME_SUFFIX); } int targetIndex = _modelEntityContainerName.IndexOf("Target", StringComparison.OrdinalIgnoreCase); if (targetIndex > 0) { _modelEntityContainerName = CreateModelName(targetSchemaNamespace.Substring(0, targetIndex) + ENTITY_CONTAINER_NAME_SUFFIX); } } } private void CheckValidSchema() { if (_modelEntityContainer == null) { throw EDesignUtil.EntityModelGeneratorSchemaNotLoaded(); } } private EntitySet CreateModelEntitySet(LoadMethodSessionState session, EntitySet storeEntitySet) { EntityType entity = CreateModelEntityType(session, storeEntitySet.ElementType); string name = CreateModelName(this._pluralizationServiceHandler.GetEntitySetName(storeEntitySet.Name), session.UsedEntityContainerItemNames); EntitySet set = new EntitySet(name, null, null, null, entity); session.MappingLookups.StoreEntitySetToModelEntitySet.Add(storeEntitySet, set); return set; } private EntityType CreateModelEntityType(LoadMethodSessionState session, EntityType storeEntityType) { Debug.Assert(MetadataUtil.IsStoreType(storeEntityType), "this is not a store type"); Debug.Assert(storeEntityType.BaseType == null, "we are assuming simple generation from a database where no types will have a base type"); EntityType foundEntity; if (session.MappingLookups.StoreEntityTypeToModelEntityType.TryGetValue(storeEntityType, out foundEntity)) { // this entity type is used in two different entity sets return foundEntity; } // create all the properties List<EdmMember> members = new List<EdmMember>(); List<String> keyMemberNames = new List<string>(); UniqueIdentifierService usedPropertyNames = new UniqueIdentifierService(false); string name = CreateModelName(this._pluralizationServiceHandler.GetEntityTypeName(storeEntityType.Name), session.UsedGlobalModelTypeNames); // Don't want to have a property with the same name as the entity type usedPropertyNames.RegisterUsedIdentifier(name); foreach (EdmProperty storeProperty in storeEntityType.Properties) { // add fk properties only if requested EdmMember member; bool isKey = storeEntityType.KeyMembers.TryGetValue(storeProperty.Name, false, out member); AssociationType association; if (isKey || this.GenerateForeignKeyProperties || !session.FkProperties.TryGetValue(storeProperty, out association)) { EdmProperty property = CreateModelProperty(session, storeProperty, usedPropertyNames); members.Add(property); if (isKey) { keyMemberNames.Add(property.Name); } } } var entityType = new EntityType(name, _namespaceName, DataSpace.CSpace, keyMemberNames, members); session.MappingLookups.StoreEntityTypeToModelEntityType.Add(storeEntityType, entityType); return entityType; } private EdmProperty CreateModelProperty(LoadMethodSessionState session, EdmProperty storeProperty, UniqueIdentifierService usedPropertyNames) { string name = CreateModelName(storeProperty.Name, usedPropertyNames); TypeUsage cspaceTypeUsage = storeProperty.TypeUsage.GetModelTypeUsage(); EdmProperty property = new EdmProperty(name, cspaceTypeUsage); this.AddStoreGeneratedPatternAnnoation(property, storeProperty.TypeUsage); session.MappingLookups.StoreEdmPropertyToModelEdmProperty.Add(storeProperty, property); return property; } private void AddStoreGeneratedPatternAnnoation(EdmProperty cSpaceProperty, TypeUsage storeTypeUsage) { if (storeTypeUsage.Facets.Contains(DesignXmlConstants.StoreGeneratedPattern)) { List<MetadataProperty> annotation = new List<MetadataProperty>(); annotation.Add( new MetadataProperty( DesignXmlConstants.EdmAnnotationNamespace + ":" + DesignXmlConstants.StoreGeneratedPattern, TypeUsage.CreateStringTypeUsage( PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String), false/*isUnicode*/, false/*isFixLength*/), storeTypeUsage.Facets.GetValue(DesignXmlConstants.StoreGeneratedPattern, false).Value)); cSpaceProperty.AddMetadataProperties(annotation); this._hasAnnotationNamespace = true; } } private AssociationSet CreateModelAssociationSet(LoadMethodSessionState session, OneToOneMappingSerializer.CollapsedEntityAssociationSet collapsedAssociationSet) { // create the association string associationName = CreateModelName(collapsedAssociationSet.EntitySet.Name, session.UsedGlobalModelTypeNames); AssociationType association = new AssociationType(associationName, _namespaceName, false, DataSpace.CSpace); // create the association set string associationSetName = CreateModelName(collapsedAssociationSet.EntitySet.Name, session.UsedEntityContainerItemNames); AssociationSet set = new AssociationSet(associationSetName, association); // create the association and association set end members UniqueIdentifierService usedEndMemberNames = new UniqueIdentifierService(false); for(int i = 0; i < collapsedAssociationSet.AssociationSets.Count; i++) { AssociationSetEnd storeEnd; RelationshipMultiplicity multiplicity; OperationAction deleteBehavior; collapsedAssociationSet.GetStoreAssociationSetEnd(i, out storeEnd, out multiplicity, out deleteBehavior); AssociationEndMember end = CreateAssociationEndMember(session, storeEnd.CorrespondingAssociationEndMember, usedEndMemberNames, multiplicity, deleteBehavior); association.AddMember(end); EntitySet entitySet = session.MappingLookups.StoreEntitySetToModelEntitySet[storeEnd.EntitySet]; AssociationSetEnd setEnd = new AssociationSetEnd(entitySet, set, end); set.AddAssociationSetEnd(setEnd); session.MappingLookups.StoreAssociationSetEndToModelAssociationSetEnd.Add(storeEnd, setEnd); } // don't need a referential constraint CreateModelNavigationProperties(session, association); collapsedAssociationSet.ModelAssociationSet = set; return set; } private AssociationSet CreateModelAssociationSet(LoadMethodSessionState session, AssociationSet storeAssociationSet) { AssociationType association; // we will get a value when the same association is used for multiple association sets if (! session.MappingLookups.StoreAssociationTypeToModelAssociationType.TryGetValue(storeAssociationSet.ElementType, out association)) { association = CreateModelAssociationType(session, storeAssociationSet.ElementType); session.MappingLookups.StoreAssociationTypeToModelAssociationType.Add(storeAssociationSet.ElementType, association); } string name = CreateModelName(storeAssociationSet.Name, session.UsedEntityContainerItemNames); AssociationSet set = new AssociationSet(name, association); foreach(AssociationSetEnd storeEnd in storeAssociationSet.AssociationSetEnds) { AssociationSetEnd end = CreateModelAssociationSetEnd(session, storeEnd, set); session.MappingLookups.StoreAssociationSetEndToModelAssociationSetEnd.Add(storeEnd, end); set.AddAssociationSetEnd(end); } session.MappingLookups.StoreAssociationSetToModelAssociationSet.Add(storeAssociationSet, set); return set; } private AssociationSetEnd CreateModelAssociationSetEnd(LoadMethodSessionState session, AssociationSetEnd storeEnd, AssociationSet parentModelAssociationSet) { AssociationEndMember associationEnd = session.MappingLookups.StoreAssociationEndMemberToModelAssociationEndMember[storeEnd.CorrespondingAssociationEndMember]; EntitySet entitySet = session.MappingLookups.StoreEntitySetToModelEntitySet[storeEnd.EntitySet]; string role = associationEnd.Name; AssociationSetEnd end = new AssociationSetEnd(entitySet, parentModelAssociationSet, associationEnd); return end; } private AssociationType CreateModelAssociationType(LoadMethodSessionState session, AssociationType storeAssociationType) { UniqueIdentifierService usedEndMemberNames = new UniqueIdentifierService(false); string name = CreateModelName(storeAssociationType.Name, session.UsedGlobalModelTypeNames); bool isFkAssociation = false; if (_targetEntityFrameworkVersion > EntityFrameworkVersions.Version1) { isFkAssociation = this.GenerateForeignKeyProperties || RequiresModelReferentialConstraint(storeAssociationType); } AssociationType association = new AssociationType(name, _namespaceName, isFkAssociation, DataSpace.CSpace); KeyValuePair<string, RelationshipMultiplicity> endMultiplicityOverride = CreateEndMultiplicityOverride(session, storeAssociationType, association); foreach (AssociationEndMember storeEndMember in storeAssociationType.RelationshipEndMembers) { AssociationEndMember end = CreateAssociationEndMember(session, storeEndMember, endMultiplicityOverride, usedEndMemberNames); session.MappingLookups.StoreAssociationEndMemberToModelAssociationEndMember.Add(storeEndMember, end); association.AddMember(end); } ReferentialConstraint constraint = CreateReferentialConstraint(session, storeAssociationType); if (constraint != null) { association.AddReferentialConstraint(constraint); } CreateModelNavigationProperties(session, association); return association; } private KeyValuePair<string, RelationshipMultiplicity> CreateEndMultiplicityOverride(LoadMethodSessionState session, AssociationType storeAssociation, AssociationType modelAssociation) { // does the store have any constraints if (storeAssociation.ReferentialConstraints.Count == 0) { return new KeyValuePair<string, RelationshipMultiplicity>(); } ReferentialConstraint storeConstraint = storeAssociation.ReferentialConstraints[0]; //For foreign key associations, having any nullable columns will imply 0..1 //multiplicity, while for independent associations, all columns must be non-nullable for //0..1 association. bool nullableColumnsImplyingOneToOneMultiplicity = false; if (this.GenerateForeignKeyProperties) { nullableColumnsImplyingOneToOneMultiplicity = storeConstraint.ToProperties.All(p => p.Nullable == false); } else { nullableColumnsImplyingOneToOneMultiplicity = storeConstraint.ToProperties.Any(p => p.Nullable == false); } if (storeConstraint.FromRole.RelationshipMultiplicity == RelationshipMultiplicity.ZeroOrOne && storeConstraint.ToRole.RelationshipMultiplicity == RelationshipMultiplicity.Many && nullableColumnsImplyingOneToOneMultiplicity) { return new KeyValuePair<string, RelationshipMultiplicity>(storeConstraint.FromRole.Name, RelationshipMultiplicity.One); } return new KeyValuePair<string, RelationshipMultiplicity>(); } private ReferentialConstraint CreateReferentialConstraint(LoadMethodSessionState session, AssociationType storeAssociation) { Debug.Assert(session != null, "session parameter is null"); Debug.Assert(storeAssociation != null, "storeAssociation parameter is null"); Debug.Assert(storeAssociation.ReferentialConstraints.Count <= 1, "We don't have a reason to have more than one constraint yet"); // does the store have any constraints if (storeAssociation.ReferentialConstraints.Count == 0) { return null; } ReferentialConstraint storeConstraint = storeAssociation.ReferentialConstraints[0]; Debug.Assert(storeConstraint.FromProperties.Count == storeConstraint.ToProperties.Count, "FromProperties and ToProperties have different counts"); Debug.Assert(storeConstraint.FromProperties.Count != 0, "No properties in the constraint, why does the constraint exist?"); Debug.Assert(storeConstraint.ToProperties[0].DeclaringType.BuiltInTypeKind == BuiltInTypeKind.EntityType, "The property is not from an EntityType"); EntityType toType = (EntityType)storeConstraint.ToProperties[0].DeclaringType; // If we are generating foreign keys, there is always a referential constraint. Otherwise, check // if the dependent end includes key properties. If so, this implies that there is a referential // constraint. Otherwise, it is assumed that the foreign key properties are not defined in the // entity (verified ealier). if (!this.GenerateForeignKeyProperties && !RequiresModelReferentialConstraint(storeConstraint, toType)) { return null; } // we need a constraint so lets build it int count = storeConstraint.FromProperties.Count; EdmProperty[] fromProperties = new EdmProperty[count]; EdmProperty[] toProperties = new EdmProperty[count]; AssociationEndMember fromRole = session.MappingLookups.StoreAssociationEndMemberToModelAssociationEndMember[(AssociationEndMember)storeConstraint.FromRole]; AssociationEndMember toRole = session.MappingLookups.StoreAssociationEndMemberToModelAssociationEndMember[(AssociationEndMember)storeConstraint.ToRole]; for (int index = 0; index < count; index++) { fromProperties[index] = session.MappingLookups.StoreEdmPropertyToModelEdmProperty[storeConstraint.FromProperties[index]]; toProperties[index] = session.MappingLookups.StoreEdmPropertyToModelEdmProperty[storeConstraint.ToProperties[index]]; } ReferentialConstraint newConstraint = new ReferentialConstraint( fromRole, toRole, fromProperties, toProperties); return newConstraint; } private static bool RequiresModelReferentialConstraint(AssociationType storeAssociation) { // does the store have any constraints if (storeAssociation.ReferentialConstraints.Count == 0) { return false; } ReferentialConstraint storeConstraint = storeAssociation.ReferentialConstraints[0]; Debug.Assert(storeConstraint.FromProperties.Count == storeConstraint.ToProperties.Count, "FromProperties and ToProperties have different counts"); Debug.Assert(storeConstraint.FromProperties.Count != 0, "No properties in the constraint, why does the constraint exist?"); Debug.Assert(storeConstraint.ToProperties[0].DeclaringType.BuiltInTypeKind == BuiltInTypeKind.EntityType, "The property is not from an EntityType"); EntityType toType = (EntityType)storeConstraint.ToProperties[0].DeclaringType; return RequiresModelReferentialConstraint(storeConstraint, toType); } private static bool RequiresModelReferentialConstraint(ReferentialConstraint storeConstraint, EntityType toType) { return toType.KeyMembers.Contains(storeConstraint.ToProperties[0]); } private void CreateModelNavigationProperties(LoadMethodSessionState session, AssociationType association) { Debug.Assert(association.Members.Count == 2, "this code assumes two ends"); AssociationEndMember end1 = (AssociationEndMember)association.Members[0]; AssociationEndMember end2 = (AssociationEndMember)association.Members[1]; CreateModelNavigationProperty(session, end1, end2); CreateModelNavigationProperty(session, end2, end1); } private void CreateModelNavigationProperty(LoadMethodSessionState session, AssociationEndMember from, AssociationEndMember to) { EntityType entityType = (EntityType)((RefType)from.TypeUsage.EdmType).ElementType; UniqueIdentifierService usedMemberNames = new UniqueIdentifierService(false); LoadNameLookupWithUsedMemberNames(entityType, usedMemberNames); string name = CreateModelName(this._pluralizationServiceHandler.GetNavigationPropertyName(to, to.Name), usedMemberNames); NavigationProperty navigationProperty = new NavigationProperty(name, to.TypeUsage); navigationProperty.RelationshipType = (AssociationType)to.DeclaringType; navigationProperty.ToEndMember = to; navigationProperty.FromEndMember = from; entityType.AddMember(navigationProperty); } private void LoadNameLookupWithUsedMemberNames(EntityType entityType, UniqueIdentifierService usedMemberNames) { // a property should not have the same name as its entity usedMemberNames.RegisterUsedIdentifier(entityType.Name); foreach (EdmMember member in entityType.Members) { usedMemberNames.RegisterUsedIdentifier(member.Name); } } private AssociationEndMember CreateAssociationEndMember(LoadMethodSessionState session, AssociationEndMember storeEndMember, KeyValuePair<string, RelationshipMultiplicity> endMultiplicityOverride, UniqueIdentifierService usedEndMemberNames) { RelationshipMultiplicity multiplicity = storeEndMember.RelationshipMultiplicity; if (endMultiplicityOverride.Key != null && endMultiplicityOverride.Key == storeEndMember.Name) { multiplicity = endMultiplicityOverride.Value; } return CreateAssociationEndMember(session, storeEndMember, usedEndMemberNames, multiplicity, storeEndMember.DeleteBehavior); } private AssociationEndMember CreateAssociationEndMember(LoadMethodSessionState session, AssociationEndMember storeEndMember, UniqueIdentifierService usedEndMemberNames, RelationshipMultiplicity multiplicityOverride, OperationAction deleteBehaviorOverride) { Debug.Assert(storeEndMember.TypeUsage.EdmType.BuiltInTypeKind == BuiltInTypeKind.RefType, "The type is not a ref type"); Debug.Assert(((RefType)storeEndMember.TypeUsage.EdmType).ElementType.BuiltInTypeKind == BuiltInTypeKind.EntityType, "the ref is not holding on to an EntityType"); EntityType storeEntityType = ((EntityType)((RefType)storeEndMember.TypeUsage.EdmType).ElementType); EntityType modelEntityType = session.MappingLookups.StoreEntityTypeToModelEntityType[storeEntityType]; string name = CreateModelName(storeEndMember.Name, usedEndMemberNames); AssociationEndMember end = new AssociationEndMember(name, modelEntityType.GetReferenceType(), multiplicityOverride); end.DeleteBehavior = deleteBehaviorOverride; return end; } private string CreateModelName(string storeName, UniqueIdentifierService usedNames) { string newName = CreateModelName(storeName); newName = usedNames.AdjustIdentifier(newName); return newName; } private static string CreateValildModelNamespaceName(string storeNamespaceName) { return CreateValidNamespaceName(storeNamespaceName, 'C'); } internal static string CreateValidNamespaceName(string storeNamespaceName, char appendToFrontIfFirstCharIsInvalid) { List<string> namespaceParts = new List<string>(); foreach (string sPart in storeNamespaceName.Split(new char[] { '.' })) { // each part of a namespace needs to be a valid // cspace name namespaceParts.Add(CreateValidEcmaName(sPart, appendToFrontIfFirstCharIsInvalid)); } string modelNamespaceName = ""; for (int i = 0; i < namespaceParts.Count - 1; i++) { modelNamespaceName += namespaceParts[i] + "."; } modelNamespaceName += namespaceParts[namespaceParts.Count - 1]; // We might get a clash in names if ssdl has two types named #table and $table. Both will generate C_table // We leave it to the calling method to resolve any name clashes return modelNamespaceName; } //This method maps invalid characters such as &^%,etc in order to generate valid names private static string CreateModelName(string storeName) { return CreateValidEcmaName(storeName, 'C'); } internal static string CreateValidEcmaName(string name, char appendToFrontIfFirstCharIsInvalid) { char[] ecmaNameArray = name.ToCharArray(); for (int i = 0; i < ecmaNameArray.Length; i++) { // replace non -(letters or digits) with _ ( underscore ) if (!char.IsLetterOrDigit(ecmaNameArray[i])) { ecmaNameArray[i] = '_'; } } string ecmaName = new string(ecmaNameArray); // the first letter in a part should only be a char // if the part is empty then implies that we have the situation like ".abc", "abc.", "ab..c", // neither of them are accepted by the schema if (string.IsNullOrEmpty(name) || !char.IsLetter(ecmaName[0])) { ecmaName = appendToFrontIfFirstCharIsInvalid + ecmaName; } return ecmaName; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Linq.Expressions.Tests { public static class BlockTests { #region Test methods [Theory, ClassData(typeof(CompilationTypes))] public static void CheckBlockClosureVariableInitializationTest(bool useInterpreter) { foreach (var kv in BlockClosureVariableInitialization()) { VerifyBlockClosureVariableInitialization(kv.Key, kv.Value, useInterpreter); } } private static IEnumerable<KeyValuePair<Expression, object>> BlockClosureVariableInitialization() { { ParameterExpression p = Expression.Parameter(typeof(int)); ParameterExpression q = Expression.Parameter(typeof(Func<int>)); Expression<Func<int>> l = Expression.Lambda<Func<int>>(p); yield return new KeyValuePair<Expression, object>(Expression.Block(new[] { p, q }, Expression.Assign(q, l), p), default(int)); } { ParameterExpression p = Expression.Parameter(typeof(int)); ParameterExpression q = Expression.Parameter(typeof(Action<int>)); ParameterExpression x = Expression.Parameter(typeof(int)); Expression<Action<int>> l = Expression.Lambda<Action<int>>(Expression.Assign(p, x), x); yield return new KeyValuePair<Expression, object>(Expression.Block(new[] { p, q }, Expression.Assign(q, l), p), default(int)); } { ParameterExpression p = Expression.Parameter(typeof(TimeSpan)); ParameterExpression q = Expression.Parameter(typeof(Func<TimeSpan>)); Expression<Func<TimeSpan>> l = Expression.Lambda<Func<TimeSpan>>(p); yield return new KeyValuePair<Expression, object>(Expression.Block(new[] { p, q }, Expression.Assign(q, l), p), default(TimeSpan)); } { ParameterExpression p = Expression.Parameter(typeof(TimeSpan)); ParameterExpression q = Expression.Parameter(typeof(Action<TimeSpan>)); ParameterExpression x = Expression.Parameter(typeof(TimeSpan)); Expression<Action<TimeSpan>> l = Expression.Lambda<Action<TimeSpan>>(Expression.Assign(p, x), x); yield return new KeyValuePair<Expression, object>(Expression.Block(new[] { p, q }, Expression.Assign(q, l), p), default(TimeSpan)); } { ParameterExpression p = Expression.Parameter(typeof(string)); ParameterExpression q = Expression.Parameter(typeof(Func<string>)); Expression<Func<string>> l = Expression.Lambda<Func<string>>(p); yield return new KeyValuePair<Expression, object>(Expression.Block(new[] { p, q }, Expression.Assign(q, l), p), default(string)); } { ParameterExpression p = Expression.Parameter(typeof(string)); ParameterExpression q = Expression.Parameter(typeof(Action<string>)); ParameterExpression x = Expression.Parameter(typeof(string)); Expression<Action<string>> l = Expression.Lambda<Action<string>>(Expression.Assign(p, x), x); yield return new KeyValuePair<Expression, object>(Expression.Block(new[] { p, q }, Expression.Assign(q, l), p), default(string)); } { ParameterExpression p = Expression.Parameter(typeof(int?)); ParameterExpression q = Expression.Parameter(typeof(Func<int?>)); Expression<Func<int?>> l = Expression.Lambda<Func<int?>>(p); yield return new KeyValuePair<Expression, object>(Expression.Block(new[] { p, q }, Expression.Assign(q, l), p), default(int?)); } { ParameterExpression p = Expression.Parameter(typeof(int?)); ParameterExpression q = Expression.Parameter(typeof(Action<int?>)); ParameterExpression x = Expression.Parameter(typeof(int?)); Expression<Action<int?>> l = Expression.Lambda<Action<int?>>(Expression.Assign(p, x), x); yield return new KeyValuePair<Expression, object>(Expression.Block(new[] { p, q }, Expression.Assign(q, l), p), default(int?)); } { ParameterExpression p = Expression.Parameter(typeof(TimeSpan?)); ParameterExpression q = Expression.Parameter(typeof(Func<TimeSpan?>)); Expression<Func<TimeSpan?>> l = Expression.Lambda<Func<TimeSpan?>>(p); yield return new KeyValuePair<Expression, object>(Expression.Block(new[] { p, q }, Expression.Assign(q, l), p), default(TimeSpan?)); } { ParameterExpression p = Expression.Parameter(typeof(TimeSpan?)); ParameterExpression q = Expression.Parameter(typeof(Action<TimeSpan?>)); ParameterExpression x = Expression.Parameter(typeof(TimeSpan?)); Expression<Action<TimeSpan?>> l = Expression.Lambda<Action<TimeSpan?>>(Expression.Assign(p, x), x); yield return new KeyValuePair<Expression, object>(Expression.Block(new[] { p, q }, Expression.Assign(q, l), p), default(TimeSpan?)); } } #endregion #region Test verifiers private static void VerifyBlockClosureVariableInitialization(Expression e, object o, bool useInterpreter) { Expression<Func<object>> f = Expression.Lambda<Func<object>>( Expression.Convert(e, typeof(object))); Func<object> c = f.Compile(useInterpreter); Assert.Equal(o, c()); } #endregion private class ParameterChangingVisitor : ExpressionVisitor { protected override Expression VisitParameter(ParameterExpression node) { return Expression.Parameter(node.IsByRef ? node.Type.MakeByRefType() : node.Type, node.Name); } } [Fact] public static void VisitChangingOnlyParmeters() { BlockExpression block = Expression.Block( new[] { Expression.Parameter(typeof(int)), Expression.Parameter(typeof(string)) }, Expression.Empty() ); Assert.NotSame(block, new ParameterChangingVisitor().Visit(block)); } [Fact] public static void VisitChangingOnlyParmetersMultiStatementBody() { BlockExpression block = Expression.Block( new[] { Expression.Parameter(typeof(int)), Expression.Parameter(typeof(string)) }, Expression.Empty(), Expression.Empty() ); Assert.NotSame(block, new ParameterChangingVisitor().Visit(block)); } [Fact] public static void VisitChangingOnlyParmetersTyped() { BlockExpression block = Expression.Block( typeof(object), new[] { Expression.Parameter(typeof(int)), Expression.Parameter(typeof(string)) }, Expression.Constant("") ); Assert.NotSame(block, new ParameterChangingVisitor().Visit(block)); } [Theory] [ClassData(typeof(CompilationTypes))] public static void EmptyBlock(bool useInterpreter) { BlockExpression block = Expression.Block(); Assert.Equal(typeof(void), block.Type); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => block.Result); Action nop = Expression.Lambda<Action>(block).Compile(useInterpreter); nop(); } [Theory] [ClassData(typeof(CompilationTypes))] public static void EmptyBlockExplicitType(bool useInterpreter) { BlockExpression block = Expression.Block(typeof(void)); Assert.Equal(typeof(void), block.Type); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => block.Result); Action nop = Expression.Lambda<Action>(block).Compile(useInterpreter); nop(); } [Fact] public static void EmptyBlockWrongExplicitType() { AssertExtensions.Throws<ArgumentException>(null, () => Expression.Block(typeof(int))); } [Theory] [ClassData(typeof(CompilationTypes))] public static void EmptyScope(bool useInterpreter) { BlockExpression scope = Expression.Block(new[] { Expression.Parameter(typeof(int), "x") }, new Expression[0]); Assert.Equal(typeof(void), scope.Type); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => scope.Result); Action nop = Expression.Lambda<Action>(scope).Compile(useInterpreter); nop(); } [Theory] [ClassData(typeof(CompilationTypes))] public static void EmptyScopeExplicitType(bool useInterpreter) { BlockExpression scope = Expression.Block(typeof(void), new[] { Expression.Parameter(typeof(int), "x") }, new Expression[0]); Assert.Equal(typeof(void), scope.Type); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => scope.Result); Action nop = Expression.Lambda<Action>(scope).Compile(useInterpreter); nop(); } [Fact] public static void EmptyScopeExplicitWrongType() { AssertExtensions.Throws<ArgumentException>(null, () => Expression.Block( typeof(int), new[] { Expression.Parameter(typeof(int), "x") }, new Expression[0])); } [Fact] public static void ToStringTest() { BlockExpression e1 = Expression.Block(Expression.Empty()); Assert.Equal("{ ... }", e1.ToString()); BlockExpression e2 = Expression.Block(new[] { Expression.Parameter(typeof(int), "x") }, Expression.Empty()); Assert.Equal("{var x; ... }", e2.ToString()); BlockExpression e3 = Expression.Block(new[] { Expression.Parameter(typeof(int), "x"), Expression.Parameter(typeof(int), "y") }, Expression.Empty()); Assert.Equal("{var x;var y; ... }", e3.ToString()); } } }
// // ColorPaletteWidget.cs // // Author: // Jonathan Pobst <[email protected]> // // Copyright (c) 2010 Jonathan Pobst // // 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 Cairo; using Pinta.Core; using Mono.Unix; namespace Pinta.Gui.Widgets { [System.ComponentModel.ToolboxItem (true)] public class ColorPaletteWidget : Gtk.DrawingArea { private Rectangle primary_rect = new Rectangle (7, 7, 30, 30); private Rectangle secondary_rect = new Rectangle (22, 22, 30, 30); private Rectangle swap_rect = new Rectangle (37, 6, 15, 15); private Rectangle reset_rect = new Rectangle (7, 37, 15, 15); private Gdk.Pixbuf swap_icon; private Gdk.Pixbuf reset_icon; private Palette palette; public ColorPaletteWidget () { // Insert initialization code here. this.AddEvents ((int)Gdk.EventMask.ButtonPressMask); swap_icon = PintaCore.Resources.GetIcon ("ColorPalette.SwapIcon.png"); reset_icon = PintaCore.Resources.GetIcon ("ColorPalette.ResetIcon.png"); palette = PintaCore.Palette.CurrentPalette; HasTooltip = true; QueryTooltip += HandleQueryTooltip; } public void Initialize () { PintaCore.Palette.PrimaryColorChanged += new EventHandler (Palette_ColorChanged); PintaCore.Palette.SecondaryColorChanged += new EventHandler (Palette_ColorChanged); PintaCore.Palette.CurrentPalette.PaletteChanged += new EventHandler (Palette_ColorChanged); } private void Palette_ColorChanged (object sender, EventArgs e) { // Color change events may be received while the widget is minimized, // so we only call Invalidate() if the widget is shown. if (IsRealized) { GdkWindow.Invalidate (); } } protected override bool OnButtonPressEvent (Gdk.EventButton ev) { if (swap_rect.ContainsPoint (ev.X, ev.Y)) { Color temp = PintaCore.Palette.PrimaryColor; PintaCore.Palette.PrimaryColor = PintaCore.Palette.SecondaryColor; PintaCore.Palette.SecondaryColor = temp; GdkWindow.Invalidate (); } else if (reset_rect.ContainsPoint (ev.X, ev.Y)) { PintaCore.Palette.PrimaryColor = new Color (0, 0, 0); PintaCore.Palette.SecondaryColor = new Color (1, 1, 1); GdkWindow.Invalidate (); } if (primary_rect.ContainsPoint (ev.X, ev.Y)) { Gtk.ColorSelectionDialog csd = new Gtk.ColorSelectionDialog (Catalog.GetString ("Choose Primary Color")); csd.TransientFor = PintaCore.Chrome.MainWindow; csd.ColorSelection.PreviousColor = PintaCore.Palette.PrimaryColor.ToGdkColor (); csd.ColorSelection.CurrentColor = PintaCore.Palette.PrimaryColor.ToGdkColor (); csd.ColorSelection.CurrentAlpha = PintaCore.Palette.PrimaryColor.GdkColorAlpha (); csd.ColorSelection.HasOpacityControl = true; int response = csd.Run (); if (response == (int)Gtk.ResponseType.Ok) { PintaCore.Palette.PrimaryColor = csd.ColorSelection.GetCairoColor (); } csd.Destroy (); } else if (secondary_rect.ContainsPoint (ev.X, ev.Y)) { Gtk.ColorSelectionDialog csd = new Gtk.ColorSelectionDialog (Catalog.GetString ("Choose Secondary Color")); csd.TransientFor = PintaCore.Chrome.MainWindow; csd.ColorSelection.PreviousColor = PintaCore.Palette.SecondaryColor.ToGdkColor (); csd.ColorSelection.CurrentColor = PintaCore.Palette.SecondaryColor.ToGdkColor (); csd.ColorSelection.CurrentAlpha = PintaCore.Palette.SecondaryColor.GdkColorAlpha (); csd.ColorSelection.HasOpacityControl = true; int response = csd.Run (); if (response == (int)Gtk.ResponseType.Ok) { PintaCore.Palette.SecondaryColor = csd.ColorSelection.GetCairoColor (); } csd.Destroy (); } int pal = PointToPalette ((int)ev.X, (int)ev.Y); if (pal >= 0) { if (ev.Button == 3) PintaCore.Palette.SecondaryColor = palette[pal]; else if (ev.Button == 1) PintaCore.Palette.PrimaryColor = palette[pal]; else { Gtk.ColorSelectionDialog csd = new Gtk.ColorSelectionDialog (Catalog.GetString ("Choose Palette Color")); csd.TransientFor = PintaCore.Chrome.MainWindow; csd.ColorSelection.PreviousColor = palette[pal].ToGdkColor (); csd.ColorSelection.CurrentColor = palette[pal].ToGdkColor (); csd.ColorSelection.CurrentAlpha = palette[pal].GdkColorAlpha (); csd.ColorSelection.HasOpacityControl = true; int response = csd.Run (); if (response == (int)Gtk.ResponseType.Ok) { palette[pal] = csd.ColorSelection.GetCairoColor (); } csd.Destroy (); } GdkWindow.Invalidate (); } // Insert button press handling code here. return base.OnButtonPressEvent (ev); } protected override bool OnExposeEvent (Gdk.EventExpose ev) { base.OnExposeEvent (ev); using (Context g = Gdk.CairoHelper.Create (GdkWindow)) { g.FillRectangle (secondary_rect, PintaCore.Palette.SecondaryColor); g.DrawRectangle (new Rectangle (secondary_rect.X + 1, secondary_rect.Y + 1, secondary_rect.Width - 2, secondary_rect.Height - 2), new Color (1, 1, 1), 1); g.DrawRectangle (secondary_rect, new Color (0, 0, 0), 1); g.FillRectangle (primary_rect, PintaCore.Palette.PrimaryColor); g.DrawRectangle (new Rectangle (primary_rect.X + 1, primary_rect.Y + 1, primary_rect.Width - 2, primary_rect.Height - 2), new Color (1, 1, 1), 1); g.DrawRectangle (primary_rect, new Color (0, 0, 0), 1); g.DrawPixbuf (swap_icon, swap_rect.Location ()); g.DrawPixbuf (reset_icon, reset_rect.Location ()); // Draw swatches int roundedCount = (palette.Count % 3 == 0) ? palette.Count : palette.Count + 3 - (palette.Count % 3); for (int i = 0; i < palette.Count; i++) { int x = 7 + 15 * (i / (roundedCount / 3)); int y = 60 +15 * (i % (roundedCount / 3)); g.FillRectangle (new Rectangle (x, y, 15, 15), palette[i]); } } return true; } protected override void OnSizeRequested (ref Gtk.Requisition requisition) { // Calculate desired size here. requisition.Height = 305; requisition.Width = 60; } private int PointToPalette (int x, int y) { int col = -1; int row = 0; int roundedCount = (palette.Count % 3 == 0) ? palette.Count : palette.Count + 3 - (palette.Count % 3); if (x >= 7 && x < 22) col = 0; else if (x >= 22 && x < 38) col = roundedCount / 3; else if (x >= 38 && x < 54) col = (roundedCount / 3) * 2; else return -1; if (y < 60 || y > 60 + ((roundedCount / 3) * 15)) return -1; row = (y - 60) / 15; return (col + row >= palette.Count) ? -1 : col + row; } /// <summary> /// Provide a custom tooltip based on the cursor location. /// </summary> private void HandleQueryTooltip (object o, Gtk.QueryTooltipArgs args) { int x = args.X; int y = args.Y; string text = null; if (swap_rect.ContainsPoint (x, y)) { text = Catalog.GetString ("Click to switch between primary and secondary color."); } else if (reset_rect.ContainsPoint (x, y)) { text = Catalog.GetString ("Click to reset primary and secondary color."); } else if (primary_rect.ContainsPoint (x, y)) { text = Catalog.GetString ("Click to select primary color."); } else if (secondary_rect.ContainsPoint (x, y)) { text = Catalog.GetString ("Click to select secondary color."); } else if (PointToPalette (x, y) >= 0) { text = Catalog.GetString ("Left click to set primary color. Right click to set secondary color. Middle click to choose palette color."); } args.Tooltip.Text = text; args.RetVal = (text != null); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using UnityEditor.Experimental.AssetImporters; using UnityEditor.Graphing; using UnityEditor.Graphing.Util; using UnityEditor.Rendering; using UnityEngine; namespace UnityEditor.ShaderGraph { [ScriptedImporter(1, ".sgsubgraphdb", 2)] class SubGraphDatabaseImporter : ScriptedImporter { public const string path = "Packages/com.unity.shadergraph/Editor/Importers/_.sgsubgraphdb"; public override void OnImportAsset(AssetImportContext ctx) { var currentTime = DateTime.Now.Ticks; if (ctx.assetPath != path) { ctx.LogImportError("The sgpostsubgraph extension may only be used internally by Shader Graph."); return; } if (SubGraphDatabase.instance == null) { SubGraphDatabase.instance = ScriptableObject.CreateInstance<SubGraphDatabase>(); } var database = SubGraphDatabase.instance; var allSubGraphGuids = AssetDatabase.FindAssets($"t:{nameof(SubGraphAsset)}").ToList(); allSubGraphGuids.Sort(); var subGraphMap = new Dictionary<string, SubGraphData>(); var graphDataMap = new Dictionary<string, GraphData>(); foreach (var subGraphData in database.subGraphs) { if (allSubGraphGuids.BinarySearch(subGraphData.assetGuid) >= 0) { subGraphMap.Add(subGraphData.assetGuid, subGraphData); } } var dirtySubGraphGuids = new List<string>(); foreach (var subGraphGuid in allSubGraphGuids) { var subGraphAsset = AssetDatabase.LoadAssetAtPath<SubGraphAsset>(AssetDatabase.GUIDToAssetPath(subGraphGuid)); if (!subGraphMap.TryGetValue(subGraphGuid, out var subGraphData)) { subGraphData = new SubGraphData(); } if (subGraphAsset.importedAt > subGraphData.processedAt) { dirtySubGraphGuids.Add(subGraphGuid); subGraphData.Reset(); subGraphData.processedAt = currentTime; var subGraphPath = AssetDatabase.GUIDToAssetPath(subGraphGuid); var textGraph = File.ReadAllText(subGraphPath, Encoding.UTF8); var graphData = new GraphData { isSubGraph = true, assetGuid = subGraphGuid }; JsonUtility.FromJsonOverwrite(textGraph, graphData); subGraphData.children.AddRange(graphData.GetNodes<SubGraphNode>().Select(x => x.subGraphGuid).Distinct()); subGraphData.assetGuid = subGraphGuid; subGraphMap[subGraphGuid] = subGraphData; graphDataMap[subGraphGuid] = graphData; } else { subGraphData.ancestors.Clear(); subGraphData.descendents.Clear(); subGraphData.isRecursive = false; } } database.subGraphs.Clear(); database.subGraphs.AddRange(subGraphMap.Values); database.subGraphs.Sort((s1, s2) => s1.assetGuid.CompareTo(s2.assetGuid)); database.subGraphGuids.Clear(); database.subGraphGuids.AddRange(database.subGraphs.Select(x => x.assetGuid)); var permanentMarks = new HashSet<string>(); var stack = new Stack<string>(allSubGraphGuids.Count); // Detect recursion, and populate `ancestors` and `descendents` per sub graph. foreach (var rootSubGraphData in database.subGraphs) { var rootSubGraphGuid = rootSubGraphData.assetGuid; stack.Push(rootSubGraphGuid); while (stack.Count > 0) { var subGraphGuid = stack.Pop(); if (!permanentMarks.Add(subGraphGuid)) { continue; } var subGraphData = subGraphMap[subGraphGuid]; if (subGraphData != rootSubGraphData) { subGraphData.ancestors.Add(rootSubGraphGuid); rootSubGraphData.descendents.Add(subGraphGuid); } foreach (var childSubGraphGuid in subGraphData.children) { if (childSubGraphGuid == rootSubGraphGuid) { rootSubGraphData.isRecursive = true; } else if (subGraphMap.ContainsKey(childSubGraphGuid)) { stack.Push(childSubGraphGuid); } } } permanentMarks.Clear(); } // Next up we build a list of sub graphs to be processed, which will later be sorted topologically. var sortedSubGraphs = new List<SubGraphData>(); foreach (var subGraphGuid in dirtySubGraphGuids) { var subGraphData = subGraphMap[subGraphGuid]; if (permanentMarks.Add(subGraphGuid)) { sortedSubGraphs.Add(subGraphData); } // Note that we're traversing up the graph via ancestors rather than descendents, because all Sub Graphs using the current sub graph needs to be re-processed. foreach (var ancestorGuid in subGraphData.ancestors) { if (permanentMarks.Add(ancestorGuid)) { var ancestorSubGraphData = subGraphMap[ancestorGuid]; sortedSubGraphs.Add(ancestorSubGraphData); } } } permanentMarks.Clear(); // Sort topologically. At this stage we can assume there are no loops because all recursive sub graphs have been filtered out. sortedSubGraphs.Sort((s1, s2) => s1.descendents.Contains(s2.assetGuid) ? 1 : s2.descendents.Contains(s1.assetGuid) ? -1 : 0); // Finally process the topologically sorted sub graphs without recursion. var registry = new FunctionRegistry(new ShaderStringBuilder(), true); var messageManager = new MessageManager(); foreach (var subGraphData in sortedSubGraphs) { try { var subGraphPath = AssetDatabase.GUIDToAssetPath(subGraphData.assetGuid); if (!graphDataMap.TryGetValue(subGraphData.assetGuid, out var graphData)) { var textGraph = File.ReadAllText(subGraphPath, Encoding.UTF8); graphData = new GraphData { isSubGraph = true, assetGuid = subGraphData.assetGuid }; JsonUtility.FromJsonOverwrite(textGraph, graphData); } graphData.messageManager = messageManager; ProcessSubGraph(subGraphMap, registry, subGraphData, graphData); if (messageManager.nodeMessagesChanged) { var subGraphAsset = AssetDatabase.LoadAssetAtPath<SubGraphAsset>(AssetDatabase.GUIDToAssetPath(subGraphData.assetGuid)); foreach (var pair in messageManager.GetNodeMessages()) { var node = graphData.GetNodeFromTempId(pair.Key); foreach (var message in pair.Value) { MessageManager.Log(node, subGraphPath, message, subGraphAsset); } } } } catch (Exception e) { subGraphData.isValid = false; var subGraphAsset = AssetDatabase.LoadAssetAtPath<SubGraphAsset>(AssetDatabase.GUIDToAssetPath(subGraphData.assetGuid)); Debug.LogException(e, subGraphAsset); } finally { subGraphData.processedAt = currentTime; messageManager.ClearAll(); } } // Carry over functions used by sub-graphs that were not re-processed in this import. foreach (var subGraphData in database.subGraphs) { foreach (var functionName in subGraphData.functionNames) { if (!registry.sources.ContainsKey(functionName)) { registry.sources.Add(functionName, database.functionSources[database.functionNames.BinarySearch(functionName)]); } } } var functions = registry.sources.ToList(); functions.Sort((p1, p2) => p1.Key.CompareTo(p2.Key)); database.functionNames.Clear(); database.functionSources.Clear(); foreach (var pair in functions) { database.functionNames.Add(pair.Key); database.functionSources.Add(pair.Value); } ctx.AddObjectToAsset("MainAsset", database); ctx.SetMainObject(database); SubGraphDatabase.instance = null; } static void ProcessSubGraph(Dictionary<string, SubGraphData> subGraphMap, FunctionRegistry registry, SubGraphData subGraphData, GraphData graph) { registry.names.Clear(); subGraphData.functionNames.Clear(); subGraphData.nodeProperties.Clear(); subGraphData.isValid = true; graph.OnEnable(); graph.messageManager.ClearAll(); graph.ValidateGraph(); var assetPath = AssetDatabase.GUIDToAssetPath(subGraphData.assetGuid); subGraphData.hlslName = NodeUtils.GetHLSLSafeName(Path.GetFileNameWithoutExtension(assetPath)); subGraphData.inputStructName = $"Bindings_{subGraphData.hlslName}_{subGraphData.assetGuid}"; subGraphData.functionName = $"SG_{subGraphData.hlslName}_{subGraphData.assetGuid}"; subGraphData.path = graph.path; var outputNode = (SubGraphOutputNode)graph.outputNode; subGraphData.outputs.Clear(); outputNode.GetInputSlots(subGraphData.outputs); List<AbstractMaterialNode> nodes = new List<AbstractMaterialNode>(); NodeUtils.DepthFirstCollectNodesFromNode(nodes, outputNode); subGraphData.effectiveShaderStage = ShaderStageCapability.All; foreach (var slot in subGraphData.outputs) { var stage = NodeUtils.GetEffectiveShaderStageCapability(slot, true); if (stage != ShaderStageCapability.All) { subGraphData.effectiveShaderStage = stage; break; } } subGraphData.requirements = ShaderGraphRequirements.FromNodes(nodes, subGraphData.effectiveShaderStage, false); subGraphData.inputs = graph.properties.ToList(); foreach (var node in nodes) { if (node.hasError) { subGraphData.isValid = false; registry.ProvideFunction(subGraphData.functionName, sb => { }); return; } } foreach (var node in nodes) { if (node is SubGraphNode subGraphNode) { var nestedData = subGraphMap[subGraphNode.subGraphGuid]; foreach (var functionName in nestedData.functionNames) { registry.names.Add(functionName); } } else if (node is IGeneratesFunction generatesFunction) { generatesFunction.GenerateNodeFunction(registry, new GraphContext(subGraphData.inputStructName), GenerationMode.ForReals); } } registry.ProvideFunction(subGraphData.functionName, sb => { var graphContext = new GraphContext(subGraphData.inputStructName); GraphUtil.GenerateSurfaceInputStruct(sb, subGraphData.requirements, subGraphData.inputStructName); sb.AppendNewLine(); // Generate arguments... first INPUTS var arguments = new List<string>(); foreach (var prop in subGraphData.inputs) arguments.Add(string.Format("{0}", prop.GetPropertyAsArgumentString())); // now pass surface inputs arguments.Add(string.Format("{0} IN", subGraphData.inputStructName)); // Now generate outputs foreach (var output in subGraphData.outputs) arguments.Add($"out {output.concreteValueType.ToString(outputNode.precision)} {output.shaderOutputName}_{output.id}"); // Create the function prototype from the arguments sb.AppendLine("void {0}({1})" , subGraphData.functionName , arguments.Aggregate((current, next) => $"{current}, {next}")); // now generate the function using (sb.BlockScope()) { // Just grab the body from the active nodes var bodyGenerator = new ShaderGenerator(); foreach (var node in nodes) { if (node is IGeneratesBodyCode) (node as IGeneratesBodyCode).GenerateNodeCode(bodyGenerator, graphContext, GenerationMode.ForReals); } foreach (var slot in subGraphData.outputs) { bodyGenerator.AddShaderChunk($"{slot.shaderOutputName}_{slot.id} = {outputNode.GetSlotValue(slot.id, GenerationMode.ForReals)};"); } sb.Append(bodyGenerator.GetShaderString(1)); } }); subGraphData.functionNames.AddRange(registry.names.Distinct()); var collector = new PropertyCollector(); subGraphData.nodeProperties = collector.properties; foreach (var node in nodes) { node.CollectShaderProperties(collector, GenerationMode.ForReals); } subGraphData.OnBeforeSerialize(); } } }
//Copyright (C) 2005 Richard J. Northedge // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser 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. //This file is based on the GISModel.java source file found in the //original java implementation of MaxEnt. That source file contains the following header: // Copyright (C) 2001 Jason Baldridge and Gann Bierner // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 Lesser 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.Collections.Generic; using System.Text; namespace SharpEntropy { /// <summary> /// A maximum entropy model which has been trained using the Generalized /// Iterative Scaling procedure. /// </summary> /// <author> /// Tom Morton and Jason Baldridge /// </author> /// <author> /// Richard J. Northedge /// </author> /// <version> /// based on GISModel.java, $Revision: 1.13 $, $Date: 2004/06/11 20:51:44 $ /// </version> public sealed class GisModel : IMaximumEntropyModel { private readonly IO.IGisModelReader _reader; private readonly string[] _outcomeNames; private readonly int _outcomeCount; private readonly double _initialProbability; private readonly double _correctionConstantInverse; private readonly int[] _featureCounts; /// <summary> /// Constructor for a maximum entropy model trained using the /// Generalized Iterative Scaling procedure. /// </summary> /// <param name="reader"> /// A reader providing the data for the model. /// </param> public GisModel(IO.IGisModelReader reader) { this._reader = reader; _outcomeNames = reader.GetOutcomeLabels(); CorrectionConstant = reader.CorrectionConstant; CorrectionParameter = reader.CorrectionParameter; _outcomeCount = _outcomeNames.Length; _initialProbability = Math.Log(1.0 / _outcomeCount); _correctionConstantInverse = 1.0 / CorrectionConstant; _featureCounts = new int[_outcomeCount]; } // implementation of IMaxentModel ------- /// <summary> /// Returns the number of outcomes for this model. /// </summary> /// <returns> /// The number of outcomes. /// </returns> public int OutcomeCount { get { return (_outcomeCount); } } /// <summary> /// Evaluates a context. /// </summary> /// <param name="context"> /// A list of string names of the contextual predicates /// which are to be evaluated together. /// </param> /// <returns> /// An array of the probabilities for each of the different /// outcomes, all of which sum to 1. /// </returns> public double[] Evaluate(string[] context) { return Evaluate(context, new double[_outcomeCount]); } /// <summary> /// Use this model to evaluate a context and return an array of the /// likelihood of each outcome given that context. /// </summary> /// <param name="context"> /// The names of the predicates which have been observed at /// the present decision point. /// </param> /// <param name="outcomeSums"> /// This is where the distribution is stored. /// </param> /// <returns> /// The normalized probabilities for the outcomes given the /// context. The indexes of the double[] are the outcome /// ids, and the actual string representation of the /// outcomes can be obtained from the method /// GetOutcome(int outcomeIndex). /// </returns> public double[] Evaluate(string[] context, double[] outcomeSums) { for (int outcomeIndex = 0; outcomeIndex < _outcomeCount; outcomeIndex++) { outcomeSums[outcomeIndex] = _initialProbability; _featureCounts[outcomeIndex] = 0; } foreach (string con in context) { _reader.GetPredicateData(con, _featureCounts, outcomeSums); } double normal = 0.0; for (int outcomeIndex = 0;outcomeIndex < _outcomeCount; outcomeIndex++) { outcomeSums[outcomeIndex] = Math.Exp((outcomeSums[outcomeIndex] * _correctionConstantInverse) + ((1.0 - (_featureCounts[outcomeIndex] / CorrectionConstant)) * CorrectionParameter)); normal += outcomeSums[outcomeIndex]; } for (int outcomeIndex = 0; outcomeIndex < _outcomeCount;outcomeIndex++) { outcomeSums[outcomeIndex] /= normal; } return outcomeSums; } /// <summary> /// Return the name of the outcome corresponding to the highest likelihood /// in the parameter outcomes. /// </summary> /// <param name="outcomes"> /// A double[] as returned by the Evaluate(string[] context) /// method. /// </param> /// <returns> /// The name of the most likely outcome. /// </returns> public string GetBestOutcome(double[] outcomes) { int bestOutcomeIndex = 0; for (int currentOutcome = 1; currentOutcome < outcomes.Length; currentOutcome++) if (outcomes[currentOutcome] > outcomes[bestOutcomeIndex]) { bestOutcomeIndex = currentOutcome; } return _outcomeNames[bestOutcomeIndex]; } /// <summary> /// Return a string matching all the outcome names with all the /// probabilities produced by the <code>Evaluate(string[] context)</code> /// method. /// </summary> /// <param name="outcomes"> /// A <code>double[]</code> as returned by the /// <code>eval(string[] context)</code> /// method. /// </param> /// <returns> /// string containing outcome names paired with the normalized /// probability (contained in the <code>double[] outcomes</code>) /// for each one. /// </returns> public string GetAllOutcomes(double[] outcomes) { if (outcomes.Length != _outcomeNames.Length) { throw new ArgumentException("The double array sent as a parameter to GisModel.GetAllOutcomes() must not have been produced by this model."); } else { var outcomeInfo = new StringBuilder(outcomes.Length * 2); outcomeInfo.Append(_outcomeNames[0]).Append("[").Append(outcomes[0].ToString("0.0000", System.Globalization.CultureInfo.CurrentCulture)).Append("]"); for (int currentOutcome = 1; currentOutcome < outcomes.Length; currentOutcome++) { outcomeInfo.Append(" ").Append(_outcomeNames[currentOutcome]).Append("[").Append(outcomes[currentOutcome].ToString("0.0000", System.Globalization.CultureInfo.CurrentCulture)).Append("]"); } return outcomeInfo.ToString(); } } /// <summary> /// Return the name of an outcome corresponding to an integer ID value. /// </summary> /// <param name="outcomeIndex"> /// An outcome ID. /// </param> /// <returns> /// The name of the outcome associated with that ID. /// </returns> public string GetOutcomeName(int outcomeIndex) { return _outcomeNames[outcomeIndex]; } /// <summary> /// Gets the index associated with the string name of the given outcome. /// </summary> /// <param name="outcome"> /// the string name of the outcome for which the /// index is desired /// </param> /// <returns> /// the index if the given outcome label exists for this /// model, -1 if it does not. /// </returns> public int GetOutcomeIndex(string outcome) { for (int iCurrentOutcomeName = 0; iCurrentOutcomeName < _outcomeNames.Length; iCurrentOutcomeName++) { if (_outcomeNames[iCurrentOutcomeName] == outcome) { return iCurrentOutcomeName; } } return - 1; } /// <summary> /// Provides the predicates data structure which is part of the encoding of the maxent model /// information. This method will usually only be needed by /// GisModelWriters. /// </summary> /// <returns> /// Dictionary containing PatternedPredicate objects. /// </returns> public Dictionary<string, PatternedPredicate> GetPredicates() { return _reader.GetPredicates(); } /// <summary> /// Provides the list of outcome patterns used by the predicates. This method will usually /// only be needed by GisModelWriters. /// </summary> /// <returns> /// Array of outcome patterns. /// </returns> public int[][] GetOutcomePatterns() { return _reader.GetOutcomePatterns(); } /// <summary> /// Provides the outcome names data structure which is part of the encoding of the maxent model /// information. This method will usually only be needed by /// GisModelWriters. /// </summary> /// <returns> /// Array containing the outcome names. /// </returns> public string[] GetOutcomeNames() { return _outcomeNames; } /// <summary> /// Provides the model's correction constant. /// This property will usually only be needed by GisModelWriters. /// </summary> public int CorrectionConstant { get; private set; } /// <summary> /// Provides the model's correction parameter. /// This property will usually only be needed by GisModelWriters. /// </summary> public double CorrectionParameter { get; private set; } } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using SDKTemplate; using System; using System.Threading.Tasks; using Windows.Media.SpeechRecognition; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; namespace SpeechAndTTS { public sealed partial class PredefinedWebSearchGrammarScenario : Page { /// <summary> /// This HResult represents the scenario where a user is prompted to allow in-app speech, but /// declines. This should only happen on a Phone device, where speech is enabled for the entire device, /// not per-app. /// </summary> private static uint HResultPrivacyStatementDeclined = 0x80045509; private SpeechRecognizer speechRecognizer; private CoreDispatcher dispatcher; public PredefinedWebSearchGrammarScenario() { InitializeComponent(); } /// <summary> /// When activating the scenario, ensure we have permission from the user to access their microphone, and /// provide an appropriate path for the user to enable access to the microphone if they haven't /// given explicit permission for it. /// </summary> /// <param name="e">The navigation event details</param> protected async override void OnNavigatedTo(NavigationEventArgs e) { // Save the UI thread dispatcher to allow speech status messages to be shown on the UI. dispatcher = CoreWindow.GetForCurrentThread().Dispatcher; bool permissionGained = await AudioCapturePermissions.RequestMicrophonePermission(); if (permissionGained) { // Enable the recognition buttons. btnRecognizeWithUI.IsEnabled = true; btnRecognizeWithoutUI.IsEnabled = true; } else { resultTextBlock.Visibility = Visibility.Visible; resultTextBlock.Text = "Permission to access capture resources was not given by the user; please set the application setting in Settings->Privacy->Microphone."; } await InitializeRecognizer(); } /// <summary> /// Ensure that we clean up any state tracking event handlers created in OnNavigatedTo to prevent leaks. /// </summary> /// <param name="e">Details about the navigation event</param> protected override void OnNavigatedFrom(NavigationEventArgs e) { base.OnNavigatedFrom(e); if (speechRecognizer != null) { speechRecognizer.StateChanged -= SpeechRecognizer_StateChanged; this.speechRecognizer.Dispose(); this.speechRecognizer = null; } } /// <summary> /// Creates a SpeechRecognizer instance and initializes the grammar. /// </summary> private async Task InitializeRecognizer() { // Create an instance of SpeechRecognizer. speechRecognizer = new SpeechRecognizer(); // Provide feedback to the user about the state of the recognizer. speechRecognizer.StateChanged += SpeechRecognizer_StateChanged; // Add a web search topic constraint to the recognizer. var webSearchGrammar = new SpeechRecognitionTopicConstraint(SpeechRecognitionScenario.WebSearch, "webSearch"); speechRecognizer.Constraints.Add(webSearchGrammar); // RecognizeWithUIAsync allows developers to customize the prompts. speechRecognizer.UIOptions.AudiblePrompt = "Say what you want to search for..."; speechRecognizer.UIOptions.ExampleText = @"Ex. ""weather for London"""; // Compile the constraint. SpeechRecognitionCompilationResult compilationResult = await speechRecognizer.CompileConstraintsAsync(); // Check to make sure that the constraints were in a proper format and the recognizer was able to compile it. if (compilationResult.Status != SpeechRecognitionResultStatus.Success) { // Disable the recognition buttons. btnRecognizeWithUI.IsEnabled = false; btnRecognizeWithoutUI.IsEnabled = false; // Let the user know that the grammar didn't compile properly. resultTextBlock.Visibility = Visibility.Visible; resultTextBlock.Text = "Unable to compile grammar."; } } /// <summary> /// Handle SpeechRecognizer state changed events by updating a UI component. /// </summary> /// <param name="sender">Speech recognizer that generated this status event</param> /// <param name="args">The recognizer's status</param> private async void SpeechRecognizer_StateChanged(SpeechRecognizer sender, SpeechRecognizerStateChangedEventArgs args) { await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { MainPage.Current.NotifyUser("Speech recognizer state: " + args.State.ToString(), NotifyType.StatusMessage); }); } /// <summary> /// Uses the recognizer constructed earlier to listen for speech from the user before displaying /// it back on the screen. Uses the built-in speech recognition UI. /// </summary> /// <param name="sender">Button that triggered this event</param> /// <param name="e">State information about the routed event</param> private async void RecognizeWithUIWebSearchGrammar_Click(object sender, RoutedEventArgs e) { heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Collapsed; // Start recognition. try { SpeechRecognitionResult speechRecognitionResult = await speechRecognizer.RecognizeWithUIAsync(); // If successful, display the recognition result. if (speechRecognitionResult.Status == SpeechRecognitionResultStatus.Success) { heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Visible; resultTextBlock.Text = speechRecognitionResult.Text; } } catch (ObjectDisposedException exception) { // ObjectDisposedException will be thrown if you exit the scenario while the recogizer is actively // processing speech. Since this happens here when we navigate out of the scenario, don't try to // show a message dialog for this exception. System.Diagnostics.Debug.WriteLine("ObjectDisposedException caught while recognition in progress (can be ignored):"); System.Diagnostics.Debug.WriteLine(exception.ToString()); } catch (Exception exception) { // Handle the speech privacy policy error. if ((uint)exception.HResult == HResultPrivacyStatementDeclined) { resultTextBlock.Visibility = Visibility.Visible; resultTextBlock.Text = "The privacy statement was declined. Go to Settings -> Privacy -> Speech, inking and typing, and ensure you have viewed the privacy policy, and Cortana is set to 'Get To Know You'"; } else { var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception"); await messageDialog.ShowAsync(); } } } /// <summary> /// Uses the recognizer constructed earlier to listen for speech from the user before displaying /// it back on the screen. Uses developer-provided UI for user feedback. /// </summary> /// <param name="sender">Button that triggered this event</param> /// <param name="e">State information about the routed event</param> private async void RecognizeWithoutUIWebSearchGrammar_Click(object sender, RoutedEventArgs e) { heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Collapsed; // Disable the UI while recognition is occurring, and provide feedback to the user about current state. btnRecognizeWithUI.IsEnabled = false; btnRecognizeWithoutUI.IsEnabled = false; listenWithoutUIButtonText.Text = " listening for speech..."; // Start recognition. try { SpeechRecognitionResult speechRecognitionResult = await speechRecognizer.RecognizeAsync(); // If successful, display the recognition result. if (speechRecognitionResult.Status == SpeechRecognitionResultStatus.Success) { heardYouSayTextBlock.Visibility = resultTextBlock.Visibility = Visibility.Visible; resultTextBlock.Text = speechRecognitionResult.Text; } } catch (ObjectDisposedException exception) { // ObjectDisposedException will be thrown if you exit the scenario while the recogizer is actively // processing speech. Since this happens here when we navigate out of the scenario, don't try to // show a message dialog for this exception. System.Diagnostics.Debug.WriteLine("ObjectDisposedException caught while recognition in progress (can be ignored):"); System.Diagnostics.Debug.WriteLine(exception.ToString()); } catch (Exception exception) { // Handle the speech privacy policy error. if ((uint)exception.HResult == HResultPrivacyStatementDeclined) { resultTextBlock.Visibility = Visibility.Visible; resultTextBlock.Text = "The privacy statement was declined. Go to Settings -> Privacy -> Speech, inking and typing, and ensure you have viewed the privacy policy, and Cortana is set to 'Get To Know You'"; } else { var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "Exception"); await messageDialog.ShowAsync(); } } // Reset UI state. listenWithoutUIButtonText.Text = " without UI"; btnRecognizeWithUI.IsEnabled = true; btnRecognizeWithoutUI.IsEnabled = true; } } }
// 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.ComponentModel; using System.Runtime.InteropServices; using System.Security.Principal; using System.Text; namespace Carbon.Security { public sealed class Privilege { // ReSharper disable InconsistentNaming [StructLayout(LayoutKind.Sequential)] internal struct LSA_UNICODE_STRING { internal LSA_UNICODE_STRING(string inputString) { if (inputString == null) { Buffer = IntPtr.Zero; Length = 0; MaximumLength = 0; } else { Buffer = Marshal.StringToHGlobalAuto(inputString); Length = (ushort)(inputString.Length * UnicodeEncoding.CharSize); MaximumLength = (ushort)((inputString.Length + 1) * UnicodeEncoding.CharSize); } } internal ushort Length; internal ushort MaximumLength; internal IntPtr Buffer; } [StructLayout(LayoutKind.Sequential)] internal struct LSA_OBJECT_ATTRIBUTES { internal uint Length; internal IntPtr RootDirectory; internal LSA_UNICODE_STRING ObjectName; internal uint Attributes; internal IntPtr SecurityDescriptor; internal IntPtr SecurityQualityOfService; } [StructLayout(LayoutKind.Sequential)] public struct LUID { public uint LowPart; public int HighPart; } // ReSharper disable UnusedMember.Local private const uint POLICY_VIEW_LOCAL_INFORMATION = 0x00000001; private const uint POLICY_VIEW_AUDIT_INFORMATION = 0x00000002; private const uint POLICY_GET_PRIVATE_INFORMATION = 0x00000004; private const uint POLICY_TRUST_ADMIN = 0x00000008; private const uint POLICY_CREATE_ACCOUNT = 0x00000010; private const uint POLICY_CREATE_SECRET = 0x00000014; private const uint POLICY_CREATE_PRIVILEGE = 0x00000040; private const uint POLICY_SET_DEFAULT_QUOTA_LIMITS = 0x00000080; private const uint POLICY_SET_AUDIT_REQUIREMENTS = 0x00000100; private const uint POLICY_AUDIT_LOG_ADMIN = 0x00000200; private const uint POLICY_SERVER_ADMIN = 0x00000400; private const uint POLICY_LOOKUP_NAMES = 0x00000800; private const uint POLICY_NOTIFICATION = 0x00001000; // ReSharper restore UnusedMember.Local [DllImport("advapi32.dll", CharSet = CharSet.Unicode)] private static extern uint LsaAddAccountRights( IntPtr PolicyHandle, IntPtr AccountSid, LSA_UNICODE_STRING[] UserRights, uint CountOfRights); [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = false)] private static extern uint LsaClose(IntPtr ObjectHandle); [DllImport("advapi32.dll", SetLastError = true)] private static extern uint LsaEnumerateAccountRights(IntPtr PolicyHandle, IntPtr AccountSid, out IntPtr UserRights, out uint CountOfRights ); [DllImport("advapi32.dll", SetLastError = true)] private static extern uint LsaFreeMemory(IntPtr pBuffer); [DllImport("advapi32.dll")] private static extern int LsaNtStatusToWinError(long status); [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] private static extern uint LsaOpenPolicy(ref LSA_UNICODE_STRING SystemName, ref LSA_OBJECT_ATTRIBUTES ObjectAttributes, uint DesiredAccess, out IntPtr PolicyHandle ); [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] private static extern uint LsaRemoveAccountRights( IntPtr PolicyHandle, IntPtr AccountSid, [MarshalAs(UnmanagedType.U1)] bool AllRights, LSA_UNICODE_STRING[] UserRights, uint CountOfRights); // ReSharper restore InconsistentNaming private static IntPtr GetIdentitySid(string identity) { var sid = new NTAccount(identity).Translate(typeof (SecurityIdentifier)) as SecurityIdentifier; if (sid == null) { throw new ArgumentException(string.Format("Account {0} not found.", identity)); } var sidBytes = new byte[sid.BinaryLength]; sid.GetBinaryForm(sidBytes, 0); var sidPtr = Marshal.AllocHGlobal(sidBytes.Length); Marshal.Copy(sidBytes, 0, sidPtr, sidBytes.Length); return sidPtr; } private static IntPtr GetLsaPolicyHandle() { var computerName = Environment.MachineName; IntPtr hPolicy; var objectAttributes = new LSA_OBJECT_ATTRIBUTES { Length = 0, RootDirectory = IntPtr.Zero, Attributes = 0, SecurityDescriptor = IntPtr.Zero, SecurityQualityOfService = IntPtr.Zero }; const uint accessMask = POLICY_CREATE_SECRET | POLICY_LOOKUP_NAMES | POLICY_VIEW_LOCAL_INFORMATION; var machineNameLsa = new LSA_UNICODE_STRING(computerName); var result = LsaOpenPolicy(ref machineNameLsa, ref objectAttributes, accessMask, out hPolicy); HandleLsaResult(result); return hPolicy; } public static string[] GetPrivileges(string identity) { var sidPtr = GetIdentitySid(identity); var hPolicy = GetLsaPolicyHandle(); var rightsPtr = IntPtr.Zero; try { var privileges = new List<string>(); uint rightsCount; var result = LsaEnumerateAccountRights(hPolicy, sidPtr, out rightsPtr, out rightsCount); var win32ErrorCode = LsaNtStatusToWinError(result); // the user has no privileges if( win32ErrorCode == StatusObjectNameNotFound ) { return new string[0]; } HandleLsaResult(result); var myLsaus = new LSA_UNICODE_STRING(); for (ulong i = 0; i < rightsCount; i++) { var itemAddr = new IntPtr(rightsPtr.ToInt64() + (long) (i*(ulong) Marshal.SizeOf(myLsaus))); myLsaus = (LSA_UNICODE_STRING) Marshal.PtrToStructure(itemAddr, myLsaus.GetType()); var cvt = new char[myLsaus.Length/UnicodeEncoding.CharSize]; Marshal.Copy(myLsaus.Buffer, cvt, 0, myLsaus.Length/UnicodeEncoding.CharSize); var thisRight = new string(cvt); privileges.Add(thisRight); } return privileges.ToArray(); } finally { Marshal.FreeHGlobal(sidPtr); var result = LsaClose(hPolicy); HandleLsaResult(result); result = LsaFreeMemory(rightsPtr); HandleLsaResult(result); } } public static void GrantPrivileges(string identity, string[] privileges) { var sidPtr = GetIdentitySid(identity); var hPolicy = GetLsaPolicyHandle(); try { var lsaPrivileges = StringsToLsaStrings(privileges); var result = LsaAddAccountRights(hPolicy, sidPtr, lsaPrivileges, (uint)lsaPrivileges.Length); HandleLsaResult(result); } finally { Marshal.FreeHGlobal(sidPtr); var result = LsaClose(hPolicy); HandleLsaResult(result); } } private const int StatusSuccess = 0x0; private const int StatusObjectNameNotFound = 0x00000002; private const int StatusAccessDenied = 0x00000005; private const int StatusInvalidHandle = 0x00000006; private const int StatusUnsuccessful = 0x0000001F; private const int StatusInvalidParameter = 0x00000057; private const int StatusNoSuchPrivilege = 0x00000521; private const int StatusInvalidServerState = 0x00000548; private const int StatusInternalDbError = 0x00000567; private const int StatusInsufficientResources = 0x000005AA; private static readonly Dictionary<int, string> ErrorMessages = new Dictionary<int, string> { {StatusObjectNameNotFound, "Object name not found. An object in the LSA policy database was not found. The object may have been specified either by SID or by name, depending on its type."}, {StatusAccessDenied, "Access denied. Caller does not have the appropriate access to complete the operation."}, {StatusInvalidHandle, "Invalid handle. Indicates an object or RPC handle is not valid in the context used."}, {StatusUnsuccessful, "Unsuccessful. Generic failure, such as RPC connection failure."}, {StatusInvalidParameter, "Invalid parameter. One of the parameters is not valid."}, {StatusNoSuchPrivilege, "No such privilege. Indicates a specified privilege does not exist."}, {StatusInvalidServerState, "Invalid server state. Indicates the LSA server is currently disabled."}, {StatusInternalDbError, "Internal database error. The LSA database contains an internal inconsistency."}, {StatusInsufficientResources, "Insufficient resources. There are not enough system resources (such as memory to allocate buffers) to complete the call."} }; private static void HandleLsaResult(uint returnCode) { var win32ErrorCode = LsaNtStatusToWinError(returnCode); if( win32ErrorCode == StatusSuccess) return; if( ErrorMessages.ContainsKey(win32ErrorCode) ) { throw new Win32Exception(win32ErrorCode, ErrorMessages[win32ErrorCode]); } throw new Win32Exception(win32ErrorCode); } public static void RevokePrivileges(string identity, string[] privileges) { var sidPtr = GetIdentitySid(identity); var hPolicy = GetLsaPolicyHandle(); try { var currentPrivileges = GetPrivileges(identity); if (currentPrivileges.Length == 0) { return; } var lsaPrivileges = StringsToLsaStrings(privileges); var result = LsaRemoveAccountRights(hPolicy, sidPtr, false, lsaPrivileges, (uint)lsaPrivileges.Length); HandleLsaResult(result); } finally { Marshal.FreeHGlobal(sidPtr); var result = LsaClose(hPolicy); HandleLsaResult(result); } } private static LSA_UNICODE_STRING[] StringsToLsaStrings(string[] privileges) { var lsaPrivileges = new LSA_UNICODE_STRING[privileges.Length]; for (var idx = 0; idx < privileges.Length; ++idx) { lsaPrivileges[idx] = new LSA_UNICODE_STRING(privileges[idx]); } return lsaPrivileges; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Threading; namespace Apache.Geode.Client.UnitTests { using NUnit.Framework; using Apache.Geode.DUnitFramework; using Apache.Geode.Client.Tests; using Apache.Geode.Client; using QueryStatics = Apache.Geode.Client.Tests.QueryStatics; using QueryCategory = Apache.Geode.Client.Tests.QueryCategory; using QueryStrings = Apache.Geode.Client.Tests.QueryStrings; [TestFixture] [Category("group1")] [Category("unicast_only")] [Category("generics")] public class ThinClientRegionQueryTests : ThinClientRegionSteps { #region Private members private UnitProcess m_client1; private UnitProcess m_client2; private static string[] QueryRegionNames = { "Portfolios", "Positions", "Portfolios2", "Portfolios3" }; #endregion protected override ClientBase[] GetClients() { m_client1 = new UnitProcess(); m_client2 = new UnitProcess(); return new ClientBase[] { m_client1, m_client2 }; } [TestFixtureSetUp] public override void InitTests() { base.InitTests(); } [TearDown] public override void EndTest() { m_client1.Call(Close); m_client2.Call(Close); CacheHelper.StopJavaServers(); base.EndTest(); } [SetUp] public override void InitTest() { m_client1.Call(InitClient); m_client2.Call(InitClient); } #region Functions invoked by the tests public void InitClient() { CacheHelper.Init(); Serializable.RegisterTypeGeneric(Portfolio.CreateDeserializable, CacheHelper.DCache); Serializable.RegisterTypeGeneric(Position.CreateDeserializable, CacheHelper.DCache); Serializable.RegisterPdxType(Apache.Geode.Client.Tests.PortfolioPdx.CreateDeserializable); Serializable.RegisterPdxType(Apache.Geode.Client.Tests.PositionPdx.CreateDeserializable); } public void StepOne(string locators, bool isPdx) { m_isPdx = isPdx; CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[0], true, true, null, locators, "__TESTPOOL1_", true); CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[1], true, true, null, locators, "__TESTPOOL1_", true); CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[2], true, true, null, locators, "__TESTPOOL1_", true); CacheHelper.CreateTCRegion_Pool<object, object>(QueryRegionNames[3], true, true, null, locators, "__TESTPOOL1_", true); IRegion<object, object> region = CacheHelper.GetRegion<object, object>(QueryRegionNames[0]); Apache.Geode.Client.RegionAttributes<object, object> regattrs = region.Attributes; region.CreateSubRegion(QueryRegionNames[1], regattrs); } public void StepTwo(bool isPdx) { m_isPdx = isPdx; IRegion<object, object> region0 = CacheHelper.GetRegion<object, object>(QueryRegionNames[0]); IRegion<object, object> subRegion0 = (IRegion<object, object>)region0.GetSubRegion(QueryRegionNames[1]); IRegion<object, object> region1 = CacheHelper.GetRegion<object, object>(QueryRegionNames[1]); IRegion<object, object> region2 = CacheHelper.GetRegion<object, object>(QueryRegionNames[2]); IRegion<object, object> region3 = CacheHelper.GetRegion<object, object>(QueryRegionNames[3]); QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache); Util.Log("SetSize {0}, NumSets {1}.", qh.PortfolioSetSize, qh.PortfolioNumSets); if (!m_isPdx) { qh.PopulatePortfolioData(region0, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePositionData(subRegion0, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePositionData(region1, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePortfolioData(region2, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePortfolioData(region3, qh.PortfolioSetSize, qh.PortfolioNumSets); } else { qh.PopulatePortfolioPdxData(region0, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePositionPdxData(subRegion0, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePositionPdxData(region1, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePortfolioPdxData(region2, qh.PortfolioSetSize, qh.PortfolioNumSets); qh.PopulatePortfolioPdxData(region3, qh.PortfolioSetSize, qh.PortfolioNumSets); } } public void KillServer() { CacheHelper.StopJavaServer(1); Util.Log("Cacheserver 1 stopped."); } public delegate void KillServerDelegate(); public void StepThreeRQ() { bool ErrorOccurred = false; IRegion<object, object> region = CacheHelper.GetRegion<object, object>(QueryRegionNames[0]); int qryIdx = 0; foreach (QueryStrings qrystr in QueryStatics.RegionQueries) { if (qrystr.Category == QueryCategory.Unsupported) { Util.Log("Skipping query index {0} because it is unsupported.", qryIdx); qryIdx++; continue; } Util.Log("Evaluating query index {0}. {1}", qryIdx, qrystr.Query); if (m_isPdx) { if (qryIdx == 18) { Util.Log("Skipping query index {0} because it is unsupported for pdx type.", qryIdx); qryIdx++; continue; } } ISelectResults<object> results = region.Query<object>(qrystr.Query); if (results.Size != QueryStatics.RegionQueryRowCounts[qryIdx]) { ErrorOccurred = true; Util.Log("FAIL: Query # {0} expected result size is {1}, actual is {2}", qryIdx, QueryStatics.RegionQueryRowCounts[qryIdx], results.Size); qryIdx++; continue; } qryIdx++; } Assert.IsFalse(ErrorOccurred, "One or more query validation errors occurred."); try { ISelectResults<object> results = region.Query<object>(""); Assert.Fail("Expected IllegalArgumentException exception for empty predicate"); } catch (IllegalArgumentException ex) { Util.Log("got expected IllegalArgumentException exception for empty predicate:"); Util.Log(ex.Message); } try { ISelectResults<object> results = region.Query<object>(QueryStatics.RegionQueries[0].Query, TimeSpan.FromSeconds(2200000)); Assert.Fail("Expected IllegalArgumentException exception for invalid timeout"); } catch (IllegalArgumentException ex) { Util.Log("got expected IllegalArgumentException exception for invalid timeout:"); Util.Log(ex.Message); } try { ISelectResults<object> results = region.Query<object>("bad predicate"); Assert.Fail("Expected QueryException exception for wrong predicate"); } catch (QueryException ex) { Util.Log("got expected QueryException exception for wrong predicate:"); Util.Log(ex.Message); } } public void StepFourRQ() { bool ErrorOccurred = false; IRegion<object, object> region = CacheHelper.GetRegion<object, object>(QueryRegionNames[0]); int qryIdx = 0; foreach (QueryStrings qrystr in QueryStatics.RegionQueries) { if (qrystr.Category == QueryCategory.Unsupported) { Util.Log("Skipping query index {0} because it is unsupported.", qryIdx); qryIdx++; continue; } Util.Log("Evaluating query index {0}.{1}", qryIdx, qrystr.Query); bool existsValue = region.ExistsValue(qrystr.Query); bool expectedResult = QueryStatics.RegionQueryRowCounts[qryIdx] > 0 ? true : false; if (existsValue != expectedResult) { ErrorOccurred = true; Util.Log("FAIL: Query # {0} existsValue expected is {1}, actual is {2}", qryIdx, expectedResult ? "true" : "false", existsValue ? "true" : "false"); qryIdx++; continue; } qryIdx++; } Assert.IsFalse(ErrorOccurred, "One or more query validation errors occurred."); try { bool existsValue = region.ExistsValue(""); Assert.Fail("Expected IllegalArgumentException exception for empty predicate"); } catch (IllegalArgumentException ex) { Util.Log("got expected IllegalArgumentException exception for empty predicate:"); Util.Log(ex.Message); } try { bool existsValue = region.ExistsValue(QueryStatics.RegionQueries[0].Query, TimeSpan.FromSeconds(2200000)); Assert.Fail("Expected IllegalArgumentException exception for invalid timeout"); } catch (IllegalArgumentException ex) { Util.Log("got expected IllegalArgumentException exception for invalid timeout:"); Util.Log(ex.Message); } try { bool existsValue = region.ExistsValue("bad predicate"); Assert.Fail("Expected QueryException exception for wrong predicate"); } catch (QueryException ex) { Util.Log("got expected QueryException exception for wrong predicate:"); Util.Log(ex.Message); } } public void StepFiveRQ() { bool ErrorOccurred = false; IRegion<object, object> region = CacheHelper.GetRegion<object, object>(QueryRegionNames[0]); int qryIdx = 0; foreach (QueryStrings qrystr in QueryStatics.RegionQueries) { if (qrystr.Category == QueryCategory.Unsupported) { Util.Log("Skipping query index {0} because it is unsupported.", qryIdx); qryIdx++; continue; } Util.Log("Evaluating query index {0}.", qryIdx); try { Object result = region.SelectValue(qrystr.Query); if (!(QueryStatics.RegionQueryRowCounts[qryIdx] == 0 || QueryStatics.RegionQueryRowCounts[qryIdx] == 1)) { ErrorOccurred = true; Util.Log("FAIL: Query # {0} expected query exception did not occur", qryIdx); qryIdx++; continue; } } catch (QueryException) { if (QueryStatics.RegionQueryRowCounts[qryIdx] == 0 || QueryStatics.RegionQueryRowCounts[qryIdx] == 1) { ErrorOccurred = true; Util.Log("FAIL: Query # {0} unexpected query exception occured", qryIdx); qryIdx++; continue; } } catch (Exception) { ErrorOccurred = true; Util.Log("FAIL: Query # {0} unexpected exception occured", qryIdx); qryIdx++; continue; } qryIdx++; } Assert.IsFalse(ErrorOccurred, "One or more query validation errors occurred."); try { Object result = region.SelectValue(""); Assert.Fail("Expected IllegalArgumentException exception for empty predicate"); } catch (IllegalArgumentException ex) { Util.Log("got expected IllegalArgumentException exception for empty predicate:"); Util.Log(ex.Message); } try { Object result = region.SelectValue(QueryStatics.RegionQueries[0].Query, TimeSpan.FromSeconds(2200000)); Assert.Fail("Expected IllegalArgumentException exception for invalid timeout"); } catch (IllegalArgumentException ex) { Util.Log("got expected IllegalArgumentException exception for invalid timeout:"); Util.Log(ex.Message); } try { Object result = region.SelectValue("bad predicate"); Assert.Fail("Expected QueryException exception for wrong predicate"); } catch (QueryException ex) { Util.Log("got expected QueryException exception for wrong predicate:"); Util.Log(ex.Message); } } public void StepSixRQ() { bool ErrorOccurred = false; IRegion<object, object> region = CacheHelper.GetRegion<object, object>(QueryRegionNames[0]); int qryIdx = 0; foreach (QueryStrings qrystr in QueryStatics.RegionQueries) { if ((qrystr.Category != QueryCategory.Unsupported) || (qryIdx == 3)) { qryIdx++; continue; } Util.Log("Evaluating unsupported query index {0}.", qryIdx); try { ISelectResults<object> results = region.Query<object>(qrystr.Query); Util.Log("Query # {0} expected exception did not occur", qryIdx); ErrorOccurred = true; qryIdx++; } catch (QueryException) { // ok, exception expected, do nothing. qryIdx++; } catch (Exception) { ErrorOccurred = true; Util.Log("FAIL: Query # {0} unexpected exception occured", qryIdx); qryIdx++; } } Assert.IsFalse(ErrorOccurred, "Query expected exceptions did not occur."); } #endregion void runRegionQuery() { CacheHelper.SetupJavaServers(true, "remotequeryN.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator started"); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1); Util.Log("Cacheserver 1 started."); m_client2.Call(StepOne, CacheHelper.Locators, m_isPdx); Util.Log("StepOne complete."); m_client2.Call(StepTwo, m_isPdx); Util.Log("StepTwo complete."); //Extra Step //m_client1.Call(StepExtra); m_client2.Call(StepThreeRQ); Util.Log("StepThree complete."); m_client2.Call(StepFourRQ); Util.Log("StepFour complete."); m_client2.Call(StepFiveRQ); Util.Log("StepFive complete."); m_client2.Call(StepSixRQ); Util.Log("StepSix complete."); m_client2.Call(Close); Util.Log("Client closed"); CacheHelper.StopJavaServer(1); Util.Log("Cacheserver 1 stopped."); CacheHelper.StopJavaLocator(1); Util.Log("Locator stopped"); } static bool m_isPdx = false; [Test] public void RegionQueryWithPdx() { m_isPdx = true; runRegionQuery(); } [Test] public void RegionQueryWithoutPdx() { m_isPdx = false; runRegionQuery(); } } }
// // This file was generated by the BinaryNotes compiler. // See http://bnotes.sourceforge.net // Any modifications to this file will be lost upon recompilation of the source ASN.1. // using GSF.ASN1; using GSF.ASN1.Attributes; using GSF.ASN1.Coders; namespace GSF.MMS.Model { [ASN1PreparedElement] [ASN1Sequence(Name = "Initiate_RequestPDU", IsSet = false)] public class Initiate_RequestPDU : IASN1PreparedElement { private static readonly IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(Initiate_RequestPDU)); private InitRequestDetailSequenceType initRequestDetail_; private Integer32 localDetailCalling_; private bool localDetailCalling_present; private Integer8 proposedDataStructureNestingLevel_; private bool proposedDataStructureNestingLevel_present; private Integer16 proposedMaxServOutstandingCalled_; private Integer16 proposedMaxServOutstandingCalling_; [ASN1Element(Name = "localDetailCalling", IsOptional = true, HasTag = true, Tag = 0, HasDefaultValue = false)] public Integer32 LocalDetailCalling { get { return localDetailCalling_; } set { localDetailCalling_ = value; localDetailCalling_present = true; } } [ASN1Element(Name = "proposedMaxServOutstandingCalling", IsOptional = false, HasTag = true, Tag = 1, HasDefaultValue = false)] public Integer16 ProposedMaxServOutstandingCalling { get { return proposedMaxServOutstandingCalling_; } set { proposedMaxServOutstandingCalling_ = value; } } [ASN1Element(Name = "proposedMaxServOutstandingCalled", IsOptional = false, HasTag = true, Tag = 2, HasDefaultValue = false)] public Integer16 ProposedMaxServOutstandingCalled { get { return proposedMaxServOutstandingCalled_; } set { proposedMaxServOutstandingCalled_ = value; } } [ASN1Element(Name = "proposedDataStructureNestingLevel", IsOptional = true, HasTag = true, Tag = 3, HasDefaultValue = false)] public Integer8 ProposedDataStructureNestingLevel { get { return proposedDataStructureNestingLevel_; } set { proposedDataStructureNestingLevel_ = value; proposedDataStructureNestingLevel_present = true; } } [ASN1Element(Name = "initRequestDetail", IsOptional = false, HasTag = true, Tag = 4, HasDefaultValue = false)] public InitRequestDetailSequenceType InitRequestDetail { get { return initRequestDetail_; } set { initRequestDetail_ = value; } } public void initWithDefaults() { } public IASN1PreparedElementData PreparedData { get { return preparedData; } } public bool isLocalDetailCallingPresent() { return localDetailCalling_present; } public bool isProposedDataStructureNestingLevelPresent() { return proposedDataStructureNestingLevel_present; } [ASN1PreparedElement] [ASN1Sequence(Name = "initRequestDetail", IsSet = false)] public class InitRequestDetailSequenceType : IASN1PreparedElement { private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(InitRequestDetailSequenceType)); private AdditionalCBBOptions additionalCbbSupportedCalling_; private AdditionalSupportOptions additionalSupportedCalling_; private string privilegeClassIdentityCalling_; private ParameterSupportOptions proposedParameterCBB_; private Integer16 proposedVersionNumber_; private ServiceSupportOptions servicesSupportedCalling_; [ASN1Element(Name = "proposedVersionNumber", IsOptional = false, HasTag = true, Tag = 0, HasDefaultValue = false)] public Integer16 ProposedVersionNumber { get { return proposedVersionNumber_; } set { proposedVersionNumber_ = value; } } [ASN1Element(Name = "proposedParameterCBB", IsOptional = false, HasTag = true, Tag = 1, HasDefaultValue = false)] public ParameterSupportOptions ProposedParameterCBB { get { return proposedParameterCBB_; } set { proposedParameterCBB_ = value; } } [ASN1Element(Name = "servicesSupportedCalling", IsOptional = false, HasTag = true, Tag = 2, HasDefaultValue = false)] public ServiceSupportOptions ServicesSupportedCalling { get { return servicesSupportedCalling_; } set { servicesSupportedCalling_ = value; } } [ASN1Element(Name = "additionalSupportedCalling", IsOptional = false, HasTag = true, Tag = 3, HasDefaultValue = false)] public AdditionalSupportOptions AdditionalSupportedCalling { get { return additionalSupportedCalling_; } set { additionalSupportedCalling_ = value; } } [ASN1Element(Name = "additionalCbbSupportedCalling", IsOptional = false, HasTag = true, Tag = 4, HasDefaultValue = false)] public AdditionalCBBOptions AdditionalCbbSupportedCalling { get { return additionalCbbSupportedCalling_; } set { additionalCbbSupportedCalling_ = value; } } [ASN1String(Name = "", StringType = UniversalTags.VisibleString, IsUCS = false)] [ASN1Element(Name = "privilegeClassIdentityCalling", IsOptional = false, HasTag = true, Tag = 5, HasDefaultValue = false)] public string PrivilegeClassIdentityCalling { get { return privilegeClassIdentityCalling_; } set { privilegeClassIdentityCalling_ = value; } } public void initWithDefaults() { } public IASN1PreparedElementData PreparedData { get { return preparedData; } } } } }
//------------------------------------------------------------------------------ // <copyright file="PanelStyle.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.WebControls { using System; using System.Collections; using System.ComponentModel; using System.Globalization; using System.Reflection; using System.Web; using System.Web.UI; /// <devdoc> /// <para>Specifies the style of the panel.</para> /// </devdoc> public class PanelStyle : Style { // !!NOTE!! // Style.cs also defines a set of flag contants and both sets have to // be unique. Please be careful when adding new flags to either list. private const int PROP_BACKIMAGEURL = 0x00010000; private const int PROP_DIRECTION = 0x00020000; private const int PROP_HORIZONTALALIGN = 0x00040000; private const int PROP_SCROLLBARS = 0x00080000; private const int PROP_WRAP = 0x00100000; private const string STR_BACKIMAGEURL = "BackImageUrl"; private const string STR_DIRECTION = "Direction"; private const string STR_HORIZONTALALIGN = "HorizontalAlign"; private const string STR_SCROLLBARS = "ScrollBars"; private const string STR_WRAP = "Wrap"; /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Web.UI.WebControls.PanelStyle'/> /// class with state bag information. /// </para> /// </devdoc> public PanelStyle(StateBag bag) : base (bag) { } /// <devdoc> /// <para>Gets or sets the URL of the background image for the panel.</para> /// </devdoc> [ WebCategory("Appearance"), DefaultValue(""), UrlProperty(), WebSysDescription(SR.Panel_BackImageUrl) ] public virtual string BackImageUrl { get { if (IsSet(PROP_BACKIMAGEURL)) { return(string)(ViewState[STR_BACKIMAGEURL]); } return String.Empty; } set { if (value == null) { throw new ArgumentNullException("value"); } ViewState[STR_BACKIMAGEURL] = value; SetBit(PROP_BACKIMAGEURL); } } /// <devdoc> /// <para>Gets or sets content direction for the panel.</para> /// </devdoc> [ WebCategory("Appearance"), DefaultValue(""), WebSysDescription(SR.Panel_Direction) ] public virtual ContentDirection Direction { get { if (IsSet(PROP_DIRECTION)) { return (ContentDirection)(ViewState[STR_DIRECTION]); } return ContentDirection.NotSet; } set { if (value < ContentDirection.NotSet || value > ContentDirection.RightToLeft) { throw new ArgumentOutOfRangeException("value"); } ViewState[STR_DIRECTION] = value; SetBit(PROP_DIRECTION); } } /// <devdoc> /// <para>Gets or sets the horizontal alignment of the contents within the panel.</para> /// </devdoc> [ WebCategory("Appearance"), DefaultValue(""), WebSysDescription(SR.Panel_HorizontalAlign) ] public virtual HorizontalAlign HorizontalAlign { get { if (IsSet(PROP_HORIZONTALALIGN)) { return (HorizontalAlign)(ViewState[STR_HORIZONTALALIGN]); } return HorizontalAlign.NotSet; } set { if (value < HorizontalAlign.NotSet || value > HorizontalAlign.Justify) { throw new ArgumentOutOfRangeException("value"); } ViewState[STR_HORIZONTALALIGN] = value; SetBit(PROP_HORIZONTALALIGN); } } /// <devdoc> /// <para>Gets or sets the scrollbar behavior of the panel.</para> /// </devdoc> [ WebCategory("Appearance"), DefaultValue(""), WebSysDescription(SR.Panel_ScrollBars) ] public virtual ScrollBars ScrollBars { get { if (IsSet(PROP_SCROLLBARS)) { return (ScrollBars)(ViewState[STR_SCROLLBARS]); } return ScrollBars.None; } set { if (value < ScrollBars.None || value > ScrollBars.Auto) { throw new ArgumentOutOfRangeException("value"); } ViewState[STR_SCROLLBARS] = value; SetBit(PROP_SCROLLBARS); } } /// <devdoc> /// <para>Gets or sets a value /// indicating whether the content wraps within the panel.</para> /// </devdoc> [ WebCategory("Appearance"), DefaultValue(""), WebSysDescription(SR.Panel_Wrap) ] public virtual bool Wrap { get { if (IsSet(PROP_WRAP)) { return (bool)(ViewState[STR_WRAP]); } return true; } set { ViewState[STR_WRAP] = value; SetBit(PROP_WRAP); } } /// <internalonly/> /// <devdoc> /// <para>Copies non-blank elements from the specified style, overwriting existing /// style elements if necessary.</para> /// </devdoc> public override void CopyFrom(Style s) { if (s != null && !s.IsEmpty) { base.CopyFrom(s); if (s is PanelStyle) { PanelStyle ts = (PanelStyle)s; if (s.RegisteredCssClass.Length != 0) { if (ts.IsSet(PROP_BACKIMAGEURL)) { ViewState.Remove(STR_BACKIMAGEURL); ClearBit(PROP_BACKIMAGEURL); } if (ts.IsSet(PROP_SCROLLBARS)) { ViewState.Remove(STR_SCROLLBARS); ClearBit(PROP_SCROLLBARS); } if (ts.IsSet(PROP_WRAP)) { ViewState.Remove(STR_WRAP); ClearBit(PROP_WRAP); } } else { if (ts.IsSet(PROP_BACKIMAGEURL)) this.BackImageUrl = ts.BackImageUrl; if (ts.IsSet(PROP_SCROLLBARS)) this.ScrollBars = ts.ScrollBars; if (ts.IsSet(PROP_WRAP)) this.Wrap = ts.Wrap; } if (ts.IsSet(PROP_DIRECTION)) this.Direction = ts.Direction; if (ts.IsSet(PROP_HORIZONTALALIGN)) this.HorizontalAlign = ts.HorizontalAlign; } } } /// <internalonly/> /// <devdoc> /// <para>Copies non-blank elements from the specified style, but will not overwrite /// any existing style elements.</para> /// </devdoc> public override void MergeWith(Style s) { if (s != null && !s.IsEmpty) { if (IsEmpty) { // merge into an empty style is equivalent to a copy, // which is more efficient CopyFrom(s); return; } base.MergeWith(s); if (s is PanelStyle) { PanelStyle ts = (PanelStyle)s; // Since we're already copying the registered CSS class in base.MergeWith, we don't // need to any attributes that would be included in that class. if (s.RegisteredCssClass.Length == 0) { if (ts.IsSet(PROP_BACKIMAGEURL) && !this.IsSet(PROP_BACKIMAGEURL)) this.BackImageUrl = ts.BackImageUrl; if (ts.IsSet(PROP_SCROLLBARS) && !this.IsSet(PROP_SCROLLBARS)) this.ScrollBars = ts.ScrollBars; if (ts.IsSet(PROP_WRAP) && !this.IsSet(PROP_WRAP)) this.Wrap = ts.Wrap; } if (ts.IsSet(PROP_DIRECTION) && !this.IsSet(PROP_DIRECTION)) this.Direction = ts.Direction; if (ts.IsSet(PROP_HORIZONTALALIGN) && !this.IsSet(PROP_HORIZONTALALIGN)) this.HorizontalAlign = ts.HorizontalAlign; } } } /// <internalonly/> /// <devdoc> /// <para>Clears out any defined style elements from the state bag.</para> /// </devdoc> public override void Reset() { if (IsSet(PROP_BACKIMAGEURL)) ViewState.Remove(STR_BACKIMAGEURL); if (IsSet(PROP_DIRECTION)) ViewState.Remove(STR_DIRECTION); if (IsSet(PROP_HORIZONTALALIGN)) ViewState.Remove(STR_HORIZONTALALIGN); if (IsSet(PROP_SCROLLBARS)) ViewState.Remove(STR_SCROLLBARS); if (IsSet(PROP_WRAP)) ViewState.Remove(STR_WRAP); base.Reset(); } } }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright 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 Facebook.Unity.Mobile.IOS { using System; using System.Collections.Generic; using System.Linq; internal class IOSFacebook : MobileFacebook { private const string CancelledResponse = "{\"cancelled\":true}"; private bool limitEventUsage; private IIOSWrapper iosWrapper; public IOSFacebook() : this(new IOSWrapper(), new CallbackManager()) { } public IOSFacebook(IIOSWrapper iosWrapper, CallbackManager callbackManager) : base(callbackManager) { this.iosWrapper = iosWrapper; } public enum FBInsightsFlushBehavior { /// <summary> /// The FB insights flush behavior auto. /// </summary> FBInsightsFlushBehaviorAuto, /// <summary> /// The FB insights flush behavior explicit only. /// </summary> FBInsightsFlushBehaviorExplicitOnly, } public override bool LimitEventUsage { get { return this.limitEventUsage; } set { this.limitEventUsage = value; this.iosWrapper.FBAppEventsSetLimitEventUsage(value); } } public override string SDKName { get { return "FBiOSSDK"; } } public override string SDKVersion { get { return this.iosWrapper.FBSdkVersion(); } } public void Init( string appId, bool frictionlessRequests, string iosURLSuffix, HideUnityDelegate hideUnityDelegate, InitDelegate onInitComplete) { base.Init( hideUnityDelegate, onInitComplete); this.iosWrapper.Init( appId, frictionlessRequests, iosURLSuffix, Constants.UnitySDKUserAgentSuffixLegacy); } public override void LogInWithReadPermissions( IEnumerable<string> permissions, FacebookDelegate<ILoginResult> callback) { this.iosWrapper.LogInWithReadPermissions(this.AddCallback(callback), permissions.ToCommaSeparateList()); } public override void LogInWithPublishPermissions( IEnumerable<string> permissions, FacebookDelegate<ILoginResult> callback) { this.iosWrapper.LogInWithPublishPermissions(this.AddCallback(callback), permissions.ToCommaSeparateList()); } public override void LogOut() { base.LogOut(); this.iosWrapper.LogOut(); } public override void AppRequest( string message, OGActionType? actionType, string objectId, IEnumerable<string> to, IEnumerable<object> filters, IEnumerable<string> excludeIds, int? maxRecipients, string data, string title, FacebookDelegate<IAppRequestResult> callback) { this.ValidateAppRequestArgs( message, actionType, objectId, to, filters, excludeIds, maxRecipients, data, title, callback); string mobileFilter = null; if (filters != null && filters.Any()) { mobileFilter = filters.First() as string; } this.iosWrapper.AppRequest( this.AddCallback(callback), message, (actionType != null) ? actionType.ToString() : string.Empty, objectId != null ? objectId : string.Empty, to != null ? to.ToArray() : null, to != null ? to.Count() : 0, mobileFilter != null ? mobileFilter : string.Empty, excludeIds != null ? excludeIds.ToArray() : null, excludeIds != null ? excludeIds.Count() : 0, maxRecipients.HasValue, maxRecipients.HasValue ? maxRecipients.Value : 0, data, title); } public override void AppInvite( Uri appLinkUrl, Uri previewImageUrl, FacebookDelegate<IAppInviteResult> callback) { string appLinkUrlStr = string.Empty; string previewImageUrlStr = string.Empty; if (appLinkUrl != null && !string.IsNullOrEmpty(appLinkUrl.AbsoluteUri)) { appLinkUrlStr = appLinkUrl.AbsoluteUri; } if (previewImageUrl != null && !string.IsNullOrEmpty(previewImageUrl.AbsoluteUri)) { previewImageUrlStr = previewImageUrl.AbsoluteUri; } this.iosWrapper.AppInvite( this.AddCallback(callback), appLinkUrlStr, previewImageUrlStr); } public override void ShareLink( Uri contentURL, string contentTitle, string contentDescription, Uri photoURL, FacebookDelegate<IShareResult> callback) { this.iosWrapper.ShareLink( this.AddCallback(callback), contentURL.AbsoluteUrlOrEmptyString(), contentTitle, contentDescription, photoURL.AbsoluteUrlOrEmptyString()); } public override void FeedShare( string toId, Uri link, string linkName, string linkCaption, string linkDescription, Uri picture, string mediaSource, FacebookDelegate<IShareResult> callback) { string linkStr = link != null ? link.ToString() : string.Empty; string pictureStr = picture != null ? picture.ToString() : string.Empty; this.iosWrapper.FeedShare( this.AddCallback(callback), toId, linkStr, linkName, linkCaption, linkDescription, pictureStr, mediaSource); } public override void GameGroupCreate( string name, string description, string privacy, FacebookDelegate<IGroupCreateResult> callback) { this.iosWrapper.CreateGameGroup(this.AddCallback(callback), name, description, privacy); } public override void GameGroupJoin( string id, FacebookDelegate<IGroupJoinResult> callback) { this.iosWrapper.JoinGameGroup(System.Convert.ToInt32(CallbackManager.AddFacebookDelegate(callback)), id); } public override void AppEventsLogEvent( string logEvent, float? valueToSum, Dictionary<string, object> parameters) { NativeDict dict = MarshallDict(parameters); if (valueToSum.HasValue) { this.iosWrapper.LogAppEvent(logEvent, valueToSum.Value, dict.NumEntries, dict.Keys, dict.Values); } else { this.iosWrapper.LogAppEvent(logEvent, 0.0, dict.NumEntries, dict.Keys, dict.Values); } } public override void AppEventsLogPurchase( float logPurchase, string currency, Dictionary<string, object> parameters) { NativeDict dict = MarshallDict(parameters); this.iosWrapper.LogPurchaseAppEvent(logPurchase, currency, dict.NumEntries, dict.Keys, dict.Values); } public override void ActivateApp(string appId) { // Activate app is logged automatically on ios. } public override void FetchDeferredAppLink(FacebookDelegate<IAppLinkResult> callback) { this.iosWrapper.FetchDeferredAppLink(this.AddCallback(callback)); } public override void GetAppLink( FacebookDelegate<IAppLinkResult> callback) { this.iosWrapper.GetAppLink(System.Convert.ToInt32(CallbackManager.AddFacebookDelegate(callback))); } public override void RefreshCurrentAccessToken( FacebookDelegate<IAccessTokenRefreshResult> callback) { this.iosWrapper.RefreshCurrentAccessToken( System.Convert.ToInt32(CallbackManager.AddFacebookDelegate(callback))); } protected override void SetShareDialogMode(ShareDialogMode mode) { this.iosWrapper.SetShareDialogMode((int)mode); } private static NativeDict MarshallDict(Dictionary<string, object> dict) { NativeDict res = new NativeDict(); if (dict != null && dict.Count > 0) { res.Keys = new string[dict.Count]; res.Values = new string[dict.Count]; res.NumEntries = 0; foreach (KeyValuePair<string, object> kvp in dict) { res.Keys[res.NumEntries] = kvp.Key; res.Values[res.NumEntries] = kvp.Value.ToString(); res.NumEntries++; } } return res; } private static NativeDict MarshallDict(Dictionary<string, string> dict) { NativeDict res = new NativeDict(); if (dict != null && dict.Count > 0) { res.Keys = new string[dict.Count]; res.Values = new string[dict.Count]; res.NumEntries = 0; foreach (KeyValuePair<string, string> kvp in dict) { res.Keys[res.NumEntries] = kvp.Key; res.Values[res.NumEntries] = kvp.Value; res.NumEntries++; } } return res; } private int AddCallback<T>(FacebookDelegate<T> callback) where T : IResult { string asyncId = this.CallbackManager.AddFacebookDelegate(callback); return Convert.ToInt32(asyncId); } private class NativeDict { public NativeDict() { this.NumEntries = 0; this.Keys = null; this.Values = null; } public int NumEntries { get; set; } public string[] Keys { get; set; } public string[] Values { get; set; } } } }
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 JeffBot2BAPI.Areas.HelpPage.ModelDescriptions; using JeffBot2BAPI.Areas.HelpPage.Models; namespace JeffBot2BAPI.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); } } } }
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Threading.Tasks; using NSubstitute; using Octokit.Reactive; using Octokit.Reactive.Internal; using Xunit; namespace Octokit.Tests.Reactive { public class ObservablePullRequestReviewRequestsClientTests { public class TheCtor { [Fact] public void EnsuresNonNullArguments() { Assert.Throws<ArgumentNullException>( () => new ObservablePullRequestReviewRequestsClient(null)); } } public class TheGetAlltMethod { [Fact] public async Task RequestsCorrectUrl() { var gitHubClient = Substitute.For<IGitHubClient>(); var client = new ObservablePullRequestReviewRequestsClient(gitHubClient); client.GetAll("owner", "name", 7); gitHubClient.Received().PullRequest.ReviewRequest.GetAll("owner", "name", 7); } [Fact] public async Task RequestsCorrectUrlWithRepositoryId() { var gitHubClient = Substitute.For<IGitHubClient>(); var client = new ObservablePullRequestReviewRequestsClient(gitHubClient); client.GetAll(42, 7); gitHubClient.Received().PullRequest.ReviewRequest.GetAll(42, 7); } [Fact] public async Task RequestsCorrectUrlWithApiOptions() { var gitHubClient = Substitute.For<IGitHubClient>(); var client = new ObservablePullRequestReviewRequestsClient(gitHubClient); var options = new ApiOptions { StartPage = 1, PageCount = 1, PageSize = 1 }; client.GetAll("owner", "name", 7, options); gitHubClient.Received().PullRequest.ReviewRequest.GetAll("owner", "name", 7, options); } [Fact] public async Task RequestsCorrectUrlWithApiOptionsWithRepositoryId() { var gitHubClient = Substitute.For<IGitHubClient>(); var client = new ObservablePullRequestReviewRequestsClient(gitHubClient); var options = new ApiOptions { StartPage = 1, PageCount = 1, PageSize = 1 }; client.GetAll(42, 7, options); gitHubClient.Received().PullRequest.ReviewRequest.GetAll(42, 7, options); } [Fact] public async Task EnsuresNonNullArguments() { var gitHubClient = Substitute.For<IGitHubClient>(); var client = new ObservablePullRequestReviewRequestsClient(gitHubClient); Assert.Throws<ArgumentNullException>(() => client.GetAll(null, "name", 1)); Assert.Throws<ArgumentNullException>(() => client.GetAll("owner", null, 1)); Assert.Throws<ArgumentNullException>(() => client.GetAll(null, "name", 1, ApiOptions.None)); Assert.Throws<ArgumentNullException>(() => client.GetAll("owner", null, 1, ApiOptions.None)); Assert.Throws<ArgumentNullException>(() => client.GetAll("owner", "name", 1, null)); Assert.Throws<ArgumentException>(() => client.GetAll("", "name", 1)); Assert.Throws<ArgumentException>(() => client.GetAll("owner", "", 1)); Assert.Throws<ArgumentException>(() => client.GetAll("", "name", 1, ApiOptions.None)); Assert.Throws<ArgumentException>(() => client.GetAll("owner", "", 1, ApiOptions.None)); Assert.Throws<ArgumentNullException>(() => client.GetAll(42, 1, null)); } } public class TheCreateMethod { [Fact] public void PostsToCorrectUrl() { var gitHubClient = Substitute.For<IGitHubClient>(); var client = new ObservablePullRequestReviewRequestsClient(gitHubClient); IReadOnlyList<string> fakeReviewers = new List<string> { "zxc", "asd" }; var pullRequestReviewRequest = new PullRequestReviewRequest(fakeReviewers); client.Create("fakeOwner", "fakeRepoName", 13, pullRequestReviewRequest); gitHubClient.Received().PullRequest.ReviewRequest.Create("fakeOwner", "fakeRepoName", 13, pullRequestReviewRequest); } [Fact] public void PostsToCorrectUrlWithRepositoryId() { var gitHubClient = Substitute.For<IGitHubClient>(); var client = new ObservablePullRequestReviewRequestsClient(gitHubClient); IReadOnlyList<string> fakeReviewers = new List<string> { "zxc", "asd" }; var pullRequestReviewRequest = new PullRequestReviewRequest(fakeReviewers); client.Create(42, 13, pullRequestReviewRequest); gitHubClient.Received().PullRequest.ReviewRequest.Create(42, 13, pullRequestReviewRequest); } [Fact] public async Task EnsuresNonNullArguments() { var gitHubClient = Substitute.For<IGitHubClient>(); var client = new ObservablePullRequestReviewRequestsClient(gitHubClient); IReadOnlyList<string> fakeReviewers = new List<string> { "zxc", "asd" }; var pullRequestReviewRequest = new PullRequestReviewRequest(fakeReviewers); Assert.Throws<ArgumentNullException>(() => client.Create(null, "fakeRepoName", 1, pullRequestReviewRequest)); Assert.Throws<ArgumentNullException>(() => client.Create("fakeOwner", null, 1, pullRequestReviewRequest)); Assert.Throws<ArgumentNullException>(() => client.Create("fakeOwner", "fakeRepoName", 1, null)); Assert.Throws<ArgumentNullException>(() => client.Create(42, 1, null)); Assert.Throws<ArgumentException>(() => client.Create("", "fakeRepoName", 1, pullRequestReviewRequest)); Assert.Throws<ArgumentException>(() => client.Create("fakeOwner", "", 1, pullRequestReviewRequest)); } } public class TheDeleteMethod { [Fact] public async Task PostsToCorrectUrl() { var gitHubClient = Substitute.For<IGitHubClient>(); var client = new ObservablePullRequestReviewRequestsClient(gitHubClient); IReadOnlyList<string> fakeReviewers = new List<string> { "zxc", "asd" }; var pullRequestReviewRequest = new PullRequestReviewRequest(fakeReviewers); await client.Delete("owner", "name", 13, pullRequestReviewRequest); gitHubClient.Received().PullRequest.ReviewRequest.Delete("owner", "name", 13, pullRequestReviewRequest); } [Fact] public async Task PostsToCorrectUrlWithRepositoryId() { var gitHubClient = Substitute.For<IGitHubClient>(); var client = new ObservablePullRequestReviewRequestsClient(gitHubClient); IReadOnlyList<string> fakeReviewers = new List<string> { "zxc", "asd" }; var pullRequestReviewRequest = new PullRequestReviewRequest(fakeReviewers); await client.Delete(42, 13, pullRequestReviewRequest); gitHubClient.Received().PullRequest.ReviewRequest.Delete(42, 13, pullRequestReviewRequest); } [Fact] public async Task EnsuresNonNullArguments() { var gitHubClient = Substitute.For<IGitHubClient>(); var client = new ObservablePullRequestReviewRequestsClient(gitHubClient); IReadOnlyList<string> fakeReviewers = new List<string> { "zxc", "asd" }; var pullRequestReviewRequest = new PullRequestReviewRequest(fakeReviewers); Assert.Throws<ArgumentNullException>(() => client.Delete(null, "name", 1, pullRequestReviewRequest)); Assert.Throws<ArgumentNullException>(() => client.Delete("owner", null, 1, pullRequestReviewRequest)); Assert.Throws<ArgumentNullException>(() => client.Delete("owner", "name", 1, null)); Assert.Throws<ArgumentNullException>(() => client.Delete(42, 1, null)); Assert.Throws<ArgumentException>(() => client.Delete("", "name", 1, pullRequestReviewRequest)); Assert.Throws<ArgumentException>(() => client.Delete("owner", "", 1, pullRequestReviewRequest)); } } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.IO; using System.Xml.Serialization; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Interfaces; using OpenMetaverse; namespace OpenSim.Region.Framework.Scenes { /// <summary> /// A new version of the old Channel class, simplified /// </summary> public class TerrainChannel : ITerrainChannel { private readonly bool[,] taint; private double[,] map; private int _revision; public TerrainChannel() { map = new double[Constants.RegionSize, Constants.RegionSize]; taint = new bool[Constants.RegionSize / 16,Constants.RegionSize / 16]; int x; for (x = 0; x < Constants.RegionSize; x++) { int y; for (y = 0; y < Constants.RegionSize; y++) { map[x, y] = TerrainUtil.PerlinNoise2D(x, y, 2, 0.125) * 10; double spherFacA = TerrainUtil.SphericalFactor(x, y, Constants.RegionSize / 2.0, Constants.RegionSize / 2.0, 50) * 0.01; double spherFacB = TerrainUtil.SphericalFactor(x, y, Constants.RegionSize / 2.0, Constants.RegionSize / 2.0, 100) * 0.001; if (map[x, y] < spherFacA) map[x, y] = spherFacA; if (map[x, y] < spherFacB) map[x, y] = spherFacB; } } } public TerrainChannel(double[,] import) { map = import; taint = new bool[import.GetLength(0),import.GetLength(1)]; } public TerrainChannel(double[,] import, int rev) : this(import) { _revision = rev; } public TerrainChannel(bool createMap) { if (createMap) { map = new double[Constants.RegionSize,Constants.RegionSize]; taint = new bool[Constants.RegionSize / 16,Constants.RegionSize / 16]; } } public TerrainChannel(int w, int h) { map = new double[w,h]; taint = new bool[w / 16,h / 16]; } #region ITerrainChannel Members public int Width { get { return map.GetLength(0); } } public int Height { get { return map.GetLength(1); } } public ITerrainChannel MakeCopy() { TerrainChannel copy = new TerrainChannel(false); copy.map = (double[,]) map.Clone(); return copy; } public float[] GetFloatsSerialized() { // Move the member variables into local variables, calling // member variables 256*256 times gets expensive int w = Width; int h = Height; float[] heights = new float[w * h]; int i, j; // map coordinates int idx = 0; // index into serialized array for (i = 0; i < h; i++) { for (j = 0; j < w; j++) { heights[idx++] = (float)map[j, i]; } } return heights; } public double[,] GetDoubles() { return map; } public double this[int x, int y] { get { if (x < map.GetLength(0) && y < map.GetLength(1) && x >= 0 && y >= 0) { return map[x, y]; } else { return 0.0; } } set { // Will "fix" terrain hole problems. Although not fantastically. if (Double.IsNaN(value) || Double.IsInfinity(value)) return; if (map[x, y] != value) { taint[x / 16, y / 16] = true; map[x, y] = value; } } } public int RevisionNumber { get { return _revision; } } public bool Tainted(int x, int y) { if (taint[x / 16, y / 16]) { taint[x / 16, y / 16] = false; return true; } return false; } #endregion public TerrainChannel Copy() { TerrainChannel copy = new TerrainChannel(false); copy.map = (double[,]) map.Clone(); return copy; } public string SaveToXmlString() { XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = Encoding.UTF8; using (StringWriter sw = new StringWriter()) { using (XmlWriter writer = XmlWriter.Create(sw, settings)) { WriteXml(writer); } string output = sw.ToString(); return output; } } private void WriteXml(XmlWriter writer) { writer.WriteStartElement(String.Empty, "TerrainMap", String.Empty); ToXml(writer); writer.WriteEndElement(); } public void LoadFromXmlString(string data) { StringReader sr = new StringReader(data); XmlTextReader reader = new XmlTextReader(sr); reader.Read(); ReadXml(reader); reader.Close(); sr.Close(); } private void ReadXml(XmlReader reader) { reader.ReadStartElement("TerrainMap"); FromXml(reader); } private void ToXml(XmlWriter xmlWriter) { float[] mapData = GetFloatsSerialized(); byte[] buffer = new byte[mapData.Length * 4]; for (int i = 0; i < mapData.Length; i++) { byte[] value = BitConverter.GetBytes(mapData[i]); Array.Copy(value, 0, buffer, (i * 4), 4); } XmlSerializer serializer = new XmlSerializer(typeof(byte[])); serializer.Serialize(xmlWriter, buffer); } private void FromXml(XmlReader xmlReader) { XmlSerializer serializer = new XmlSerializer(typeof(byte[])); byte[] dataArray = (byte[])serializer.Deserialize(xmlReader); int index = 0; for (int y = 0; y < Height; y++) { for (int x = 0; x < Width; x++) { float value; value = BitConverter.ToSingle(dataArray, index); index += 4; this[x, y] = (double)value; } } } /// <summary> /// Get the raw height at the given x/y coordinates on 1m boundary. /// </summary> /// <param name="x">X coordinate</param> /// <param name="y">Y coordinate</param> /// <returns></returns> public float GetRawHeightAt(int x, int y) { return (float)(map[x, y]); } public float GetRawHeightAt(uint x, uint y) { return (float)(map[x, y]); } public double GetRawHeightAt(Vector3 point) { return map[(int)point.X, (int)point.Y]; } /// <summary> /// Get the height of the terrain at given horizontal coordinates. /// </summary> /// <param name="xPos">X coordinate</param> /// <param name="yPos">Y coordinate</param> /// <returns>Height at given coordinates</returns> public float CalculateHeightAt(float xPos, float yPos) { if (!Util.IsValidRegionXY(xPos, yPos)) return 0.0f; int x = (int)xPos; int y = (int)yPos; float xOffset = xPos - (float)x; float yOffset = yPos - (float)y; if ((xOffset == 0.0f) && (yOffset == 0.0f)) return (float)(map[x, y]); // optimize the exact heightmap entry case int xPlusOne = x + 1; int yPlusOne = y + 1; // Check for edge cases (literally) if ((xPlusOne > Constants.RegionSize - 1) || (yPlusOne > Constants.RegionSize - 1)) return (float)map[x, y]; if (xPlusOne > Constants.RegionSize - 1) { if (yPlusOne > Constants.RegionSize - 1) return (float)map[x, y]; // upper right corner // Simpler linear interpolation between 2 points along y (right map edge) return (float)((map[x, yPlusOne] - map[x, y]) * yOffset + map[x, y]); } if (yPlusOne > Constants.RegionSize - 1) { // Simpler linear interpolation between 2 points along x (top map edge) return (float)((map[xPlusOne, y] - map[x, y]) * xOffset + map[x, y]); } // LL terrain triangles are divided like [/] rather than [\] ... // Vertex/triangle layout is: Z2 - Z3 // | / | // Z0 - Z1 float triZ0 = (float)(map[x, y]); float triZ1 = (float)(map[xPlusOne, y]); float triZ2 = (float)(map[x, yPlusOne]); float triZ3 = (float)(map[xPlusOne, yPlusOne]); float height = 0.0f; if ((xOffset + (1.0 - yOffset)) < 1.0f) { // Upper left (NW) triangle // So relative to Z2 corner height = triZ2; height += (triZ3 - triZ2) * xOffset; height += (triZ0 - triZ2) * (1.0f - yOffset); } else { // Lower right (SE) triangle // So relative to Z1 corner height = triZ1; height += (triZ0 - triZ1) * (1.0f - xOffset); height += (triZ3 - triZ1) * yOffset; } return height; } /// <summary> /// Get the height of the terrain at given horizontal coordinates. /// Uses a 4-point bilinear calculation to smooth the terrain based /// on all 4 nearest terrain heightmap vertices. /// </summary> /// <param name="xPos">X coordinate</param> /// <param name="yPos">Y coordinate</param> /// <returns>Height at given coordinates</returns> public float Calculate4PointHeightAt(float xPos, float yPos) { if (!Util.IsValidRegionXY(xPos, yPos)) return 0.0f; int x = (int)xPos; int y = (int)yPos; float xOffset = xPos - (float)x; float yOffset = yPos - (float)y; if ((xOffset == 0.0f) && (yOffset == 0.0f)) return (float)(map[x, y]); // optimize the exact heightmap entry case int xPlusOne = x + 1; int yPlusOne = y + 1; // Check for edge cases (literally) if ((xPlusOne > Constants.RegionSize - 1) || (yPlusOne > Constants.RegionSize - 1)) return (float)map[x, y]; if (xPlusOne > Constants.RegionSize - 1) { if (yPlusOne > Constants.RegionSize - 1) return (float)map[x, y]; // upper right corner // Simpler linear interpolation between 2 points along y (right map edge) return (float)((map[x, yPlusOne] - map[x, y]) * yOffset + map[x, y]); } if (yPlusOne > Constants.RegionSize - 1) { // Simpler linear interpolation between 2 points along x (top map edge) return (float)((map[xPlusOne, y] - map[x, y]) * xOffset + map[x, y]); } // Inside the map square: use 4-point bilinear interpolation // f(x,y) = f(0,0) * (1-x)(1-y) + f(1,0) * x(1-y) + f(0,1) * (1-x)y + f(1,1) * xy float f00 = GetRawHeightAt(x, y); float f01 = GetRawHeightAt(x, yPlusOne); float f10 = GetRawHeightAt(xPlusOne, y); float f11 = GetRawHeightAt(xPlusOne, yPlusOne); float lowest = f00; lowest = Math.Min(lowest, f01); lowest = Math.Min(lowest, f10); lowest = Math.Min(lowest, f11); f00 -= lowest; f01 -= lowest; f10 -= lowest; f11 -= lowest; float z = (float)( f00 * (1.0f - xOffset) * (1.0f - yOffset) + f01 * xOffset * (1.0f - yOffset) + f10 * (1.0f - xOffset) * yOffset + f11 * xOffset * yOffset ); return lowest + z; } // Pass the deltas between point1 and the corner and point2 and the corner private Vector3 TriangleNormal(Vector3 delta1, Vector3 delta2) { Vector3 normal; if (delta1 == Vector3.Zero) normal = new Vector3(0.0f, delta2.Y * -delta1.Z, 1.0f); else if (delta2 == Vector3.Zero) normal = new Vector3(delta1.X * -delta1.Z, 0.0f, 1.0f); else { // The cross product is the slope normal. normal = new Vector3( (delta1.Y * delta2.Z) - (delta1.Z * delta2.Y), (delta1.Z * delta2.X) - (delta1.X * delta2.Z), (delta1.X * delta2.Y) - (delta1.Y * delta2.X) ); } return normal; } public Vector3 NormalToSlope(Vector3 normal) { Vector3 slope = new Vector3(normal); if (slope.Z == 0.0f) slope.Z = 1.0f; else slope.Z = ((normal.X * normal.X) + (normal.Y * normal.Y)) / (-1.0f * normal.Z); return slope; } // Pass the deltas between point1 and the corner and point2 and the corner private Vector3 TriangleSlope(Vector3 delta1, Vector3 delta2) { return NormalToSlope(TriangleNormal(delta1, delta2)); } public Vector3 CalculateNormalAt(float xPos, float yPos) // 3-point triangle surface normal { if (xPos < 0 || yPos < 0 || xPos >= Constants.RegionSize || yPos >= Constants.RegionSize) return new Vector3(0.00000f, 0.00000f, 1.00000f); uint x = (uint)xPos; uint y = (uint)yPos; uint xPlusOne = x + 1; uint yPlusOne = y + 1; if (xPlusOne > Constants.RegionSize - 1) xPlusOne = Constants.RegionSize - 1; if (yPlusOne > Constants.RegionSize - 1) yPlusOne = Constants.RegionSize - 1; Vector3 P0 = new Vector3(x, y, (float)map[x, y]); Vector3 P1 = new Vector3(xPlusOne, y, (float)map[xPlusOne, y]); Vector3 P2 = new Vector3(x, yPlusOne, (float)map[x, yPlusOne]); Vector3 P3 = new Vector3(xPlusOne, yPlusOne, (float)map[xPlusOne, yPlusOne]); float xOffset = xPos - (float)x; float yOffset = yPos - (float)y; Vector3 normal; if ((xOffset + (1.0 - yOffset)) < 1.0f) normal = TriangleNormal(P2 - P3, P0 - P2); // Upper left (NW) triangle else normal = TriangleNormal(P0 - P1, P1 - P3); // Lower right (SE) triangle return normal; } public Vector3 CalculateSlopeAt(float xPos, float yPos) // 3-point triangle slope { return NormalToSlope(CalculateNormalAt(xPos, yPos)); } public Vector3 Calculate4PointNormalAt(float xPos, float yPos) { if (!Util.IsValidRegionXY(xPos, yPos)) return new Vector3(0.00000f, 0.00000f, 1.00000f); uint x = (uint)xPos; uint y = (uint)yPos; uint xPlusOne = x + 1; uint yPlusOne = y + 1; if (xPlusOne > Constants.RegionSize - 1) xPlusOne = Constants.RegionSize - 1; if (yPlusOne > Constants.RegionSize - 1) yPlusOne = Constants.RegionSize - 1; Vector3 P0 = new Vector3(x, y, (float)map[x, y]); Vector3 P1 = new Vector3(xPlusOne, y, (float)map[xPlusOne, y]); Vector3 P2 = new Vector3(x, yPlusOne, (float)map[x, yPlusOne]); Vector3 P3 = new Vector3(xPlusOne, yPlusOne, (float)map[xPlusOne, yPlusOne]); // LL terrain triangles are divided like [/] rather than [\] ... // Vertex/triangle layout is: P2 - P3 // | / | // P0 - P1 Vector3 normal0 = TriangleNormal(P2 - P3, P0 - P2); // larger values first, so slope points down Vector3 normal1 = TriangleNormal(P1 - P0, P3 - P1); // and counter-clockwise edge order Vector3 normal = (normal0 + normal1) / 2.0f; if ((normal.X == 0.0f) && (normal.Y == 0.0f)) { // The two triangles are completely symmetric and will result in a vertical slope when averaged. // i.e. the location is on one side of a perfectly balanced ridge or valley. // So use only the triangle the location is in, so that it points into the valley or down the ridge. float xOffset = xPos - x; float yOffset = yPos - y; if ((xOffset + (1.0 - yOffset)) <= 1.0f) { // Upper left (NW) triangle normal = normal0; } else { // Lower right (SE) triangle normal = normal1; } } normal.Normalize(); return normal; } public Vector3 Calculate4PointSlopeAt(float xPos, float yPos) // 3-point triangle slope { return NormalToSlope(Calculate4PointNormalAt(xPos, yPos)); } public int IncrementRevisionNumber() { return ++_revision; } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the PnCategoria class. /// </summary> [Serializable] public partial class PnCategoriaCollection : ActiveList<PnCategoria, PnCategoriaCollection> { public PnCategoriaCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>PnCategoriaCollection</returns> public PnCategoriaCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { PnCategoria o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the PN_categorias table. /// </summary> [Serializable] public partial class PnCategoria : ActiveRecord<PnCategoria>, IActiveRecord { #region .ctors and Default Settings public PnCategoria() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public PnCategoria(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public PnCategoria(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public PnCategoria(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("PN_categorias", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdCategoria = new TableSchema.TableColumn(schema); colvarIdCategoria.ColumnName = "id_categoria"; colvarIdCategoria.DataType = DbType.Int32; colvarIdCategoria.MaxLength = 0; colvarIdCategoria.AutoIncrement = true; colvarIdCategoria.IsNullable = false; colvarIdCategoria.IsPrimaryKey = true; colvarIdCategoria.IsForeignKey = false; colvarIdCategoria.IsReadOnly = false; colvarIdCategoria.DefaultSetting = @""; colvarIdCategoria.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdCategoria); TableSchema.TableColumn colvarCategoria = new TableSchema.TableColumn(schema); colvarCategoria.ColumnName = "categoria"; colvarCategoria.DataType = DbType.AnsiString; colvarCategoria.MaxLength = 50; colvarCategoria.AutoIncrement = false; colvarCategoria.IsNullable = true; colvarCategoria.IsPrimaryKey = false; colvarCategoria.IsForeignKey = false; colvarCategoria.IsReadOnly = false; colvarCategoria.DefaultSetting = @""; colvarCategoria.ForeignKeyTableName = ""; schema.Columns.Add(colvarCategoria); TableSchema.TableColumn colvarTipoFicha = new TableSchema.TableColumn(schema); colvarTipoFicha.ColumnName = "tipo_ficha"; colvarTipoFicha.DataType = DbType.AnsiStringFixedLength; colvarTipoFicha.MaxLength = 1; colvarTipoFicha.AutoIncrement = false; colvarTipoFicha.IsNullable = true; colvarTipoFicha.IsPrimaryKey = false; colvarTipoFicha.IsForeignKey = false; colvarTipoFicha.IsReadOnly = false; colvarTipoFicha.DefaultSetting = @""; colvarTipoFicha.ForeignKeyTableName = ""; schema.Columns.Add(colvarTipoFicha); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("PN_categorias",schema); } } #endregion #region Props [XmlAttribute("IdCategoria")] [Bindable(true)] public int IdCategoria { get { return GetColumnValue<int>(Columns.IdCategoria); } set { SetColumnValue(Columns.IdCategoria, value); } } [XmlAttribute("Categoria")] [Bindable(true)] public string Categoria { get { return GetColumnValue<string>(Columns.Categoria); } set { SetColumnValue(Columns.Categoria, value); } } [XmlAttribute("TipoFicha")] [Bindable(true)] public string TipoFicha { get { return GetColumnValue<string>(Columns.TipoFicha); } set { SetColumnValue(Columns.TipoFicha, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varCategoria,string varTipoFicha) { PnCategoria item = new PnCategoria(); item.Categoria = varCategoria; item.TipoFicha = varTipoFicha; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdCategoria,string varCategoria,string varTipoFicha) { PnCategoria item = new PnCategoria(); item.IdCategoria = varIdCategoria; item.Categoria = varCategoria; item.TipoFicha = varTipoFicha; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdCategoriaColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn CategoriaColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn TipoFichaColumn { get { return Schema.Columns[2]; } } #endregion #region Columns Struct public struct Columns { public static string IdCategoria = @"id_categoria"; public static string Categoria = @"categoria"; public static string TipoFicha = @"tipo_ficha"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
/* * 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 OpenMetaverse; using OpenMetaverse.StructuredData; using System.Collections.Generic; namespace OpenSim.Framework { public struct WearableItem { public UUID AssetID; public UUID ItemID; public WearableItem(UUID itemID, UUID assetID) { ItemID = itemID; AssetID = assetID; } } public class AvatarWearable { public static readonly int ALPHA = 13; // these are guessed at by the list here - // http://wiki.secondlife.com/wiki/Avatar_Appearance. We'll // correct them over time for when were are wrong. public static readonly int BODY = 0; public static readonly UUID DEFAULT_BODY_ASSET = new UUID("66c41e39-38f9-f75a-024e-585989bfab73"); public static readonly UUID DEFAULT_BODY_ITEM = new UUID("66c41e39-38f9-f75a-024e-585989bfaba9"); public static readonly UUID DEFAULT_HAIR_ASSET = new UUID("d342e6c0-b9d2-11dc-95ff-0800200c9a66"); public static readonly UUID DEFAULT_HAIR_ITEM = new UUID("d342e6c1-b9d2-11dc-95ff-0800200c9a66"); public static readonly UUID DEFAULT_PANTS_ASSET = new UUID("00000000-38f9-1111-024e-222222111120"); public static readonly UUID DEFAULT_PANTS_ITEM = new UUID("77c41e39-38f9-f75a-0000-5859892f1111"); public static readonly UUID DEFAULT_SHIRT_ASSET = new UUID("00000000-38f9-1111-024e-222222111110"); public static readonly UUID DEFAULT_SHIRT_ITEM = new UUID("77c41e39-38f9-f75a-0000-585989bf0000"); public static readonly UUID DEFAULT_SKIN_ASSET = new UUID("77c41e39-38f9-f75a-024e-585989bbabbb"); public static readonly UUID DEFAULT_SKIN_ITEM = new UUID("77c41e39-38f9-f75a-024e-585989bfabc9"); public static readonly int EYES = 3; public static readonly int GLOVES = 9; public static readonly int HAIR = 2; public static readonly int JACKET = 8; public static readonly int MAX_WEARABLES = 15; public static readonly int PANTS = 5; public static readonly int SHIRT = 4; public static readonly int SHOES = 6; public static readonly int SKIN = 1; public static readonly int SKIRT = 12; public static readonly int SOCKS = 7; public static readonly int TATTOO = 14; public static readonly int UNDERPANTS = 11; public static readonly int UNDERSHIRT = 10; // public static readonly UUID DEFAULT_ALPHA_ITEM = new UUID("bfb9923c-4838-4d2d-bf07-608c5b1165c8"); // public static readonly UUID DEFAULT_ALPHA_ASSET = new UUID("1578a2b1-5179-4b53-b618-fe00ca5a5594"); // public static readonly UUID DEFAULT_TATTOO_ITEM = new UUID("c47e22bd-3021-4ba4-82aa-2b5cb34d35e1"); // public static readonly UUID DEFAULT_TATTOO_ASSET = new UUID("00000000-0000-2222-3333-100000001007"); protected List<UUID> m_ids = new List<UUID>(); protected Dictionary<UUID, UUID> m_items = new Dictionary<UUID, UUID>(); public AvatarWearable() { } public AvatarWearable(UUID itemID, UUID assetID) { Wear(itemID, assetID); } public AvatarWearable(OSDArray args) { Unpack(args); } public static AvatarWearable[] DefaultWearables { get { AvatarWearable[] defaultWearables = new AvatarWearable[MAX_WEARABLES]; //should be 15 of these for (int i = 0; i < MAX_WEARABLES; i++) { defaultWearables[i] = new AvatarWearable(); } // Body defaultWearables[BODY].Add(DEFAULT_BODY_ITEM, DEFAULT_BODY_ASSET); // Hair defaultWearables[HAIR].Add(DEFAULT_HAIR_ITEM, DEFAULT_HAIR_ASSET); // Skin defaultWearables[SKIN].Add(DEFAULT_SKIN_ITEM, DEFAULT_SKIN_ASSET); // Shirt defaultWearables[SHIRT].Add(DEFAULT_SHIRT_ITEM, DEFAULT_SHIRT_ASSET); // Pants defaultWearables[PANTS].Add(DEFAULT_PANTS_ITEM, DEFAULT_PANTS_ASSET); // // Alpha // defaultWearables[ALPHA].Add(DEFAULT_ALPHA_ITEM, DEFAULT_ALPHA_ASSET); // // Tattoo // defaultWearables[TATTOO].Add(DEFAULT_TATTOO_ITEM, DEFAULT_TATTOO_ASSET); return defaultWearables; } } public int Count { get { return m_ids.Count; } } public WearableItem this[int idx] { get { if (idx >= m_ids.Count || idx < 0) return new WearableItem(UUID.Zero, UUID.Zero); return new WearableItem(m_ids[idx], m_items[m_ids[idx]]); } } public void Add(UUID itemID, UUID assetID) { if (itemID == UUID.Zero) return; if (m_items.ContainsKey(itemID)) { m_items[itemID] = assetID; return; } if (m_ids.Count >= 5) return; m_ids.Add(itemID); m_items[itemID] = assetID; } public void Clear() { m_ids.Clear(); m_items.Clear(); } public UUID GetAsset(UUID itemID) { if (!m_items.ContainsKey(itemID)) return UUID.Zero; return m_items[itemID]; } public OSD Pack() { OSDArray wearlist = new OSDArray(); foreach (UUID id in m_ids) { OSDMap weardata = new OSDMap(); weardata["item"] = OSD.FromUUID(id); weardata["asset"] = OSD.FromUUID(m_items[id]); wearlist.Add(weardata); } return wearlist; } public void RemoveAsset(UUID assetID) { UUID itemID = UUID.Zero; foreach (KeyValuePair<UUID, UUID> kvp in m_items) { if (kvp.Value == assetID) { itemID = kvp.Key; break; } } if (itemID != UUID.Zero) { m_ids.Remove(itemID); m_items.Remove(itemID); } } public void RemoveItem(UUID itemID) { if (m_items.ContainsKey(itemID)) { m_ids.Remove(itemID); m_items.Remove(itemID); } } public void Unpack(OSDArray args) { Clear(); foreach (OSDMap weardata in args) { Add(weardata["item"].AsUUID(), weardata["asset"].AsUUID()); } } public void Wear(WearableItem item) { Wear(item.ItemID, item.AssetID); } public void Wear(UUID itemID, UUID assetID) { Clear(); Add(itemID, assetID); } } }
//---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------------------- namespace System.ServiceModel.Channels { using System.Runtime; using System.ServiceModel; using System.ServiceModel.Security; using System.Xml; sealed class CreateSequence : BodyWriter { AddressingVersion addressingVersion; IClientReliableChannelBinder binder; UniqueId offerIdentifier; bool ordered; ReliableMessagingVersion reliableMessagingVersion; CreateSequence() : base(true) { } public CreateSequence(AddressingVersion addressingVersion, ReliableMessagingVersion reliableMessagingVersion, bool ordered, IClientReliableChannelBinder binder, UniqueId offerIdentifier) : base(true) { this.addressingVersion = addressingVersion; this.reliableMessagingVersion = reliableMessagingVersion; this.ordered = ordered; this.binder = binder; this.offerIdentifier = offerIdentifier; } public static CreateSequenceInfo Create(MessageVersion messageVersion, ReliableMessagingVersion reliableMessagingVersion, ISecureConversationSession securitySession, XmlDictionaryReader reader) { if (reader == null) { Fx.Assert("Argument reader cannot be null."); } try { CreateSequenceInfo info = new CreateSequenceInfo(); WsrmFeb2005Dictionary wsrmFeb2005Dictionary = XD.WsrmFeb2005Dictionary; XmlDictionaryString wsrmNs = WsrmIndex.GetNamespace(reliableMessagingVersion); reader.ReadStartElement(wsrmFeb2005Dictionary.CreateSequence, wsrmNs); info.AcksTo = EndpointAddress.ReadFrom(messageVersion.Addressing, reader, wsrmFeb2005Dictionary.AcksTo, wsrmNs); if (reader.IsStartElement(wsrmFeb2005Dictionary.Expires, wsrmNs)) { info.Expires = reader.ReadElementContentAsTimeSpan(); } if (reader.IsStartElement(wsrmFeb2005Dictionary.Offer, wsrmNs)) { reader.ReadStartElement(); reader.ReadStartElement(wsrmFeb2005Dictionary.Identifier, wsrmNs); info.OfferIdentifier = reader.ReadContentAsUniqueId(); reader.ReadEndElement(); bool wsrm11 = reliableMessagingVersion == ReliableMessagingVersion.WSReliableMessaging11; Wsrm11Dictionary wsrm11Dictionary = wsrm11 ? DXD.Wsrm11Dictionary : null; if (wsrm11) { EndpointAddress endpoint = EndpointAddress.ReadFrom(messageVersion.Addressing, reader, wsrm11Dictionary.Endpoint, wsrmNs); if (endpoint.Uri != info.AcksTo.Uri) { string reason = SR.GetString(SR.CSRefusedAcksToMustEqualEndpoint); Message faultReply = WsrmUtilities.CreateCSRefusedProtocolFault(messageVersion, reliableMessagingVersion, reason); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(WsrmMessageInfo.CreateInternalFaultException(faultReply, reason, new ProtocolException(reason))); } } if (reader.IsStartElement(wsrmFeb2005Dictionary.Expires, wsrmNs)) { info.OfferExpires = reader.ReadElementContentAsTimeSpan(); } if (wsrm11) { if (reader.IsStartElement(wsrm11Dictionary.IncompleteSequenceBehavior, wsrmNs)) { string incompleteSequenceBehavior = reader.ReadElementContentAsString(); if ((incompleteSequenceBehavior != Wsrm11Strings.DiscardEntireSequence) && (incompleteSequenceBehavior != Wsrm11Strings.DiscardFollowingFirstGap) && (incompleteSequenceBehavior != Wsrm11Strings.NoDiscard)) { string reason = SR.GetString(SR.CSRefusedInvalidIncompleteSequenceBehavior); Message faultReply = WsrmUtilities.CreateCSRefusedProtocolFault(messageVersion, reliableMessagingVersion, reason); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( WsrmMessageInfo.CreateInternalFaultException(faultReply, reason, new ProtocolException(reason))); } // Otherwise ignore the value. } } while (reader.IsStartElement()) { reader.Skip(); } reader.ReadEndElement(); } // Check for security only if we expect a soap security session. if (securitySession != null) { bool hasValidToken = false; // Since the security element is amongst the extensible elements (i.e. there is no // gaurantee of ordering or placement), a loop is required to attempt to parse the // security element. while (reader.IsStartElement()) { if (securitySession.TryReadSessionTokenIdentifier(reader)) { hasValidToken = true; break; } reader.Skip(); } if (!hasValidToken) { string reason = SR.GetString(SR.CSRefusedRequiredSecurityElementMissing); Message faultReply = WsrmUtilities.CreateCSRefusedProtocolFault(messageVersion, reliableMessagingVersion, reason); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(WsrmMessageInfo.CreateInternalFaultException(faultReply, reason, new ProtocolException(reason))); } } while (reader.IsStartElement()) { reader.Skip(); } reader.ReadEndElement(); if (reader.IsStartElement()) { string reason = SR.GetString(SR.CSRefusedUnexpectedElementAtEndOfCSMessage); Message faultReply = WsrmUtilities.CreateCSRefusedProtocolFault(messageVersion, reliableMessagingVersion, reason); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(WsrmMessageInfo.CreateInternalFaultException(faultReply, reason, new ProtocolException(reason))); } return info; } catch (XmlException e) { string reason = SR.GetString(SR.CouldNotParseWithAction, WsrmIndex.GetCreateSequenceActionString(reliableMessagingVersion)); Message faultReply = WsrmUtilities.CreateCSRefusedProtocolFault(messageVersion, reliableMessagingVersion, reason); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(WsrmMessageInfo.CreateInternalFaultException(faultReply, reason, new ProtocolException(reason, e))); } } protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { WsrmFeb2005Dictionary wsrmFeb2005Dictionary = XD.WsrmFeb2005Dictionary; XmlDictionaryString wsrmNs = WsrmIndex.GetNamespace(this.reliableMessagingVersion); writer.WriteStartElement(wsrmFeb2005Dictionary.CreateSequence, wsrmNs); EndpointAddress localAddress = this.binder.LocalAddress; localAddress.WriteTo(this.addressingVersion, writer, wsrmFeb2005Dictionary.AcksTo, wsrmNs); if (this.offerIdentifier != null) { writer.WriteStartElement(wsrmFeb2005Dictionary.Offer, wsrmNs); writer.WriteStartElement(wsrmFeb2005Dictionary.Identifier, wsrmNs); writer.WriteValue(this.offerIdentifier); writer.WriteEndElement(); if (this.reliableMessagingVersion == ReliableMessagingVersion.WSReliableMessaging11) { Wsrm11Dictionary wsrm11Dictionary = DXD.Wsrm11Dictionary; localAddress.WriteTo(this.addressingVersion, writer, wsrm11Dictionary.Endpoint, wsrmNs); writer.WriteStartElement(wsrm11Dictionary.IncompleteSequenceBehavior, wsrmNs); writer.WriteValue( this.ordered ? wsrm11Dictionary.DiscardFollowingFirstGap : wsrm11Dictionary.NoDiscard); writer.WriteEndElement(); } writer.WriteEndElement(); } ISecureConversationSession securitySession = this.binder.GetInnerSession() as ISecureConversationSession; if (securitySession != null) securitySession.WriteSessionTokenIdentifier(writer); writer.WriteEndElement(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Internal.Text; using Internal.TypeSystem; using Debug = System.Diagnostics.Debug; namespace ILCompiler.DependencyAnalysis { public enum ReadyToRunHelperId { Invalid, NewHelper, NewArr1, VirtualCall, IsInstanceOf, CastClass, GetNonGCStaticBase, GetGCStaticBase, GetThreadStaticBase, DelegateCtor, ResolveVirtualFunction, // The following helpers are used for generic lookups only TypeHandle, NecessaryTypeHandle, MethodHandle, FieldHandle, MethodDictionary, MethodEntry, VirtualDispatchCell, DefaultConstructor, } public partial class ReadyToRunHelperNode : AssemblyStubNode, INodeWithDebugInfo { private ReadyToRunHelperId _id; private Object _target; public ReadyToRunHelperNode(NodeFactory factory, ReadyToRunHelperId id, Object target) { _id = id; _target = target; switch (id) { case ReadyToRunHelperId.NewHelper: case ReadyToRunHelperId.NewArr1: { // Make sure that if the EEType can't be generated, we throw the exception now. // This way we can fail generating code for the method that references the EEType // and (depending on the policy), we could avoid scraping the entire compilation. TypeDesc type = (TypeDesc)target; factory.ConstructedTypeSymbol(type); } break; case ReadyToRunHelperId.IsInstanceOf: case ReadyToRunHelperId.CastClass: { // Make sure that if the EEType can't be generated, we throw the exception now. // This way we can fail generating code for the method that references the EEType // and (depending on the policy), we could avoid scraping the entire compilation. TypeDesc type = (TypeDesc)target; factory.NecessaryTypeSymbol(type); Debug.Assert(!type.IsNullable, "Nullable needs to be unwrapped"); } break; case ReadyToRunHelperId.GetNonGCStaticBase: case ReadyToRunHelperId.GetGCStaticBase: case ReadyToRunHelperId.GetThreadStaticBase: { // Make sure we can compute static field layout now so we can fail early DefType defType = (DefType)target; defType.ComputeStaticFieldLayout(StaticLayoutKind.StaticRegionSizesAndFields); } break; case ReadyToRunHelperId.VirtualCall: { // Make sure we aren't trying to callvirt Object.Finalize MethodDesc method = (MethodDesc)target; if (method.IsFinalizer) ThrowHelper.ThrowInvalidProgramException(ExceptionStringID.InvalidProgramCallVirtFinalize, method); } break; } } protected override bool IsVisibleFromManagedCode => false; protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler); public ReadyToRunHelperId Id => _id; public Object Target => _target; public override void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { switch (_id) { case ReadyToRunHelperId.NewHelper: sb.Append("__NewHelper_").Append(nameMangler.GetMangledTypeName((TypeDesc)_target)); break; case ReadyToRunHelperId.NewArr1: sb.Append("__NewArr1_").Append(nameMangler.GetMangledTypeName((TypeDesc)_target)); break; case ReadyToRunHelperId.VirtualCall: sb.Append("__VirtualCall_").Append(nameMangler.GetMangledMethodName((MethodDesc)_target)); break; case ReadyToRunHelperId.IsInstanceOf: sb.Append("__IsInstanceOf_").Append(nameMangler.GetMangledTypeName((TypeDesc)_target)); break; case ReadyToRunHelperId.CastClass: sb.Append("__CastClass_").Append(nameMangler.GetMangledTypeName((TypeDesc)_target)); break; case ReadyToRunHelperId.GetNonGCStaticBase: sb.Append("__GetNonGCStaticBase_").Append(nameMangler.GetMangledTypeName((TypeDesc)_target)); break; case ReadyToRunHelperId.GetGCStaticBase: sb.Append("__GetGCStaticBase_").Append(nameMangler.GetMangledTypeName((TypeDesc)_target)); break; case ReadyToRunHelperId.GetThreadStaticBase: sb.Append("__GetThreadStaticBase_").Append(nameMangler.GetMangledTypeName((TypeDesc)_target)); break; case ReadyToRunHelperId.DelegateCtor: ((DelegateCreationInfo)_target).AppendMangledName(nameMangler, sb); break; case ReadyToRunHelperId.ResolveVirtualFunction: sb.Append("__ResolveVirtualFunction_"); sb.Append(nameMangler.GetMangledMethodName((MethodDesc)_target)); break; default: throw new NotImplementedException(); } } public override bool IsShareable => true; protected override DependencyList ComputeNonRelocationBasedDependencies(NodeFactory factory) { if (_id == ReadyToRunHelperId.VirtualCall || _id == ReadyToRunHelperId.ResolveVirtualFunction) { var targetMethod = (MethodDesc)_target; DependencyList dependencyList = new DependencyList(); #if !SUPPORT_JIT factory.MetadataManager.GetDependenciesDueToVirtualMethodReflectability(ref dependencyList, factory, targetMethod); if (!factory.VTable(targetMethod.OwningType).HasFixedSlots) { dependencyList.Add(factory.VirtualMethodUse((MethodDesc)_target), "ReadyToRun Virtual Method Call"); } #endif return dependencyList; } else if (_id == ReadyToRunHelperId.DelegateCtor) { var info = (DelegateCreationInfo)_target; if (info.NeedsVirtualMethodUseTracking) { MethodDesc targetMethod = info.TargetMethod; DependencyList dependencyList = new DependencyList(); #if !SUPPORT_JIT factory.MetadataManager.GetDependenciesDueToVirtualMethodReflectability(ref dependencyList, factory, targetMethod); if (!factory.VTable(info.TargetMethod.OwningType).HasFixedSlots) { dependencyList.Add(factory.VirtualMethodUse(info.TargetMethod), "ReadyToRun Delegate to virtual method"); } #endif return dependencyList; } } return null; } DebugLocInfo[] INodeWithDebugInfo.DebugLocInfos { get { if (_id == ReadyToRunHelperId.VirtualCall) { // Generate debug information that lets debuggers step into the virtual calls. // We generate a step into sequence point at the point where the helper jumps to // the target of the virtual call. TargetDetails target = ((MethodDesc)_target).Context.Target; int debuggerStepInOffset = -1; switch (target.Architecture) { case TargetArchitecture.X64: debuggerStepInOffset = 3; break; } if (debuggerStepInOffset != -1) { return new DebugLocInfo[] { new DebugLocInfo(0, String.Empty, WellKnownLineNumber.DebuggerStepThrough), new DebugLocInfo(debuggerStepInOffset, String.Empty, WellKnownLineNumber.DebuggerStepIn) }; } } return Array.Empty<DebugLocInfo>(); } } DebugVarInfo[] INodeWithDebugInfo.DebugVarInfos { get { return Array.Empty<DebugVarInfo>(); } } #if !SUPPORT_JIT protected internal override int ClassCode => -911637948; protected internal override int CompareToImpl(SortableDependencyNode other, CompilerComparer comparer) { var compare = _id.CompareTo(((ReadyToRunHelperNode)other)._id); if (compare != 0) return compare; switch (_id) { case ReadyToRunHelperId.NewHelper: case ReadyToRunHelperId.NewArr1: case ReadyToRunHelperId.IsInstanceOf: case ReadyToRunHelperId.CastClass: case ReadyToRunHelperId.GetNonGCStaticBase: case ReadyToRunHelperId.GetGCStaticBase: case ReadyToRunHelperId.GetThreadStaticBase: return comparer.Compare((TypeDesc)_target, (TypeDesc)((ReadyToRunHelperNode)other)._target); case ReadyToRunHelperId.VirtualCall: case ReadyToRunHelperId.ResolveVirtualFunction: return comparer.Compare((MethodDesc)_target, (MethodDesc)((ReadyToRunHelperNode)other)._target); case ReadyToRunHelperId.DelegateCtor: return ((DelegateCreationInfo)_target).CompareTo((DelegateCreationInfo)((ReadyToRunHelperNode)other)._target, comparer); default: throw new NotImplementedException(); } } #endif } }
using System; using NUnit.Framework; using MiaPlaza.ExpressionUtils; using System.Linq.Expressions; using System.Collections.Generic; namespace MiaPlaza.Test.ExpressionUtilsTest { [TestFixture] public class StructuralIdentity { [Test] public void NullTreatmentTest() { Assert.IsTrue((null as Expression).StructuralIdentical(null)); Expression exp = Expression.Constant(12); Assert.IsFalse(exp.StructuralIdentical(null)); Assert.IsFalse((null as Expression).StructuralIdentical(exp)); } [Test] public void DifferentNodeType() { Assert.IsFalse(Expression.Constant(12).StructuralIdentical(Expression.Parameter(typeof(int)))); } [Test] public void Constants() { var expA = Expression.Constant(12); var expB = Expression.Constant(12); Assert.IsTrue(expA.StructuralIdentical(expB)); expA = Expression.Constant(new object()); expB = Expression.Constant(new object()); Assert.IsFalse(expA.StructuralIdentical(expB)); var obj = new object(); expA = Expression.Constant(obj); expB = Expression.Constant(obj); Assert.IsTrue(expA.StructuralIdentical(expB)); } [Test] public void Lambdas() { Func<LambdaExpression> factory = delegate { Expression<Func<bool>> exp = () => (5 + 17) == 20; return exp; }; var expA = factory(); var expB = factory(); Assert.IsTrue(expA.StructuralIdentical(expB)); } [Test] public void Closures() { Func<object, LambdaExpression> factory = delegate (object o) { Expression<Func<bool>> exp = () => (5 + 17).Equals(o); return exp; }; var expA = factory(12); var expB = factory(12); Assert.IsFalse(expA.StructuralIdentical(expB)); expA = PartialEvaluator.PartialEvalBody(expA, ExpressionUtils.Evaluating.ExpressionInterpreter.Instance); expB = PartialEvaluator.PartialEvalBody(expB, ExpressionUtils.Evaluating.ExpressionInterpreter.Instance); Assert.IsTrue(expA.StructuralIdentical(expB)); } [Test] public void ConstantIgnoring() { Func<int, LambdaExpression> buildExpression = c => { Expression<Func<bool>> exp = () => (5 + 17) == c; return exp; }; var expA = buildExpression(10); var expB = buildExpression(12); Assert.IsTrue(expA.StructuralIdentical(expB, ignoreConstantValues: true)); } [Test] public void Conditionals() { Func<LambdaExpression> buildExpression = () => { Expression<Func<int, bool>> exp = x => x % 2 == 0 ? x == 14 : x == 15; return exp; }; var expA = buildExpression(); var expB = buildExpression(); Assert.IsTrue(expA.StructuralIdentical(expB)); } [Test] public void IndexAccesses() { IReadOnlyList<int> array = new int[9]; Func<LambdaExpression> buildExpression = () => { Expression<Func<int, bool>> exp = x => x < 9 && array[x] > 2; return exp; }; var expA = buildExpression(); var expB = buildExpression(); Assert.IsTrue(expA.StructuralIdentical(expB)); } [Test] public void TypeBinary() { Func<LambdaExpression> buildExpression = () => { Expression<Func<object, bool>> exp = x => x is string; return exp; }; var expA = buildExpression(); var expB = buildExpression(); Assert.IsTrue(expA.StructuralIdentical(expB)); } [Test] public void Unary() { Func<LambdaExpression> buildExpression = () => { Expression<Func<int, bool>> exp = x => -x > 4; return exp; }; var expA = buildExpression(); var expB = buildExpression(); Assert.IsTrue(expA.StructuralIdentical(expB)); } [Test] public void New() { Func<LambdaExpression> buildExpression = () => { Expression<Func<bool>> exp = () => new object() != new object(); return exp; }; var expA = buildExpression(); var expB = buildExpression(); Assert.IsTrue(expA.StructuralIdentical(expB)); } [Test] public void NewArray() { Func<LambdaExpression> buildExpression = () => { Expression<Func<int[]>> exp = () => new int[0]; return exp; }; var expA = buildExpression(); var expB = buildExpression(); Assert.IsTrue(expA.StructuralIdentical(expB)); } [Test] public void NewArrayInit() { Func<LambdaExpression> buildExpression = () => { Expression<Func<object>> exp = () => new List<int>() { 2, 3, 5, 7 }; return exp; }; var expA = buildExpression(); var expB = buildExpression(); Assert.IsTrue(expA.StructuralIdentical(expB)); } [Test] public void ComplexLambda() { Func<Expression<Func<int, bool>>> buildExpression = () => i => i == 0 || (i < 43 && i > 12 && (i % 3) == 2 && i != 15); var expA = buildExpression(); var expB = buildExpression(); Assert.IsTrue(expA.StructuralIdentical(expB)); } [Test] public void TestClosureLambda() { int variable = 7; Expression<Func<int, bool>> expA = (int a) => a != variable; Expression<Func<int, bool>> expB = (int a) => a != 8; Assert.IsFalse(expA.StructuralIdentical(expB, true)); } } }
using System; using NBitcoin.BouncyCastle.Math.EC.Endo; using NBitcoin.BouncyCastle.Math.EC.Multiplier; using NBitcoin.BouncyCastle.Math.Field; namespace NBitcoin.BouncyCastle.Math.EC { public class ECAlgorithms { public static bool IsF2mCurve(ECCurve c) { IFiniteField field = c.Field; return field.Dimension > 1 && field.Characteristic.Equals(BigInteger.Two) && field is IPolynomialExtensionField; } public static bool IsFpCurve(ECCurve c) { return c.Field.Dimension == 1; } public static ECPoint SumOfMultiplies(ECPoint[] ps, BigInteger[] ks) { if (ps == null || ks == null || ps.Length != ks.Length || ps.Length < 1) throw new ArgumentException("point and scalar arrays should be non-null, and of equal, non-zero, length"); int count = ps.Length; switch (count) { case 1: return ps[0].Multiply(ks[0]); case 2: return SumOfTwoMultiplies(ps[0], ks[0], ps[1], ks[1]); default: break; } ECPoint p = ps[0]; ECCurve c = p.Curve; ECPoint[] imported = new ECPoint[count]; imported[0] = p; for (int i = 1; i < count; ++i) { imported[i] = ImportPoint(c, ps[i]); } GlvEndomorphism glvEndomorphism = c.GetEndomorphism() as GlvEndomorphism; if (glvEndomorphism != null) { return ValidatePoint(ImplSumOfMultipliesGlv(imported, ks, glvEndomorphism)); } return ValidatePoint(ImplSumOfMultiplies(imported, ks)); } public static ECPoint SumOfTwoMultiplies(ECPoint P, BigInteger a, ECPoint Q, BigInteger b) { ECCurve cp = P.Curve; Q = ImportPoint(cp, Q); // Point multiplication for Koblitz curves (using WTNAF) beats Shamir's trick if (cp is F2mCurve) { F2mCurve f2mCurve = (F2mCurve) cp; if (f2mCurve.IsKoblitz) { return ValidatePoint(P.Multiply(a).Add(Q.Multiply(b))); } } GlvEndomorphism glvEndomorphism = cp.GetEndomorphism() as GlvEndomorphism; if (glvEndomorphism != null) { return ValidatePoint( ImplSumOfMultipliesGlv(new ECPoint[] { P, Q }, new BigInteger[] { a, b }, glvEndomorphism)); } return ValidatePoint(ImplShamirsTrickWNaf(P, a, Q, b)); } /* * "Shamir's Trick", originally due to E. G. Straus * (Addition chains of vectors. American Mathematical Monthly, * 71(7):806-808, Aug./Sept. 1964) * * Input: The points P, Q, scalar k = (km?, ... , k1, k0) * and scalar l = (lm?, ... , l1, l0). * Output: R = k * P + l * Q. * 1: Z <- P + Q * 2: R <- O * 3: for i from m-1 down to 0 do * 4: R <- R + R {point doubling} * 5: if (ki = 1) and (li = 0) then R <- R + P end if * 6: if (ki = 0) and (li = 1) then R <- R + Q end if * 7: if (ki = 1) and (li = 1) then R <- R + Z end if * 8: end for * 9: return R */ public static ECPoint ShamirsTrick(ECPoint P, BigInteger k, ECPoint Q, BigInteger l) { ECCurve cp = P.Curve; Q = ImportPoint(cp, Q); return ValidatePoint(ImplShamirsTrickJsf(P, k, Q, l)); } public static ECPoint ImportPoint(ECCurve c, ECPoint p) { ECCurve cp = p.Curve; if (!c.Equals(cp)) throw new ArgumentException("Point must be on the same curve"); return c.ImportPoint(p); } public static void MontgomeryTrick(ECFieldElement[] zs, int off, int len) { /* * Uses the "Montgomery Trick" to invert many field elements, with only a single actual * field inversion. See e.g. the paper: * "Fast Multi-scalar Multiplication Methods on Elliptic Curves with Precomputation Strategy Using Montgomery Trick" * by Katsuyuki Okeya, Kouichi Sakurai. */ ECFieldElement[] c = new ECFieldElement[len]; c[0] = zs[off]; int i = 0; while (++i < len) { c[i] = c[i - 1].Multiply(zs[off + i]); } ECFieldElement u = c[--i].Invert(); while (i > 0) { int j = off + i--; ECFieldElement tmp = zs[j]; zs[j] = c[i].Multiply(u); u = u.Multiply(tmp); } zs[off] = u; } /** * Simple shift-and-add multiplication. Serves as reference implementation * to verify (possibly faster) implementations, and for very small scalars. * * @param p * The point to multiply. * @param k * The multiplier. * @return The result of the point multiplication <code>kP</code>. */ public static ECPoint ReferenceMultiply(ECPoint p, BigInteger k) { BigInteger x = k.Abs(); ECPoint q = p.Curve.Infinity; int t = x.BitLength; if (t > 0) { if (x.TestBit(0)) { q = p; } for (int i = 1; i < t; i++) { p = p.Twice(); if (x.TestBit(i)) { q = q.Add(p); } } } return k.SignValue < 0 ? q.Negate() : q; } public static ECPoint ValidatePoint(ECPoint p) { if (!p.IsValid()) throw new ArgumentException("Invalid point", "p"); return p; } internal static ECPoint ImplShamirsTrickJsf(ECPoint P, BigInteger k, ECPoint Q, BigInteger l) { ECCurve curve = P.Curve; ECPoint infinity = curve.Infinity; // TODO conjugate co-Z addition (ZADDC) can return both of these ECPoint PaddQ = P.Add(Q); ECPoint PsubQ = P.Subtract(Q); ECPoint[] points = new ECPoint[] { Q, PsubQ, P, PaddQ }; curve.NormalizeAll(points); ECPoint[] table = new ECPoint[] { points[3].Negate(), points[2].Negate(), points[1].Negate(), points[0].Negate(), infinity, points[0], points[1], points[2], points[3] }; byte[] jsf = WNafUtilities.GenerateJsf(k, l); ECPoint R = infinity; int i = jsf.Length; while (--i >= 0) { int jsfi = jsf[i]; // NOTE: The shifting ensures the sign is extended correctly int kDigit = ((jsfi << 24) >> 28), lDigit = ((jsfi << 28) >> 28); int index = 4 + (kDigit * 3) + lDigit; R = R.TwicePlus(table[index]); } return R; } internal static ECPoint ImplShamirsTrickWNaf(ECPoint P, BigInteger k, ECPoint Q, BigInteger l) { bool negK = k.SignValue < 0, negL = l.SignValue < 0; k = k.Abs(); l = l.Abs(); int widthP = System.Math.Max(2, System.Math.Min(16, WNafUtilities.GetWindowSize(k.BitLength))); int widthQ = System.Math.Max(2, System.Math.Min(16, WNafUtilities.GetWindowSize(l.BitLength))); WNafPreCompInfo infoP = WNafUtilities.Precompute(P, widthP, true); WNafPreCompInfo infoQ = WNafUtilities.Precompute(Q, widthQ, true); ECPoint[] preCompP = negK ? infoP.PreCompNeg : infoP.PreComp; ECPoint[] preCompQ = negL ? infoQ.PreCompNeg : infoQ.PreComp; ECPoint[] preCompNegP = negK ? infoP.PreComp : infoP.PreCompNeg; ECPoint[] preCompNegQ = negL ? infoQ.PreComp : infoQ.PreCompNeg; byte[] wnafP = WNafUtilities.GenerateWindowNaf(widthP, k); byte[] wnafQ = WNafUtilities.GenerateWindowNaf(widthQ, l); return ImplShamirsTrickWNaf(preCompP, preCompNegP, wnafP, preCompQ, preCompNegQ, wnafQ); } internal static ECPoint ImplShamirsTrickWNaf(ECPoint P, BigInteger k, ECPointMap pointMapQ, BigInteger l) { bool negK = k.SignValue < 0, negL = l.SignValue < 0; k = k.Abs(); l = l.Abs(); int width = System.Math.Max(2, System.Math.Min(16, WNafUtilities.GetWindowSize(System.Math.Max(k.BitLength, l.BitLength)))); ECPoint Q = WNafUtilities.MapPointWithPrecomp(P, width, true, pointMapQ); WNafPreCompInfo infoP = WNafUtilities.GetWNafPreCompInfo(P); WNafPreCompInfo infoQ = WNafUtilities.GetWNafPreCompInfo(Q); ECPoint[] preCompP = negK ? infoP.PreCompNeg : infoP.PreComp; ECPoint[] preCompQ = negL ? infoQ.PreCompNeg : infoQ.PreComp; ECPoint[] preCompNegP = negK ? infoP.PreComp : infoP.PreCompNeg; ECPoint[] preCompNegQ = negL ? infoQ.PreComp : infoQ.PreCompNeg; byte[] wnafP = WNafUtilities.GenerateWindowNaf(width, k); byte[] wnafQ = WNafUtilities.GenerateWindowNaf(width, l); return ImplShamirsTrickWNaf(preCompP, preCompNegP, wnafP, preCompQ, preCompNegQ, wnafQ); } private static ECPoint ImplShamirsTrickWNaf(ECPoint[] preCompP, ECPoint[] preCompNegP, byte[] wnafP, ECPoint[] preCompQ, ECPoint[] preCompNegQ, byte[] wnafQ) { int len = System.Math.Max(wnafP.Length, wnafQ.Length); ECCurve curve = preCompP[0].Curve; ECPoint infinity = curve.Infinity; ECPoint R = infinity; int zeroes = 0; for (int i = len - 1; i >= 0; --i) { int wiP = i < wnafP.Length ? (int)(sbyte)wnafP[i] : 0; int wiQ = i < wnafQ.Length ? (int)(sbyte)wnafQ[i] : 0; if ((wiP | wiQ) == 0) { ++zeroes; continue; } ECPoint r = infinity; if (wiP != 0) { int nP = System.Math.Abs(wiP); ECPoint[] tableP = wiP < 0 ? preCompNegP : preCompP; r = r.Add(tableP[nP >> 1]); } if (wiQ != 0) { int nQ = System.Math.Abs(wiQ); ECPoint[] tableQ = wiQ < 0 ? preCompNegQ : preCompQ; r = r.Add(tableQ[nQ >> 1]); } if (zeroes > 0) { R = R.TimesPow2(zeroes); zeroes = 0; } R = R.TwicePlus(r); } if (zeroes > 0) { R = R.TimesPow2(zeroes); } return R; } internal static ECPoint ImplSumOfMultiplies(ECPoint[] ps, BigInteger[] ks) { int count = ps.Length; bool[] negs = new bool[count]; WNafPreCompInfo[] infos = new WNafPreCompInfo[count]; byte[][] wnafs = new byte[count][]; for (int i = 0; i < count; ++i) { BigInteger ki = ks[i]; negs[i] = ki.SignValue < 0; ki = ki.Abs(); int width = System.Math.Max(2, System.Math.Min(16, WNafUtilities.GetWindowSize(ki.BitLength))); infos[i] = WNafUtilities.Precompute(ps[i], width, true); wnafs[i] = WNafUtilities.GenerateWindowNaf(width, ki); } return ImplSumOfMultiplies(negs, infos, wnafs); } internal static ECPoint ImplSumOfMultipliesGlv(ECPoint[] ps, BigInteger[] ks, GlvEndomorphism glvEndomorphism) { BigInteger n = ps[0].Curve.Order; int len = ps.Length; BigInteger[] abs = new BigInteger[len << 1]; for (int i = 0, j = 0; i < len; ++i) { BigInteger[] ab = glvEndomorphism.DecomposeScalar(ks[i].Mod(n)); abs[j++] = ab[0]; abs[j++] = ab[1]; } ECPointMap pointMap = glvEndomorphism.PointMap; if (glvEndomorphism.HasEfficientPointMap) { return ECAlgorithms.ImplSumOfMultiplies(ps, pointMap, abs); } ECPoint[] pqs = new ECPoint[len << 1]; for (int i = 0, j = 0; i < len; ++i) { ECPoint p = ps[i], q = pointMap.Map(p); pqs[j++] = p; pqs[j++] = q; } return ECAlgorithms.ImplSumOfMultiplies(pqs, abs); } internal static ECPoint ImplSumOfMultiplies(ECPoint[] ps, ECPointMap pointMap, BigInteger[] ks) { int halfCount = ps.Length, fullCount = halfCount << 1; bool[] negs = new bool[fullCount]; WNafPreCompInfo[] infos = new WNafPreCompInfo[fullCount]; byte[][] wnafs = new byte[fullCount][]; for (int i = 0; i < halfCount; ++i) { int j0 = i << 1, j1 = j0 + 1; BigInteger kj0 = ks[j0]; negs[j0] = kj0.SignValue < 0; kj0 = kj0.Abs(); BigInteger kj1 = ks[j1]; negs[j1] = kj1.SignValue < 0; kj1 = kj1.Abs(); int width = System.Math.Max(2, System.Math.Min(16, WNafUtilities.GetWindowSize(System.Math.Max(kj0.BitLength, kj1.BitLength)))); ECPoint P = ps[i], Q = WNafUtilities.MapPointWithPrecomp(P, width, true, pointMap); infos[j0] = WNafUtilities.GetWNafPreCompInfo(P); infos[j1] = WNafUtilities.GetWNafPreCompInfo(Q); wnafs[j0] = WNafUtilities.GenerateWindowNaf(width, kj0); wnafs[j1] = WNafUtilities.GenerateWindowNaf(width, kj1); } return ImplSumOfMultiplies(negs, infos, wnafs); } private static ECPoint ImplSumOfMultiplies(bool[] negs, WNafPreCompInfo[] infos, byte[][] wnafs) { int len = 0, count = wnafs.Length; for (int i = 0; i < count; ++i) { len = System.Math.Max(len, wnafs[i].Length); } ECCurve curve = infos[0].PreComp[0].Curve; ECPoint infinity = curve.Infinity; ECPoint R = infinity; int zeroes = 0; for (int i = len - 1; i >= 0; --i) { ECPoint r = infinity; for (int j = 0; j < count; ++j) { byte[] wnaf = wnafs[j]; int wi = i < wnaf.Length ? (int)(sbyte)wnaf[i] : 0; if (wi != 0) { int n = System.Math.Abs(wi); WNafPreCompInfo info = infos[j]; ECPoint[] table = (wi < 0 == negs[j]) ? info.PreComp : info.PreCompNeg; r = r.Add(table[n >> 1]); } } if (r == infinity) { ++zeroes; continue; } if (zeroes > 0) { R = R.TimesPow2(zeroes); zeroes = 0; } R = R.TwicePlus(r); } if (zeroes > 0) { R = R.TimesPow2(zeroes); } return R; } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/api/servicecontrol/v1/service_controller.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Api.Servicecontrol.V1 { /// <summary>Holder for reflection information generated from google/api/servicecontrol/v1/service_controller.proto</summary> public static partial class ServiceControllerReflection { #region Descriptor /// <summary>File descriptor for google/api/servicecontrol/v1/service_controller.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static ServiceControllerReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjVnb29nbGUvYXBpL3NlcnZpY2Vjb250cm9sL3YxL3NlcnZpY2VfY29udHJv", "bGxlci5wcm90bxIcZ29vZ2xlLmFwaS5zZXJ2aWNlY29udHJvbC52MRocZ29v", "Z2xlL2FwaS9hbm5vdGF0aW9ucy5wcm90bxouZ29vZ2xlL2FwaS9zZXJ2aWNl", "Y29udHJvbC92MS9jaGVja19lcnJvci5wcm90bxosZ29vZ2xlL2FwaS9zZXJ2", "aWNlY29udHJvbC92MS9vcGVyYXRpb24ucHJvdG8aF2dvb2dsZS9ycGMvc3Rh", "dHVzLnByb3RvInsKDENoZWNrUmVxdWVzdBIUCgxzZXJ2aWNlX25hbWUYASAB", "KAkSOgoJb3BlcmF0aW9uGAIgASgLMicuZ29vZ2xlLmFwaS5zZXJ2aWNlY29u", "dHJvbC52MS5PcGVyYXRpb24SGQoRc2VydmljZV9jb25maWdfaWQYBCABKAki", "gAEKDUNoZWNrUmVzcG9uc2USFAoMb3BlcmF0aW9uX2lkGAEgASgJEj4KDGNo", "ZWNrX2Vycm9ycxgCIAMoCzIoLmdvb2dsZS5hcGkuc2VydmljZWNvbnRyb2wu", "djEuQ2hlY2tFcnJvchIZChFzZXJ2aWNlX2NvbmZpZ19pZBgFIAEoCSJ9Cg1S", "ZXBvcnRSZXF1ZXN0EhQKDHNlcnZpY2VfbmFtZRgBIAEoCRI7CgpvcGVyYXRp", "b25zGAIgAygLMicuZ29vZ2xlLmFwaS5zZXJ2aWNlY29udHJvbC52MS5PcGVy", "YXRpb24SGQoRc2VydmljZV9jb25maWdfaWQYAyABKAkixQEKDlJlcG9ydFJl", "c3BvbnNlEk8KDXJlcG9ydF9lcnJvcnMYASADKAsyOC5nb29nbGUuYXBpLnNl", "cnZpY2Vjb250cm9sLnYxLlJlcG9ydFJlc3BvbnNlLlJlcG9ydEVycm9yEhkK", "EXNlcnZpY2VfY29uZmlnX2lkGAIgASgJGkcKC1JlcG9ydEVycm9yEhQKDG9w", "ZXJhdGlvbl9pZBgBIAEoCRIiCgZzdGF0dXMYAiABKAsyEi5nb29nbGUucnBj", "LlN0YXR1czK5AgoRU2VydmljZUNvbnRyb2xsZXISjgEKBUNoZWNrEiouZ29v", "Z2xlLmFwaS5zZXJ2aWNlY29udHJvbC52MS5DaGVja1JlcXVlc3QaKy5nb29n", "bGUuYXBpLnNlcnZpY2Vjb250cm9sLnYxLkNoZWNrUmVzcG9uc2UiLILT5JMC", "JiIhL3YxL3NlcnZpY2VzL3tzZXJ2aWNlX25hbWV9OmNoZWNrOgEqEpIBCgZS", "ZXBvcnQSKy5nb29nbGUuYXBpLnNlcnZpY2Vjb250cm9sLnYxLlJlcG9ydFJl", "cXVlc3QaLC5nb29nbGUuYXBpLnNlcnZpY2Vjb250cm9sLnYxLlJlcG9ydFJl", "c3BvbnNlIi2C0+STAiciIi92MS9zZXJ2aWNlcy97c2VydmljZV9uYW1lfTpy", "ZXBvcnQ6ASpCkgEKIGNvbS5nb29nbGUuYXBpLnNlcnZpY2Vjb250cm9sLnYx", "QhZTZXJ2aWNlQ29udHJvbGxlclByb3RvUAFaSmdvb2dsZS5nb2xhbmcub3Jn", "L2dlbnByb3RvL2dvb2dsZWFwaXMvYXBpL3NlcnZpY2Vjb250cm9sL3YxO3Nl", "cnZpY2Vjb250cm9s+AEBogIER0FTQ2IGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Api.Servicecontrol.V1.CheckErrorReflection.Descriptor, global::Google.Api.Servicecontrol.V1.OperationReflection.Descriptor, global::Google.Rpc.StatusReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Servicecontrol.V1.CheckRequest), global::Google.Api.Servicecontrol.V1.CheckRequest.Parser, new[]{ "ServiceName", "Operation", "ServiceConfigId" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Servicecontrol.V1.CheckResponse), global::Google.Api.Servicecontrol.V1.CheckResponse.Parser, new[]{ "OperationId", "CheckErrors", "ServiceConfigId" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Servicecontrol.V1.ReportRequest), global::Google.Api.Servicecontrol.V1.ReportRequest.Parser, new[]{ "ServiceName", "Operations", "ServiceConfigId" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Servicecontrol.V1.ReportResponse), global::Google.Api.Servicecontrol.V1.ReportResponse.Parser, new[]{ "ReportErrors", "ServiceConfigId" }, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Servicecontrol.V1.ReportResponse.Types.ReportError), global::Google.Api.Servicecontrol.V1.ReportResponse.Types.ReportError.Parser, new[]{ "OperationId", "Status" }, null, null, null)}) })); } #endregion } #region Messages /// <summary> /// Request message for the Check method. /// </summary> public sealed partial class CheckRequest : pb::IMessage<CheckRequest> { private static readonly pb::MessageParser<CheckRequest> _parser = new pb::MessageParser<CheckRequest>(() => new CheckRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<CheckRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Api.Servicecontrol.V1.ServiceControllerReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CheckRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CheckRequest(CheckRequest other) : this() { serviceName_ = other.serviceName_; Operation = other.operation_ != null ? other.Operation.Clone() : null; serviceConfigId_ = other.serviceConfigId_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CheckRequest Clone() { return new CheckRequest(this); } /// <summary>Field number for the "service_name" field.</summary> public const int ServiceNameFieldNumber = 1; private string serviceName_ = ""; /// <summary> /// The service name as specified in its service configuration. For example, /// `"pubsub.googleapis.com"`. /// /// See [google.api.Service][google.api.Service] for the definition of a service name. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string ServiceName { get { return serviceName_; } set { serviceName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "operation" field.</summary> public const int OperationFieldNumber = 2; private global::Google.Api.Servicecontrol.V1.Operation operation_; /// <summary> /// The operation to be checked. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Api.Servicecontrol.V1.Operation Operation { get { return operation_; } set { operation_ = value; } } /// <summary>Field number for the "service_config_id" field.</summary> public const int ServiceConfigIdFieldNumber = 4; private string serviceConfigId_ = ""; /// <summary> /// Specifies which version of service configuration should be used to process /// the request. /// /// If unspecified or no matching version can be found, the /// latest one will be used. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string ServiceConfigId { get { return serviceConfigId_; } set { serviceConfigId_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as CheckRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(CheckRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (ServiceName != other.ServiceName) return false; if (!object.Equals(Operation, other.Operation)) return false; if (ServiceConfigId != other.ServiceConfigId) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (ServiceName.Length != 0) hash ^= ServiceName.GetHashCode(); if (operation_ != null) hash ^= Operation.GetHashCode(); if (ServiceConfigId.Length != 0) hash ^= ServiceConfigId.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (ServiceName.Length != 0) { output.WriteRawTag(10); output.WriteString(ServiceName); } if (operation_ != null) { output.WriteRawTag(18); output.WriteMessage(Operation); } if (ServiceConfigId.Length != 0) { output.WriteRawTag(34); output.WriteString(ServiceConfigId); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (ServiceName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ServiceName); } if (operation_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Operation); } if (ServiceConfigId.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ServiceConfigId); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(CheckRequest other) { if (other == null) { return; } if (other.ServiceName.Length != 0) { ServiceName = other.ServiceName; } if (other.operation_ != null) { if (operation_ == null) { operation_ = new global::Google.Api.Servicecontrol.V1.Operation(); } Operation.MergeFrom(other.Operation); } if (other.ServiceConfigId.Length != 0) { ServiceConfigId = other.ServiceConfigId; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { ServiceName = input.ReadString(); break; } case 18: { if (operation_ == null) { operation_ = new global::Google.Api.Servicecontrol.V1.Operation(); } input.ReadMessage(operation_); break; } case 34: { ServiceConfigId = input.ReadString(); break; } } } } } /// <summary> /// Response message for the Check method. /// </summary> public sealed partial class CheckResponse : pb::IMessage<CheckResponse> { private static readonly pb::MessageParser<CheckResponse> _parser = new pb::MessageParser<CheckResponse>(() => new CheckResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<CheckResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Api.Servicecontrol.V1.ServiceControllerReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CheckResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CheckResponse(CheckResponse other) : this() { operationId_ = other.operationId_; checkErrors_ = other.checkErrors_.Clone(); serviceConfigId_ = other.serviceConfigId_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CheckResponse Clone() { return new CheckResponse(this); } /// <summary>Field number for the "operation_id" field.</summary> public const int OperationIdFieldNumber = 1; private string operationId_ = ""; /// <summary> /// The same operation_id value used in the CheckRequest. /// Used for logging and diagnostics purposes. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string OperationId { get { return operationId_; } set { operationId_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "check_errors" field.</summary> public const int CheckErrorsFieldNumber = 2; private static readonly pb::FieldCodec<global::Google.Api.Servicecontrol.V1.CheckError> _repeated_checkErrors_codec = pb::FieldCodec.ForMessage(18, global::Google.Api.Servicecontrol.V1.CheckError.Parser); private readonly pbc::RepeatedField<global::Google.Api.Servicecontrol.V1.CheckError> checkErrors_ = new pbc::RepeatedField<global::Google.Api.Servicecontrol.V1.CheckError>(); /// <summary> /// Indicate the decision of the check. /// /// If no check errors are present, the service should process the operation. /// Otherwise the service should use the list of errors to determine the /// appropriate action. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Api.Servicecontrol.V1.CheckError> CheckErrors { get { return checkErrors_; } } /// <summary>Field number for the "service_config_id" field.</summary> public const int ServiceConfigIdFieldNumber = 5; private string serviceConfigId_ = ""; /// <summary> /// The actual config id used to process the request. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string ServiceConfigId { get { return serviceConfigId_; } set { serviceConfigId_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as CheckResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(CheckResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (OperationId != other.OperationId) return false; if(!checkErrors_.Equals(other.checkErrors_)) return false; if (ServiceConfigId != other.ServiceConfigId) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (OperationId.Length != 0) hash ^= OperationId.GetHashCode(); hash ^= checkErrors_.GetHashCode(); if (ServiceConfigId.Length != 0) hash ^= ServiceConfigId.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (OperationId.Length != 0) { output.WriteRawTag(10); output.WriteString(OperationId); } checkErrors_.WriteTo(output, _repeated_checkErrors_codec); if (ServiceConfigId.Length != 0) { output.WriteRawTag(42); output.WriteString(ServiceConfigId); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (OperationId.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(OperationId); } size += checkErrors_.CalculateSize(_repeated_checkErrors_codec); if (ServiceConfigId.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ServiceConfigId); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(CheckResponse other) { if (other == null) { return; } if (other.OperationId.Length != 0) { OperationId = other.OperationId; } checkErrors_.Add(other.checkErrors_); if (other.ServiceConfigId.Length != 0) { ServiceConfigId = other.ServiceConfigId; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { OperationId = input.ReadString(); break; } case 18: { checkErrors_.AddEntriesFrom(input, _repeated_checkErrors_codec); break; } case 42: { ServiceConfigId = input.ReadString(); break; } } } } } /// <summary> /// Request message for the Report method. /// </summary> public sealed partial class ReportRequest : pb::IMessage<ReportRequest> { private static readonly pb::MessageParser<ReportRequest> _parser = new pb::MessageParser<ReportRequest>(() => new ReportRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ReportRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Api.Servicecontrol.V1.ServiceControllerReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ReportRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ReportRequest(ReportRequest other) : this() { serviceName_ = other.serviceName_; operations_ = other.operations_.Clone(); serviceConfigId_ = other.serviceConfigId_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ReportRequest Clone() { return new ReportRequest(this); } /// <summary>Field number for the "service_name" field.</summary> public const int ServiceNameFieldNumber = 1; private string serviceName_ = ""; /// <summary> /// The service name as specified in its service configuration. For example, /// `"pubsub.googleapis.com"`. /// /// See [google.api.Service][google.api.Service] for the definition of a service name. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string ServiceName { get { return serviceName_; } set { serviceName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "operations" field.</summary> public const int OperationsFieldNumber = 2; private static readonly pb::FieldCodec<global::Google.Api.Servicecontrol.V1.Operation> _repeated_operations_codec = pb::FieldCodec.ForMessage(18, global::Google.Api.Servicecontrol.V1.Operation.Parser); private readonly pbc::RepeatedField<global::Google.Api.Servicecontrol.V1.Operation> operations_ = new pbc::RepeatedField<global::Google.Api.Servicecontrol.V1.Operation>(); /// <summary> /// Operations to be reported. /// /// Typically the service should report one operation per request. /// Putting multiple operations into a single request is allowed, but should /// be used only when multiple operations are natually available at the time /// of the report. /// /// If multiple operations are in a single request, the total request size /// should be no larger than 1MB. See [ReportResponse.report_errors][google.api.servicecontrol.v1.ReportResponse.report_errors] for /// partial failure behavior. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Api.Servicecontrol.V1.Operation> Operations { get { return operations_; } } /// <summary>Field number for the "service_config_id" field.</summary> public const int ServiceConfigIdFieldNumber = 3; private string serviceConfigId_ = ""; /// <summary> /// Specifies which version of service config should be used to process the /// request. /// /// If unspecified or no matching version can be found, the /// latest one will be used. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string ServiceConfigId { get { return serviceConfigId_; } set { serviceConfigId_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ReportRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ReportRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (ServiceName != other.ServiceName) return false; if(!operations_.Equals(other.operations_)) return false; if (ServiceConfigId != other.ServiceConfigId) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (ServiceName.Length != 0) hash ^= ServiceName.GetHashCode(); hash ^= operations_.GetHashCode(); if (ServiceConfigId.Length != 0) hash ^= ServiceConfigId.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (ServiceName.Length != 0) { output.WriteRawTag(10); output.WriteString(ServiceName); } operations_.WriteTo(output, _repeated_operations_codec); if (ServiceConfigId.Length != 0) { output.WriteRawTag(26); output.WriteString(ServiceConfigId); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (ServiceName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ServiceName); } size += operations_.CalculateSize(_repeated_operations_codec); if (ServiceConfigId.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ServiceConfigId); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ReportRequest other) { if (other == null) { return; } if (other.ServiceName.Length != 0) { ServiceName = other.ServiceName; } operations_.Add(other.operations_); if (other.ServiceConfigId.Length != 0) { ServiceConfigId = other.ServiceConfigId; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { ServiceName = input.ReadString(); break; } case 18: { operations_.AddEntriesFrom(input, _repeated_operations_codec); break; } case 26: { ServiceConfigId = input.ReadString(); break; } } } } } /// <summary> /// Response message for the Report method. /// </summary> public sealed partial class ReportResponse : pb::IMessage<ReportResponse> { private static readonly pb::MessageParser<ReportResponse> _parser = new pb::MessageParser<ReportResponse>(() => new ReportResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ReportResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Api.Servicecontrol.V1.ServiceControllerReflection.Descriptor.MessageTypes[3]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ReportResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ReportResponse(ReportResponse other) : this() { reportErrors_ = other.reportErrors_.Clone(); serviceConfigId_ = other.serviceConfigId_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ReportResponse Clone() { return new ReportResponse(this); } /// <summary>Field number for the "report_errors" field.</summary> public const int ReportErrorsFieldNumber = 1; private static readonly pb::FieldCodec<global::Google.Api.Servicecontrol.V1.ReportResponse.Types.ReportError> _repeated_reportErrors_codec = pb::FieldCodec.ForMessage(10, global::Google.Api.Servicecontrol.V1.ReportResponse.Types.ReportError.Parser); private readonly pbc::RepeatedField<global::Google.Api.Servicecontrol.V1.ReportResponse.Types.ReportError> reportErrors_ = new pbc::RepeatedField<global::Google.Api.Servicecontrol.V1.ReportResponse.Types.ReportError>(); /// <summary> /// Partial failures, one for each `Operation` in the request that failed /// processing. There are three possible combinations of the RPC status: /// /// 1. The combination of a successful RPC status and an empty `report_errors` /// list indicates a complete success where all `Operations` in the /// request are processed successfully. /// 2. The combination of a successful RPC status and a non-empty /// `report_errors` list indicates a partial success where some /// `Operations` in the request succeeded. Each /// `Operation` that failed processing has a corresponding item /// in this list. /// 3. A failed RPC status indicates a complete failure where none of the /// `Operations` in the request succeeded. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Api.Servicecontrol.V1.ReportResponse.Types.ReportError> ReportErrors { get { return reportErrors_; } } /// <summary>Field number for the "service_config_id" field.</summary> public const int ServiceConfigIdFieldNumber = 2; private string serviceConfigId_ = ""; /// <summary> /// The actual config id used to process the request. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string ServiceConfigId { get { return serviceConfigId_; } set { serviceConfigId_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ReportResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ReportResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!reportErrors_.Equals(other.reportErrors_)) return false; if (ServiceConfigId != other.ServiceConfigId) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= reportErrors_.GetHashCode(); if (ServiceConfigId.Length != 0) hash ^= ServiceConfigId.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { reportErrors_.WriteTo(output, _repeated_reportErrors_codec); if (ServiceConfigId.Length != 0) { output.WriteRawTag(18); output.WriteString(ServiceConfigId); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += reportErrors_.CalculateSize(_repeated_reportErrors_codec); if (ServiceConfigId.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ServiceConfigId); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ReportResponse other) { if (other == null) { return; } reportErrors_.Add(other.reportErrors_); if (other.ServiceConfigId.Length != 0) { ServiceConfigId = other.ServiceConfigId; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { reportErrors_.AddEntriesFrom(input, _repeated_reportErrors_codec); break; } case 18: { ServiceConfigId = input.ReadString(); break; } } } } #region Nested types /// <summary>Container for nested types declared in the ReportResponse message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { /// <summary> /// Represents the processing error of one `Operation` in the request. /// </summary> public sealed partial class ReportError : pb::IMessage<ReportError> { private static readonly pb::MessageParser<ReportError> _parser = new pb::MessageParser<ReportError>(() => new ReportError()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ReportError> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Api.Servicecontrol.V1.ReportResponse.Descriptor.NestedTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ReportError() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ReportError(ReportError other) : this() { operationId_ = other.operationId_; Status = other.status_ != null ? other.Status.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ReportError Clone() { return new ReportError(this); } /// <summary>Field number for the "operation_id" field.</summary> public const int OperationIdFieldNumber = 1; private string operationId_ = ""; /// <summary> /// The [Operation.operation_id][google.api.servicecontrol.v1.Operation.operation_id] value from the request. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string OperationId { get { return operationId_; } set { operationId_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "status" field.</summary> public const int StatusFieldNumber = 2; private global::Google.Rpc.Status status_; /// <summary> /// Details of the error when processing the `Operation`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Rpc.Status Status { get { return status_; } set { status_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ReportError); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ReportError other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (OperationId != other.OperationId) return false; if (!object.Equals(Status, other.Status)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (OperationId.Length != 0) hash ^= OperationId.GetHashCode(); if (status_ != null) hash ^= Status.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (OperationId.Length != 0) { output.WriteRawTag(10); output.WriteString(OperationId); } if (status_ != null) { output.WriteRawTag(18); output.WriteMessage(Status); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (OperationId.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(OperationId); } if (status_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Status); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ReportError other) { if (other == null) { return; } if (other.OperationId.Length != 0) { OperationId = other.OperationId; } if (other.status_ != null) { if (status_ == null) { status_ = new global::Google.Rpc.Status(); } Status.MergeFrom(other.Status); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { OperationId = input.ReadString(); break; } case 18: { if (status_ == null) { status_ = new global::Google.Rpc.Status(); } input.ReadMessage(status_); break; } } } } } } #endregion } #endregion } #endregion Designer generated code
// ******************************************************************************************************** // Product Name: DotSpatial.Symbology.dll // Description: Contains the business logic for symbology layers and symbol categories. // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 4/9/2009 3:42:59 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Xml.Serialization; using DotSpatial.Data; using DotSpatial.Serialization; namespace DotSpatial.Symbology { [Serializable, XmlRoot("CartographicStroke")] public class CartographicStroke : SimpleStroke, ICartographicStroke { #region Private Variables private float[] _compondArray; private bool[] _compoundButtons; private bool[] _dashButtons; private DashCap _dashCap; private float[] _dashPattern; private IList<ILineDecoration> _decorations; private LineCap _endCap; private LineJoinType _joinType; private float _offset; private LineCap _startCap; #endregion #region Constructors /// <summary> /// Creates a new instance of CartographicStroke /// </summary> public CartographicStroke() { Color = SymbologyGlobal.RandomDarkColor(1); Configure(); } /// <summary> /// Getnerates a cartographic stroke of the specified color /// </summary> /// <param name="color"></param> public CartographicStroke(Color color) { Color = color; Configure(); } private void Configure() { _joinType = LineJoinType.Round; _startCap = LineCap.Round; _endCap = LineCap.Round; _decorations = new CopyList<ILineDecoration>(); } #endregion #region Methods /// <summary> /// Creates a pen for drawing the non-decorative portion of the line. /// </summary> ///<param name="scaleWidth">The base width in pixels that is equivalent to a width of 1</param> /// <returns>A new Pen</returns> public override Pen ToPen(double scaleWidth) { Pen myPen = base.ToPen(scaleWidth); myPen.EndCap = _endCap; myPen.StartCap = _startCap; if (_compondArray != null) myPen.CompoundArray = _compondArray; if (_offset != 0F) { float[] pattern = new float[] { 0, 1 }; float w = (float)Width; if (w == 0) w = 1; w = (float)(scaleWidth * w); float w2 = (Math.Abs(_offset) + w / 2) * 2; if (_compondArray != null) { pattern = new float[_compondArray.Length]; for (int i = 0; i < _compondArray.Length; i++) { pattern[i] = _compondArray[i]; } } for (int i = 0; i < pattern.Length; i++) { if (_offset > 0) { pattern[i] = (w / w2) * pattern[i]; } else { pattern[i] = 1 - (w / w2) + (w / w2) * pattern[i]; } } myPen.CompoundArray = pattern; myPen.Width = w2; } if (_dashPattern != null) { myPen.DashPattern = _dashPattern; } else { if (myPen.DashStyle == DashStyle.Custom) { myPen.DashStyle = DashStyle.Solid; } } switch (_joinType) { case LineJoinType.Bevel: myPen.LineJoin = LineJoin.Bevel; break; case LineJoinType.Mitre: myPen.LineJoin = LineJoin.Miter; break; case LineJoinType.Round: myPen.LineJoin = LineJoin.Round; break; } return myPen; } /// <summary> /// Draws the line with max. 2 decorations. Otherwise the legend line might show only decorations. /// </summary> /// <param name="g"></param> /// <param name="path"></param> /// <param name="scaleWidth"></param> public void DrawLegendPath(Graphics g, GraphicsPath path, double scaleWidth) { base.DrawPath(g, path, scaleWidth); // draw the actual line if (Decorations != null) { int temp = -1; foreach (ILineDecoration decoration in Decorations) { if (decoration.NumSymbols > 2) { temp = decoration.NumSymbols; decoration.NumSymbols = 2; } decoration.Draw(g, path, scaleWidth); if (temp > -1) { decoration.NumSymbols = temp; temp = -1; } } } } /// <summary> /// Draws the actual path, overriding the base behavior to include markers. /// </summary> /// <param name="g"></param> /// <param name="path"></param> /// <param name="scaleWidth"></param> public override void DrawPath(Graphics g, GraphicsPath path, double scaleWidth) { base.DrawPath(g, path, scaleWidth); // draw the actual line if (Decorations != null) { foreach (ILineDecoration decoration in Decorations) { decoration.Draw(g, path, scaleWidth); } } } /// <summary> /// Gets the width and height that is needed to draw this stroke with max. 2 decorations. /// </summary> public Size GetLegendSymbolSize() { Size size = new Size(16, 16); foreach (ILineDecoration decoration in Decorations) { Size s = decoration.GetLegendSymbolSize(); if (s.Height > size.Height) size.Height = s.Height; if (s.Width > size.Width) size.Width = s.Width; } return size; } #endregion #region Properties /// <summary> /// Gets or sets an array of floating point values ranging from 0 to 1 that /// indicate the start and end point for where the line should draw. /// </summary> [XmlIgnore] public float[] CompoundArray { get { return _compondArray; } set { _compondArray = value; } } /// <summary> /// gets or sets the DashCap for both the start and end caps of the dashes /// </summary> [Serialize("DashCap")] public DashCap DashCap { get { return _dashCap; } set { _dashCap = value; } } /// <summary> /// Gets or sets the DashPattern as an array of floating point values from 0 to 1 /// </summary> [XmlIgnore] public float[] DashPattern { get { return _dashPattern; } set { _dashPattern = value; } } /// <summary> /// Gets or sets the line decoration that describes symbols that should /// be drawn along the line as decoration. /// </summary> [Serialize("Decorations")] public IList<ILineDecoration> Decorations { get { return _decorations; } set { _decorations = value; } } /// <summary> /// Gets or sets the line cap for both the start and end of the line /// </summary> [Serialize("EndCap")] public LineCap EndCap { get { return _endCap; } set { _endCap = value; } } /// <summary> /// Gets or sets the OGC line characteristic that controls how connected segments /// are drawn where they come together. /// </summary> [Serialize("JoinType")] public LineJoinType JoinType { get { return _joinType; } set { _joinType = value; } } /// <summary> /// Gets or sets the line cap for both the start and end of the line /// </summary> [Serialize("LineCap")] public LineCap StartCap { get { return _startCap; } set { _startCap = value; } } /// <summary> /// This is a cached version of the horizontal pattern that should appear in the custom dash control. /// This is only used if DashStyle is set to custom, and only controls the pattern control, /// and does not directly affect the drawing pen. /// </summary> public bool[] DashButtons { get { return _dashButtons; } set { _dashButtons = value; } } /// <summary> /// This is a cached version of the vertical pattern that should appear in the custom dash control. /// This is only used if DashStyle is set to custom, and only controls the pattern control, /// and does not directly affect the drawing pen. /// </summary> public bool[] CompoundButtons { get { return _compoundButtons; } set { _compoundButtons = value; } } /// <summary> /// Gets or sets the floating poing offset (in pixels) for the line to be drawn to the left of /// the original line. (Internally, this will modify the width and compound array for the /// actual pen being used, as Pens do not support an offset property). /// </summary> [Serialize("Offset")] public float Offset { get { return _offset; } set { _offset = value; } } #endregion #region Protected Methods /// <summary> /// Handles the randomization of the cartographic properties of this stroke. /// </summary> /// <param name="generator">The random class that generates the random numbers</param> protected override void OnRandomize(Random generator) { base.OnRandomize(generator); DashStyle = DashStyle.Custom; _dashCap = generator.NextEnum<DashCap>(); _startCap = generator.NextEnum<LineCap>(); _endCap = generator.NextEnum<LineCap>(); _dashButtons = generator.NextBoolArray(1, 20); _compoundButtons = generator.NextBoolArray(1, 5); _offset = generator.NextFloat(10); _joinType = generator.NextEnum<LineJoinType>(); int len = generator.Next(0, 1); if (len > 0) { _decorations.Clear(); LineDecoration ld = new LineDecoration(); ld.Randomize(generator); _decorations.Add(ld); } } #endregion } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.WebSitesExtensions; using Microsoft.WindowsAzure.WebSitesExtensions.Models; namespace Microsoft.WindowsAzure { /// <summary> /// The websites extensions client manages the web sites deployments, web /// jobs and other extensions. /// </summary> public static partial class TriggeredWebJobOperationsExtensions { /// <summary> /// Delete a triggered WebJob. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.ITriggeredWebJobOperations. /// </param> /// <param name='jobName'> /// Required. The triggered WebJob name. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static OperationResponse Delete(this ITriggeredWebJobOperations operations, string jobName) { return Task.Factory.StartNew((object s) => { return ((ITriggeredWebJobOperations)s).DeleteAsync(jobName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete a triggered WebJob. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.ITriggeredWebJobOperations. /// </param> /// <param name='jobName'> /// Required. The triggered WebJob name. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<OperationResponse> DeleteAsync(this ITriggeredWebJobOperations operations, string jobName) { return operations.DeleteAsync(jobName, CancellationToken.None); } /// <summary> /// Get a triggered web job. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.ITriggeredWebJobOperations. /// </param> /// <param name='jobName'> /// Required. The triggered WebJob name. /// </param> /// <returns> /// The get triggered WebJob Operation Response. /// </returns> public static TriggeredWebJobGetResponse Get(this ITriggeredWebJobOperations operations, string jobName) { return Task.Factory.StartNew((object s) => { return ((ITriggeredWebJobOperations)s).GetAsync(jobName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get a triggered web job. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.ITriggeredWebJobOperations. /// </param> /// <param name='jobName'> /// Required. The triggered WebJob name. /// </param> /// <returns> /// The get triggered WebJob Operation Response. /// </returns> public static Task<TriggeredWebJobGetResponse> GetAsync(this ITriggeredWebJobOperations operations, string jobName) { return operations.GetAsync(jobName, CancellationToken.None); } /// <summary> /// Get a web job run. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.ITriggeredWebJobOperations. /// </param> /// <param name='jobName'> /// Required. The triggered WebJob name. /// </param> /// <param name='jobRunId'> /// Required. The triggered WebJob run identifier. /// </param> /// <returns> /// The get triggered WebJob Run operation response. /// </returns> public static TriggeredWebJobGetRunResponse GetRun(this ITriggeredWebJobOperations operations, string jobName, string jobRunId) { return Task.Factory.StartNew((object s) => { return ((ITriggeredWebJobOperations)s).GetRunAsync(jobName, jobRunId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get a web job run. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.ITriggeredWebJobOperations. /// </param> /// <param name='jobName'> /// Required. The triggered WebJob name. /// </param> /// <param name='jobRunId'> /// Required. The triggered WebJob run identifier. /// </param> /// <returns> /// The get triggered WebJob Run operation response. /// </returns> public static Task<TriggeredWebJobGetRunResponse> GetRunAsync(this ITriggeredWebJobOperations operations, string jobName, string jobRunId) { return operations.GetRunAsync(jobName, jobRunId, CancellationToken.None); } /// <summary> /// Get the settings of a triggered WebJob. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.ITriggeredWebJobOperations. /// </param> /// <param name='jobName'> /// Required. The triggered WebJob name. /// </param> /// <returns> /// The triggered WebJob settings operation response. /// </returns> public static TriggeredWebJobSettingsResponse GetSettings(this ITriggeredWebJobOperations operations, string jobName) { return Task.Factory.StartNew((object s) => { return ((ITriggeredWebJobOperations)s).GetSettingsAsync(jobName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the settings of a triggered WebJob. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.ITriggeredWebJobOperations. /// </param> /// <param name='jobName'> /// Required. The triggered WebJob name. /// </param> /// <returns> /// The triggered WebJob settings operation response. /// </returns> public static Task<TriggeredWebJobSettingsResponse> GetSettingsAsync(this ITriggeredWebJobOperations operations, string jobName) { return operations.GetSettingsAsync(jobName, CancellationToken.None); } /// <summary> /// List the triggered WebJobs. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.ITriggeredWebJobOperations. /// </param> /// <returns> /// The list of triggered WebJobs operation response. /// </returns> public static TriggeredWebJobListResponse List(this ITriggeredWebJobOperations operations) { return Task.Factory.StartNew((object s) => { return ((ITriggeredWebJobOperations)s).ListAsync(); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// List the triggered WebJobs. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.ITriggeredWebJobOperations. /// </param> /// <returns> /// The list of triggered WebJobs operation response. /// </returns> public static Task<TriggeredWebJobListResponse> ListAsync(this ITriggeredWebJobOperations operations) { return operations.ListAsync(CancellationToken.None); } /// <summary> /// List the triggered WebJob runs. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.ITriggeredWebJobOperations. /// </param> /// <param name='jobName'> /// Required. The triggered WebJob name. /// </param> /// <returns> /// The triggered WebJob run list operation response. /// </returns> public static TriggeredWebJobRunListResponse ListRuns(this ITriggeredWebJobOperations operations, string jobName) { return Task.Factory.StartNew((object s) => { return ((ITriggeredWebJobOperations)s).ListRunsAsync(jobName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// List the triggered WebJob runs. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.ITriggeredWebJobOperations. /// </param> /// <param name='jobName'> /// Required. The triggered WebJob name. /// </param> /// <returns> /// The triggered WebJob run list operation response. /// </returns> public static Task<TriggeredWebJobRunListResponse> ListRunsAsync(this ITriggeredWebJobOperations operations, string jobName) { return operations.ListRunsAsync(jobName, CancellationToken.None); } /// <summary> /// Run a triggered WebJob. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.ITriggeredWebJobOperations. /// </param> /// <param name='jobName'> /// Required. The triggered WebJob name. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static OperationResponse Run(this ITriggeredWebJobOperations operations, string jobName) { return Task.Factory.StartNew((object s) => { return ((ITriggeredWebJobOperations)s).RunAsync(jobName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Run a triggered WebJob. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.ITriggeredWebJobOperations. /// </param> /// <param name='jobName'> /// Required. The triggered WebJob name. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<OperationResponse> RunAsync(this ITriggeredWebJobOperations operations, string jobName) { return operations.RunAsync(jobName, CancellationToken.None); } /// <summary> /// Set the settings of a triggered WebJob (will replace the current /// settings of the WebJob). /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.ITriggeredWebJobOperations. /// </param> /// <param name='jobName'> /// Required. The triggered WebJob name. /// </param> /// <param name='settings'> /// Required. The triggered WebJob settings. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static OperationResponse SetSettings(this ITriggeredWebJobOperations operations, string jobName, TriggeredWebJobSettingsUpdateParameters settings) { return Task.Factory.StartNew((object s) => { return ((ITriggeredWebJobOperations)s).SetSettingsAsync(jobName, settings); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Set the settings of a triggered WebJob (will replace the current /// settings of the WebJob). /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.ITriggeredWebJobOperations. /// </param> /// <param name='jobName'> /// Required. The triggered WebJob name. /// </param> /// <param name='settings'> /// Required. The triggered WebJob settings. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<OperationResponse> SetSettingsAsync(this ITriggeredWebJobOperations operations, string jobName, TriggeredWebJobSettingsUpdateParameters settings) { return operations.SetSettingsAsync(jobName, settings, CancellationToken.None); } /// <summary> /// Create or replace a triggered WebJob with a script file (.exe, /// .bat, .php, .js...). /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.ITriggeredWebJobOperations. /// </param> /// <param name='jobName'> /// Required. The triggered WebJob name. /// </param> /// <param name='fileName'> /// Required. The file name. /// </param> /// <param name='jobContent'> /// Required. The file content. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static OperationResponse UploadFile(this ITriggeredWebJobOperations operations, string jobName, string fileName, Stream jobContent) { return Task.Factory.StartNew((object s) => { return ((ITriggeredWebJobOperations)s).UploadFileAsync(jobName, fileName, jobContent); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create or replace a triggered WebJob with a script file (.exe, /// .bat, .php, .js...). /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.ITriggeredWebJobOperations. /// </param> /// <param name='jobName'> /// Required. The triggered WebJob name. /// </param> /// <param name='fileName'> /// Required. The file name. /// </param> /// <param name='jobContent'> /// Required. The file content. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<OperationResponse> UploadFileAsync(this ITriggeredWebJobOperations operations, string jobName, string fileName, Stream jobContent) { return operations.UploadFileAsync(jobName, fileName, jobContent, CancellationToken.None); } /// <summary> /// Create or replace a triggered WebJob with a zip file (containing /// the WebJob binaries). /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.ITriggeredWebJobOperations. /// </param> /// <param name='jobName'> /// Required. The triggered WebJob name. /// </param> /// <param name='fileName'> /// Required. The zip file name. /// </param> /// <param name='jobContent'> /// Required. The zip file content. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static OperationResponse UploadZip(this ITriggeredWebJobOperations operations, string jobName, string fileName, Stream jobContent) { return Task.Factory.StartNew((object s) => { return ((ITriggeredWebJobOperations)s).UploadZipAsync(jobName, fileName, jobContent); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create or replace a triggered WebJob with a zip file (containing /// the WebJob binaries). /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.ITriggeredWebJobOperations. /// </param> /// <param name='jobName'> /// Required. The triggered WebJob name. /// </param> /// <param name='fileName'> /// Required. The zip file name. /// </param> /// <param name='jobContent'> /// Required. The zip file content. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<OperationResponse> UploadZipAsync(this ITriggeredWebJobOperations operations, string jobName, string fileName, Stream jobContent) { return operations.UploadZipAsync(jobName, fileName, jobContent, CancellationToken.None); } } }
using System; using System.Collections.Generic; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using UniTestAssert = Microsoft.VisualStudio.TestTools.UnitTesting.Assert; using System.Text.RegularExpressions; namespace LTAF.UnitTests.UI { [TestClass] public class HtmlElementBuilderTest { private HtmlElementBuilder _builder; [TestInitialize] public void SetUp() { ServiceLocator.ApplicationPathFinder = new ApplicationPathFinder("http://test"); _builder = new HtmlElementBuilder(null); } [TestMethod] public void CreateElementOnlyOneTagWithInnerText() { string html = @" <html> foo </html> "; HtmlElement element = _builder.CreateElement(html); Assert.AreEqual("html", element.TagName); Assert.AreEqual(0, element.ChildElements.Count); } [TestMethod] [ExpectedException(typeof(WebTestException))] public void CreateElementThrowsIfMoreThanOneRootTags() { // 2 root tags is not valid string html = @" <foo> </foo> <html> </html> "; HtmlElement element = _builder.CreateElement(html); } [TestMethod] public void CreateElementPopulatesAttributesDictionary() { string html = @" <html a=a b=b c=c d=d> </html> "; HtmlElement element = _builder.CreateElement(html); Assert.AreEqual(4, element.GetAttributes().Dictionary.Count); } [TestMethod] public void CreateElementWithMultipleChildTagsWithDifferentSpacing() { string html = @" <html > <tag1 /> <tag2 ></tag2> <tag3 /> </html> "; HtmlElement element = _builder.CreateElement(html); Assert.AreEqual(3, element.ChildElements.Count); foreach (HtmlElement child in element.ChildElements) { Assert.AreEqual(0, child.ChildElements.Count); Assert.AreEqual(0, child.GetAttributes().Dictionary.Count); } } [TestMethod] public void CreateElementDeepTagHierarchy() { string html = @" <html > <tag1> <tag2 > <tag3 > <tag4 /> </tag3> </tag2> </tag1> foo </html> "; HtmlElement element = _builder.CreateElement(html); Assert.AreEqual(1, element.ChildElements.Count); Assert.AreEqual(1, element.ChildElements[0].ChildElements[0].ChildElements.Count); } [TestMethod] public void CreateElementDoesNotTreatOperatorsAsTags() { string html = @" <html > <script> for(i=0; i<5;i++); </script> <script> if(c>t || c > t || c> t || c >t || c<>t || c< >t); </script> <script> <!-- <foo></bar> --> </script> </html> "; HtmlElement element = _builder.CreateElement(html); Assert.AreEqual(3, element.ChildElements.Count); Assert.AreEqual("for(i=0; i<5;i++);", element.ChildElements[0].CachedInnerText.Trim()); Assert.AreEqual("if(c>t || c > t || c> t || c >t || c<>t || c< >t);", element.ChildElements[1].CachedInnerText.Trim()); Assert.AreEqual("<!-- <foo></bar> -->", element.ChildElements[2].CachedInnerText.Trim()); } [TestMethod] public void CreateElementSelftClosingTags() { string html = @" <html> <foo> <bar /> </foo> </html> "; HtmlElement element = _builder.CreateElement(html); Assert.IsNull(element.ParentElement); Assert.AreEqual(element, element.ChildElements[0].ParentElement); Assert.AreEqual(element.ChildElements[0], element.ChildElements[0].ChildElements[0].ParentElement); } [TestMethod] public void CreateElementWithComments() { string html = @" <html > <div> for(i=0; i<5;i++); </div> <div> if(c>t || c > t || c> t || c >t || c<>t || c< >t); </div> <div> <!-- <foo></bar> --> </div> </html> "; HtmlElement element = _builder.CreateElement(html); Assert.AreEqual(3, element.ChildElements.Count); Assert.AreEqual("for(i=0; i<5;i++);", element.ChildElements[0].CachedInnerText.Trim()); Assert.AreEqual("if(c>t || c > t || c> t || c >t || c<>t || c< >t);", element.ChildElements[1].CachedInnerText.Trim()); Assert.AreEqual("<!-- <foo></bar> -->", element.ChildElements[2].CachedInnerText.Trim()); } [TestMethod] public void CreateElementScriptIsConsideredAsLiteral() { string html = @" <html > <script> <foo>bar</foo> </script> </html> "; HtmlElement element = _builder.CreateElement(html); Assert.AreEqual(0, element.ChildElements[0].ChildElements.Count); Assert.AreEqual("<foo>bar</foo>", element.ChildElements[0].CachedInnerText.Trim()); } [TestMethod] public void CreateElementTagsWithDifferentCasing() { string html = @" <html> <FOO> hola </foo> </HTML> "; HtmlElement element = _builder.CreateElement(html); Assert.AreEqual("hola", element.ChildElements[0].CachedInnerText.Trim()); } [TestMethod] public void CreateElementAttributesWithNoQuotes() { string html = @" <html> <FOO a=a c=c> <bar b=b /> </foo> </HTML> "; HtmlElement element = _builder.CreateElement(html); Assert.AreEqual("a", element.ChildElements[0].GetAttributes().Dictionary["a"]); Assert.AreEqual("c", element.ChildElements[0].GetAttributes().Dictionary["c"]); Assert.AreEqual("b", element.ChildElements[0].ChildElements[0].GetAttributes().Dictionary["b"]); } [TestMethod] public void CreateElementCorrectsMalFormedHtml() { string html = @" <html> <bar /> </foo> "; HtmlElement element = _builder.CreateElement(html); Assert.AreEqual(1, element.ChildElements.Count); Assert.AreEqual("bar", element.ChildElements[0].TagName); } [TestMethod] [ExpectedException(typeof(WebTestException))] public void CreateElementThrowsIfEnsureValidMarkup() { string html = @" <html> <bar /> </foo> "; _builder.EnsureValidMarkup = true; HtmlElement element = _builder.CreateElement(html); } [TestMethod] public void CreateElementUpperCaseID() { string html = @" <html> <bar ID='bar1' /> </html> "; _builder.EnsureValidMarkup = true; HtmlElement element = _builder.CreateElement(html); Assert.IsNull(element.Id); Assert.AreEqual("bar1", element.ChildElements[0].Id); } [TestMethod] public void CreateElementStronglyTypedElements() { string html = @" <html> <input ID='control1' /> <select ID='control2' /> <a ID='control3' /> </html> "; HtmlElement element = _builder.CreateElement(html); Assert.IsTrue(element.ChildElements[0] is HtmlInputElement); Assert.IsTrue(element.ChildElements[1] is HtmlSelectElement); Assert.IsTrue(element.ChildElements[2] is HtmlAnchorElement); } [TestMethod] public void CreateElementCheckTagNameIndex() { string html = @" <html> <input ID='control1' /> <input ID='control2' /> <input Id='control3' /> </html> "; HtmlElement element = _builder.CreateElement(html); Assert.AreEqual(0, element.ChildElements[0].TagNameIndex); Assert.AreEqual(1, element.ChildElements[1].TagNameIndex); Assert.AreEqual(2, element.ChildElements[2].TagNameIndex); } [TestMethod] public void IgnoreDuplicateAttributesWhenBuildingDictionary() { string html = @"<a foo='blah' foo='bar' />"; HtmlElement element = _builder.CreateElement(html); Assert.AreEqual("blah", element.AttributeDictionary["foo"]); } [TestMethod] public void VerifyFormElementIsCreated() { string html = @"<html><form id='form1' /></html>"; HtmlElement element = _builder.CreateElement(html); Assert.IsInstanceOfType(element.ChildElements.Find("form1"), typeof(HtmlFormElement)); Assert.AreEqual("form", element.ChildElements.Find("form1").TagName); } [TestMethod] public void WhenGenerateHtmlElement_ShouldStoreStartAndEndIndeces() { // Arrange string html = @" <html> <FOO a=a c=c> <bar b=b /> </foo> </HTML> "; // Act HtmlElement element = _builder.CreateElement(html); // Assert Assert.AreEqual(46, element.ChildElements[0].StartPosition); Assert.AreEqual(123, element.ChildElements[0].EndPosition); } } }
using Android.Views; using Android.Views.Animations; using Java.Lang; using SciChart.Charting.Model.DataSeries; using SciChart.Charting.Modifiers; using SciChart.Charting.Numerics.LabelProviders; using SciChart.Charting.Visuals; using SciChart.Charting.Visuals.Animations; using SciChart.Charting.Visuals.Axes; using SciChart.Charting.Visuals.RenderableSeries; using SciChart.Core.Utility; using SciChart.Data.Model; using SciChart.Drawing.Common; using Xamarin.Examples.Demo; using Xamarin.Examples.Demo.Droid.Fragments.Base; namespace Xamarin.Examples.Demo.Droid.Fragments.Examples { [ExampleDefinition("Stacked Column Side By Side Chart", description: "A Stacked Column chart with columns grouped side by side", icon: ExampleIcon.StackedColumn)] public class StackedColumnSideBySideFragment : ExampleBaseFragment { public SciChartSurface Surface => View.FindViewById<SciChartSurface>(Resource.Id.chart); public override int ExampleLayoutId => Resource.Layout.Example_Single_Chart_Fragment; protected override void InitExample() { var xAxis = new NumericAxis(Activity) { AutoTicks = false, MajorDelta = 1d.FromComparable(), MinorDelta = 0.5d.FromComparable(), DrawMajorBands = true, LabelProvider = new YearsLabelProvider(), }; var yAxis = new NumericAxis(Activity) { AutoRange = AutoRange.Always, AxisTitle = "billions of People", GrowBy = new DoubleRange(0, 0.1), DrawMajorBands = true, }; var china = new[] {1.269, 1.330, 1.356, 1.304}; var india = new[] {1.004, 1.173, 1.236, 1.656}; var usa = new[] {0.282, 0.310, 0.319, 0.439}; var indonesia = new[] {0.214, 0.243, 0.254, 0.313}; var brazil = new[] {0.176, 0.201, 0.203, 0.261}; var pakistan = new[] {0.146, 0.184, 0.196, 0.276}; var nigeria = new[] {0.123, 0.152, 0.177, 0.264}; var bangladesh = new[] {0.130, 0.156, 0.166, 0.234}; var russia = new[] {0.147, 0.139, 0.142, 0.109}; var japan = new[] {0.126, 0.127, 0.127, 0.094}; var restOfTheWorld = new[] {2.466, 2.829, 3.005, 4.306}; var chinaDataSeries = new XyDataSeries<double, double> {SeriesName = "China"}; var indiaDataSeries = new XyDataSeries<double, double> {SeriesName = "India"}; var usaDataSeries = new XyDataSeries<double, double> {SeriesName = "USA"}; var indonesiaDataSeries = new XyDataSeries<double, double> {SeriesName = "Indonesia"}; var brazilDataSeries = new XyDataSeries<double, double> {SeriesName = "Brazil"}; var pakistanDataSeries = new XyDataSeries<double, double> {SeriesName = "Pakistan"}; var nigeriaDataSeries = new XyDataSeries<double, double> {SeriesName = "Nigeria"}; var bangladeshDataSeries = new XyDataSeries<double, double> {SeriesName = "Bangladesh"}; var russiaDataSeries = new XyDataSeries<double, double> {SeriesName = "Russia"}; var japanDataSeries = new XyDataSeries<double, double> {SeriesName = "Japan"}; var restOfTheWorldDataSeries = new XyDataSeries<double, double> {SeriesName = "Rest Of The World"}; var totalDataSeries = new XyDataSeries<double, double> {SeriesName = "Total"}; for (var i = 0; i < 4; i++) { double xValue = i; chinaDataSeries.Append(xValue, china[i]); if (i != 2) { indiaDataSeries.Append(xValue, india[i]); usaDataSeries.Append(xValue, usa[i]); indonesiaDataSeries.Append(xValue, indonesia[i]); brazilDataSeries.Append(xValue, brazil[i]); } else { indiaDataSeries.Append(xValue, Double.NaN); usaDataSeries.Append(xValue, Double.NaN); indonesiaDataSeries.Append(xValue, Double.NaN); brazilDataSeries.Append(xValue, Double.NaN); } pakistanDataSeries.Append(xValue, pakistan[i]); nigeriaDataSeries.Append(xValue, nigeria[i]); bangladeshDataSeries.Append(xValue, bangladesh[i]); russiaDataSeries.Append(xValue, russia[i]); japanDataSeries.Append(xValue, japan[i]); restOfTheWorldDataSeries.Append(xValue, restOfTheWorld[i]); totalDataSeries.Append(xValue, china[i] + india[i] + usa[i] + indonesia[i] + brazil[i] + pakistan[i] + nigeria[i] + bangladesh[i] + russia[i] + japan[i] + restOfTheWorld[i]); } var rs1 = GetRenderableSeries(chinaDataSeries, 0xff3399ff, 0xff2D68BC); var rs2 = GetRenderableSeries(indiaDataSeries, 0xff014358, 0xff013547); var rs3 = GetRenderableSeries(usaDataSeries, 0xff1f8a71, 0xff1B5D46); var rs4 = GetRenderableSeries(indonesiaDataSeries, 0xffbdd63b, 0xff7E952B); var rs5 = GetRenderableSeries(brazilDataSeries, 0xffffe00b, 0xffAA8F0B); var rs6 = GetRenderableSeries(pakistanDataSeries, 0xfff27421, 0xffA95419); var rs7 = GetRenderableSeries(nigeriaDataSeries, 0xffbb0000, 0xff840000); var rs8 = GetRenderableSeries(bangladeshDataSeries, 0xff550033, 0xff370018); var rs9 = GetRenderableSeries(russiaDataSeries, 0xff339933, 0xff2D732D); var rs10 = GetRenderableSeries(japanDataSeries, 0xff00aba9, 0xff006C6A); var rs11 = GetRenderableSeries(restOfTheWorldDataSeries, 0xff560068, 0xff3D0049); var columnsCollection = new HorizontallyStackedColumnsCollection(); columnsCollection.Add(rs1); columnsCollection.Add(rs2); columnsCollection.Add(rs3); columnsCollection.Add(rs4); columnsCollection.Add(rs5); columnsCollection.Add(rs6); columnsCollection.Add(rs7); columnsCollection.Add(rs8); columnsCollection.Add(rs9); columnsCollection.Add(rs10); columnsCollection.Add(rs11); var legendModifier = new LegendModifier(Activity); legendModifier.SetLegendPosition(GravityFlags.Top | GravityFlags.Left, 10); using (Surface.SuspendUpdates()) { Surface.XAxes.Add(xAxis); Surface.YAxes.Add(yAxis); Surface.RenderableSeries.Add(columnsCollection); Surface.ChartModifiers.Add(legendModifier); Surface.ChartModifiers.Add(new TooltipModifier()); } new WaveAnimatorBuilder(rs1) { Interpolator = new DecelerateInterpolator(), Duration = 3000, StartDelay = 350 }.Start(); new WaveAnimatorBuilder(rs2) { Interpolator = new DecelerateInterpolator(), Duration = 3000, StartDelay = 350 }.Start(); new WaveAnimatorBuilder(rs3) { Interpolator = new DecelerateInterpolator(), Duration = 3000, StartDelay = 350 }.Start(); new WaveAnimatorBuilder(rs4) { Interpolator = new DecelerateInterpolator(), Duration = 3000, StartDelay = 350 }.Start(); new WaveAnimatorBuilder(rs5) { Interpolator = new DecelerateInterpolator(), Duration = 3000, StartDelay = 350 }.Start(); new WaveAnimatorBuilder(rs6) { Interpolator = new DecelerateInterpolator(), Duration = 3000, StartDelay = 350 }.Start(); new WaveAnimatorBuilder(rs7) { Interpolator = new DecelerateInterpolator(), Duration = 3000, StartDelay = 350 }.Start(); new WaveAnimatorBuilder(rs8) { Interpolator = new DecelerateInterpolator(), Duration = 3000, StartDelay = 350 }.Start(); new WaveAnimatorBuilder(rs9) { Interpolator = new DecelerateInterpolator(), Duration = 3000, StartDelay = 350 }.Start(); new WaveAnimatorBuilder(rs10) { Interpolator = new DecelerateInterpolator(), Duration = 3000, StartDelay = 350 }.Start(); new WaveAnimatorBuilder(rs11) { Interpolator = new DecelerateInterpolator(), Duration = 3000, StartDelay = 350 }.Start(); } private StackedColumnRenderableSeries GetRenderableSeries(IDataSeries dataSeries, uint fillColor, uint strokeColor) { return new StackedColumnRenderableSeries { DataSeries = dataSeries, StrokeStyle = new SolidPenStyle(Activity, strokeColor), FillBrushStyle = new SolidBrushStyle(fillColor) }; } } class YearsLabelFormatter : LabelFormatterBase { private readonly string[] _xLabels = {"2000", "2010", "2014", "2050"}; public override void Update(Object axis) { } public override ICharSequence FormatLabelFormatted(double dataValue) { var i = (int) dataValue; var result = ""; if (i >= 0 && i < 4) { result = _xLabels[i]; } return new String(result); } public override ICharSequence FormatCursorLabelFormatted(double dataValue) { var i = (int) dataValue; string result; if (i >= 0 && i < 4) { result = _xLabels[i]; } else if (i < 0) { result = _xLabels[0]; } else { result = _xLabels[3]; } return new String(result); } } class YearsLabelProvider : FormatterLabelProviderBase { public YearsLabelProvider() : base(typeof (NumericAxis).ToClass(), new YearsLabelFormatter()) { } } }
using System.IO; using AsmResolver.PE.File; using AsmResolver.PE.File.Headers; using AsmResolver.PE.Tls; using Xunit; namespace AsmResolver.PE.Tests.Tls { public class TlsDirectoryTest { [Fact] public void ReadTemplateDataX86() { var image = PEImage.FromBytes(Properties.Resources.TlsTest_x86); Assert.Equal(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x56, 0x34, 0x12, 0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64, 0x21, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, image.TlsDirectory!.TemplateData!.ToArray()); } [Fact] public void ReadTemplateDataX64() { var image = PEImage.FromBytes(Properties.Resources.TlsTest_x64); Assert.Equal(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x56, 0x34, 0x12, 0x00, 0x00, 0x00, 0x00, 0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64, 0x21, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, image.TlsDirectory!.TemplateData!.ToArray()); } [Fact] public void ReadCallbacksTableX86() { var image = PEImage.FromBytes(Properties.Resources.TlsTest_x86); Assert.Single(image.TlsDirectory!.CallbackFunctions); } [Fact] public void ReadCallbacksTableX64() { var image = PEImage.FromBytes(Properties.Resources.TlsTest_x64); Assert.Single(image.TlsDirectory!.CallbackFunctions); } [Theory] [InlineData(false)] [InlineData(true)] public void Persistent(bool is32Bit) { // Build PE file skeleton. var text = new PESection(".text", SectionFlags.ContentCode | SectionFlags.MemoryExecute | SectionFlags.MemoryRead); var textBuilder = new SegmentBuilder(); text.Contents = textBuilder; var rdata = new PESection(".rdata", SectionFlags.ContentInitializedData | SectionFlags.MemoryRead); var rdataBuilder = new SegmentBuilder(); rdata.Contents = rdataBuilder; var data = new PESection(".data", SectionFlags.ContentInitializedData | SectionFlags.MemoryRead | SectionFlags.MemoryWrite); var dataBuilder = new SegmentBuilder(); data.Contents = dataBuilder; var tls = new PESection(".tls", SectionFlags.ContentInitializedData | SectionFlags.MemoryRead | SectionFlags.MemoryWrite); var tlsBuilder = new SegmentBuilder(); tls.Contents = tlsBuilder; var file = new PEFile { FileHeader = { Machine = is32Bit ? MachineType.I386 : MachineType.Amd64, }, OptionalHeader = { Magic = is32Bit ? OptionalHeaderMagic.Pe32 : OptionalHeaderMagic.Pe32Plus }, Sections = { text, rdata, data, tls }, }; // Create dummy functions and TLS data. var callbackFunction1 = new DataSegment(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 }); var callbackFunction2 = new DataSegment(new byte[] { 8, 9, 10, 11, 12, 13, 14, 15 }); var indexSegment = new DataSegment(new byte[] { 30, 31, 32, 33, 34, 35, 36, 37 }); var templateData = new DataSegment(new byte[] { 20, 21, 22, 23, 24, 25, 26, 27 }); var directory = new TlsDirectory { ImageBase = file.OptionalHeader.ImageBase, Is32Bit = file.OptionalHeader.Magic == OptionalHeaderMagic.Pe32, TemplateData = templateData, Index = indexSegment.ToReference(), Characteristics = TlsCharacteristics.Align4Bytes, CallbackFunctions = { callbackFunction1.ToReference(), callbackFunction2.ToReference(), } }; // Put dummy data into the sections. textBuilder.Add(callbackFunction1, 4); textBuilder.Add(callbackFunction2, 4); rdataBuilder.Add(directory); rdataBuilder.Add(directory.CallbackFunctions); dataBuilder.Add(indexSegment); tlsBuilder.Add(directory.TemplateData); // Update TLS directory. file.UpdateHeaders(); file.OptionalHeader.DataDirectories[(int) DataDirectoryIndex.TlsDirectory] = new DataDirectory(directory.Rva, directory.GetPhysicalSize()); // Write. using var s = new MemoryStream(); file.Write(s); // Read. var image = PEImage.FromBytes(s.ToArray()); var newDirectory = image.TlsDirectory!; Assert.NotNull(newDirectory); // Verify. Assert.Equal(2, newDirectory.CallbackFunctions.Count); byte[] buffer = new byte[8]; Assert.Equal(buffer.Length, newDirectory.Index.CreateReader().ReadBytes(buffer, 0, buffer.Length)); Assert.Equal(indexSegment.Data, buffer); Assert.NotNull(newDirectory.TemplateData); Assert.Equal(templateData.Data, newDirectory.TemplateData!.ToArray()); Assert.Equal(buffer.Length, newDirectory.CallbackFunctions[0].CreateReader().ReadBytes(buffer, 0, buffer.Length)); Assert.Equal(callbackFunction1.Data, buffer); Assert.Equal(buffer.Length, newDirectory.CallbackFunctions[1].CreateReader().ReadBytes(buffer, 0, buffer.Length)); Assert.Equal(callbackFunction2.Data, buffer); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; namespace System.Collections.Immutable { public sealed partial class ImmutableSortedDictionary<TKey, TValue> { /// <summary> /// A node in the AVL tree storing this map. /// </summary> [DebuggerDisplay("{_key} = {_value}")] internal sealed class Node : IBinaryTree<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>> { /// <summary> /// The default empty node. /// </summary> internal static readonly Node EmptyNode = new Node(); /// <summary> /// The key associated with this node. /// </summary> private readonly TKey _key; /// <summary> /// The value associated with this node. /// </summary> private readonly TValue _value; /// <summary> /// A value indicating whether this node has been frozen (made immutable). /// </summary> /// <remarks> /// Nodes must be frozen before ever being observed by a wrapping collection type /// to protect collections from further mutations. /// </remarks> private bool _frozen; /// <summary> /// The depth of the tree beneath this node. /// </summary> private byte _height; // AVL tree max height <= ~1.44 * log2(maxNodes + 2) /// <summary> /// The left tree. /// </summary> private Node _left; /// <summary> /// The right tree. /// </summary> private Node _right; /// <summary> /// Initializes a new instance of the <see cref="ImmutableSortedDictionary{TKey, TValue}.Node"/> class /// that is pre-frozen. /// </summary> private Node() { Contract.Ensures(this.IsEmpty); _frozen = true; // the empty node is *always* frozen. } /// <summary> /// Initializes a new instance of the <see cref="ImmutableSortedDictionary{TKey, TValue}.Node"/> class /// that is not yet frozen. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <param name="frozen">Whether this node is prefrozen.</param> private Node(TKey key, TValue value, Node left, Node right, bool frozen = false) { Requires.NotNullAllowStructs(key, nameof(key)); Requires.NotNull(left, nameof(left)); Requires.NotNull(right, nameof(right)); Debug.Assert(!frozen || (left._frozen && right._frozen)); Contract.Ensures(!this.IsEmpty); Contract.Ensures(_key != null); Contract.Ensures(_left == left); Contract.Ensures(_right == right); _key = key; _value = value; _left = left; _right = right; _height = checked((byte)(1 + Math.Max(left._height, right._height))); _frozen = frozen; } /// <summary> /// Gets a value indicating whether this instance is empty. /// </summary> /// <value> /// <c>true</c> if this instance is empty; otherwise, <c>false</c>. /// </value> public bool IsEmpty { get { Contract.Ensures((_left != null && _right != null) || Contract.Result<bool>()); return _left == null; } } /// <summary> /// Gets the left branch of this node. /// </summary> IBinaryTree<KeyValuePair<TKey, TValue>> IBinaryTree<KeyValuePair<TKey, TValue>>.Left { get { return _left; } } /// <summary> /// Gets the right branch of this node. /// </summary> IBinaryTree<KeyValuePair<TKey, TValue>> IBinaryTree<KeyValuePair<TKey, TValue>>.Right { get { return _right; } } /// <summary> /// Gets the height of the tree beneath this node. /// </summary> public int Height { get { return _height; } } /// <summary> /// Gets the left branch of this node. /// </summary> public Node Left { get { return _left; } } /// <summary> /// Gets the left branch of this node. /// </summary> IBinaryTree IBinaryTree.Left { get { return _left; } } /// <summary> /// Gets the right branch of this node. /// </summary> public Node Right { get { return _right; } } /// <summary> /// Gets the right branch of this node. /// </summary> IBinaryTree IBinaryTree.Right { get { return _right; } } /// <summary> /// Gets the value represented by the current node. /// </summary> public KeyValuePair<TKey, TValue> Value { get { return new KeyValuePair<TKey, TValue>(_key, _value); } } /// <summary> /// Gets the number of elements contained by this node and below. /// </summary> int IBinaryTree.Count { get { throw new NotSupportedException(); } } /// <summary> /// Gets the keys. /// </summary> internal IEnumerable<TKey> Keys { get { return Linq.Enumerable.Select(this, p => p.Key); } } /// <summary> /// Gets the values. /// </summary> internal IEnumerable<TValue> Values { get { return Linq.Enumerable.Select(this, p => p.Value); } } #region IEnumerable<TKey> Members /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> public Enumerator GetEnumerator() { return new Enumerator(this); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <param name="builder">The builder, if applicable.</param> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> internal Enumerator GetEnumerator(Builder builder) { return new Enumerator(this, builder); } /// <summary> /// See <see cref="IDictionary{TKey, TValue}"/> /// </summary> internal void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex, int dictionarySize) { Requires.NotNull(array, nameof(array)); Requires.Range(arrayIndex >= 0, nameof(arrayIndex)); Requires.Range(array.Length >= arrayIndex + dictionarySize, nameof(arrayIndex)); foreach (var item in this) { array[arrayIndex++] = item; } } /// <summary> /// See <see cref="IDictionary{TKey, TValue}"/> /// </summary> internal void CopyTo(Array array, int arrayIndex, int dictionarySize) { Requires.NotNull(array, nameof(array)); Requires.Range(arrayIndex >= 0, nameof(arrayIndex)); Requires.Range(array.Length >= arrayIndex + dictionarySize, nameof(arrayIndex)); foreach (var item in this) { array.SetValue(new DictionaryEntry(item.Key, item.Value), arrayIndex++); } } /// <summary> /// Creates a node tree from an existing (mutable) collection. /// </summary> /// <param name="dictionary">The collection.</param> /// <returns>The root of the node tree.</returns> [Pure] internal static Node NodeTreeFromSortedDictionary(SortedDictionary<TKey, TValue> dictionary) { Requires.NotNull(dictionary, nameof(dictionary)); Contract.Ensures(Contract.Result<Node>() != null); var list = dictionary.AsOrderedCollection(); return NodeTreeFromList(list, 0, list.Count); } /// <summary> /// Adds the specified key. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="keyComparer">The key comparer.</param> /// <param name="valueComparer">The value comparer.</param> /// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param> internal Node Add(TKey key, TValue value, IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer, out bool mutated) { Requires.NotNullAllowStructs(key, nameof(key)); Requires.NotNull(keyComparer, nameof(keyComparer)); Requires.NotNull(valueComparer, nameof(valueComparer)); bool dummy; return this.SetOrAdd(key, value, keyComparer, valueComparer, false, out dummy, out mutated); } /// <summary> /// Adds the specified key. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="keyComparer">The key comparer.</param> /// <param name="valueComparer">The value comparer.</param> /// <param name="replacedExistingValue">Receives a value indicating whether an existing value was replaced.</param> /// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param> internal Node SetItem(TKey key, TValue value, IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer, out bool replacedExistingValue, out bool mutated) { Requires.NotNullAllowStructs(key, nameof(key)); Requires.NotNull(keyComparer, nameof(keyComparer)); Requires.NotNull(valueComparer, nameof(valueComparer)); return this.SetOrAdd(key, value, keyComparer, valueComparer, true, out replacedExistingValue, out mutated); } /// <summary> /// Removes the specified key. /// </summary> /// <param name="key">The key.</param> /// <param name="keyComparer">The key comparer.</param> /// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param> /// <returns>The new AVL tree.</returns> internal Node Remove(TKey key, IComparer<TKey> keyComparer, out bool mutated) { Requires.NotNullAllowStructs(key, nameof(key)); Requires.NotNull(keyComparer, nameof(keyComparer)); return this.RemoveRecursive(key, keyComparer, out mutated); } #if FEATURE_ITEMREFAPI /// <summary> /// Returns a read-only reference to the value associated with the provided key. /// </summary> /// <exception cref="KeyNotFoundException">If the key is not present.</exception> [Pure] internal ref readonly TValue ValueRef(TKey key, IComparer<TKey> keyComparer) { Requires.NotNullAllowStructs(key, nameof(key)); Requires.NotNull(keyComparer, nameof(keyComparer)); var match = this.Search(key, keyComparer); if (match.IsEmpty) { throw new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString())); } return ref match._value; } #endif /// <summary> /// Tries to get the value. /// </summary> /// <param name="key">The key.</param> /// <param name="keyComparer">The key comparer.</param> /// <param name="value">The value.</param> /// <returns>True if the key was found.</returns> [Pure] internal bool TryGetValue(TKey key, IComparer<TKey> keyComparer, out TValue value) { Requires.NotNullAllowStructs(key, nameof(key)); Requires.NotNull(keyComparer, nameof(keyComparer)); var match = this.Search(key, keyComparer); if (match.IsEmpty) { value = default(TValue); return false; } else { value = match._value; return true; } } /// <summary> /// Searches the dictionary for a given key and returns the equal key it finds, if any. /// </summary> /// <param name="equalKey">The key to search for.</param> /// <param name="keyComparer">The key comparer.</param> /// <param name="actualKey">The key from the dictionary that the search found, or <paramref name="equalKey"/> if the search yielded no match.</param> /// <returns>A value indicating whether the search was successful.</returns> /// <remarks> /// This can be useful when you want to reuse a previously stored reference instead of /// a newly constructed one (so that more sharing of references can occur) or to look up /// the canonical value, or a value that has more complete data than the value you currently have, /// although their comparer functions indicate they are equal. /// </remarks> [Pure] internal bool TryGetKey(TKey equalKey, IComparer<TKey> keyComparer, out TKey actualKey) { Requires.NotNullAllowStructs(equalKey, nameof(equalKey)); Requires.NotNull(keyComparer, nameof(keyComparer)); var match = this.Search(equalKey, keyComparer); if (match.IsEmpty) { actualKey = equalKey; return false; } else { actualKey = match._key; return true; } } /// <summary> /// Determines whether the specified key contains key. /// </summary> /// <param name="key">The key.</param> /// <param name="keyComparer">The key comparer.</param> /// <returns> /// <c>true</c> if the specified key contains key; otherwise, <c>false</c>. /// </returns> [Pure] internal bool ContainsKey(TKey key, IComparer<TKey> keyComparer) { Requires.NotNullAllowStructs(key, nameof(key)); Requires.NotNull(keyComparer, nameof(keyComparer)); return !this.Search(key, keyComparer).IsEmpty; } /// <summary> /// Determines whether the <see cref="ImmutableSortedDictionary{TKey, TValue}"/> /// contains an element with the specified value. /// </summary> /// <param name="value"> /// The value to locate in the <see cref="ImmutableSortedDictionary{TKey, TValue}"/>. /// The value can be null for reference types. /// </param> /// <param name="valueComparer">The value comparer to use.</param> /// <returns> /// true if the <see cref="ImmutableSortedDictionary{TKey, TValue}"/> contains /// an element with the specified value; otherwise, false. /// </returns> [Pure] internal bool ContainsValue(TValue value, IEqualityComparer<TValue> valueComparer) { Requires.NotNull(valueComparer, nameof(valueComparer)); foreach (KeyValuePair<TKey, TValue> item in this) { if (valueComparer.Equals(value, item.Value)) { return true; } } return false; } /// <summary> /// Determines whether [contains] [the specified pair]. /// </summary> /// <param name="pair">The pair.</param> /// <param name="keyComparer">The key comparer.</param> /// <param name="valueComparer">The value comparer.</param> /// <returns> /// <c>true</c> if [contains] [the specified pair]; otherwise, <c>false</c>. /// </returns> [Pure] internal bool Contains(KeyValuePair<TKey, TValue> pair, IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer) { Requires.NotNullAllowStructs(pair.Key, nameof(pair.Key)); Requires.NotNull(keyComparer, nameof(keyComparer)); Requires.NotNull(valueComparer, nameof(valueComparer)); var matchingNode = this.Search(pair.Key, keyComparer); if (matchingNode.IsEmpty) { return false; } return valueComparer.Equals(matchingNode._value, pair.Value); } /// <summary> /// Freezes this node and all descendant nodes so that any mutations require a new instance of the nodes. /// </summary> internal void Freeze() { // If this node is frozen, all its descendants must already be frozen. if (!_frozen) { _left.Freeze(); _right.Freeze(); _frozen = true; } } #region Tree balancing methods /// <summary> /// AVL rotate left operation. /// </summary> /// <param name="tree">The tree.</param> /// <returns>The rotated tree.</returns> private static Node RotateLeft(Node tree) { Requires.NotNull(tree, nameof(tree)); Debug.Assert(!tree.IsEmpty); Contract.Ensures(Contract.Result<Node>() != null); if (tree._right.IsEmpty) { return tree; } var right = tree._right; return right.Mutate(left: tree.Mutate(right: right._left)); } /// <summary> /// AVL rotate right operation. /// </summary> /// <param name="tree">The tree.</param> /// <returns>The rotated tree.</returns> private static Node RotateRight(Node tree) { Requires.NotNull(tree, nameof(tree)); Debug.Assert(!tree.IsEmpty); Contract.Ensures(Contract.Result<Node>() != null); if (tree._left.IsEmpty) { return tree; } var left = tree._left; return left.Mutate(right: tree.Mutate(left: left._right)); } /// <summary> /// AVL rotate double-left operation. /// </summary> /// <param name="tree">The tree.</param> /// <returns>The rotated tree.</returns> private static Node DoubleLeft(Node tree) { Requires.NotNull(tree, nameof(tree)); Debug.Assert(!tree.IsEmpty); Contract.Ensures(Contract.Result<Node>() != null); if (tree._right.IsEmpty) { return tree; } Node rotatedRightChild = tree.Mutate(right: RotateRight(tree._right)); return RotateLeft(rotatedRightChild); } /// <summary> /// AVL rotate double-right operation. /// </summary> /// <param name="tree">The tree.</param> /// <returns>The rotated tree.</returns> private static Node DoubleRight(Node tree) { Requires.NotNull(tree, nameof(tree)); Debug.Assert(!tree.IsEmpty); Contract.Ensures(Contract.Result<Node>() != null); if (tree._left.IsEmpty) { return tree; } Node rotatedLeftChild = tree.Mutate(left: RotateLeft(tree._left)); return RotateRight(rotatedLeftChild); } /// <summary> /// Returns a value indicating whether the tree is in balance. /// </summary> /// <param name="tree">The tree.</param> /// <returns>0 if the tree is in balance, a positive integer if the right side is heavy, or a negative integer if the left side is heavy.</returns> [Pure] private static int Balance(Node tree) { Requires.NotNull(tree, nameof(tree)); Debug.Assert(!tree.IsEmpty); return tree._right._height - tree._left._height; } /// <summary> /// Determines whether the specified tree is right heavy. /// </summary> /// <param name="tree">The tree.</param> /// <returns> /// <c>true</c> if [is right heavy] [the specified tree]; otherwise, <c>false</c>. /// </returns> [Pure] private static bool IsRightHeavy(Node tree) { Requires.NotNull(tree, nameof(tree)); Debug.Assert(!tree.IsEmpty); return Balance(tree) >= 2; } /// <summary> /// Determines whether the specified tree is left heavy. /// </summary> [Pure] private static bool IsLeftHeavy(Node tree) { Requires.NotNull(tree, nameof(tree)); Debug.Assert(!tree.IsEmpty); return Balance(tree) <= -2; } /// <summary> /// Balances the specified tree. /// </summary> /// <param name="tree">The tree.</param> /// <returns>A balanced tree.</returns> [Pure] private static Node MakeBalanced(Node tree) { Requires.NotNull(tree, nameof(tree)); Debug.Assert(!tree.IsEmpty); Contract.Ensures(Contract.Result<Node>() != null); if (IsRightHeavy(tree)) { return Balance(tree._right) < 0 ? DoubleLeft(tree) : RotateLeft(tree); } if (IsLeftHeavy(tree)) { return Balance(tree._left) > 0 ? DoubleRight(tree) : RotateRight(tree); } return tree; } #endregion /// <summary> /// Creates a node tree that contains the contents of a list. /// </summary> /// <param name="items">An indexable list with the contents that the new node tree should contain.</param> /// <param name="start">The starting index within <paramref name="items"/> that should be captured by the node tree.</param> /// <param name="length">The number of elements from <paramref name="items"/> that should be captured by the node tree.</param> /// <returns>The root of the created node tree.</returns> [Pure] private static Node NodeTreeFromList(IOrderedCollection<KeyValuePair<TKey, TValue>> items, int start, int length) { Requires.NotNull(items, nameof(items)); Requires.Range(start >= 0, nameof(start)); Requires.Range(length >= 0, nameof(length)); Contract.Ensures(Contract.Result<Node>() != null); if (length == 0) { return EmptyNode; } int rightCount = (length - 1) / 2; int leftCount = (length - 1) - rightCount; Node left = NodeTreeFromList(items, start, leftCount); Node right = NodeTreeFromList(items, start + leftCount + 1, rightCount); var item = items[start + leftCount]; return new Node(item.Key, item.Value, left, right, true); } /// <summary> /// Adds the specified key. Callers are expected to have validated arguments. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="keyComparer">The key comparer.</param> /// <param name="valueComparer">The value comparer.</param> /// <param name="overwriteExistingValue">if <c>true</c>, an existing key=value pair will be overwritten with the new one.</param> /// <param name="replacedExistingValue">Receives a value indicating whether an existing value was replaced.</param> /// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param> /// <returns>The new AVL tree.</returns> private Node SetOrAdd(TKey key, TValue value, IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer, bool overwriteExistingValue, out bool replacedExistingValue, out bool mutated) { // Arg validation skipped in this private method because it's recursive and the tax // of revalidating arguments on each recursive call is significant. // All our callers are therefore required to have done input validation. replacedExistingValue = false; if (this.IsEmpty) { mutated = true; return new Node(key, value, this, this); } else { Node result = this; int compareResult = keyComparer.Compare(key, _key); if (compareResult > 0) { var newRight = _right.SetOrAdd(key, value, keyComparer, valueComparer, overwriteExistingValue, out replacedExistingValue, out mutated); if (mutated) { result = this.Mutate(right: newRight); } } else if (compareResult < 0) { var newLeft = _left.SetOrAdd(key, value, keyComparer, valueComparer, overwriteExistingValue, out replacedExistingValue, out mutated); if (mutated) { result = this.Mutate(left: newLeft); } } else { if (valueComparer.Equals(_value, value)) { mutated = false; return this; } else if (overwriteExistingValue) { mutated = true; replacedExistingValue = true; result = new Node(key, value, _left, _right); } else { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.DuplicateKey, key)); } } return mutated ? MakeBalanced(result) : result; } } /// <summary> /// Removes the specified key. Callers are expected to validate arguments. /// </summary> /// <param name="key">The key.</param> /// <param name="keyComparer">The key comparer.</param> /// <param name="mutated">Receives a value indicating whether this node tree has mutated because of this operation.</param> /// <returns>The new AVL tree.</returns> private Node RemoveRecursive(TKey key, IComparer<TKey> keyComparer, out bool mutated) { // Skip parameter validation because it's too expensive and pointless in recursive methods. if (this.IsEmpty) { mutated = false; return this; } else { Node result = this; int compare = keyComparer.Compare(key, _key); if (compare == 0) { // We have a match. mutated = true; // If this is a leaf, just remove it // by returning Empty. If we have only one child, // replace the node with the child. if (_right.IsEmpty && _left.IsEmpty) { result = EmptyNode; } else if (_right.IsEmpty && !_left.IsEmpty) { result = _left; } else if (!_right.IsEmpty && _left.IsEmpty) { result = _right; } else { // We have two children. Remove the next-highest node and replace // this node with it. var successor = _right; while (!successor._left.IsEmpty) { successor = successor._left; } bool dummyMutated; var newRight = _right.Remove(successor._key, keyComparer, out dummyMutated); result = successor.Mutate(left: _left, right: newRight); } } else if (compare < 0) { var newLeft = _left.Remove(key, keyComparer, out mutated); if (mutated) { result = this.Mutate(left: newLeft); } } else { var newRight = _right.Remove(key, keyComparer, out mutated); if (mutated) { result = this.Mutate(right: newRight); } } return result.IsEmpty ? result : MakeBalanced(result); } } /// <summary> /// Creates a node mutation, either by mutating this node (if not yet frozen) or by creating a clone of this node /// with the described changes. /// </summary> /// <param name="left">The left branch of the mutated node.</param> /// <param name="right">The right branch of the mutated node.</param> /// <returns>The mutated (or created) node.</returns> private Node Mutate(Node left = null, Node right = null) { if (_frozen) { return new Node(_key, _value, left ?? _left, right ?? _right); } else { if (left != null) { _left = left; } if (right != null) { _right = right; } _height = checked((byte)(1 + Math.Max(_left._height, _right._height))); return this; } } /// <summary> /// Searches the specified key. Callers are expected to validate arguments. /// </summary> /// <param name="key">The key.</param> /// <param name="keyComparer">The key comparer.</param> [Pure] private Node Search(TKey key, IComparer<TKey> keyComparer) { // Arg validation is too expensive for recursive methods. // Callers are expected to have validated parameters. if (this.IsEmpty) { return this; } else { int compare = keyComparer.Compare(key, _key); if (compare == 0) { return this; } else if (compare > 0) { return _right.Search(key, keyComparer); } else { return _left.Search(key, keyComparer); } } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace davidhartmanninfo.FireIncidentRealtime.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Diagnostics.CodeAnalysis; using System.Globalization; namespace System.ComponentModel { /// <summary> /// <para>Converts the value of an object into a different data type.</para> /// </summary> public class TypeConverter { /// <summary> /// <para>Gets a value indicating whether this converter can convert an object in the /// given source type to the native type of the converter.</para> /// </summary> public bool CanConvertFrom(Type sourceType) { return CanConvertFrom(null, sourceType); } /// <summary> /// <para>Gets a value indicating whether this converter can /// convert an object in the given source type to the native type of the converter /// using the context.</para> /// </summary> public virtual bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return false; } /// <summary> /// <para>Gets a value indicating whether this converter can /// convert an object to the given destination type using the context.</para> /// </summary> public bool CanConvertTo(Type destinationType) { return CanConvertTo(null, destinationType); } /// <summary> /// <para>Gets a value indicating whether this converter can /// convert an object to the given destination type using the context.</para> /// </summary> public virtual bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return (destinationType == typeof(string)); } /// <summary> /// <para>Converts the given value /// to the converter's native type.</para> /// </summary> public object ConvertFrom(object value) { return ConvertFrom(null, CultureInfo.CurrentCulture, value); } /// <summary> /// <para>Converts the given object to the converter's native type.</para> /// </summary> public virtual object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { throw GetConvertFromException(value); } /// <summary> /// Converts the given string to the converter's native type using the invariant culture. /// </summary> public object ConvertFromInvariantString(string text) { return ConvertFromString(null, CultureInfo.InvariantCulture, text); } /// <summary> /// Converts the given string to the converter's native type using the invariant culture. /// </summary> public object ConvertFromInvariantString(ITypeDescriptorContext context, string text) { return ConvertFromString(context, CultureInfo.InvariantCulture, text); } /// <summary> /// <para>Converts the specified text into an object.</para> /// </summary> public object ConvertFromString(string text) { return ConvertFrom(null, null, text); } /// <summary> /// <para>Converts the specified text into an object.</para> /// </summary> public object ConvertFromString(ITypeDescriptorContext context, string text) { return ConvertFrom(context, CultureInfo.CurrentCulture, text); } /// <summary> /// <para>Converts the specified text into an object.</para> /// </summary> public object ConvertFromString(ITypeDescriptorContext context, CultureInfo culture, string text) { return ConvertFrom(context, culture, text); } /// <summary> /// <para>Converts the given /// value object to the specified destination type using the arguments.</para> /// </summary> public object ConvertTo(object value, Type destinationType) { return ConvertTo(null, null, value, destinationType); } /// <summary> /// <para>Converts the given value object to /// the specified destination type using the specified context and arguments.</para> /// </summary> public virtual object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == null) { throw new ArgumentNullException(nameof(destinationType)); } if (destinationType == typeof(string)) { if (value == null) { return string.Empty; } if (culture != null && culture != CultureInfo.CurrentCulture) { IFormattable formattable = value as IFormattable; if (formattable != null) { return formattable.ToString(/* format = */ null, /* formatProvider = */ culture); } } return value.ToString(); } throw GetConvertToException(value, destinationType); } /// <summary> /// <para>Converts the specified value to a culture-invariant string representation.</para> /// </summary> public string ConvertToInvariantString(object value) { return ConvertToString(null, CultureInfo.InvariantCulture, value); } /// <summary> /// <para>Converts the specified value to a culture-invariant string representation.</para> /// </summary> [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] public string ConvertToInvariantString(ITypeDescriptorContext context, object value) { return ConvertToString(context, CultureInfo.InvariantCulture, value); } /// <summary> /// <para>Converts the specified value to a string representation.</para> /// </summary> public string ConvertToString(object value) { return (string)ConvertTo(null, CultureInfo.CurrentCulture, value, typeof(string)); } /// <summary> /// <para>Converts the specified value to a string representation.</para> /// </summary> public string ConvertToString(ITypeDescriptorContext context, object value) { return (string)ConvertTo(context, CultureInfo.CurrentCulture, value, typeof(string)); } /// <summary> /// <para>Converts the specified value to a string representation.</para> /// </summary> public string ConvertToString(ITypeDescriptorContext context, CultureInfo culture, object value) { return (string)ConvertTo(context, culture, value, typeof(string)); } /// <summary> /// <para>Re-creates an <see cref='System.Object'/> given a set of property values for the object.</para> /// </summary> public object CreateInstance(IDictionary propertyValues) { return CreateInstance(null, propertyValues); } /// <summary> /// <para>Re-creates an <see cref='System.Object'/> given a set of property values for the object.</para> /// </summary> public virtual object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues) { return null; } /// <summary> /// <para>Gets a suitable exception to throw when a conversion cannot be performed.</para> /// </summary> protected Exception GetConvertFromException(object value) { string valueTypeName; if (value == null) { valueTypeName = SR.Null; } else { valueTypeName = value.GetType().FullName; } throw new NotSupportedException(SR.Format(SR.ConvertFromException, GetType().Name, valueTypeName)); } /// <summary> /// <para>Retrieves a suitable exception to throw when a conversion cannot /// be performed.</para> /// </summary> protected Exception GetConvertToException(object value, Type destinationType) { string valueTypeName; if (value == null) { valueTypeName = SR.Null; } else { valueTypeName = value.GetType().FullName; } throw new NotSupportedException(SR.Format(SR.ConvertToException, GetType().Name, valueTypeName, destinationType.FullName)); } /// <summary> /// <para> /// Gets a value indicating whether changing a value on this object requires a call to /// <see cref='System.ComponentModel.TypeConverter.CreateInstance'/> to create a new value. /// </para> /// </summary> public bool GetCreateInstanceSupported() { return GetCreateInstanceSupported(null); } /// <summary> /// <para> /// Gets a value indicating whether changing a value on this object requires a call to /// <see cref='System.ComponentModel.TypeConverter.CreateInstance'/> to create a new value, /// using the specified context. /// </para> /// </summary> public virtual bool GetCreateInstanceSupported(ITypeDescriptorContext context) { return false; } /// <summary> /// <para>Gets a collection of properties for the type of array specified by the value parameter.</para> /// </summary> public PropertyDescriptorCollection GetProperties(object value) { return GetProperties(null, value); } /// <summary> /// <para> /// Gets a collection of properties for the type of array specified by the value parameter using /// the specified context. /// </para> /// </summary> public PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value) { return GetProperties(context, value, new Attribute[] { BrowsableAttribute.Yes }); } /// <summary> /// <para> /// Gets a collection of properties for the type of array specified by the value parameter using /// the specified context and attributes. /// </para> /// </summary> public virtual PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) { return null; } /// <summary> /// <para>Gets a value indicating whether this object supports properties.</para> /// </summary> public bool GetPropertiesSupported() { return GetPropertiesSupported(null); } /// <summary> /// <para>Gets a value indicating whether this object supports properties using the specified context.</para> /// </summary> public virtual bool GetPropertiesSupported(ITypeDescriptorContext context) { return false; } /// <summary> /// <para>Gets a collection of standard values for the data type this type converter is designed for.</para> /// </summary> public ICollection GetStandardValues() { return GetStandardValues(null); } /// <summary> /// <para>Gets a collection of standard values for the data type this type converter is designed for.</para> /// </summary> public virtual StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { return null; } /// <summary> /// <para> /// Gets a value indicating whether the collection of standard values returned from /// <see cref='System.ComponentModel.TypeConverter.GetStandardValues'/> is an exclusive list. /// </para> /// </summary> public bool GetStandardValuesExclusive() { return GetStandardValuesExclusive(null); } /// <summary> /// <para> /// Gets a value indicating whether the collection of standard values returned from /// <see cref='System.ComponentModel.TypeConverter.GetStandardValues'/> is an exclusive /// list of possible values, using the specified context. /// </para> /// </summary> public virtual bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; } /// <summary> /// <para> /// Gets a value indicating whether this object supports a standard set of values /// that can be picked from a list. /// </para> /// </summary> public bool GetStandardValuesSupported() { return GetStandardValuesSupported(null); } /// <summary> /// <para> /// Gets a value indicating whether this object supports a standard set of values that can be picked /// from a list using the specified context. /// </para> /// </summary> public virtual bool GetStandardValuesSupported(ITypeDescriptorContext context) { return false; } /// <summary> /// <para>Gets a value indicating whether the given value object is valid for this type.</para> /// </summary> public bool IsValid(object value) { return IsValid(null, value); } /// <summary> /// <para>Gets a value indicating whether the given value object is valid for this type.</para> /// </summary> public virtual bool IsValid(ITypeDescriptorContext context, object value) { bool isValid = true; try { // Because null doesn't have a type, so we couldn't pass this to CanConvertFrom. // Meanwhile, we couldn't silence null value here, such as type converter like // NullableConverter would consider null value as a valid value. if (value == null || CanConvertFrom(context, value.GetType())) { ConvertFrom(context, CultureInfo.InvariantCulture, value); } else { isValid = false; } } catch { isValid = false; } return isValid; } /// <summary> /// <para>Sorts a collection of properties.</para> /// </summary> protected PropertyDescriptorCollection SortProperties(PropertyDescriptorCollection props, string[] names) { props.Sort(names); return props; } /// <summary> /// <para> /// An <see langword='abstract '/> class that provides properties for objects that do not have properties. /// </para> /// </summary> protected abstract class SimplePropertyDescriptor : PropertyDescriptor { private Type _componentType; private Type _propertyType; /// <summary> /// <para> /// Initializes a new instance of the <see cref='System.ComponentModel.TypeConverter.SimplePropertyDescriptor'/> class. /// </para> /// </summary> protected SimplePropertyDescriptor(Type componentType, string name, Type propertyType) : this(componentType, name, propertyType, new Attribute[0]) { } /// <summary> /// <para> /// Initializes a new instance of the <see cref='System.ComponentModel.TypeConverter.SimplePropertyDescriptor'/> class. /// </para> /// </summary> protected SimplePropertyDescriptor(Type componentType, string name, Type propertyType, Attribute[] attributes) : base(name, attributes) { _componentType = componentType; _propertyType = propertyType; } /// <summary> /// <para>Gets the type of the component this property description is bound to.</para> /// </summary> public override Type ComponentType { get { return _componentType; } } /// <summary> /// <para>Gets a value indicating whether this property is read-only.</para> /// </summary> public override bool IsReadOnly { get { return Attributes.Contains(ReadOnlyAttribute.Yes); } } /// <summary> /// <para>Gets the type of the property.</para> /// </summary> public override Type PropertyType { get { return _propertyType; } } /// <summary> /// <para> /// Gets a value indicating whether resetting the component will change the value of the component. /// </para> /// </summary> public override bool CanResetValue(object component) { DefaultValueAttribute attr = (DefaultValueAttribute)Attributes[typeof(DefaultValueAttribute)]; if (attr == null) { return false; } return (attr.Value.Equals(GetValue(component))); } /// <summary> /// <para>Resets the value for this property of the component.</para> /// </summary> public override void ResetValue(object component) { DefaultValueAttribute attr = (DefaultValueAttribute)Attributes[typeof(DefaultValueAttribute)]; if (attr != null) { SetValue(component, attr.Value); } } /// <summary> /// <para>Gets a value indicating whether the value of this property needs to be persisted.</para> /// </summary> public override bool ShouldSerializeValue(object component) { return false; } } /// <summary> /// <para>Represents a collection of values.</para> /// </summary> public class StandardValuesCollection : ICollection { private ICollection _values; private Array _valueArray; /// <summary> /// <para> /// Initializes a new instance of the <see cref='System.ComponentModel.TypeConverter.StandardValuesCollection'/> class. /// </para> /// </summary> public StandardValuesCollection(ICollection values) { if (values == null) { values = new object[0]; } Array a = values as Array; if (a != null) { _valueArray = a; } _values = values; } /// <summary> /// <para> /// Gets the number of objects in the collection. /// </para> /// </summary> public int Count { get { if (_valueArray != null) { return _valueArray.Length; } else { return _values.Count; } } } /// <summary> /// <para>Gets the object at the specified index number.</para> /// </summary> public object this[int index] { get { if (_valueArray != null) { return _valueArray.GetValue(index); } IList list = _values as IList; if (list != null) { return list[index]; } // No other choice but to enumerate the collection. // _valueArray = new object[_values.Count]; _values.CopyTo(_valueArray, 0); return _valueArray.GetValue(index); } } /// <summary> /// <para> /// Copies the contents of this collection to an array. /// </para> /// </summary> public void CopyTo(Array array, int index) { _values.CopyTo(array, index); } /// <summary> /// <para> /// Gets an enumerator for this collection. /// </para> /// </summary> public IEnumerator GetEnumerator() { return _values.GetEnumerator(); } /// <internalonly/> /// <summary> /// Determines if this collection is synchronized. The ValidatorCollection is not synchronized for /// speed. Also, since it is read-only, there is no need to synchronize it. /// </summary> bool ICollection.IsSynchronized { get { return false; } } /// <internalonly/> /// <summary> /// Retrieves the synchronization root for this collection. Because we are not synchronized, /// this returns null. /// </summary> object ICollection.SyncRoot { get { return null; } } } } }
// <copyright file="NativeTurnBasedMultiplayerClient.cs" company="Google Inc."> // Copyright (C) 2014 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> #if (UNITY_ANDROID || (UNITY_IPHONE && !NO_GPGS)) namespace GooglePlayGames.Native { using System; using System.Collections; using GooglePlayGames.BasicApi; using GooglePlayGames.BasicApi.Multiplayer; using GooglePlayGames.Native.PInvoke; using GooglePlayGames.OurUtils; using Types = GooglePlayGames.Native.Cwrapper.Types; public class NativeTurnBasedMultiplayerClient : ITurnBasedMultiplayerClient { private readonly TurnBasedManager mTurnBasedManager; private readonly NativeClient mNativeClient; private volatile Action<TurnBasedMatch, bool> mMatchDelegate; internal NativeTurnBasedMultiplayerClient(NativeClient nativeClient, TurnBasedManager manager) { this.mTurnBasedManager = manager; this.mNativeClient = nativeClient; } /// <summary> /// Starts a game with randomly selected opponent(s). No exclusivebitmask. /// </summary> /// <param name="minOpponents">Minimum number opponents, not counting the current /// player -- so for a 2-player game, use 1).</param> /// <param name="maxOpponents">Max opponents, not counting the current player.</param> /// <param name="variant">Variant. Use 0 for default.</param> /// <param name="callback">Callback. Called when match setup is complete or fails. /// If it succeeds, will be called with (true, match); if it fails, will be /// called with (false, null).</param> public void CreateQuickMatch(uint minOpponents, uint maxOpponents, uint variant, Action<bool, TurnBasedMatch> callback) { CreateQuickMatch(minOpponents, maxOpponents, variant, 0L, callback); } /// <summary> /// Starts a game with randomly selected opponent(s) using exclusiveBitMask. /// No UI will be shown. /// </summary> /// <param name="minOpponents">Minimum number opponents, not counting the current /// player -- so for a 2-player game, use 1).</param> /// <param name="maxOpponents">Max opponents, not counting the current player.</param> /// <param name="variant">Variant. Use 0 for default.</param> /// <param name="exclusiveBitmask">The bitmask used to match players. The /// xor operation of all the bitmasks must be 0 to match players.</param> /// <param name="callback">Callback. Called when match setup is complete or fails. /// If it succeeds, will be called with (true, match); if it fails, will be /// called with (false, null).</param> public void CreateQuickMatch(uint minOpponents, uint maxOpponents, uint variant, ulong exclusiveBitmask, Action<bool, TurnBasedMatch> callback) { callback = Callbacks.AsOnGameThreadCallback(callback); using (var configBuilder = TurnBasedMatchConfigBuilder.Create()) { configBuilder.SetVariant(variant) .SetMinimumAutomatchingPlayers(minOpponents) .SetMaximumAutomatchingPlayers(maxOpponents) .SetExclusiveBitMask(exclusiveBitmask); using (var config = configBuilder.Build()) { mTurnBasedManager.CreateMatch(config, BridgeMatchToUserCallback( (status, match) => callback(status == UIStatus.Valid, match))); } } } public void CreateWithInvitationScreen(uint minOpponents, uint maxOpponents, uint variant, Action<bool, TurnBasedMatch> callback) { CreateWithInvitationScreen(minOpponents, maxOpponents, variant, (status, match) => callback(status == UIStatus.Valid, match)); } public void CreateWithInvitationScreen(uint minOpponents, uint maxOpponents, uint variant, Action<UIStatus, TurnBasedMatch> callback) { callback = Callbacks.AsOnGameThreadCallback(callback); mTurnBasedManager.ShowPlayerSelectUI(minOpponents, maxOpponents, true, result => { if (result.Status() != Cwrapper.CommonErrorStatus.UIStatus.VALID) { callback((UIStatus)result.Status(), null); return; } using (var configBuilder = TurnBasedMatchConfigBuilder.Create()) { configBuilder.PopulateFromUIResponse(result) .SetVariant(variant); using (var config = configBuilder.Build()) { mTurnBasedManager.CreateMatch(config, BridgeMatchToUserCallback(callback)); } } }); } public void GetAllInvitations(Action<Invitation[]> callback) { mTurnBasedManager.GetAllTurnbasedMatches(allMatches => { Invitation[] invites = new Invitation[allMatches.InvitationCount()]; int i=0; foreach (var invitation in allMatches.Invitations()) { invites[i++] = invitation.AsInvitation(); } callback(invites); }); } public void GetAllMatches(Action<TurnBasedMatch[]> callback) { mTurnBasedManager.GetAllTurnbasedMatches(allMatches => { int count = allMatches.MyTurnMatchesCount() + allMatches.TheirTurnMatchesCount() + allMatches.CompletedMatchesCount(); TurnBasedMatch[] matches = new TurnBasedMatch[count]; int i=0; foreach (var match in allMatches.MyTurnMatches()) { matches[i++] = match.AsTurnBasedMatch(mNativeClient.GetUserId()); } foreach (var match in allMatches.TheirTurnMatches()) { matches[i++] = match.AsTurnBasedMatch(mNativeClient.GetUserId()); } foreach (var match in allMatches.CompletedMatches()) { matches[i++] = match.AsTurnBasedMatch(mNativeClient.GetUserId()); } callback(matches); }); } private Action<TurnBasedManager.TurnBasedMatchResponse> BridgeMatchToUserCallback( Action<UIStatus, TurnBasedMatch> userCallback) { return callbackResult => { using (var match = callbackResult.Match()) { if (match == null) { UIStatus status = UIStatus.InternalError; switch(callbackResult.ResponseStatus()) { case Cwrapper.CommonErrorStatus.MultiplayerStatus.VALID: status = UIStatus.Valid; break; case Cwrapper.CommonErrorStatus.MultiplayerStatus.VALID_BUT_STALE: status = UIStatus.Valid; break; case Cwrapper.CommonErrorStatus.MultiplayerStatus.ERROR_INTERNAL: status = UIStatus.InternalError; break; case Cwrapper.CommonErrorStatus.MultiplayerStatus.ERROR_NOT_AUTHORIZED: status = UIStatus.NotAuthorized; break; case Cwrapper.CommonErrorStatus.MultiplayerStatus.ERROR_VERSION_UPDATE_REQUIRED: status = UIStatus.VersionUpdateRequired; break; case Cwrapper.CommonErrorStatus.MultiplayerStatus.ERROR_TIMEOUT: status = UIStatus.Timeout; break; } userCallback(status, null); } else { var converted = match.AsTurnBasedMatch(mNativeClient.GetUserId()); Logger.d("Passing converted match to user callback:" + converted); userCallback(UIStatus.Valid, converted); } } }; } public void AcceptFromInbox(Action<bool, TurnBasedMatch> callback) { callback = Callbacks.AsOnGameThreadCallback(callback); mTurnBasedManager.ShowInboxUI(callbackResult => { using (var match = callbackResult.Match()) { if (match == null) { callback(false, null); } else { var converted = match.AsTurnBasedMatch(mNativeClient.GetUserId()); Logger.d("Passing converted match to user callback:" + converted); callback(true, converted); } } }); } public void AcceptInvitation(string invitationId, Action<bool, TurnBasedMatch> callback) { callback = Callbacks.AsOnGameThreadCallback(callback); FindInvitationWithId(invitationId, invitation => { if (invitation == null) { Logger.e("Could not find invitation with id " + invitationId); callback(false, null); return; } mTurnBasedManager.AcceptInvitation(invitation, BridgeMatchToUserCallback( (status, match) => callback(status == UIStatus.Valid, match))); } ); } private void FindInvitationWithId(string invitationId, Action<MultiplayerInvitation> callback) { mTurnBasedManager.GetAllTurnbasedMatches(allMatches => { if (allMatches.Status() <= 0) { callback(null); return; } foreach (var invitation in allMatches.Invitations()) { using (invitation) { if (invitation.Id().Equals(invitationId)) { callback(invitation); return; } } } callback(null); }); } public void RegisterMatchDelegate(MatchDelegate del) { if (del == null) { mMatchDelegate = null; } else { mMatchDelegate = Callbacks.AsOnGameThreadCallback<TurnBasedMatch, bool>( (match, autoLaunch) => del(match, autoLaunch)); } } internal void HandleMatchEvent(Types.MultiplayerEvent eventType, string matchId, NativeTurnBasedMatch match) { // Capture the current value of the delegate to protect against racing updates. var currentDelegate = mMatchDelegate; if (currentDelegate == null) { return; } // Ignore REMOVED events - this plugin has no use for them. if (eventType == Types.MultiplayerEvent.REMOVED) { Logger.d("Ignoring REMOVE event for match " + matchId); return; } bool shouldAutolaunch = eventType == Types.MultiplayerEvent.UPDATED_FROM_APP_LAUNCH; match.ReferToMe(); Callbacks.AsCoroutine(WaitForLogin(()=> {currentDelegate(match.AsTurnBasedMatch(mNativeClient.GetUserId()), shouldAutolaunch); match.ForgetMe();})); } IEnumerator WaitForLogin(Action method) { if (string.IsNullOrEmpty(mNativeClient.GetUserId())) { yield return null; } method.Invoke(); } public void TakeTurn(TurnBasedMatch match, byte[] data, string pendingParticipantId, Action<bool> callback) { Logger.describe(data); callback = Callbacks.AsOnGameThreadCallback(callback); // Find the indicated match, take the turn if the match is: // a) Still present // b) Still of a matching version (i.e. there were no updates to it since the passed match // was retrieved) // c) The indicated pending participant matches a participant in the match. FindEqualVersionMatchWithParticipant(match, pendingParticipantId, callback, (pendingParticipant, foundMatch) => { // If we got here, the match and the participant are in a good state. mTurnBasedManager.TakeTurn(foundMatch, data, pendingParticipant, result => { if (result.RequestSucceeded()) { callback(true); } else { Logger.d("Taking turn failed: " + result.ResponseStatus()); callback(false); } }); }); } private void FindEqualVersionMatch(TurnBasedMatch match, Action<bool> onFailure, Action<NativeTurnBasedMatch> onVersionMatch) { mTurnBasedManager.GetMatch(match.MatchId, response => { using (var foundMatch = response.Match()) { if (foundMatch == null) { Logger.e(string.Format("Could not find match {0}", match.MatchId)); onFailure(false); return; } if (foundMatch.Version() != match.Version) { Logger.e(string.Format("Attempted to update a stale version of the " + "match. Expected version was {0} but current version is {1}.", match.Version, foundMatch.Version())); onFailure(false); return; } onVersionMatch(foundMatch); } }); } private void FindEqualVersionMatchWithParticipant(TurnBasedMatch match, string participantId, Action<bool> onFailure, Action<MultiplayerParticipant, NativeTurnBasedMatch> onFoundParticipantAndMatch) { FindEqualVersionMatch(match, onFailure, foundMatch => { // If we received a null participantId, we're using an automatching player instead - // issue the callback using that. if (participantId == null) { using (var sentinelParticipant = MultiplayerParticipant.AutomatchingSentinel()) { onFoundParticipantAndMatch(sentinelParticipant, foundMatch); return; } } using (var participant = foundMatch.ParticipantWithId(participantId)) { if (participant == null) { Logger.e(string.Format("Located match {0} but desired participant with ID " + "{1} could not be found", match.MatchId, participantId)); onFailure(false); return; } onFoundParticipantAndMatch(participant, foundMatch); } }); } public int GetMaxMatchDataSize() { throw new NotImplementedException(); } public void Finish(TurnBasedMatch match, byte[] data, MatchOutcome outcome, Action<bool> callback) { callback = Callbacks.AsOnGameThreadCallback(callback); FindEqualVersionMatch(match, callback, foundMatch => { ParticipantResults results = foundMatch.Results(); foreach (string participantId in outcome.ParticipantIds) { Types.MatchResult matchResult = ResultToMatchResult(outcome.GetResultFor(participantId)); uint placing = outcome.GetPlacementFor(participantId); if (results.HasResultsForParticipant(participantId)) { // If the match already has results for this participant, make sure that they're // consistent with what's already there. var existingResults = results.ResultsForParticipant(participantId); var existingPlacing = results.PlacingForParticipant(participantId); if (matchResult != existingResults || placing != existingPlacing) { Logger.e(string.Format("Attempted to override existing results for " + "participant {0}: Placing {1}, Result {2}", participantId, existingPlacing, existingResults)); callback(false); return; } } else { // Otherwise, get updated results and dispose of the old ones. var oldResults = results; results = oldResults.WithResult(participantId, placing, matchResult); oldResults.Dispose(); } } mTurnBasedManager.FinishMatchDuringMyTurn(foundMatch, data, results, response => callback(response.RequestSucceeded())); }); } private static Types.MatchResult ResultToMatchResult(MatchOutcome.ParticipantResult result) { switch (result) { case MatchOutcome.ParticipantResult.Loss: return Types.MatchResult.LOSS; case MatchOutcome.ParticipantResult.None: return Types.MatchResult.NONE; case MatchOutcome.ParticipantResult.Tie: return Types.MatchResult.TIE; case MatchOutcome.ParticipantResult.Win: return Types.MatchResult.WIN; default: Logger.e("Received unknown ParticipantResult " + result); return Types.MatchResult.NONE; } } public void AcknowledgeFinished(TurnBasedMatch match, Action<bool> callback) { callback = Callbacks.AsOnGameThreadCallback(callback); FindEqualVersionMatch(match, callback, foundMatch => { mTurnBasedManager.ConfirmPendingCompletion( foundMatch, response => callback(response.RequestSucceeded())); }); } public void Leave(TurnBasedMatch match, Action<bool> callback) { callback = Callbacks.AsOnGameThreadCallback(callback); FindEqualVersionMatch(match, callback, foundMatch => { mTurnBasedManager.LeaveMatchDuringTheirTurn(foundMatch, status => callback(status > 0)); }); } public void LeaveDuringTurn(TurnBasedMatch match, string pendingParticipantId, Action<bool> callback) { callback = Callbacks.AsOnGameThreadCallback(callback); FindEqualVersionMatchWithParticipant(match, pendingParticipantId, callback, (pendingParticipant, foundMatch) => { mTurnBasedManager.LeaveDuringMyTurn(foundMatch, pendingParticipant, status => callback(status > 0)); }); } public void Cancel(TurnBasedMatch match, Action<bool> callback) { callback = Callbacks.AsOnGameThreadCallback(callback); FindEqualVersionMatch(match, callback, foundMatch => { mTurnBasedManager.CancelMatch(foundMatch, status => callback(status > 0)); }); } public void Rematch(TurnBasedMatch match, Action<bool, TurnBasedMatch> callback) { callback = Callbacks.AsOnGameThreadCallback(callback); FindEqualVersionMatch(match, failed => callback(false, null), foundMatch => { mTurnBasedManager.Rematch(foundMatch, BridgeMatchToUserCallback( (status, m) => callback(status == UIStatus.Valid, m))); }); } public void DeclineInvitation(string invitationId) { FindInvitationWithId(invitationId, invitation => { if (invitation == null) { return; } mTurnBasedManager.DeclineInvitation(invitation); }); } } } #endif
using Lucene.Net.Support; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Lucene.Net.Search.Spans { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using IBits = Lucene.Net.Util.IBits; using IndexReader = Lucene.Net.Index.IndexReader; using Term = Lucene.Net.Index.Term; using TermContext = Lucene.Net.Index.TermContext; using ToStringUtils = Lucene.Net.Util.ToStringUtils; /// <summary> /// Matches spans which are near one another. One can specify <i>slop</i>, the /// maximum number of intervening unmatched positions, as well as whether /// matches are required to be in-order. /// </summary> public class SpanNearQuery : SpanQuery #if FEATURE_CLONEABLE , System.ICloneable #endif { protected readonly IList<SpanQuery> m_clauses; protected int m_slop; protected bool m_inOrder; protected string m_field; private bool collectPayloads; /// <summary> /// Construct a <see cref="SpanNearQuery"/>. Matches spans matching a span from each /// clause, with up to <paramref name="slop"/> total unmatched positions between /// them. * When <paramref name="inOrder"/> is <c>true</c>, the spans from each clause /// must be * ordered as in <paramref name="clauses"/>. </summary> /// <param name="clauses"> The clauses to find near each other </param> /// <param name="slop"> The slop value </param> /// <param name="inOrder"> <c>true</c> if order is important</param> public SpanNearQuery(SpanQuery[] clauses, int slop, bool inOrder) : this(clauses, slop, inOrder, true) { } public SpanNearQuery(SpanQuery[] clauses, int slop, bool inOrder, bool collectPayloads) { // copy clauses array into an ArrayList this.m_clauses = new EquatableList<SpanQuery>(clauses.Length); for (int i = 0; i < clauses.Length; i++) { SpanQuery clause = clauses[i]; if (m_field == null) // check field { m_field = clause.Field; } else if (clause.Field != null && !clause.Field.Equals(m_field, StringComparison.Ordinal)) { throw new System.ArgumentException("Clauses must have same field."); } this.m_clauses.Add(clause); } this.collectPayloads = collectPayloads; this.m_slop = slop; this.m_inOrder = inOrder; } /// <summary> /// Return the clauses whose spans are matched. </summary> public virtual SpanQuery[] GetClauses() { return m_clauses.ToArray(); } /// <summary> /// Return the maximum number of intervening unmatched positions permitted. </summary> public virtual int Slop { get { return m_slop; } } /// <summary> /// Return <c>true</c> if matches are required to be in-order. </summary> public virtual bool IsInOrder { get { return m_inOrder; } } public override string Field { get { return m_field; } } public override void ExtractTerms(ISet<Term> terms) { foreach (SpanQuery clause in m_clauses) { clause.ExtractTerms(terms); } } public override string ToString(string field) { StringBuilder buffer = new StringBuilder(); buffer.Append("SpanNear(["); IEnumerator<SpanQuery> i = m_clauses.GetEnumerator(); bool isFirst = true; while (i.MoveNext()) { SpanQuery clause = i.Current; if (!isFirst) { buffer.Append(", "); } buffer.Append(clause.ToString(field)); isFirst = false; } buffer.Append("], "); buffer.Append(m_slop); buffer.Append(", "); buffer.Append(m_inOrder); buffer.Append(")"); buffer.Append(ToStringUtils.Boost(Boost)); return buffer.ToString(); } public override Spans GetSpans(AtomicReaderContext context, IBits acceptDocs, IDictionary<Term, TermContext> termContexts) { if (m_clauses.Count == 0) // optimize 0-clause case { return (new SpanOrQuery(GetClauses())).GetSpans(context, acceptDocs, termContexts); } if (m_clauses.Count == 1) // optimize 1-clause case { return m_clauses[0].GetSpans(context, acceptDocs, termContexts); } return m_inOrder ? (Spans)new NearSpansOrdered(this, context, acceptDocs, termContexts, collectPayloads) : (Spans)new NearSpansUnordered(this, context, acceptDocs, termContexts); } public override Query Rewrite(IndexReader reader) { SpanNearQuery clone = null; for (int i = 0; i < m_clauses.Count; i++) { SpanQuery c = m_clauses[i]; SpanQuery query = (SpanQuery)c.Rewrite(reader); if (query != c) // clause rewrote: must clone { if (clone == null) { clone = (SpanNearQuery)this.Clone(); } clone.m_clauses[i] = query; } } if (clone != null) { return clone; // some clauses rewrote } else { return this; // no clauses rewrote } } public override object Clone() { int sz = m_clauses.Count; SpanQuery[] newClauses = new SpanQuery[sz]; for (int i = 0; i < sz; i++) { newClauses[i] = (SpanQuery)m_clauses[i].Clone(); } SpanNearQuery spanNearQuery = new SpanNearQuery(newClauses, m_slop, m_inOrder); spanNearQuery.Boost = Boost; return spanNearQuery; } /// <summary> /// Returns true iff <code>o</code> is equal to this. </summary> public override bool Equals(object o) { if (this == o) { return true; } if (!(o is SpanNearQuery)) { return false; } SpanNearQuery spanNearQuery = (SpanNearQuery)o; if (m_inOrder != spanNearQuery.m_inOrder) { return false; } if (m_slop != spanNearQuery.m_slop) { return false; } if (!Equatable.Wrap(m_clauses).Equals(spanNearQuery.m_clauses)) { return false; } return Boost == spanNearQuery.Boost; } public override int GetHashCode() { int result; result = Equatable.Wrap(m_clauses).GetHashCode(); // Mix bits before folding in things like boost, since it could cancel the // last element of clauses. this particular mix also serves to // differentiate SpanNearQuery hashcodes from others. result ^= (result << 14) | ((int)((uint)result >> 19)); // reversible result += Number.SingleToRawInt32Bits(Boost); result += m_slop; result ^= (m_inOrder ? unchecked((int)0x99AFD3BD) : 0); return result; } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Converters; namespace Twilio.Rest.Preview.Understand.Assistant { /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact [email protected]. /// /// FetchQueryOptions /// </summary> public class FetchQueryOptions : IOptions<QueryResource> { /// <summary> /// The unique ID of the Assistant. /// </summary> public string PathAssistantSid { get; } /// <summary> /// A 34 character string that uniquely identifies this resource. /// </summary> public string PathSid { get; } /// <summary> /// Construct a new FetchQueryOptions /// </summary> /// <param name="pathAssistantSid"> The unique ID of the Assistant. </param> /// <param name="pathSid"> A 34 character string that uniquely identifies this resource. </param> public FetchQueryOptions(string pathAssistantSid, string pathSid) { PathAssistantSid = pathAssistantSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact [email protected]. /// /// ReadQueryOptions /// </summary> public class ReadQueryOptions : ReadOptions<QueryResource> { /// <summary> /// The unique ID of the parent Assistant. /// </summary> public string PathAssistantSid { get; } /// <summary> /// An ISO language-country string of the sample. /// </summary> public string Language { get; set; } /// <summary> /// The Model Build Sid or unique name of the Model Build to be queried. /// </summary> public string ModelBuild { get; set; } /// <summary> /// A string that described the query status. The values can be: pending_review, reviewed, discarded /// </summary> public string Status { get; set; } /// <summary> /// Construct a new ReadQueryOptions /// </summary> /// <param name="pathAssistantSid"> The unique ID of the parent Assistant. </param> public ReadQueryOptions(string pathAssistantSid) { PathAssistantSid = pathAssistantSid; } /// <summary> /// Generate the necessary parameters /// </summary> public override List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (Language != null) { p.Add(new KeyValuePair<string, string>("Language", Language)); } if (ModelBuild != null) { p.Add(new KeyValuePair<string, string>("ModelBuild", ModelBuild.ToString())); } if (Status != null) { p.Add(new KeyValuePair<string, string>("Status", Status)); } if (PageSize != null) { p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString())); } return p; } } /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact [email protected]. /// /// CreateQueryOptions /// </summary> public class CreateQueryOptions : IOptions<QueryResource> { /// <summary> /// The unique ID of the parent Assistant. /// </summary> public string PathAssistantSid { get; } /// <summary> /// An ISO language-country string of the sample. /// </summary> public string Language { get; } /// <summary> /// A user-provided string that uniquely identifies this resource as an alternative to the sid. It can be up to 2048 characters long. /// </summary> public string Query { get; } /// <summary> /// Constraints the query to a set of tasks. Useful when you need to constrain the paths the user can take. Tasks should be comma separated task-unique-name-1, task-unique-name-2 /// </summary> public string Tasks { get; set; } /// <summary> /// The Model Build Sid or unique name of the Model Build to be queried. /// </summary> public string ModelBuild { get; set; } /// <summary> /// Constraints the query to a given Field with an task. Useful when you know the Field you are expecting. It accepts one field in the format task-unique-name-1:field-unique-name /// </summary> public string Field { get; set; } /// <summary> /// Construct a new CreateQueryOptions /// </summary> /// <param name="pathAssistantSid"> The unique ID of the parent Assistant. </param> /// <param name="language"> An ISO language-country string of the sample. </param> /// <param name="query"> A user-provided string that uniquely identifies this resource as an alternative to the sid. It /// can be up to 2048 characters long. </param> public CreateQueryOptions(string pathAssistantSid, string language, string query) { PathAssistantSid = pathAssistantSid; Language = language; Query = query; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (Language != null) { p.Add(new KeyValuePair<string, string>("Language", Language)); } if (Query != null) { p.Add(new KeyValuePair<string, string>("Query", Query)); } if (Tasks != null) { p.Add(new KeyValuePair<string, string>("Tasks", Tasks)); } if (ModelBuild != null) { p.Add(new KeyValuePair<string, string>("ModelBuild", ModelBuild.ToString())); } if (Field != null) { p.Add(new KeyValuePair<string, string>("Field", Field)); } return p; } } /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact [email protected]. /// /// UpdateQueryOptions /// </summary> public class UpdateQueryOptions : IOptions<QueryResource> { /// <summary> /// The unique ID of the parent Assistant. /// </summary> public string PathAssistantSid { get; } /// <summary> /// A 34 character string that uniquely identifies this resource. /// </summary> public string PathSid { get; } /// <summary> /// An optional reference to the Sample created from this query. /// </summary> public string SampleSid { get; set; } /// <summary> /// A string that described the query status. The values can be: pending_review, reviewed, discarded /// </summary> public string Status { get; set; } /// <summary> /// Construct a new UpdateQueryOptions /// </summary> /// <param name="pathAssistantSid"> The unique ID of the parent Assistant. </param> /// <param name="pathSid"> A 34 character string that uniquely identifies this resource. </param> public UpdateQueryOptions(string pathAssistantSid, string pathSid) { PathAssistantSid = pathAssistantSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (SampleSid != null) { p.Add(new KeyValuePair<string, string>("SampleSid", SampleSid.ToString())); } if (Status != null) { p.Add(new KeyValuePair<string, string>("Status", Status)); } return p; } } /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact [email protected]. /// /// DeleteQueryOptions /// </summary> public class DeleteQueryOptions : IOptions<QueryResource> { /// <summary> /// The unique ID of the Assistant. /// </summary> public string PathAssistantSid { get; } /// <summary> /// A 34 character string that uniquely identifies this resource. /// </summary> public string PathSid { get; } /// <summary> /// Construct a new DeleteQueryOptions /// </summary> /// <param name="pathAssistantSid"> The unique ID of the Assistant. </param> /// <param name="pathSid"> A 34 character string that uniquely identifies this resource. </param> public DeleteQueryOptions(string pathAssistantSid, string pathSid) { PathAssistantSid = pathAssistantSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } }
using System; using System.Reflection; /* * Regression tests for the mono JIT. * * Each test needs to be of the form: * * public static int test_<result>_<name> (); * * where <result> is an integer (the value that needs to be returned by * the method to make it pass. * <name> is a user-displayed name used to identify the test. * * The tests can be driven in two ways: * *) running the program directly: Main() uses reflection to find and invoke * the test methods (this is useful mostly to check that the tests are correct) * *) with the --regression switch of the jit (this is the preferred way since * all the tests will be run with optimizations on and off) * * The reflection logic could be moved to a .dll since we need at least another * regression test file written in IL code to have better control on how * the IL code looks. */ public partial class Tests { static void dummy() { } public static int test_0_return() { dummy(); return 0; } static int dummy1() { return 1; } public static int test_2_int_return() { int r = dummy1(); if (r == 1) return 2; return 0; } static int add1(int val) { return val + 1; } public static int test_1_int_pass() { int r = add1(5); if (r == 6) return 1; return 0; } static int add_many(int val, short t, byte b, int da) { return val + t + b + da; } public static int test_1_int_pass_many() { byte b = 6; int r = add_many(5, 2, b, 1); if (r == 14) return 1; return 0; } unsafe static float GetFloat(byte* ptr) { return *(float*)ptr; } unsafe public static float GetFloat(float value) { return GetFloat((byte*)&value); } /* bug #42134 */ public static int test_2_inline_saved_arg_type() { float f = 100.0f; return GetFloat(f) == f ? 2 : 1; } static int pass_many_types(int a, long b, int c, long d) { return a + (int)b + c + (int)d; } public static int test_5_pass_longs() { return pass_many_types(1, 2, -5, 7); } static int overflow_registers(int a, int b, int c, int d, int e, int f, int g, int h, int i, int j) { return a + b + c + d + e + f + g + h + i + j; } public static int test_55_pass_even_more() { return overflow_registers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); } static int pass_ints_longs(int a, long b, long c, long d, long e, int f, long g) { return (int)(a + b + c + d + e + f + g); } public static int test_1_sparc_argument_passing() { // The 4. argument tests split reg/mem argument passing // The 5. argument tests mem argument passing // The 7. argument tests passing longs in misaligned memory // The MaxValues are needed so the MS word of the long is not 0 return pass_ints_longs(1, 2, System.Int64.MaxValue, System.Int64.MinValue, System.Int64.MaxValue, 0, System.Int64.MinValue); } static int pass_bytes(byte a, byte b, byte c, byte d, byte e, byte f, byte g) { return (int)(a + b + c + d + e + f + g); } public static int test_21_sparc_byte_argument_passing() { return pass_bytes(0, 1, 2, 3, 4, 5, 6); } static int pass_sbytes(sbyte a, sbyte b, sbyte c, sbyte d, sbyte e, sbyte f, sbyte g) { return (int)(a + b + c + d + e + f + g); } public static int test_21_sparc_sbyte_argument_passing() { return pass_sbytes(0, 1, 2, 3, 4, 5, 6); } static int pass_shorts(short a, short b, short c, short d, short e, short f, short g) { return (int)(a + b + c + d + e + f + g); } public static int test_21_sparc_short_argument_passing() { return pass_shorts(0, 1, 2, 3, 4, 5, 6); } static int pass_floats_doubles(float a, double b, double c, double d, double e, float f, double g) { return (int)(a + b + c + d + e + f + g); } public static int test_721_sparc_float_argument_passing() { return pass_floats_doubles(100.0f, 101.0, 102.0, 103.0, 104.0, 105.0f, 106.0); } static float pass_floats(float a, float b, float c, float d, float e, float f, float g, float h, float i, float j) { return a + b + c + d + e + f + g + h + i + j; } public static int test_55_sparc_float_argument_passing2() { return (int)pass_floats(1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f); } public static bool is_small(float value) { double d = (double)value; double d2 = 7.183757E-41; return d - d2 < 0.000001; } public static int test_0_float_argument_passing_precision() { float f = 7.183757E-41f; return is_small(f) ? 0 : 1; } // The first argument must be passed on a dword aligned stack location static int pass_byref_ints_longs(ref long a, ref int b, ref byte c, ref short d, ref long e, ref int f, ref long g) { return (int)(a + b + c + d + e + f + g); } static int pass_takeaddr_ints_longs(long a, int b, byte c, short d, long e, int f, long g) { return pass_byref_ints_longs(ref a, ref b, ref c, ref d, ref e, ref f, ref g); } // Test that arguments are moved to the stack from incoming registers // when the argument must reside in the stack because its address is taken public static int test_2_sparc_takeaddr_argument_passing() { return pass_takeaddr_ints_longs(1, 2, 253, -253, System.Int64.MaxValue, 0, System.Int64.MinValue); } static int pass_byref_floats_doubles(ref float a, ref double b, ref double c, ref double d, ref double e, ref float f, ref double g) { return (int)(a + b + c + d + e + f + g); } static int pass_takeaddr_floats_doubles(float a, double b, double c, double d, double e, float f, double g) { return pass_byref_floats_doubles(ref a, ref b, ref c, ref d, ref e, ref f, ref g); } public static int test_721_sparc_takeaddr_argument_passing2() { return pass_takeaddr_floats_doubles(100.0f, 101.0, 102.0, 103.0, 104.0, 105.0f, 106.0); } static void pass_byref_double(out double d) { d = 5.0; } // Test byref double argument passing public static int test_0_sparc_byref_double_argument_passing() { double d; pass_byref_double(out d); return (d == 5.0) ? 0 : 1; } static void shift_un_arg(ulong value) { do { value = value >> 4; } while (value != 0); } // Test that assignment to long arguments work public static int test_0_long_arg_assign() { ulong c = 0x800000ff00000000; shift_un_arg(c >> 4); return 0; } static unsafe void* ptr_return(void* ptr) { return ptr; } public static unsafe int test_0_ptr_return() { void* ptr = new IntPtr(55).ToPointer(); if (ptr_return(ptr) == ptr) return 0; else return 1; } static bool isnan(float f) { return (f != f); } public static int test_0_isnan() { float f = 1.0f; return isnan(f) ? 1 : 0; } static int first_is_zero(int v1, int v2) { if (v1 != 0) return -1; return v2; } public static int test_1_handle_dup_stloc() { int index = 0; int val = first_is_zero(index, ++index); if (val != 1) return 2; return 1; } static long return_5low() { return 5; } static long return_5high() { return 0x500000000; } public static int test_3_long_ret() { long val = return_5low(); return (int)(val - 2); } public static int test_1_long_ret2() { long val = return_5high(); if (val > 0xffffffff) return 1; return 0; } public static void use_long_arg(ulong l) { for (int i = 0; i < 10; ++i) l++; } public static ulong return_long_arg(object o, ulong perm) { use_long_arg(perm); perm = 0x8000000000000FFF; use_long_arg(perm); return perm; } public static int test_0_sparc_long_ret_regress_541577() { ulong perm = 0x8000000000000FFF; ulong work = return_long_arg(null, perm); return work == perm ? 0 : 1; } static void doit(double value, out long m) { m = (long)value; } public static int test_0_ftol_clobber() { long m; doit(1.3, out m); if (m != 1) return 2; return 0; } }
using System; using System.Collections.Generic; using System.Text.Json; using NetFusion.Rest.Resources; namespace NetFusion.Rest.Client { /// <summary> /// Extension methods used by a .NET WebApi client used to obtain links /// and embedded resources and models. /// </summary> public static class HalResourceExtensions { static HalResourceExtensions() { DefaultOptions = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; } private static JsonSerializerOptions DefaultOptions { get; } /// <summary> /// Determines if the resource contains a named link. /// </summary> /// <param name="resource">The resource with associated links.</param> /// <param name="named">The name identifying the link.</param> /// <returns>True if found. Otherwise, False.</returns> public static bool HasLink(this HalResource resource, string named) { if (resource == null) throw new ArgumentNullException(nameof(resource)); if (string.IsNullOrWhiteSpace(named)) throw new ArgumentException("Name of link not specified.", nameof(named)); return resource.Links != null && resource.Links.ContainsKey(named); } /// <summary> /// Returns a link identified by name associated with resource. /// </summary> /// <param name="resource">The resource with associated links.</param> /// <param name="named">The name identifying the link.</param> /// <returns>The link if found. Otherwise an exception is raised.</returns> public static Link GetLink(this HalResource resource, string named) { if (TryGetLink(resource, named, out Link link)) { return link; } throw new InvalidOperationException($"Link named: {named} does not exists."); } /// <summary> /// Attempts to find a resource's link by name. /// </summary> /// <param name="resource">The resource with associated links.</param> /// <param name="named">The name identifying the link.</param> /// <param name="link">Will contain reference to link if found.</param> /// <returns>True if the link is found. Otherwise False.</returns> public static bool TryGetLink(this HalResource resource, string named, out Link link) { if (resource == null) throw new ArgumentNullException(nameof(resource)); if (string.IsNullOrWhiteSpace(named)) throw new ArgumentException("Link name not specified.", nameof(named)); link = null; return resource.Links != null && resource.Links.TryGetValue(named, out link); } /// <summary> /// Determines if the resource contains a named embedded resource/model. /// </summary> /// <param name="resource">The resource with embedded items.</param> /// <param name="named">The name identifying the embedded resource/model.</param> /// <returns>True if found. Otherwise, False.</returns> public static bool HasEmbedded(this HalResource resource, string named) { if (resource == null) throw new ArgumentNullException(nameof(resource)); if (string.IsNullOrWhiteSpace(named)) throw new ArgumentException("Name of embedded resource not provided.", nameof(named)); return resource.Embedded != null && resource.Embedded.ContainsKey(named); } /// <summary> /// Returns an embedded resource model. /// </summary> /// <param name="resource">The parent resource containing the embedded model.</param> /// <param name="named">The name identifying the embedded model.</param> /// <typeparam name="TChildModel">The type of the embedded model.</typeparam> /// <returns>Reference to the deserialized model or an exception if not present.</returns> public static TChildModel GetEmbeddedModel<TChildModel>(this HalResource resource, string named) where TChildModel: class { if (TryGetEmbeddedModel(resource, named, out TChildModel model)) { return model; } throw new InvalidOperationException( $"Embedded model named: {named} of parent resource does not exist."); } /// <summary> /// Returns an embedded model if present. /// </summary> /// <param name="resource">The parent resource containing the embedded model.</param> /// <param name="named">The name identifying the embedded model.</param> /// <param name="model">Reference to the embedded model if found.</param> /// <typeparam name="TChildModel">The type of the embedded model.</typeparam> /// <returns>True if the embedded model was found. Otherwise, False.</returns> public static bool TryGetEmbeddedModel<TChildModel>(this HalResource resource, string named, out TChildModel model) where TChildModel: class { if (resource == null) throw new ArgumentNullException(nameof(resource)); if (string.IsNullOrWhiteSpace(named)) throw new ArgumentException("Name of embedded model not specified.", nameof(named)); model = null; if (! resource.HasEmbedded(named)) { return false; } // Check if the embedded resource has been deserialized from the base JsonElement // representation and return it. if (resource.Embedded[named] is TChildModel embeddedItem) { model = embeddedItem; return true; } // Deserialize the embedded JsonElement into a type object instance. if (resource.Embedded[named] is JsonElement embeddedJson) { model = JsonSerializer.Deserialize<TChildModel>( embeddedJson.GetRawText(), DefaultOptions); resource.Embedded[named] = model; // Override the JsonElement reference. return true; } if (model == null) { throw new InvalidCastException("The named embedded model: {named} does not contain a JsonElement."); } return false; } /// <summary> /// Returns an instance of an embedded resource. /// </summary> /// <typeparam name="TChildModel">The type of the embedded resource's model.</typeparam> /// <param name="resource">The parent resource with embedded resource.</param> /// <param name="named">The name identifying the embedded resource.</param> /// <returns>Instance of the populated embedded resource or an exception if not found.</returns> public static HalResource<TChildModel> GetEmbeddedResource<TChildModel>(this HalResource resource, string named) where TChildModel : class { if (TryGetEmbeddedResource<TChildModel>(resource, named, out var embeddedResource)) { return embeddedResource; } throw new InvalidOperationException( $"Embedded resource named: {named} of parent resource does not exist."); } /// <summary> /// Returns an instance of an embedded resource. /// </summary> /// <typeparam name="TChildModel">The type of the embedded resource's model.</typeparam> /// <param name="resource">The parent resource with embedded resource.</param> /// <param name="named">The name identifying the embedded resource.</param> /// <param name="embeddedResource">Reference to the embedded resource if found.</param> /// <returns>True if the embedded resource if found. Otherwise False.</returns> public static bool TryGetEmbeddedResource<TChildModel>(this HalResource resource, string named, out HalResource<TChildModel> embeddedResource) where TChildModel: class { if (resource == null) throw new ArgumentNullException(nameof(resource)); if (string.IsNullOrWhiteSpace(named)) throw new ArgumentException("Name of embedded resource not specified.", nameof(named)); embeddedResource = null; if (! resource.Embedded.ContainsKey(named)) { return false; } // Check if the embedded resource has been deserialized from the base JsonElement representation and return it. if (resource.Embedded[named] is HalResource<TChildModel> embeddedItem) { embeddedResource = embeddedItem; return true; } // Deserialize the embedded JsonElement into a type object instance. if (resource.Embedded[named] is JsonElement embeddedJson) { embeddedResource = JsonSerializer.Deserialize<HalResource<TChildModel>>( embeddedJson.GetRawText(), DefaultOptions); resource.Embedded[named] = embeddedResource; // Override the JsonElement reference. return true; } if (embeddedResource == null) { throw new InvalidCastException("The named embedded model: {named} does not contain a JsonElement."); } return false; } /// <summary> /// Returns an instance of an embedded resource collection. /// </summary> /// <typeparam name="TChildModel">The type of the embedded resource model.</typeparam> /// <param name="resource">The parent resource with embedded resources.</param> /// <param name="named">The name identifying the embedded resource collection.</param> /// <returns>List of embedded collection of resources if found. Otherwise, /// and exception is raised.</returns> public static IEnumerable<HalResource<TChildModel>> GetEmbeddedResources<TChildModel>( this HalResource resource, string named) where TChildModel : class { if (TryGetEmbeddedResources<TChildModel>(resource, named, out var embeddedResources)) { return embeddedResources; } throw new InvalidOperationException( $"Embedded resource collection named: {named} of parent resource does not exist."); } /// <summary> /// Returns an instance of an embedded resource collection. /// </summary> /// <typeparam name="TChildModel">The type of the embedded resource model.</typeparam> /// <param name="resource">The parent resource with embedded resources.</param> /// <param name="named">The name identifying the embedded resource collection.</param> /// <param name="embeddedResources">Reference to the embedded resources if found.</param> /// <returns>True if the list of embedded resources are found. Otherwise, False.</returns> public static bool TryGetEmbeddedResources<TChildModel>(this HalResource resource, string named, out IEnumerable<HalResource<TChildModel>> embeddedResources) where TChildModel: class { if (resource == null) throw new ArgumentNullException(nameof(resource)); if (string.IsNullOrWhiteSpace(named)) throw new ArgumentException("Name of embedded resource collection not provided.", nameof(named)); embeddedResources = null; if (! resource.HasEmbedded(named)) { return false; } if (resource.Embedded[named] is List<HalResource<TChildModel>> embeddedItems) { embeddedResources = embeddedItems; return true; } if (resource.Embedded[named] is JsonElement embeddedJson && embeddedJson.ValueKind == JsonValueKind.Array) { embeddedResources = JsonSerializer.Deserialize<List<HalResource<TChildModel>>>( embeddedJson.GetRawText(), DefaultOptions); resource.Embedded[named] = embeddedResources; // Override the JsonElement reference. return true; } if (embeddedResources == null) { throw new InvalidCastException( $"The named embedded collection: {named} does not contain a JsonElement of type array."); } return false; } /// <summary> /// Returns an instance of an embedded collection of models. /// </summary> /// <param name="resource">The parent resource with embedded models.</param> /// <param name="named">The name identifying the embedded models.</param> /// <typeparam name="TChildModel">The type of the embedded model.</typeparam> /// <returns>Instance of the embedded collection of models. If not found, /// and exceptions is raised.</returns> public static IEnumerable<TChildModel> GetEmbeddedModels<TChildModel>(this HalResource resource, string named) where TChildModel : class { if (TryGetEmbeddedModels<TChildModel>(resource, named, out var embeddedModels)) { return embeddedModels; } throw new InvalidOperationException( $"Embedded model collection named: {named} of parent resource does not exist."); } /// <summary> /// Returns an instance of an embedded collection of models. /// </summary> /// <param name="resource">The parent resource with embedded models.</param> /// <param name="named">The name identifying the embedded models.</param> /// <param name="embeddedModels">Reference to the embedded models if found.</param> /// <typeparam name="TChildModel">The type of the embedded model.</typeparam> /// <returns>True if the embedded collection of models is found. Otherwise, False.</returns> public static bool TryGetEmbeddedModels<TChildModel>(this HalResource resource, string named, out IEnumerable<TChildModel> embeddedModels) where TChildModel: class { if (resource == null) throw new ArgumentNullException(nameof(resource)); if (string.IsNullOrWhiteSpace(named)) throw new ArgumentException("Name of embedded model collection not provided.", nameof(named)); embeddedModels = null; if (! resource.HasEmbedded(named)) { return false; } if (resource.Embedded[named] is List<TChildModel> embeddedItems) { embeddedModels = embeddedItems; return true; } if (resource.Embedded[named] is JsonElement embeddedJson && embeddedJson.ValueKind == JsonValueKind.Array) { embeddedModels = JsonSerializer.Deserialize<List<TChildModel>>( embeddedJson.GetRawText(), DefaultOptions); resource.Embedded[named] = embeddedModels; // Override the JsonElement reference. return true; } if (embeddedModels == null) { throw new InvalidCastException( $"The named embedded collection: {named} does not contain a JsonElement of type array."); } return false; } } }
// <copyright file="Program.cs" company="OSIsoft, LLC"> // //Copyright 2019 OSIsoft, 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 // //<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 System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using OSIsoft.Data; using OSIsoft.Data.Reflection; using OSIsoft.Identity; namespace SdsClientLibraries { public class Program { public static void Main() => MainAsync().GetAwaiter().GetResult(); public static async Task<bool> MainAsync(bool test = false) { bool success = true; Exception toThrow = null; IConfigurationBuilder builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json") .AddJsonFile("appsettings.test.json", optional: true); IConfiguration configuration = builder.Build(); // ==== Client constants ==== var tenantId = configuration["TenantId"]; var namespaceId = configuration["NamespaceId"]; var resource = configuration["Resource"]; var clientId = configuration["ClientId"]; var clientKey = configuration["ClientKey"]; // ==== Metadata IDs ==== string streamId = "SampleStream"; string streamIdSecondary = "SampleStream_Secondary"; string streamIdCompound = "SampleStream_Compound"; string typeId = "SampleType"; string targetTypeId = "SampleType_Target"; string targetIntTypeId = "SampleType_TargetInt"; string autoStreamViewId = "SampleAutoStreamView"; string manualStreamViewId = "SampleManualStreamView"; string compoundTypeId = "SampleType_Compound"; var uriResource = new Uri(resource); // Step 1 // Get Sds Services to communicate with server AuthenticationHandler authenticationHandler = new AuthenticationHandler(uriResource, clientId, clientKey); SdsService sdsService = new SdsService(new Uri(resource), authenticationHandler); var metadataService = sdsService.GetMetadataService(tenantId, namespaceId); var dataService = sdsService.GetDataService(tenantId, namespaceId); var tableService = sdsService.GetTableService(tenantId, namespaceId); // LoggerCallbackHandler.UseDefaultLogging = false; Console.WriteLine(@"-------------------------------------------------------------"); Console.WriteLine(@" _________ .___ _______ ______________________"); Console.WriteLine(@" / _____/ __| _/______ \ \ \_ _____/\__ ___/"); Console.WriteLine(@" \_____ \ / __ |/ ___/ / | \ | __)_ | | "); Console.WriteLine(@" / \/ /_/ |\___ \ / | \| \ | | "); Console.WriteLine(@"/_______ /\____ /____ > /\ \____|__ /_______ / |____| "); Console.WriteLine(@" \/ \/ \/ \/ \/ \/ "); Console.WriteLine(@"-------------------------------------------------------------"); Console.WriteLine(); Console.WriteLine($"Sds endpoint at {resource}"); Console.WriteLine(); try { // Step 2 // create an SdsType Console.WriteLine("Creating an SdsType"); SdsType type = SdsTypeBuilder.CreateSdsType<WaveData>(); type.Id = typeId; type = await metadataService.GetOrCreateTypeAsync(type); // Step 3 // create an SdsStream Console.WriteLine("Creating an SdsStream"); var stream = new SdsStream { Id = streamId, Name = "Wave Data Sample", TypeId = type.Id, Description = "This is a sample SdsStream for storing WaveData type measurements" }; stream = await metadataService.GetOrCreateStreamAsync(stream); // Step 4 // insert data Console.WriteLine("Inserting data"); // insert a single event var wave = GetWave(0, 200, 2); await dataService.InsertValueAsync(stream.Id, wave); // insert a list of events var waves = new List<WaveData>(); for (var i = 2; i <= 18; i += 2) { waves.Add(GetWave(i, 200, 2)); } await dataService.InsertValuesAsync(stream.Id, waves); // Step 5 // get last event Console.WriteLine("Getting latest event"); var latest = await dataService.GetLastValueAsync<WaveData>(streamId); Console.WriteLine(latest.ToString()); Console.WriteLine(); // get all events Console.WriteLine("Getting all events"); var allEvents = (List<WaveData>) await dataService.GetWindowValuesAsync<WaveData>(streamId, "0", "180"); Console.WriteLine($"Total events found: {allEvents.Count}"); foreach (var evnt in allEvents) { Console.WriteLine(evnt.ToString()); } Console.WriteLine(); // Step 6 //Step2 Getting all events in table format with headers. var tableEvents = await tableService.GetWindowValuesAsync(stream.Id, "0", "180"); Console.WriteLine("Getting table events"); foreach (var evnt in tableEvents.Rows) { Console.WriteLine(String.Join(",", evnt.ToArray())); } Console.WriteLine(); // Step 7 // update events Console.WriteLine("Updating events"); // update one event var updatedWave = UpdateWave(allEvents.First(), 4); await dataService.UpdateValueAsync(stream.Id, updatedWave); // update all events, adding ten more var updatedCollection = new List<WaveData>(); for (int i = 2; i < 40; i = i+2) { updatedCollection.Add(GetWave(i, 400, 4)); } await dataService.UpdateValuesAsync(stream.Id, updatedCollection); allEvents = (List<WaveData>)await dataService.GetWindowValuesAsync<WaveData>(stream.Id, "0", "180"); Console.WriteLine("Getting updated events"); Console.WriteLine($"Total events found: {allEvents.Count}"); foreach (var evnt in allEvents) { Console.WriteLine(evnt.ToString()); } Console.WriteLine(); // Step 8 // replacing events Console.WriteLine("Replacing events"); // replace one event var replaceEvent = allEvents.First(); replaceEvent.Sin = 0.717; replaceEvent.Cos = 0.717; replaceEvent.Tan = Math.Sqrt(2 * (0.717 * 0.717)); await dataService.ReplaceValueAsync<WaveData>(streamId, replaceEvent); // replace all events foreach (var evnt in allEvents) { evnt.Sin = 5.0/2; evnt.Cos = 5*Math.Sqrt(3)/2; evnt.Tan = 5/Math.Sqrt(3); } await dataService.ReplaceValuesAsync<WaveData>(streamId, allEvents); Console.WriteLine("Getting replaced events"); var replacedEvents = (List<WaveData>)await dataService.GetWindowValuesAsync<WaveData>(streamId, "0", "180"); Console.WriteLine($"Total events found: {replacedEvents.Count}"); foreach (var evnt in replacedEvents) { Console.WriteLine(evnt.ToString()); } Console.WriteLine(); // Step 9 // Property Overrides Console.WriteLine("Sds can interpolate or extrapolate data at an index location where data does not explicitly exist:"); Console.WriteLine(); // We will retrieve three events using the default behavior, Continuous var retrieved = await dataService .GetRangeValuesAsync<WaveData>(stream.Id, "1", 3, SdsBoundaryType.ExactOrCalculated); Console.WriteLine("Default (Continuous) requesting data starting at index location '1', where we have not entered data, Sds will interpolate a value for this property and then return entered values:"); foreach (var value in retrieved) { Console.WriteLine(value.ToString()); } Console.WriteLine(); var retrievedInterpolated = await dataService .GetValuesAsync<WaveData>(stream.Id, "5", "32", 4); Console.WriteLine(" Sds will interpolate a value for each index asked for (5,14,23,32):"); foreach (var value in retrievedInterpolated) { Console.WriteLine(value.ToString()); } Console.WriteLine(); // Step 10 // We will retrieve events filtered to only get the ones where the radians are less than 50. Note, this can be done on index properties too. var retrievedInterpolatedFiltered = (await dataService.GetWindowFilteredValuesAsync<WaveData>(stream.Id, "0", "180", SdsBoundaryType.ExactOrCalculated, "Radians lt 50")); Console.WriteLine(" Sds will only return the values where the radains are less than 50:"); foreach (var value in retrievedInterpolatedFiltered) { Console.WriteLine(value.ToString()); } Console.WriteLine(); // Step 11 // create a Discrete stream PropertyOverride indicating that we do not want Sds to calculate a value for Radians and update our stream var propertyOverride = new SdsStreamPropertyOverride() { SdsTypePropertyId = "Radians", InterpolationMode = SdsInterpolationMode.Discrete }; var propertyOverrides = new List<SdsStreamPropertyOverride>() {propertyOverride}; // update the stream stream.PropertyOverrides = propertyOverrides; await metadataService.CreateOrUpdateStreamAsync(stream); retrieved = await dataService .GetRangeValuesAsync<WaveData>(stream.Id, "1", 3, SdsBoundaryType.ExactOrCalculated); Console.WriteLine("We can override this behavior on a property by property basis, here we override the Radians property instructing Sds not to interpolate."); Console.WriteLine("Sds will now return the default value for the data type:"); foreach (var value in retrieved) { Console.WriteLine(value.ToString()); } Console.WriteLine(); // Step 12 // StreamViews Console.WriteLine("SdsStreamViews"); // create target types var targetType = SdsTypeBuilder.CreateSdsType<WaveDataTarget>(); targetType.Id = targetTypeId; var targetIntType = SdsTypeBuilder.CreateSdsType<WaveDataInteger>(); targetIntType.Id = targetIntTypeId; await metadataService.CreateOrUpdateTypeAsync(targetType); await metadataService.CreateOrUpdateTypeAsync(targetIntType); // create StreamViews var autoStreamView = new SdsStreamView() { Id = autoStreamViewId, SourceTypeId = typeId, TargetTypeId = targetTypeId }; // create explicit mappings var vp1 = new SdsStreamViewProperty() { SourceId = "Order", TargetId = "OrderTarget" }; var vp2 = new SdsStreamViewProperty() { SourceId = "Sin", TargetId = "SinInt" }; var vp3 = new SdsStreamViewProperty() { SourceId = "Cos", TargetId = "CosInt" }; var vp4 = new SdsStreamViewProperty() { SourceId = "Tan", TargetId = "TanInt" }; var manualStreamView = new SdsStreamView() { Id = manualStreamViewId, SourceTypeId = typeId, TargetTypeId = targetIntTypeId, Properties = new List<SdsStreamViewProperty>() { vp1, vp2, vp3, vp4 } }; await metadataService.CreateOrUpdateStreamViewAsync(autoStreamView); await metadataService.CreateOrUpdateStreamViewAsync(manualStreamView); Console.WriteLine("Here is some of our data as it is stored on the server:"); foreach (var evnt in retrieved) { Console.WriteLine($"Sin: {evnt.Sin}, Cos: {evnt.Cos}, Tan {evnt.Tan}"); } Console.WriteLine(); // get autoStreamView data var autoStreamViewData = await dataService.GetRangeValuesAsync<WaveDataTarget>(stream.Id, "1", 3, SdsBoundaryType.ExactOrCalculated, autoStreamViewId); Console.WriteLine("Specifying a StreamView with an SdsType of the same shape returns values that are automatically mapped to the target SdsType's properties:"); foreach (var value in autoStreamViewData) { Console.WriteLine($"SinTarget: {value.SinTarget} CosTarget: {value.CosTarget} TanTarget: {value.TanTarget}"); } Console.WriteLine(); // get manaulStreamView data Console.WriteLine("SdsStreamViews can also convert certain types of data, here we return integers where the original values were doubles:"); var manualStreamViewData = await dataService.GetRangeValuesAsync<WaveDataInteger>(stream.Id, "1", 3, SdsBoundaryType.ExactOrCalculated, manualStreamViewId); foreach (var value in manualStreamViewData) { Console.WriteLine($"SinInt: {value.SinInt} CosInt: {value.CosInt} TanInt: {value.TanInt}"); } Console.WriteLine(); // get SdsStreamViewMap Console.WriteLine("We can query Sds to return the SdsStreamViewMap for our SdsStreamView, here is the one generated automatically:"); var autoStreamViewMap = await metadataService.GetStreamViewMapAsync(autoStreamViewId); PrintStreamViewMapProperties(autoStreamViewMap); Console.WriteLine("Here is our explicit mapping, note SdsStreamViewMap will return all properties of the Source Type, even those without a corresponding Target property:"); var manualStreamViewMap = await metadataService.GetStreamViewMapAsync(manualStreamViewId); PrintStreamViewMapProperties(manualStreamViewMap); // Step 13 // Update Stream Type based on SdsStreamView Console.WriteLine("We will now update the stream type based on the streamview"); var firstVal = await dataService.GetFirstValueAsync<WaveData>(stream.Id); await metadataService.UpdateStreamTypeAsync(stream.Id, autoStreamViewId); var newStream = await metadataService.GetStreamAsync(stream.Id); var firstValUpdated = await dataService.GetFirstValueAsync<WaveDataTarget>(stream.Id); Console.WriteLine($"The new type id {newStream.TypeId} compared to the original one {stream.TypeId}."); Console.WriteLine($"The new type value {firstValUpdated.ToString()} compared to the original one {firstVal.ToString()}."); // Step 14 // Show filtering on Type, works the same as filtering on Streams var types = await metadataService.GetTypesAsync(""); var typesFiltered = await metadataService.GetTypesAsync("", "contains(Id, 'Target')"); Console.WriteLine($"The number of types returned without filtering: {types.Count()}. With filtering {typesFiltered.Count()}."); // Step 15 // tags and metadata Console.WriteLine("Let's add some Tags and Metadata to our stream:"); var tags = new List<string> { "waves", "periodic", "2018", "validated" }; var metadata = new Dictionary<string, string>() { { "Region", "North America" }, { "Country", "Canada" }, { "Province", "Quebec" } }; await metadataService.UpdateStreamTagsAsync(streamId, tags); await metadataService.UpdateStreamMetadataAsync(streamId, metadata); tags = (List<string>)await metadataService.GetStreamTagsAsync(streamId); Console.WriteLine(); Console.WriteLine($"Tags now associated with {streamId}:"); foreach (var tag in tags) { Console.WriteLine(tag); } Console.WriteLine(); Console.WriteLine($"Metadata now associated with {streamId}:"); Console.WriteLine("Metadata key Region: " + await metadataService.GetStreamMetadataValueAsync(streamId, "Region")); Console.WriteLine("Metadata key Country: " + await metadataService.GetStreamMetadataValueAsync(streamId, "Country")); Console.WriteLine("Metadata key Province: " + await metadataService.GetStreamMetadataValueAsync(streamId, "Province")); Console.WriteLine(); // Step 16 // delete values Console.WriteLine("Deleting values from the SdsStream"); // delete one event await dataService.RemoveValueAsync(stream.Id, 0); // delete all events await dataService.RemoveWindowValuesAsync(stream.Id, 1, 200); retrieved = await dataService.GetWindowValuesAsync<WaveData>(stream.Id, "0", "200"); if (retrieved.ToList<WaveData>().Count == 0) { Console.WriteLine("All values deleted successfully!"); } Console.WriteLine(); // Step 17 // Adding a new stream with a secondary index. Console.WriteLine("Adding a stream with a secondary index."); SdsStreamIndex measurementIndex = new SdsStreamIndex() { SdsTypePropertyId = type.Properties.First(p => p.Id.Equals("Radians")).Id }; SdsStream secondary = new SdsStream() { Id = streamIdSecondary, TypeId = type.Id, Indexes = new List<SdsStreamIndex>() { measurementIndex } }; secondary = await metadataService.GetOrCreateStreamAsync(secondary); Console.WriteLine($"Secondary indexes on streams. {stream.Id}:{stream.Indexes?.Count()}. {secondary.Id}:{secondary.Indexes.Count()}. "); Console.WriteLine(); // Modifying an existing stream with a secondary index. Console.WriteLine("Modifying a stream to have a secondary index."); stream = await metadataService.GetStreamAsync(stream.Id); type = await metadataService.GetTypeAsync(stream.TypeId); SdsStreamIndex measurementTargetIndex = new SdsStreamIndex() { SdsTypePropertyId = type.Properties.First(p => p.Id.Equals("RadiansTarget")).Id }; stream.Indexes = new List<SdsStreamIndex>() { measurementTargetIndex }; await metadataService.CreateOrUpdateStreamAsync(stream); stream = await metadataService.GetStreamAsync(stream.Id); // Modifying an existing stream to remove the secondary index Console.WriteLine("Removing a secondary index from a stream."); secondary.Indexes = null; await metadataService.CreateOrUpdateStreamAsync(secondary); secondary = await metadataService.GetStreamAsync(secondary.Id); Console.WriteLine($"Secondary indexes on streams. {stream.Id}:{stream.Indexes?.Count()}. {secondary.Id}:{secondary.Indexes?.Count()}. "); Console.WriteLine(); // Step 18 // Adding Compound Index Type Console.WriteLine("Creating an SdsType with a compound index"); SdsType typeCompound = SdsTypeBuilder.CreateSdsType<WaveDataCompound>(); typeCompound.Id = compoundTypeId; typeCompound = await metadataService.GetOrCreateTypeAsync(typeCompound); // create an SdsStream Console.WriteLine("Creating an SdsStream off of type with compound index"); var streamCompound = new SdsStream { Id = streamIdCompound, Name = "Wave Data Sample", TypeId = typeCompound.Id, Description = "This is a sample SdsStream for storing WaveData type measurements" }; streamCompound = await metadataService.GetOrCreateStreamAsync(streamCompound); // Step 19 // insert compound data Console.WriteLine("Inserting data"); await dataService.InsertValueAsync(streamCompound.Id, GetWaveMultiplier(1, 10)); await dataService.InsertValueAsync(streamCompound.Id, GetWaveMultiplier(2, 2)); await dataService.InsertValueAsync(streamCompound.Id, GetWaveMultiplier(3, 1)); await dataService.InsertValueAsync(streamCompound.Id, GetWaveMultiplier(10, 3)); await dataService.InsertValueAsync(streamCompound.Id, GetWaveMultiplier(10, 8)); await dataService.InsertValueAsync(streamCompound.Id, GetWaveMultiplier(10, 10)); var latestCompound = await dataService.GetLastValueAsync<WaveDataCompound>(streamCompound.Id); var firstCompound = await dataService.GetFirstValueAsync<WaveDataCompound>(streamCompound.Id); var data = await dataService.GetWindowValuesAsync<WaveDataCompound, int, int>(streamCompound.Id, Tuple.Create(2, 1), Tuple.Create(10, 8)); Console.WriteLine($"First data: {firstCompound.ToString()}. Latest data: {latestCompound.ToString()}."); Console.WriteLine(); Console.WriteLine("Window Data:"); foreach (var evnt in data) { Console.WriteLine(evnt.ToString()); } } catch (Exception ex) { success = false; Console.WriteLine(ex.Message); toThrow = ex; } finally { //step 20 Console.WriteLine("Cleaning up"); // Delete the stream, types and streamViews making sure Console.WriteLine("Deleting stream"); RunInTryCatch(metadataService.DeleteStreamAsync,streamId); RunInTryCatch(metadataService.DeleteStreamAsync, streamIdSecondary); RunInTryCatch(metadataService.DeleteStreamAsync, streamIdCompound); Console.WriteLine("Deleting streamViews"); RunInTryCatch(metadataService.DeleteStreamViewAsync, autoStreamViewId); RunInTryCatch(metadataService.DeleteStreamViewAsync, manualStreamViewId); Console.WriteLine("Deleting types"); RunInTryCatch(metadataService.DeleteTypeAsync, typeId); RunInTryCatch(metadataService.DeleteTypeAsync, compoundTypeId); RunInTryCatch(metadataService.DeleteTypeAsync, targetTypeId); RunInTryCatch(metadataService.DeleteTypeAsync, targetIntTypeId); Console.WriteLine("done"); if(!test) Console.ReadKey(); } if (test && !success) throw toThrow; return success; } /// <summary> /// Use this to run a method that you don't want to stop the program if there is an error and you don't want to report the error /// </summary> /// <param name="methodToRun">The method to run.</param> /// <param name="value">The value to put into the method to run</param> private static async void RunInTryCatch(Func<string,Task> methodToRun, string value) { try { await methodToRun(value); } catch (Exception ex) { Console.WriteLine($"Got error in {methodToRun.Method.Name} with value {value} but continued on:" + ex.Message); } } private static void PrintStreamViewMapProperties(SdsStreamViewMap sdsStreamViewMap) { foreach (var prop in sdsStreamViewMap.Properties) { if (prop.TargetId != null) { Console.WriteLine($"{prop.SourceId} => {prop.TargetId}"); } else { Console.WriteLine($"{prop.SourceId} => Not Mapped"); } } Console.WriteLine(); } private static WaveData GetWave(int order, double range, double multiplier) { var radians = order * 2 * Math.PI; return new WaveData { Order = order, Radians = radians, Tau = radians / (2 * Math.PI), Sin = multiplier * Math.Sin(radians), Cos = multiplier * Math.Cos(radians), Tan = multiplier * Math.Tan(radians), Sinh = multiplier * Math.Sinh(radians), Cosh = multiplier * Math.Cosh(radians), Tanh = multiplier * Math.Tanh(radians) }; } private static WaveData UpdateWave(WaveData wave, double multiplier) { wave.Tau = wave.Radians / (2 * Math.PI); wave.Sin = multiplier * Math.Sin(wave.Radians); wave.Cos = multiplier * Math.Cos(wave.Radians); wave.Tan = multiplier * Math.Tan(wave.Radians); wave.Sinh = multiplier * Math.Sinh(wave.Radians); wave.Cosh = multiplier * Math.Cosh(wave.Radians); wave.Tanh = multiplier * Math.Tanh(wave.Radians); return wave; } private static WaveDataCompound GetWaveMultiplier(int order, int multiplier) { var radians = order * 2 * Math.PI; return new WaveDataCompound { Order = order, Radians = radians, Tau = radians / (2 * Math.PI), Sin = multiplier * Math.Sin(radians), Cos = multiplier * Math.Cos(radians), Tan = multiplier * Math.Tan(radians), Sinh = multiplier * Math.Sinh(radians), Cosh = multiplier * Math.Cosh(radians), Tanh = multiplier * Math.Tanh(radians), Multiplier = multiplier }; } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Net.Sockets; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Threading.Tasks; using Elasticsearch.Net.Connection.Thrift.Protocol; using Elasticsearch.Net.Connection.Thrift.Transport; using Elasticsearch.Net.ConnectionPool; using Elasticsearch.Net.Providers; namespace Elasticsearch.Net.Connection.Thrift { public class ThriftConnection : IConnection, IDisposable { private readonly ConcurrentDictionary<Uri, ConcurrentQueue<Rest.Client>> _clients = new ConcurrentDictionary<Uri, ConcurrentQueue<Rest.Client>>(); private readonly Semaphore _resourceLock; private readonly int _timeout; private readonly int _poolSize; private bool _disposed; private readonly IConnectionConfigurationValues _connectionSettings; public ThriftConnection(IConnectionConfigurationValues connectionSettings) { this._connectionSettings = connectionSettings; this._timeout = connectionSettings.Timeout; var connectionPool = this._connectionSettings.ConnectionPool; var maximumConnections = Math.Max(1, connectionSettings.MaximumAsyncConnections); var maximumUrls = connectionPool.MaxRetries + 1; this._poolSize = maximumConnections; this._resourceLock = new Semaphore(_poolSize, _poolSize); int seed; int initialSeed = 0; bool shouldPingHint; for (var i = 0; i < maximumUrls; i++) { var uri = connectionPool.GetNext(initialSeed, out seed, out shouldPingHint); var queue = new ConcurrentQueue<Rest.Client>(); for (var c = 0; c < maximumConnections; c++) { var host = uri.Host; var port = uri.Port; var tsocket = new TSocket(host, port); var transport = new TBufferedTransport(tsocket, 1024); var protocol = new TBinaryProtocol(transport); var client = new Rest.Client(protocol); tsocket.Timeout = this._connectionSettings.Timeout; tsocket.TcpClient.SendTimeout = this._connectionSettings.Timeout; tsocket.TcpClient.ReceiveTimeout = this._connectionSettings.Timeout; //tsocket.TcpClient.NoDelay = true; queue.Enqueue(client); initialSeed = seed; } _clients.TryAdd(uri, queue); } } #region IConnection Members public Task<ElasticsearchResponse<Stream>> Get(Uri uri, IRequestConnectionConfiguration deserializationState = null) { var restRequest = new RestRequest(); restRequest.Method = Method.GET; restRequest.Uri = uri; restRequest.Headers = new Dictionary<string, string>(); restRequest.Headers.Add("Content-Type", "application/json"); return Task.Factory.StartNew<ElasticsearchResponse<Stream>>(() => { return this.Execute(restRequest, deserializationState); }); } public Task<ElasticsearchResponse<Stream>> Head(Uri uri, IRequestConnectionConfiguration deserializationState = null) { var restRequest = new RestRequest(); restRequest.Method = Method.HEAD; restRequest.Uri = uri; restRequest.Headers = new Dictionary<string, string>(); restRequest.Headers.Add("Content-Type", "application/json"); return Task.Factory.StartNew<ElasticsearchResponse<Stream>>(() => { return this.Execute(restRequest, deserializationState); }); } public ElasticsearchResponse<Stream> GetSync(Uri uri, IRequestConnectionConfiguration deserializationState = null) { var restRequest = new RestRequest(); restRequest.Method = Method.GET; restRequest.Uri = uri; restRequest.Headers = new Dictionary<string, string>(); restRequest.Headers.Add("Content-Type", "application/json"); return this.Execute(restRequest, deserializationState); } public ElasticsearchResponse<Stream> HeadSync(Uri uri, IRequestConnectionConfiguration deserializationState = null) { var restRequest = new RestRequest(); restRequest.Method = Method.HEAD; restRequest.Uri = uri; restRequest.Headers = new Dictionary<string, string>(); restRequest.Headers.Add("Content-Type", "application/json"); return this.Execute(restRequest, deserializationState); } public Task<ElasticsearchResponse<Stream>> Post(Uri uri, byte[] data, IRequestConnectionConfiguration deserializationState = null) { var restRequest = new RestRequest(); restRequest.Method = Method.POST; restRequest.Uri = uri; restRequest.Body = data; restRequest.Headers = new Dictionary<string, string>(); restRequest.Headers.Add("Content-Type", "application/json"); return Task.Factory.StartNew<ElasticsearchResponse<Stream>>(() => { return this.Execute(restRequest, deserializationState); }); } public Task<ElasticsearchResponse<Stream>> Put(Uri uri, byte[] data, IRequestConnectionConfiguration deserializationState = null) { var restRequest = new RestRequest(); restRequest.Method = Method.PUT; restRequest.Uri = uri; restRequest.Body = data; restRequest.Headers = new Dictionary<string, string>(); restRequest.Headers.Add("Content-Type", "application/json"); return Task.Factory.StartNew<ElasticsearchResponse<Stream>>(() => { return this.Execute(restRequest, deserializationState); }); } public Task<ElasticsearchResponse<Stream>> Delete(Uri uri, byte[] data, IRequestConnectionConfiguration deserializationState = null) { var restRequest = new RestRequest(); restRequest.Method = Method.DELETE; restRequest.Uri = uri; restRequest.Body = data; restRequest.Headers = new Dictionary<string, string>(); restRequest.Headers.Add("Content-Type", "application/json"); return Task.Factory.StartNew<ElasticsearchResponse<Stream>>(() => { return this.Execute(restRequest, deserializationState); }); } public ElasticsearchResponse<Stream> PostSync(Uri uri, byte[] data, IRequestConnectionConfiguration deserializationState = null) { var restRequest = new RestRequest(); restRequest.Method = Method.POST; restRequest.Uri = uri; restRequest.Body = data; restRequest.Headers = new Dictionary<string, string>(); restRequest.Headers.Add("Content-Type", "application/json"); return this.Execute(restRequest, deserializationState); } public ElasticsearchResponse<Stream> PutSync(Uri uri, byte[] data, IRequestConnectionConfiguration deserializationState = null) { var restRequest = new RestRequest(); restRequest.Method = Method.PUT; restRequest.Uri = uri; restRequest.Body = data; restRequest.Headers = new Dictionary<string, string>(); restRequest.Headers.Add("Content-Type", "application/json"); return this.Execute(restRequest, deserializationState); } public Task<ElasticsearchResponse<Stream>> Delete(Uri uri, IRequestConnectionConfiguration deserializationState = null) { var restRequest = new RestRequest(); restRequest.Method = Method.DELETE; restRequest.Uri = uri; restRequest.Headers = new Dictionary<string, string>(); restRequest.Headers.Add("Content-Type", "application/json"); return Task.Factory.StartNew<ElasticsearchResponse<Stream>>(() => { return this.Execute(restRequest, deserializationState); }); } public ElasticsearchResponse<Stream> DeleteSync(Uri uri, IRequestConnectionConfiguration deserializationState = null) { var restRequest = new RestRequest(); restRequest.Method = Method.DELETE; restRequest.Uri = uri; restRequest.Headers = new Dictionary<string, string>(); restRequest.Headers.Add("Content-Type", "application/json"); return this.Execute(restRequest, deserializationState); } public ElasticsearchResponse<Stream> DeleteSync(Uri uri, byte[] data, IRequestConnectionConfiguration deserializationState = null) { var restRequest = new RestRequest(); restRequest.Method = Method.DELETE; restRequest.Uri = uri; restRequest.Body = data; restRequest.Headers = new Dictionary<string, string>(); restRequest.Headers.Add("Content-Type", "application/json"); return this.Execute(restRequest, deserializationState); } #endregion #region IDisposable Members /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { Dispose(true); } #endregion /// <summary> /// Releases unmanaged and - optionally - managed resources /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (_disposed) return; foreach (var c in this._clients.SelectMany(c=>c.Value)) { if (c != null && c.InputProtocol != null && c.InputProtocol.Transport != null && c.InputProtocol.Transport.IsOpen) c.InputProtocol.Transport.Close(); } _disposed = true; } /// <summary> /// Releases unmanaged resources and performs other cleanup operations before the /// <see cref="HttpConnection"/> is reclaimed by garbage collection. /// </summary> ~ThriftConnection() { Dispose(false); } private ElasticsearchResponse<Stream> Execute(RestRequest restRequest, object deserializationState) { //RestResponse result = GetClient().execute(restRequest); // var method = Enum.GetName(typeof(Method), restRequest.Method); var uri = restRequest.Uri; var path = uri.ToString(); var baseUri = new Uri(string.Format("{0}://{1}:{2}", uri.Scheme, uri.Host, uri.Port)); var requestData = restRequest.Body; if (!this._resourceLock.WaitOne(this._timeout)) { var m = "Could not start the thrift operation before the timeout of " + this._timeout + "ms completed while waiting for the semaphore"; return ElasticsearchResponse<Stream>.CreateError(this._connectionSettings, new TimeoutException(m), method, path, requestData); } try { ConcurrentQueue<Rest.Client> queue; if (!this._clients.TryGetValue(baseUri,out queue)) { var m = string.Format("Could dequeue a thrift client from internal socket pool of size {0}", this._poolSize); var status = ElasticsearchResponse<Stream>.CreateError(this._connectionSettings, new Exception(m), method, path, requestData); return status; } Rest.Client client; if (!queue.TryDequeue(out client)) { var m = string.Format("Could dequeue a thrift client from internal socket pool of size {0}", this._poolSize); var status = ElasticsearchResponse<Stream>.CreateError(this._connectionSettings, new Exception(m), method, path, requestData); return status; } try { if (!client.InputProtocol.Transport.IsOpen) client.InputProtocol.Transport.Open(); var result = client.execute(restRequest); if (result.Status == Status.OK || result.Status == Status.CREATED || result.Status == Status.ACCEPTED) { var response = ElasticsearchResponse<Stream>.Create( this._connectionSettings, (int)result.Status, method, path, requestData, new MemoryStream(result.Body ?? new byte[0])); return response; } else { var response = ElasticsearchResponse<Stream>.Create( this._connectionSettings, (int)result.Status, method, path, requestData, new MemoryStream(result.Body ?? new byte[0])); return response; } } catch (SocketException) { client.InputProtocol.Transport.Close(); throw; } catch (IOException) { client.InputProtocol.Transport.Close(); throw; } catch (TTransportException) { client.InputProtocol.Transport.Close(); throw; } finally { //make sure we make the client available again. if (queue != null && client != null) queue.Enqueue(client); } } catch (Exception e) { return ElasticsearchResponse<Stream>.CreateError(this._connectionSettings, e, method, path, requestData); } finally { this._resourceLock.Release(); } } public string DecodeStr(byte[] bytes) { if (bytes != null && bytes.Length > 0) { return Encoding.UTF8.GetString(bytes); } return string.Empty; } } }
namespace Nancy { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Nancy.Bootstrapper; using Nancy.Configuration; using Nancy.Diagnostics; using Nancy.TinyIoc; using Extensions; /// <summary> /// TinyIoC bootstrapper - registers default route resolver and registers itself as /// INancyModuleCatalog for resolving modules but behavior can be overridden if required. /// </summary> public class DefaultNancyBootstrapper : NancyBootstrapperWithRequestContainerBase<TinyIoCContainer> { /// <summary> /// Default assemblies that are ignored for autoregister /// </summary> public static IEnumerable<Func<Assembly, bool>> DefaultAutoRegisterIgnoredAssemblies = new Func<Assembly, bool>[] { asm => asm.FullName.StartsWith("Microsoft.", StringComparison.Ordinal), asm => asm.FullName.StartsWith("System.", StringComparison.Ordinal), asm => asm.FullName.StartsWith("System,", StringComparison.Ordinal), asm => asm.FullName.StartsWith("CR_ExtUnitTest", StringComparison.Ordinal), asm => asm.FullName.StartsWith("mscorlib,", StringComparison.Ordinal), asm => asm.FullName.StartsWith("CR_VSTest", StringComparison.Ordinal), asm => asm.FullName.StartsWith("DevExpress.CodeRush", StringComparison.Ordinal), asm => asm.FullName.StartsWith("IronPython", StringComparison.Ordinal), asm => asm.FullName.StartsWith("IronRuby", StringComparison.Ordinal), asm => asm.FullName.StartsWith("xunit", StringComparison.Ordinal), asm => asm.FullName.StartsWith("Nancy.Testing", StringComparison.Ordinal), asm => asm.FullName.StartsWith("MonoDevelop.NUnit", StringComparison.Ordinal), asm => asm.FullName.StartsWith("SMDiagnostics", StringComparison.Ordinal), asm => asm.FullName.StartsWith("CppCodeProvider", StringComparison.Ordinal), asm => asm.FullName.StartsWith("WebDev.WebHost40", StringComparison.Ordinal), asm => asm.FullName.StartsWith("nunit", StringComparison.Ordinal), asm => asm.FullName.StartsWith("nCrunch", StringComparison.Ordinal), }; /// <summary> /// Gets the assemblies to ignore when autoregistering the application container /// Return true from the delegate to ignore that particular assembly, returning false /// does not mean the assembly *will* be included, a true from another delegate will /// take precedence. /// </summary> protected virtual IEnumerable<Func<Assembly, bool>> AutoRegisterIgnoredAssemblies { get { return DefaultAutoRegisterIgnoredAssemblies; } } /// <summary> /// Configures the container using AutoRegister followed by registration /// of default INancyModuleCatalog and IRouteResolver. /// </summary> /// <param name="container">Container instance</param> protected override void ConfigureApplicationContainer(TinyIoCContainer container) { AutoRegister(container, this.AutoRegisterIgnoredAssemblies); } /// <summary> /// Resolve INancyEngine /// </summary> /// <returns>INancyEngine implementation</returns> protected override sealed INancyEngine GetEngineInternal() { return this.ApplicationContainer.Resolve<INancyEngine>(); } /// <summary> /// Create a default, unconfigured, container /// </summary> /// <returns>Container instance</returns> protected override TinyIoCContainer GetApplicationContainer() { return new TinyIoCContainer(); } /// <summary> /// Registers an <see cref="INancyEnvironment"/> instance in the container. /// </summary> /// <param name="container">The container to register into.</param> /// <param name="environment">The <see cref="INancyEnvironment"/> instance to register.</param> protected override void RegisterNancyEnvironment(TinyIoCContainer container, INancyEnvironment environment) { container.Register(environment); } /// <summary> /// Register the bootstrapper's implemented types into the container. /// This is necessary so a user can pass in a populated container but not have /// to take the responsibility of registering things like INancyModuleCatalog manually. /// </summary> /// <param name="applicationContainer">Application container to register into</param> protected override sealed void RegisterBootstrapperTypes(TinyIoCContainer applicationContainer) { applicationContainer.Register<INancyModuleCatalog>(this); } /// <summary> /// Register the default implementations of internally used types into the container as singletons /// </summary> /// <param name="container">Container to register into</param> /// <param name="typeRegistrations">Type registrations to register</param> protected override sealed void RegisterTypes(TinyIoCContainer container, IEnumerable<TypeRegistration> typeRegistrations) { foreach (var typeRegistration in typeRegistrations) { switch (typeRegistration.Lifetime) { case Lifetime.Transient: container.Register(typeRegistration.RegistrationType, typeRegistration.ImplementationType).AsMultiInstance(); break; case Lifetime.Singleton: container.Register(typeRegistration.RegistrationType, typeRegistration.ImplementationType).AsSingleton(); break; case Lifetime.PerRequest: throw new InvalidOperationException("Unable to directly register a per request lifetime."); default: throw new ArgumentOutOfRangeException(); } } } /// <summary> /// Register the various collections into the container as singletons to later be resolved /// by IEnumerable{Type} constructor dependencies. /// </summary> /// <param name="container">Container to register into</param> /// <param name="collectionTypeRegistrations">Collection type registrations to register</param> protected override sealed void RegisterCollectionTypes(TinyIoCContainer container, IEnumerable<CollectionTypeRegistration> collectionTypeRegistrations) { foreach (var collectionTypeRegistration in collectionTypeRegistrations) { switch (collectionTypeRegistration.Lifetime) { case Lifetime.Transient: container.RegisterMultiple(collectionTypeRegistration.RegistrationType, collectionTypeRegistration.ImplementationTypes).AsMultiInstance(); break; case Lifetime.Singleton: container.RegisterMultiple(collectionTypeRegistration.RegistrationType, collectionTypeRegistration.ImplementationTypes).AsSingleton(); break; case Lifetime.PerRequest: throw new InvalidOperationException("Unable to directly register a per request lifetime."); default: throw new ArgumentOutOfRangeException(); } } } /// <summary> /// Register the given module types into the container /// </summary> /// <param name="container">Container to register into</param> /// <param name="moduleRegistrationTypes">NancyModule types</param> protected override sealed void RegisterRequestContainerModules(TinyIoCContainer container, IEnumerable<ModuleRegistration> moduleRegistrationTypes) { foreach (var moduleRegistrationType in moduleRegistrationTypes) { container.Register( typeof(INancyModule), moduleRegistrationType.ModuleType, moduleRegistrationType.ModuleType.FullName). AsSingleton(); } } /// <summary> /// Register the given instances into the container /// </summary> /// <param name="container">Container to register into</param> /// <param name="instanceRegistrations">Instance registration types</param> protected override void RegisterInstances(TinyIoCContainer container, IEnumerable<InstanceRegistration> instanceRegistrations) { foreach (var instanceRegistration in instanceRegistrations) { container.Register( instanceRegistration.RegistrationType, instanceRegistration.Implementation); } } /// <summary> /// Creates a per request child/nested container /// </summary> /// <param name="context">Current context</param> /// <returns>Request container instance</returns> protected override TinyIoCContainer CreateRequestContainer(NancyContext context) { return this.ApplicationContainer.GetChildContainer(); } /// <summary> /// Gets the <see cref="INancyEnvironmentConfigurator"/> used by th. /// </summary> /// <returns>An <see cref="INancyEnvironmentConfigurator"/> instance.</returns> protected override INancyEnvironmentConfigurator GetEnvironmentConfigurator() { return this.ApplicationContainer.Resolve<INancyEnvironmentConfigurator>(); } /// <summary> /// Gets the diagnostics for initialization /// </summary> /// <returns>IDiagnostics implementation</returns> protected override IDiagnostics GetDiagnostics() { return this.ApplicationContainer.Resolve<IDiagnostics>(); } /// <summary> /// Gets all registered startup tasks /// </summary> /// <returns>An <see cref="IEnumerable{T}"/> instance containing <see cref="IApplicationStartup"/> instances. </returns> protected override IEnumerable<IApplicationStartup> GetApplicationStartupTasks() { return this.ApplicationContainer.ResolveAll<IApplicationStartup>(false); } /// <summary> /// Gets all registered request startup tasks /// </summary> /// <returns>An <see cref="IEnumerable{T}"/> instance containing <see cref="IRequestStartup"/> instances.</returns> protected override IEnumerable<IRequestStartup> RegisterAndGetRequestStartupTasks(TinyIoCContainer container, Type[] requestStartupTypes) { container.RegisterMultiple(typeof(IRequestStartup), requestStartupTypes); return container.ResolveAll<IRequestStartup>(false); } /// <summary> /// Gets all registered application registration tasks /// </summary> /// <returns>An <see cref="IEnumerable{T}"/> instance containing <see cref="IRegistrations"/> instances.</returns> protected override IEnumerable<IRegistrations> GetRegistrationTasks() { return this.ApplicationContainer.ResolveAll<IRegistrations>(false); } /// <summary> /// Get the <see cref="INancyEnvironment"/> instance. /// </summary> /// <returns>An configured <see cref="INancyEnvironment"/> instance.</returns> /// <remarks>The boostrapper must be initialised (<see cref="INancyBootstrapper.Initialise"/>) prior to calling this.</remarks> public override INancyEnvironment GetEnvironment() { return this.ApplicationContainer.Resolve<INancyEnvironment>(); } /// <summary> /// Retrieve all module instances from the container /// </summary> /// <param name="container">Container to use</param> /// <returns>Collection of NancyModule instances</returns> protected override sealed IEnumerable<INancyModule> GetAllModules(TinyIoCContainer container) { var nancyModules = container.ResolveAll<INancyModule>(false); return nancyModules; } /// <summary> /// Retrieve a specific module instance from the container /// </summary> /// <param name="container">Container to use</param> /// <param name="moduleType">Type of the module</param> /// <returns>NancyModule instance</returns> protected override sealed INancyModule GetModule(TinyIoCContainer container, Type moduleType) { container.Register(typeof(INancyModule), moduleType); return container.Resolve<INancyModule>(); } /// <summary> /// Executes auto registration with the given container. /// </summary> /// <param name="container">Container instance</param> private void AutoRegister(TinyIoCContainer container, IEnumerable<Func<Assembly, bool>> ignoredAssemblies) { var assembly = typeof(NancyEngine).GetTypeInfo().Assembly; container.AutoRegister(this.AssemblyCatalog.GetAssemblies().Where(a => !ignoredAssemblies.Any(ia => ia(a))), DuplicateImplementationActions.RegisterMultiple, t => t.GetAssembly() != assembly); } } }
using UnityEngine; using System.Collections; using System; public class Math3d : MonoBehaviour { private static Transform tempChild = null; private static Transform tempParent = null; public static void Init(){ tempChild = (new GameObject("Math3d_TempChild")).transform; tempParent = (new GameObject("Math3d_TempParent")).transform; tempChild.gameObject.hideFlags = HideFlags.HideAndDontSave; DontDestroyOnLoad(tempChild.gameObject); tempParent.gameObject.hideFlags = HideFlags.HideAndDontSave; DontDestroyOnLoad(tempParent.gameObject); //set the parent tempChild.parent = tempParent; } public static Vector3 ParabolaLerp(Vector3 start, Vector3 apex, Vector3 end, float t) { t = Mathf.Clamp01(t); Vector3 parabolaPos = Vector3.zero; parabolaPos.x = ParabolaPosLerp(start.x, apex.x, end.x, t); parabolaPos.y = ParabolaPosLerp(start.y, apex.y, end.y, t); parabolaPos.z = ParabolaPosLerp(start.z, apex.z, end.z, t); return parabolaPos; } private static float ParabolaPosLerp(float start, float apex, float end, float t) { return start - t * (3 * start - 4 * apex + end) + 2 * Mathf.Pow(t, 2f) * (start - 2 * apex + end); } //increase or decrease the length of vector by size public static Vector3 AddVectorLength(Vector3 vector, float size){ //get the vector length float magnitude = Vector3.Magnitude(vector); //change the length magnitude += size; //normalize the vector Vector3 vectorNormalized = Vector3.Normalize(vector); //scale the vector return Vector3.Scale(vectorNormalized, new Vector3(magnitude, magnitude, magnitude)); } //create a vector of direction "vector" with length "size" public static Vector3 SetVectorLength(Vector3 vector, float size){ //normalize the vector Vector3 vectorNormalized = Vector3.Normalize(vector); //scale the vector return vectorNormalized *= size; } //caclulate the rotational difference from A to B public static Quaternion SubtractRotation(Quaternion B, Quaternion A){ Quaternion C = Quaternion.Inverse(A) * B; return C; } //Find the line of intersection between two planes. The planes are defined by a normal and a point on that plane. //The outputs are a point on the line and a vector which indicates it's direction. If the planes are not parallel, //the function outputs true, otherwise false. public static bool PlanePlaneIntersection(out Vector3 linePoint, out Vector3 lineVec, Vector3 plane1Normal, Vector3 plane1Position, Vector3 plane2Normal, Vector3 plane2Position){ linePoint = Vector3.zero; lineVec = Vector3.zero; //We can get the direction of the line of intersection of the two planes by calculating the //cross product of the normals of the two planes. Note that this is just a direction and the line //is not fixed in space yet. We need a point for that to go with the line vector. lineVec = Vector3.Cross(plane1Normal, plane2Normal); //Next is to calculate a point on the line to fix it's position in space. This is done by finding a vector from //the plane2 location, moving parallel to it's plane, and intersecting plane1. To prevent rounding //errors, this vector also has to be perpendicular to lineDirection. To get this vector, calculate //the cross product of the normal of plane2 and the lineDirection. Vector3 ldir = Vector3.Cross(plane2Normal, lineVec); float denominator = Vector3.Dot(plane1Normal, ldir); //Prevent divide by zero and rounding errors by requiring about 5 degrees angle between the planes. if(Mathf.Abs(denominator) > 0.006f){ Vector3 plane1ToPlane2 = plane1Position - plane2Position; float t = Vector3.Dot(plane1Normal, plane1ToPlane2) / denominator; linePoint = plane2Position + t * ldir; return true; } //output not valid else{ return false; } } //Get the intersection between a line and a plane. //If the line and plane are not parallel, the function outputs true, otherwise false. public static bool LinePlaneIntersection(out Vector3 intersection, Vector3 linePoint, Vector3 lineVec, Vector3 planeNormal, Vector3 planePoint){ float length; float dotNumerator; float dotDenominator; Vector3 vector; intersection = Vector3.zero; //calculate the distance between the linePoint and the line-plane intersection point dotNumerator = Vector3.Dot((planePoint - linePoint), planeNormal); dotDenominator = Vector3.Dot(lineVec, planeNormal); //line and plane are not parallel if(dotDenominator != 0.0f){ length = dotNumerator / dotDenominator; //create a vector from the linePoint to the intersection point vector = SetVectorLength(lineVec, length); //get the coordinates of the line-plane intersection point intersection = linePoint + vector; return true; } //output not valid else{ return false; } } //Calculate the intersection point of two lines. Returns true if lines intersect, otherwise false. //Note that in 3d, two lines do not intersect most of the time. So if the two lines are not in the //same plane, use ClosestPointsOnTwoLines() instead. public static bool LineLineIntersection(out Vector3 intersection, Vector3 linePoint1, Vector3 lineVec1, Vector3 linePoint2, Vector3 lineVec2){ intersection = Vector3.zero; Vector3 lineVec3 = linePoint2 - linePoint1; Vector3 crossVec1and2 = Vector3.Cross(lineVec1, lineVec2); Vector3 crossVec3and2 = Vector3.Cross(lineVec3, lineVec2); float planarFactor = Vector3.Dot(lineVec3, crossVec1and2); //Lines are not coplanar. Take into account rounding errors. if((planarFactor >= 0.00001f) || (planarFactor <= -0.00001f)){ return false; } //Note: sqrMagnitude does x*x+y*y+z*z on the input vector. float s = Vector3.Dot(crossVec3and2, crossVec1and2) / crossVec1and2.sqrMagnitude; if((s >= 0.0f) && (s <= 1.0f)){ intersection = linePoint1 + (lineVec1 * s); return true; } else{ return false; } } //Two non-parallel lines which may or may not touch each other have a point on each line which are closest //to each other. This function finds those two points. If the lines are not parallel, the function //outputs true, otherwise false. public static bool ClosestPointsOnTwoLines(out Vector3 closestPointLine1, out Vector3 closestPointLine2, Vector3 linePoint1, Vector3 lineVec1, Vector3 linePoint2, Vector3 lineVec2){ closestPointLine1 = Vector3.zero; closestPointLine2 = Vector3.zero; float a = Vector3.Dot(lineVec1, lineVec1); float b = Vector3.Dot(lineVec1, lineVec2); float e = Vector3.Dot(lineVec2, lineVec2); float d = a*e - b*b; //lines are not parallel if(d != 0.0f){ Vector3 r = linePoint1 - linePoint2; float c = Vector3.Dot(lineVec1, r); float f = Vector3.Dot(lineVec2, r); float s = (b*f - c*e) / d; float t = (a*f - c*b) / d; closestPointLine1 = linePoint1 + lineVec1 * s; closestPointLine2 = linePoint2 + lineVec2 * t; return true; } else{ return false; } } //This function returns a point which is a projection from a point to a line. public static Vector3 ProjectPointOnLine(Vector3 linePoint, Vector3 lineVec, Vector3 point){ //get vector from point on line to point in space Vector3 linePointToPoint = point - linePoint; float t = Vector3.Dot(linePointToPoint, lineVec); return linePoint + lineVec * t; } //This function returns a point which is a projection from a point to a plane. public static Vector3 ProjectPointOnPlane(Vector3 planeNormal, Vector3 planePoint, Vector3 point){ float distance; Vector3 translationVector; //First calculate the distance from the point to the plane: distance = SignedDistancePlanePoint(planeNormal, planePoint, point); //Reverse the sign of the distance distance *= -1; //Get a translation vector translationVector = SetVectorLength(planeNormal, distance); //Translate the point to form a projection return point + translationVector; } //Projects a vector onto a plane. The output is not normalized. public static Vector3 ProjectVectorOnPlane(Vector3 planeNormal, Vector3 vector){ return vector - (Vector3.Dot(vector, planeNormal) * planeNormal); } //Get the shortest distance between a point and a plane. The output is signed so it holds information //as to which side of the plane normal the point is. public static float SignedDistancePlanePoint(Vector3 planeNormal, Vector3 planePoint, Vector3 point){ return Vector3.Dot(planeNormal, (point - planePoint)); } //This function calculates a signed (+ or - sign instead of being ambiguous) dot product. It is basically used //to figure out whether a vector is positioned to the left or right of another vector. The way this is done is //by calculating a vector perpendicular to one of the vectors and using that as a reference. This is because //the result of a dot product only has signed information when an angle is transitioning between more or less //then 90 degrees. public static float SignedDotProduct(Vector3 vectorA, Vector3 vectorB, Vector3 normal){ Vector3 perpVector; float dot; //Use the geometry object normal and one of the input vectors to calculate the perpendicular vector perpVector = Vector3.Cross(normal, vectorA); //Now calculate the dot product between the perpendicular vector (perpVector) and the other input vector dot = Vector3.Dot(perpVector, vectorB); return dot; } /// <summary> /// Calculate the signed angle between two vectors, given a normal /// </summary> /// <param name="referenceVector"></param> /// <param name="otherVector"></param> /// <param name="normal"></param> /// <returns></returns> public static float SignedVectorAngle(Vector3 referenceVector, Vector3 otherVector, Vector3 normal) { Vector3 perpVector; float angle; //Use the geometry object normal and one of the input vectors to calculate the perpendicular vector perpVector = Vector3.Cross(normal, referenceVector); //Now calculate the dot product between the perpendicular vector (perpVector) and the other input vector angle = Vector3.Angle(referenceVector, otherVector); angle *= Mathf.Sign(Vector3.Dot(perpVector, otherVector)); return angle; } //Calculate the angle between a vector and a plane. The plane is made by a normal vector. //Output is in radians. public static float AngleVectorPlane(Vector3 vector, Vector3 normal){ float dot; float angle; //calculate the the dot product between the two input vectors. This gives the cosine between the two vectors dot = Vector3.Dot(vector, normal); //this is in radians angle = (float)Math.Acos(dot); return 1.570796326794897f - angle; //90 degrees - angle } //Calculate the dot product as an angle public static float DotProductAngle(Vector3 vec1, Vector3 vec2){ double dot; double angle; //get the dot product dot = Vector3.Dot(vec1, vec2); //Clamp to prevent NaN error. Shouldn't need this in the first place, but there could be a rounding error issue. if(dot < -1.0f){ dot = -1.0f; } if(dot > 1.0f){ dot =1.0f; } //Calculate the angle. The output is in radians //This step can be skipped for optimization... angle = Math.Acos(dot); return (float)angle; } //Convert a plane defined by 3 points to a plane defined by a vector and a point. //The plane point is the middle of the triangle defined by the 3 points. public static void PlaneFrom3Points(out Vector3 planeNormal, out Vector3 planePoint, Vector3 pointA, Vector3 pointB, Vector3 pointC){ planeNormal = Vector3.zero; planePoint = Vector3.zero; //Make two vectors from the 3 input points, originating from point A Vector3 AB = pointB - pointA; Vector3 AC = pointC - pointA; //Calculate the normal planeNormal = Vector3.Normalize(Vector3.Cross(AB, AC)); //Get the points in the middle AB and AC Vector3 middleAB = pointA + (AB / 2.0f); Vector3 middleAC = pointA + (AC / 2.0f); //Get vectors from the middle of AB and AC to the point which is not on that line. Vector3 middleABtoC = pointC - middleAB; Vector3 middleACtoB = pointB - middleAC; //Calculate the intersection between the two lines. This will be the center //of the triangle defined by the 3 points. //We could use LineLineIntersection instead of ClosestPointsOnTwoLines but due to rounding errors //this sometimes doesn't work. Vector3 temp; ClosestPointsOnTwoLines(out planePoint, out temp, middleAB, middleABtoC, middleAC, middleACtoB); } //Returns the forward vector of a quaternion public static Vector3 GetForwardVector(Quaternion q){ return q * Vector3.forward; } //Returns the up vector of a quaternion public static Vector3 GetUpVector(Quaternion q){ return q * Vector3.up; } //Returns the right vector of a quaternion public static Vector3 GetRightVector(Quaternion q){ return q * Vector3.right; } //Gets a quaternion from a matrix public static Quaternion QuaternionFromMatrix(Matrix4x4 m){ return Quaternion.LookRotation(m.GetColumn(2), m.GetColumn(1)); } //Gets a position from a matrix public static Vector3 PositionFromMatrix(Matrix4x4 m){ Vector4 vector4Position = m.GetColumn(3); return new Vector3(vector4Position.x, vector4Position.y, vector4Position.z); } //This is an alternative for Quaternion.LookRotation. Instead of aligning the forward and up vector of the game //object with the input vectors, a custom direction can be used instead of the fixed forward and up vectors. //alignWithVector and alignWithNormal are in world space. //customForward and customUp are in object space. //Usage: use alignWithVector and alignWithNormal as if you are using the default LookRotation function. //Set customForward and customUp to the vectors you wish to use instead of the default forward and up vectors. public static void LookRotationExtended(ref GameObject gameObjectInOut, Vector3 alignWithVector, Vector3 alignWithNormal, Vector3 customForward, Vector3 customUp){ //Set the rotation of the destination Quaternion rotationA = Quaternion.LookRotation(alignWithVector, alignWithNormal); //Set the rotation of the custom normal and up vectors. //When using the default LookRotation function, this would be hard coded to the forward and up vector. Quaternion rotationB = Quaternion.LookRotation(customForward, customUp); //Calculate the rotation gameObjectInOut.transform.rotation = rotationA * Quaternion.Inverse(rotationB); } //This function transforms one object as if it was parented to the other. //Before using this function, the Init() function must be called //Input: parentRotation and parentPosition: the current parent transform. //Input: startParentRotation and startParentPosition: the transform of the parent object at the time the objects are parented. //Input: startChildRotation and startChildPosition: the transform of the child object at the time the objects are parented. //Output: childRotation and childPosition. //All transforms are in world space. public static void TransformWithParent(out Quaternion childRotation, out Vector3 childPosition, Quaternion parentRotation, Vector3 parentPosition, Quaternion startParentRotation, Vector3 startParentPosition, Quaternion startChildRotation, Vector3 startChildPosition){ childRotation = Quaternion.identity; childPosition = Vector3.zero; //set the parent start transform tempParent.rotation = startParentRotation; tempParent.position = startParentPosition; tempParent.localScale = Vector3.one; //to prevent scale wandering //set the child start transform tempChild.rotation = startChildRotation; tempChild.position = startChildPosition; tempChild.localScale = Vector3.one; //to prevent scale wandering //translate and rotate the child by moving the parent tempParent.rotation = parentRotation; tempParent.position = parentPosition; //get the child transform childRotation = tempChild.rotation; childPosition = tempChild.position; } //With this function you can align a triangle of an object with any transform. //Usage: gameObjectInOut is the game object you want to transform. //alignWithVector, alignWithNormal, and alignWithPosition is the transform with which the triangle of the object should be aligned with. //triangleForward, triangleNormal, and trianglePosition is the transform of the triangle from the object. //alignWithVector, alignWithNormal, and alignWithPosition are in world space. //triangleForward, triangleNormal, and trianglePosition are in object space. //trianglePosition is the mesh position of the triangle. The effect of the scale of the object is handled automatically. //trianglePosition can be set at any position, it does not have to be at a vertex or in the middle of the triangle. public static void PreciseAlign(ref GameObject gameObjectInOut, Vector3 alignWithVector, Vector3 alignWithNormal, Vector3 alignWithPosition, Vector3 triangleForward, Vector3 triangleNormal, Vector3 trianglePosition){ //Set the rotation. LookRotationExtended(ref gameObjectInOut, alignWithVector, alignWithNormal, triangleForward, triangleNormal); //Get the world space position of trianglePosition Vector3 trianglePositionWorld = gameObjectInOut.transform.TransformPoint(trianglePosition); //Get a vector from trianglePosition to alignWithPosition Vector3 translateVector = alignWithPosition - trianglePositionWorld; //Now transform the object so the triangle lines up correctly. gameObjectInOut.transform.Translate(translateVector, Space.World); } //Convert a position, direction, and normal vector to a transform public static void VectorsToTransform(ref GameObject gameObjectInOut, Vector3 positionVector, Vector3 directionVector, Vector3 normalVector){ gameObjectInOut.transform.position = positionVector; gameObjectInOut.transform.rotation = Quaternion.LookRotation(directionVector, normalVector); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /*============================================================ ** ** ** ** Purpose: This class will encapsulate a short and provide an ** Object representation of it. ** ** ===========================================================*/ namespace System { using System; using System.Globalization; using System.Runtime.InteropServices; using System.Diagnostics.Contracts; [System.Runtime.InteropServices.ComVisible(true)] [Serializable] [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)] public struct Int16 : IComparable, IFormattable, IConvertible , IComparable<Int16>, IEquatable<Int16> { internal short m_value; public const short MaxValue = (short)0x7FFF; public const short MinValue = unchecked((short)0x8000); // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type Int16, this method throws an ArgumentException. // public int CompareTo(Object value) { if (value == null) { return 1; } if (value is Int16) { return m_value - ((Int16)value).m_value; } throw new ArgumentException(Environment.GetResourceString("Arg_MustBeInt16")); } public int CompareTo(Int16 value) { return m_value - value; } public override bool Equals(Object obj) { if (!(obj is Int16)) { return false; } return m_value == ((Int16)obj).m_value; } [System.Runtime.Versioning.NonVersionable] public bool Equals(Int16 obj) { return m_value == obj; } // Returns a HashCode for the Int16 public override int GetHashCode() { return ((int)((ushort)m_value) | (((int)m_value) << 16)); } [System.Security.SecuritySafeCritical] // auto-generated public override String ToString() { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo); } [System.Security.SecuritySafeCritical] // auto-generated public String ToString(IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider)); } public String ToString(String format) { Contract.Ensures(Contract.Result<String>() != null); return ToString(format, NumberFormatInfo.CurrentInfo); } public String ToString(String format, IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return ToString(format, NumberFormatInfo.GetInstance(provider)); } [System.Security.SecuritySafeCritical] // auto-generated private String ToString(String format, NumberFormatInfo info) { Contract.Ensures(Contract.Result<String>() != null); if (m_value<0 && format!=null && format.Length>0 && (format[0]=='X' || format[0]=='x')) { uint temp = (uint)(m_value & 0x0000FFFF); return Number.FormatUInt32(temp,format, info); } return Number.FormatInt32(m_value, format, info); } public static short Parse(String s) { return Parse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } public static short Parse(String s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); return Parse(s, style, NumberFormatInfo.CurrentInfo); } public static short Parse(String s, IFormatProvider provider) { return Parse(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } public static short Parse(String s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleInteger(style); return Parse(s, style, NumberFormatInfo.GetInstance(provider)); } private static short Parse(String s, NumberStyles style, NumberFormatInfo info) { int i = 0; try { i = Number.ParseInt32(s, style, info); } catch(OverflowException e) { throw new OverflowException(Environment.GetResourceString("Overflow_Int16"), e); } // We need this check here since we don't allow signs to specified in hex numbers. So we fixup the result // for negative numbers if ((style & NumberStyles.AllowHexSpecifier) != 0) { // We are parsing a hexadecimal number if ((i < 0) || (i > UInt16.MaxValue)) { throw new OverflowException(Environment.GetResourceString("Overflow_Int16")); } return (short)i; } if (i < MinValue || i > MaxValue) throw new OverflowException(Environment.GetResourceString("Overflow_Int16")); return (short)i; } public static bool TryParse(String s, out Int16 result) { return TryParse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out Int16 result) { NumberFormatInfo.ValidateParseStyleInteger(style); return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } private static bool TryParse(String s, NumberStyles style, NumberFormatInfo info, out Int16 result) { result = 0; int i; if (!Number.TryParseInt32(s, style, info, out i)) { return false; } // We need this check here since we don't allow signs to specified in hex numbers. So we fixup the result // for negative numbers if ((style & NumberStyles.AllowHexSpecifier) != 0) { // We are parsing a hexadecimal number if ((i < 0) || i > UInt16.MaxValue) { return false; } result = (Int16) i; return true; } if (i < MinValue || i > MaxValue) { return false; } result = (Int16) i; return true; } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.Int16; } /// <internalonly/> bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(m_value); } /// <internalonly/> char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(m_value); } /// <internalonly/> sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } /// <internalonly/> byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } /// <internalonly/> short IConvertible.ToInt16(IFormatProvider provider) { return m_value; } /// <internalonly/> ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } /// <internalonly/> int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(m_value); } /// <internalonly/> uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } /// <internalonly/> long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } /// <internalonly/> ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } /// <internalonly/> float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(m_value); } /// <internalonly/> double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(m_value); } /// <internalonly/> Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } /// <internalonly/> DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Int16", "DateTime")); } /// <internalonly/> Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
using System; using System.Collections.Generic; using System.Linq; namespace CppSharp.AST { /// <summary> /// Represents a declaration context. /// </summary> public abstract class DeclarationContext : Declaration { public bool IsAnonymous { get; set; } public List<Declaration> Declarations; public List<TypeReference> TypeReferences; public DeclIterator<Namespace> Namespaces { get { return new DeclIterator<Namespace>(Declarations); } } public DeclIterator<Enumeration> Enums { get { return new DeclIterator<Enumeration>(Declarations); } } public DeclIterator<Function> Functions { get { return new DeclIterator<Function>(Declarations); } } public DeclIterator<Class> Classes { get { return new DeclIterator<Class>(Declarations); } } public DeclIterator<Template> Templates { get { return new DeclIterator<Template>(Declarations); } } public DeclIterator<TypedefDecl> Typedefs { get { return new DeclIterator<TypedefDecl>(Declarations); } } public DeclIterator<Variable> Variables { get { return new DeclIterator<Variable>(Declarations); } } public DeclIterator<Event> Events { get { return new DeclIterator<Event>(Declarations); } } // Used to keep track of anonymous declarations. public Dictionary<ulong, Declaration> Anonymous; // True if the context is inside an extern "C" context. public bool IsExternCContext; public override string LogicalName { get { return IsAnonymous ? "<anonymous>" : base.Name; } } public override string LogicalOriginalName { get { return IsAnonymous ? "<anonymous>" : base.OriginalName; } } protected DeclarationContext() { Declarations = new List<Declaration>(); TypeReferences = new List<TypeReference>(); Anonymous = new Dictionary<ulong, Declaration>(); } protected DeclarationContext(DeclarationContext dc) : base(dc) { Declarations = dc.Declarations; TypeReferences = new List<TypeReference>(dc.TypeReferences); Anonymous = new Dictionary<ulong, Declaration>(dc.Anonymous); IsAnonymous = dc.IsAnonymous; } public IEnumerable<DeclarationContext> GatherParentNamespaces() { var children = new List<DeclarationContext>(); var currentNamespace = this; while (currentNamespace != null) { if (!(currentNamespace is TranslationUnit)) children.Add(currentNamespace); currentNamespace = currentNamespace.Namespace; } children.Reverse(); return children; } public Declaration FindAnonymous(ulong key) { return Anonymous.ContainsKey(key) ? Anonymous[key] : null; } public DeclarationContext FindDeclaration(IEnumerable<string> declarations) { DeclarationContext currentDeclaration = this; foreach (var declaration in declarations) { var subDeclaration = currentDeclaration.Namespaces .Concat<DeclarationContext>(currentDeclaration.Classes) .FirstOrDefault(e => e.Name.Equals(declaration)); if (subDeclaration == null) return null; currentDeclaration = subDeclaration; } return currentDeclaration as DeclarationContext; } public Namespace FindNamespace(string name) { var namespaces = name.Split(new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries); return FindNamespace(namespaces); } public Namespace FindNamespace(IEnumerable<string> namespaces) { DeclarationContext currentNamespace = this; foreach (var @namespace in namespaces) { var childNamespace = currentNamespace.Namespaces.Find( e => e.Name.Equals(@namespace)); if (childNamespace == null) return null; currentNamespace = childNamespace; } return currentNamespace as Namespace; } public Namespace FindCreateNamespace(string name) { var @namespace = FindNamespace(name); if (@namespace == null) { @namespace = new Namespace { Name = name, Namespace = this, }; Namespaces.Add(@namespace); } return @namespace; } public Enumeration FindEnum(string name, bool createDecl = false) { var entries = name.Split(new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (entries.Count <= 1) { var @enum = Enums.Find(e => e.Name.Equals(name)); if (@enum == null && createDecl) { @enum = new Enumeration() { Name = name, Namespace = this }; Enums.Add(@enum); } return @enum; } var enumName = entries[entries.Count - 1]; var namespaces = entries.Take(entries.Count - 1); var @namespace = FindNamespace(namespaces); if (@namespace == null) return null; return @namespace.FindEnum(enumName, createDecl); } public Enumeration FindEnum(IntPtr ptr) { return Enums.FirstOrDefault(f => f.OriginalPtr == ptr); } public Function FindFunction(string name, bool createDecl = false) { if (string.IsNullOrEmpty(name)) return null; var entries = name.Split(new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (entries.Count <= 1) { var function = Functions.Find(e => e.Name.Equals(name)); if (function == null && createDecl) { function = new Function() { Name = name, Namespace = this }; Functions.Add(function); } return function; } var funcName = entries[entries.Count - 1]; var namespaces = entries.Take(entries.Count - 1); var @namespace = FindNamespace(namespaces); if (@namespace == null) return null; return @namespace.FindFunction(funcName, createDecl); } public Function FindFunction(string name) { return Functions .Concat(Templates.OfType<FunctionTemplate>() .Select(t => t.TemplatedFunction)) .FirstOrDefault(f => f.Name == name); } public Function FindFunctionByUSR(string usr) { return Functions .Concat(Templates.OfType<FunctionTemplate>() .Select(t => t.TemplatedFunction)) .FirstOrDefault(f => f.USR == usr); } Class CreateClass(string name, bool isComplete) { var @class = new Class { Name = name, Namespace = this, IsIncomplete = !isComplete }; return @class; } public Class FindClass(string name, StringComparison stringComparison = StringComparison.Ordinal) { if (string.IsNullOrEmpty(name)) return null; var entries = name.Split(new[] { "::" }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (entries.Count <= 1) { var @class = Classes.Find(c => c.Name.Equals(name, stringComparison)) ?? Namespaces.Select(n => n.FindClass(name, stringComparison)).FirstOrDefault(c => c != null); if (@class != null) return @class.CompleteDeclaration == null ? @class : (Class) @class.CompleteDeclaration; return null; } var className = entries[entries.Count - 1]; var namespaces = entries.Take(entries.Count - 1); DeclarationContext declContext = FindDeclaration(namespaces); if (declContext == null) { declContext = FindClass(entries[0]); if (declContext == null) return null; } return declContext.FindClass(className); } public Class FindClass(string name, bool isComplete, bool createDecl = false) { var @class = FindClass(name); if (@class == null) { if (createDecl) { @class = CreateClass(name, isComplete); Classes.Add(@class); } return @class; } if (@class.IsIncomplete == !isComplete) return @class; if (!createDecl) return null; var newClass = CreateClass(name, isComplete); // Replace the incomplete declaration with the complete one. if (@class.IsIncomplete) { @class.CompleteDeclaration = newClass; Classes.Replace(@class, newClass); } return newClass; } public FunctionTemplate FindFunctionTemplate(string name) { return Templates.OfType<FunctionTemplate>() .FirstOrDefault(t => t.Name == name); } public FunctionTemplate FindFunctionTemplateByUSR(string usr) { return Templates.OfType<FunctionTemplate>() .FirstOrDefault(t => t.USR == usr); } public ClassTemplate FindClassTemplate(string name) { return Templates.OfType<ClassTemplate>() .FirstOrDefault(t => t.Name == name); } public ClassTemplate FindClassTemplateByUSR(string usr) { return Templates.OfType<ClassTemplate>() .FirstOrDefault(t => t.USR == usr); } public TypedefDecl FindTypedef(string name, bool createDecl = false) { var entries = name.Split(new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (entries.Count <= 1) { var typeDef = Typedefs.Find(e => e.Name.Equals(name)); if (typeDef == null && createDecl) { typeDef = new TypedefDecl() { Name = name, Namespace = this }; Typedefs.Add(typeDef); } return typeDef; } var typeDefName = entries[entries.Count - 1]; var namespaces = entries.Take(entries.Count - 1); var @namespace = FindNamespace(namespaces); if (@namespace == null) return null; return @namespace.FindTypedef(typeDefName, createDecl); } public T FindType<T>(string name) where T : Declaration { var type = FindEnum(name) ?? FindFunction(name) ?? (Declaration)FindClass(name) ?? FindTypedef(name); return type as T; } public Enumeration FindEnumWithItem(string name) { var result = Enums.Find(e => e.ItemsByName.ContainsKey(name)); if (result == null) result = Namespaces.Select(ns => ns.FindEnumWithItem(name)).FirstOrDefault(); if (result == null) result = Classes.Select(c => c.FindEnumWithItem(name)).FirstOrDefault(); return result; } public virtual IEnumerable<Function> FindOperator(CXXOperatorKind kind) { return Functions.Where(fn => fn.OperatorKind == kind); } public virtual IEnumerable<Function> GetOverloads(Function function) { if (function.IsOperator) return FindOperator(function.OperatorKind); return Functions.Where(fn => fn.Name == function.Name); } public bool HasDeclarations { get { Func<Declaration, bool> pred = (t => t.IsGenerated); return Enums.Exists(pred) || HasFunctions || Typedefs.Exists(pred) || Classes.Any() || Namespaces.Exists(n => n.HasDeclarations); } } public bool HasFunctions { get { Func<Declaration, bool> pred = (t => t.IsGenerated); return Functions.Exists(pred) || Namespaces.Exists(n => n.HasFunctions); } } public bool IsRoot { get { return Namespace == null; } } } /// <summary> /// Represents a C++ namespace. /// </summary> public class Namespace : DeclarationContext { public override string LogicalName { get { return IsInline ? string.Empty : base.Name; } } public override string LogicalOriginalName { get { return IsInline ? string.Empty : base.OriginalName; } } public bool IsInline; public override T Visit<T>(IDeclVisitor<T> visitor) { return visitor.VisitNamespace(this); } } }
using System; using System.CodeDom; using System.Collections.Generic; using System.IO; using System.Text; namespace IronAHK.Scripting { partial class Parser { #region Name string VarNormalisedName(string name) { return name.ToLowerInvariant(); } CodeArrayIndexerExpression VarId(string name) { return VarId(VarIdExpand(VarNormalisedName(name))); } CodeArrayIndexerExpression VarId(CodeExpression name) { var scope = Scope + ScopeVar; if (name is CodePrimitiveExpression) { var raw = (CodePrimitiveExpression)name; if (raw.Value is string) return VarRef(scope + (string)raw.Value); } return VarRef(StringConcat(new CodePrimitiveExpression(scope), name)); } #endregion #region Reference CodeArrayIndexerExpression VarRef(params CodeExpression[] name) { var vars = new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(typeof(Script)), VarProperty); return new CodeArrayIndexerExpression(vars, name); } CodeArrayIndexerExpression VarRef(string name) { return VarRef(new CodePrimitiveExpression(name)); } CodeBinaryOperatorExpression VarAssign(CodeArrayIndexerExpression name, CodeExpression value) { return new CodeBinaryOperatorExpression(name, CodeBinaryOperatorType.Assign, value); } #endregion #region Expansion CodeExpression VarIdExpand(string code) { code = EscapedString(code, true); object result; if (IsPrimativeObject(code, out result)) return new CodePrimitiveExpression(result); if (code.IndexOf(Resolve) == -1) return new CodePrimitiveExpression(code); if (!DynamicVars) { throw new ParseException(ExNoDynamicVars); } var parts = new List<CodeExpression>(); var sub = new StringBuilder(); bool id = false; for (int i = 0; i < code.Length; i++) { char sym = code[i]; if (sym == Resolve && (i == 0 || code[i - 1] != Escape)) { if (id) { if (sub.Length == 0) throw new ParseException(ExEmptyVarRef, i); parts.Add(VarRefOrPrimitive(VarIdOrConstant(sub.ToString()))); sub.Length = 0; id = false; } else { parts.Add(new CodePrimitiveExpression(sub.ToString())); sub.Length = 0; id = true; } } else if (id && !IsIdentifier(sym)) throw new ParseException(ExInvalidVarToken, i); else sub.Append(sym); } if (sub.Length != 0) parts.Add(new CodePrimitiveExpression(sub.ToString())); if (parts.Count == 1) return new CodePrimitiveExpression(code); CodeExpression[] all = parts.ToArray(); return StringConcat(all); } CodeExpression VarIdOrConstant(string name) { switch (name.ToLowerInvariant()) { case "a_linenumber": return new CodePrimitiveExpression(line); case "a_linefile": return new CodePrimitiveExpression(Path.GetFullPath(fileName)); case "a_scriptdir": return new CodePrimitiveExpression(Path.GetDirectoryName(Path.GetFullPath(fileName))); case "a_scriptfullpath": return new CodePrimitiveExpression(Path.GetFullPath(fileName)); case "a_scriptname": return new CodePrimitiveExpression(Path.GetFileName(Path.GetFullPath(fileName))); case "a_thisfunc": return new CodePrimitiveExpression(Scope); case "a_thislabel": { if (blocks.Count == 0) return new CodePrimitiveExpression(string.Empty); var all = blocks.ToArray(); for (int i = all.Length - 1; i > -1; i--) if (all[i].Kind == CodeBlock.BlockKind.Label) return new CodePrimitiveExpression(all[i].Name); } return new CodePrimitiveExpression(string.Empty); default: return VarId(name); } } CodeArrayIndexerExpression InternalVariable { get { return VarRef(string.Concat(Scope, ScopeVar + "\0", InternalID)); } } #endregion #region Checks bool IsVarAssignment(object expr) { return expr is CodeBinaryOperatorExpression && ((CodeBinaryOperatorExpression)expr).Operator == CodeBinaryOperatorType.Assign; } bool IsVarReference(object expr) { return expr is CodeArrayIndexerExpression; } #endregion #region Casts CodeExpression VarRefOrPrimitive(object var) { if (var is CodePrimitiveExpression) return (CodePrimitiveExpression)var; if (!IsVarReference(var)) throw new ArgumentException(); return (CodeArrayIndexerExpression)var; } CodeExpression VarMixedExpr(object part) { return IsVarReference(part) ? VarRefOrPrimitive(part) : IsVarAssignment(part) ? (CodeBinaryOperatorExpression)part : part is CodeExpression ? (CodeExpression)part : new CodePrimitiveExpression(part); } #endregion } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using Be.Windows.Forms; using System.Collections.Generic; using System.Text; namespace Be.HexEditor { /// <summary> /// Summary description for FormFind. /// </summary> public class FormFind : Core.FormEx { private Be.Windows.Forms.HexBox hexFind; private System.Windows.Forms.TextBox txtFind; private System.Windows.Forms.RadioButton rbString; private System.Windows.Forms.RadioButton rbHex; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button btnOK; private System.Windows.Forms.Button btnCancel; private Label lblPercent; private Label lblFinding; private CheckBox chkMatchCase; private Timer timerPercent; private Timer timer; private FlowLayoutPanel flowLayoutPanel1; private FlowLayoutPanel flowLayoutPanel2; private Panel line; private IContainer components; public FormFind() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // rbString.CheckedChanged += new EventHandler(rb_CheckedChanged); rbHex.CheckedChanged += new EventHandler(rb_CheckedChanged); } void ByteProvider_Changed(object sender, EventArgs e) { ValidateFind(); } /// <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.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormFind)); this.txtFind = new System.Windows.Forms.TextBox(); this.rbString = new System.Windows.Forms.RadioButton(); this.rbHex = new System.Windows.Forms.RadioButton(); this.label1 = new System.Windows.Forms.Label(); this.btnOK = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.lblPercent = new System.Windows.Forms.Label(); this.lblFinding = new System.Windows.Forms.Label(); this.chkMatchCase = new System.Windows.Forms.CheckBox(); this.timerPercent = new System.Windows.Forms.Timer(this.components); this.timer = new System.Windows.Forms.Timer(this.components); this.hexFind = new Be.Windows.Forms.HexBox(); this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); this.line = new System.Windows.Forms.Panel(); this.flowLayoutPanel2 = new System.Windows.Forms.FlowLayoutPanel(); this.flowLayoutPanel1.SuspendLayout(); this.flowLayoutPanel2.SuspendLayout(); this.SuspendLayout(); // // txtFind // resources.ApplyResources(this.txtFind, "txtFind"); this.txtFind.Name = "txtFind"; this.txtFind.TextChanged += new System.EventHandler(this.txtString_TextChanged); // // rbString // resources.ApplyResources(this.rbString, "rbString"); this.rbString.Checked = true; this.rbString.Name = "rbString"; this.rbString.TabStop = true; // // rbHex // resources.ApplyResources(this.rbHex, "rbHex"); this.rbHex.Name = "rbHex"; // // label1 // resources.ApplyResources(this.label1, "label1"); this.label1.ForeColor = System.Drawing.Color.Blue; this.label1.Name = "label1"; // // btnOK // resources.ApplyResources(this.btnOK, "btnOK"); this.btnOK.Name = "btnOK"; this.btnOK.Click += new System.EventHandler(this.btnOK_Click); // // btnCancel // resources.ApplyResources(this.btnCancel, "btnCancel"); this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Name = "btnCancel"; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // lblPercent // resources.ApplyResources(this.lblPercent, "lblPercent"); this.lblPercent.Name = "lblPercent"; // // lblFinding // this.lblFinding.ForeColor = System.Drawing.Color.Blue; resources.ApplyResources(this.lblFinding, "lblFinding"); this.lblFinding.Name = "lblFinding"; // // chkMatchCase // resources.ApplyResources(this.chkMatchCase, "chkMatchCase"); this.chkMatchCase.Name = "chkMatchCase"; this.chkMatchCase.UseVisualStyleBackColor = true; // // timerPercent // this.timerPercent.Tick += new System.EventHandler(this.timerPercent_Tick); // // timer // this.timer.Interval = 50; this.timer.Tick += new System.EventHandler(this.timer_Tick); // // hexFind // resources.ApplyResources(this.hexFind, "hexFind"); // // // this.hexFind.BuiltInContextMenu.CopyMenuItemImage = global::Be.HexEditor.images.CopyHS; this.hexFind.BuiltInContextMenu.CopyMenuItemText = resources.GetString("hexFind.BuiltInContextMenu.CopyMenuItemText"); this.hexFind.BuiltInContextMenu.CutMenuItemImage = global::Be.HexEditor.images.CutHS; this.hexFind.BuiltInContextMenu.CutMenuItemText = resources.GetString("hexFind.BuiltInContextMenu.CutMenuItemText"); this.hexFind.BuiltInContextMenu.PasteMenuItemImage = global::Be.HexEditor.images.PasteHS; this.hexFind.BuiltInContextMenu.PasteMenuItemText = resources.GetString("hexFind.BuiltInContextMenu.PasteMenuItemText"); this.hexFind.BuiltInContextMenu.SelectAllMenuItemText = resources.GetString("hexFind.BuiltInContextMenu.SelectAllMenuItemText"); this.hexFind.InfoForeColor = System.Drawing.Color.Empty; this.hexFind.Name = "hexFind"; this.hexFind.ShadowSelectionColor = System.Drawing.Color.FromArgb(((int)(((byte)(100)))), ((int)(((byte)(60)))), ((int)(((byte)(188)))), ((int)(((byte)(255))))); // // flowLayoutPanel1 // this.flowLayoutPanel1.Controls.Add(this.label1); this.flowLayoutPanel1.Controls.Add(this.line); resources.ApplyResources(this.flowLayoutPanel1, "flowLayoutPanel1"); this.flowLayoutPanel1.Name = "flowLayoutPanel1"; this.flowLayoutPanel1.Paint += new System.Windows.Forms.PaintEventHandler(this.flowLayoutPanel1_Paint); // // line // resources.ApplyResources(this.line, "line"); this.line.BackColor = System.Drawing.Color.LightGray; this.line.Name = "line"; // // flowLayoutPanel2 // resources.ApplyResources(this.flowLayoutPanel2, "flowLayoutPanel2"); this.flowLayoutPanel2.Controls.Add(this.btnCancel); this.flowLayoutPanel2.Controls.Add(this.btnOK); this.flowLayoutPanel2.Controls.Add(this.lblFinding); this.flowLayoutPanel2.Controls.Add(this.lblPercent); this.flowLayoutPanel2.Name = "flowLayoutPanel2"; // // FormFind // this.AcceptButton = this.btnOK; resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.BackColor = System.Drawing.SystemColors.Control; this.CancelButton = this.btnCancel; this.Controls.Add(this.flowLayoutPanel2); this.Controls.Add(this.flowLayoutPanel1); this.Controls.Add(this.chkMatchCase); this.Controls.Add(this.rbHex); this.Controls.Add(this.rbString); this.Controls.Add(this.txtFind); this.Controls.Add(this.hexFind); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "FormFind"; this.ShowIcon = false; this.ShowInTaskbar = false; this.Activated += new System.EventHandler(this.FormFind_Activated); this.flowLayoutPanel1.ResumeLayout(false); this.flowLayoutPanel1.PerformLayout(); this.flowLayoutPanel2.ResumeLayout(false); this.flowLayoutPanel2.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private FindOptions _findOptions; public FindOptions FindOptions { get { return _findOptions; } set { _findOptions = value; Reinitialize(); } } public HexBox HexBox { get; set; } private void Reinitialize() { rbString.Checked = _findOptions.Type == FindType.Text; txtFind.Text = _findOptions.Text; chkMatchCase.Checked = _findOptions.MatchCase; rbHex.Checked = _findOptions.Type == FindType.Hex; if (hexFind.ByteProvider != null) hexFind.ByteProvider.Changed -= new EventHandler(ByteProvider_Changed); var hex = this._findOptions.Hex != null ? _findOptions.Hex : new byte[0]; hexFind.ByteProvider = new DynamicByteProvider(hex, true, false, false); hexFind.ByteProvider.Changed += new EventHandler(ByteProvider_Changed); } private void rb_CheckedChanged(object sender, System.EventArgs e) { txtFind.Enabled = rbString.Checked; hexFind.Enabled = !txtFind.Enabled; if(txtFind.Enabled) txtFind.Focus(); else hexFind.Focus(); } private void rbString_Enter(object sender, EventArgs e) { txtFind.Focus(); } private void rbHex_Enter(object sender, EventArgs e) { hexFind.Focus(); } private void FormFind_Activated(object sender, System.EventArgs e) { if(rbString.Checked) txtFind.Focus(); else hexFind.Focus(); } private void btnOK_Click(object sender, System.EventArgs e) { _findOptions.MatchCase = chkMatchCase.Checked; var provider = this.hexFind.ByteProvider as DynamicByteProvider; _findOptions.Hex = provider.Bytes.ToArray(); _findOptions.Text = txtFind.Text; _findOptions.Type = rbHex.Checked ? FindType.Hex : FindType.Text; _findOptions.MatchCase = chkMatchCase.Checked; _findOptions.IsValid = true; FindNext(); } bool _finding; public void FindNext() { if (!_findOptions.IsValid) return; UpdateUIToFindingState(); // start find process long res = HexBox.Find(_findOptions); UpdateUIToNormalState(); Application.DoEvents(); if (res == -1) // -1 = no match { MessageBox.Show(strings.FindOperationEndOfFile, Program.SoftwareName, MessageBoxButtons.OK, MessageBoxIcon.Information); } else if (res == -2) // -2 = find was aborted { return; } else // something was found { this.Close(); Application.DoEvents(); if (!HexBox.Focused) HexBox.Focus(); } } private void UpdateUIToNormalState() { timer.Stop(); timerPercent.Stop(); _finding = false; txtFind.Enabled = chkMatchCase.Enabled = rbHex.Enabled = rbString.Enabled = hexFind.Enabled = btnOK.Enabled = true; } private void UpdateUIToFindingState() { _finding = true; timer.Start(); timerPercent.Start(); txtFind.Enabled = chkMatchCase.Enabled = rbHex.Enabled = rbString.Enabled = hexFind.Enabled = btnOK.Enabled = false; } private void btnCancel_Click(object sender, System.EventArgs e) { if (_finding) this.HexBox.AbortFind(); else this.Close(); } private void txtString_TextChanged(object sender, EventArgs e) { ValidateFind(); } private void ValidateFind() { var isValid = false; if (rbString.Checked && txtFind.Text.Length > 0) isValid = true; if (rbHex.Checked && hexFind.ByteProvider.Length > 0) isValid = true; this.btnOK.Enabled = isValid; } private void timer_Tick(object sender, EventArgs e) { if (lblFinding.Text.Length == 13) lblFinding.Text = ""; lblFinding.Text += "."; } private void timerPercent_Tick(object sender, EventArgs e) { long pos = this.HexBox.CurrentFindingPosition; long length = HexBox.ByteProvider.Length; double percent = (double)pos / (double)length * (double)100; System.Globalization.NumberFormatInfo nfi = new System.Globalization.CultureInfo("en-US").NumberFormat; string text = percent.ToString("0.00", nfi) + " %"; lblPercent.Text = text; } private void flowLayoutPanel1_Paint(object sender, PaintEventArgs e) { } } }
using System; using Gtk; using Gdk; using System.Collections.Generic; using Cairo; namespace Exameer { public partial class PngViewer : Gtk.Window { private PngNode CurrentNode { get; set; } private List<PngNode> Nodes { get; set; } private Pixbuf PixelBuffer { get; set; } private Pixbuf ScaledPixelBuffer { get; set; } private bool toResize { get; set; } private EditMode CurrentMode { get; set; } private float LeftLine { get; set; } private float RightLine { get; set; } private Tuple<int, int> Size { get; set; } private Gdk.Color borderColor = new Gdk.Color (); private int OffsetX { get; set; } private int OffsetY { get; set; } private Point<int> MousePos { get; set; } int CurrentID { get; set; } //public List<Cairo.Rectangle> selections = new List<Cairo.Rectangle> (); public Point<int> Topleft { get; set; } private int NodeIdx { get; set; } private bool isShiftPressed {get;set;} private List<Gdk.Key> pressedKeys = new List<Gdk.Key> (); enum EditMode { None, LeftLine, RightLine, Rectangle } public PngViewer () : base(Gtk.WindowType.Toplevel) { this.Build (); drawingarea1.ExposeEvent += new ExposeEventHandler (OnExpose); Gdk.Color.Parse ("black", ref borderColor); drawingarea1.ModifyFg (StateType.Normal, borderColor); LeftLine = (float)scaleLeftLine.Value; RightLine = (float)scaleRightLine.Value; OffsetX = 0; OffsetY = 0; drawingarea1.AddEvents ((int)(EventMask.ButtonPressMask | EventMask.ButtonReleaseMask | EventMask.PointerMotionMask) ); drawingarea1.ButtonPressEvent += new ButtonPressEventHandler (OnButtonPressEvent); drawingarea1.ButtonReleaseEvent += new ButtonReleaseEventHandler (OnButtonReleaseEvent); drawingarea1.MotionNotifyEvent += new MotionNotifyEventHandler (OnMotionNotifyEvent); CurrentID = 0; } public void OnButtonPressEvent (object sender, ButtonPressEventArgs args) { var x = (int)args.Event.X; var y = (int)args.Event.Y; if (args.Event.Button == 3) { // Remove selection if we click on it. int i = 0; bool toRemove = false; foreach (var selection in CurrentNode.Rectangles) { if (selection.IsInisde (x + OffsetX, y + OffsetY)) { toRemove = true; break; } i++; } if (toRemove) CurrentNode.Rectangles.RemoveAt (i); } // If LMB if (args.Event.Button == 1 && ScaledPixelBuffer != null) { // If we left-click on a rectangle, let's select it. bool toSelect = false; //int selectedId = -1; foreach (var selection in CurrentNode.Rectangles) { if (selection.IsInside (x, y)) { toSelect = true; //selectedId = selection.ID; NewIdDialog nid = new NewIdDialog (); nid.entryNewID.Text = selection.ID.ToString (); nid.Modal = true; ResponseType resp = (ResponseType)nid.Run (); if (resp == ResponseType.Ok) { selection.ID = nid.NewId (); nid.Destroy (); } } } // If we didn't hit a rectangle, then we can draw a new one! if (!toSelect) { if (pressedKeys.Contains (Gdk.Key.Shift_L)) { CurrentID--; } // Set top left point var tmpRec = new Rectangle (0, 0 + OffsetX, 0 + OffsetY, ScaledPixelBuffer.Width, ScaledPixelBuffer.Height); if (tmpRec.IsInside (x, y)) { Topleft = new Point<int> (x, y); Console.WriteLine ("Inside drawing area"); } } } this.QueueDraw (); } public void OnMotionNotifyEvent (object sender, MotionNotifyEventArgs args) { //Console.WriteLine("On motion notify event {0}", args.ToString()); var x = (int)args.Event.X; var y = (int)args.Event.Y; MousePos = new Point<int> (x, y); this.QueueDraw (); } public void OnButtonReleaseEvent (object sender, ButtonReleaseEventArgs args) { var x = (int)args.Event.X; var y = (int)args.Event.Y; // If LMB if (args.Event.Button == 1 && ScaledPixelBuffer != null) { var rectangle = new Rectangle (0, 0 + OffsetX, 0 + OffsetY, ScaledPixelBuffer.Width, ScaledPixelBuffer.Height); if (rectangle.IsInside (x, y)) { if (Topleft != null) { var x1 = LeftLine; //Toplerft.X; var y1 = Topleft.Y; var x2 = RightLine; //x; var y2 = y; // TODO: Handle case when mouse is outside of canvas area.. var parentRect = new Rectangle (0, 0, 0, ScaledPixelBuffer.Width, ScaledPixelBuffer.Height); CurrentNode.Rectangles.Add (new Rectangle (CurrentID++, (int)x1, (int)y1, (int)x2, (int)y2) { Parent = parentRect }); Topleft = null; } Console.WriteLine ("Inside drawing area"); } } this.QueueDraw (); } public void SetNode (PngNode pn) { CurrentNode = pn; PixelBuffer = new Pixbuf (CurrentNode.FileName); lblFilename.Text = CurrentNode.FileName; int winWidth = 0; int winHeight = 0; drawingarea1.GdkWindow.GetSize (out winWidth, out winHeight); Size = ScaleBufferToDrawingArea (winWidth, winHeight); // Reset values when we go to next image. Topleft = null; RenderImage (); this.QueueDraw (); } public void SetNodes (List<PngNode> images) { NodeIdx = 0; this.Nodes = images; if (Nodes.Count > 0) { SetNode (this.Nodes [0]); } } public void ResizeWindow (int width) { // Update window to new size, keep old height. int w = 0, h = 0; this.GetSize (out w, out h); this.SetDefaultSize (width, h); } public Tuple<int, int> ScaleBufferToDrawingArea (int width, int height) { var size = ScaleToHeight (height, PixelBuffer); ScaledPixelBuffer = PixelBuffer.ScaleSimple (size.Item1, size.Item2, InterpType.Bilinear); return size; } Tuple<int, int> ScaleToHeight (int baseHeight, Pixbuf pixbuf) { var width = pixbuf.Width; var height = pixbuf.Height; var ratio = baseHeight / (float)height; var newWidth = (int)(width * ratio); var newHeight = baseHeight; return new Tuple<int,int> (newWidth, newHeight); } void RenderImage () { Console.WriteLine ("Rendering..."); Cairo.Context cr = Gdk.CairoHelper.Create (drawingarea1.GdkWindow); // Draw rectangle cr.SetSourceRGB (0.2, 0.23, 0.9); cr.LineWidth = 1; cr.Rectangle (0 + OffsetX, 0 + OffsetY, ScaledPixelBuffer.Width, ScaledPixelBuffer.Height); cr.Stroke (); int x1 = 0 + OffsetX; int y1 = 0 + OffsetY; // Draw image drawingarea1.GdkWindow.DrawPixbuf (Style.ForegroundGC (StateType.Normal), ScaledPixelBuffer, 0, 0, x1, y1, ScaledPixelBuffer.Width, ScaledPixelBuffer.Height, RgbDither.Normal, 0, 0); // Draw lines cr.SetSourceRGB (0.1, 0, 0); cr.LineWidth = 2; cr.Rectangle (LeftLine + OffsetX, 0, 1, ScaledPixelBuffer.Height); cr.Rectangle (RightLine + OffsetX, 0, 1, ScaledPixelBuffer.Height); cr.Fill (); cr.SelectFontFace ("Monospace", FontSlant.Normal, FontWeight.Bold); cr.SetFontSize (20); // Draw selections foreach (var rectangle in CurrentNode.Rectangles) { //Draw rectangle cr.SetSourceRGBA (0.1, 0.1, 0, 0.1); cr.LineWidth = 2; var rec = new Cairo.Rectangle (rectangle.x1 + OffsetX, rectangle.y1 + OffsetY, rectangle.Width, rectangle.Height); cr.Rectangle (rec); cr.Fill (); // Draw text shadow cr.SetSourceRGB (0, 0, 0); cr.MoveTo (rectangle.x1 + (int)(rectangle.Width / 2.0) - 9, rectangle.y1 + (int)(rectangle.Height / 2.0)); cr.ShowText (rectangle.ID.ToString ()); // Draw text cr.SetSourceRGB (1, 1, 1); cr.MoveTo (rectangle.x1 + (int)(rectangle.Width / 2.0) - 10, rectangle.y1 + (int)(rectangle.Height / 2.0)); cr.ShowText (rectangle.ID.ToString ()); } if (Topleft != null) { cr.SetSourceRGBA (0.1, 0.1, 0, 0.1); cr.LineWidth = 2; cr.Rectangle (new Cairo.Rectangle (Topleft.X + OffsetX, Topleft.Y + OffsetY, MousePos.X - Topleft.X, MousePos.Y - Topleft.Y) ); cr.Fill (); } ((IDisposable)cr.Target).Dispose (); ((IDisposable)cr).Dispose (); } void OnExpose (object o, Gtk.ExposeEventArgs args) { if (PixelBuffer != null) { RenderImage (); drawingarea1.ShowAll (); } } void OnSizeAllocated (object sender, Gtk.SizeAllocatedArgs args) { if (CurrentNode != null) { int w = 0, h = 0; drawingarea1.GdkWindow.GetSize (out w, out h); Size = ScaleBufferToDrawingArea (w, h); this.QueueDraw (); } } protected void OnBtnPrevImgClicked (object sender, EventArgs e) { if (NodeIdx == 0) { NodeIdx = Nodes.Count - 1; } else { NodeIdx = (NodeIdx - 1) % Nodes.Count; } SetNode (Nodes [NodeIdx]); } protected void OnBtnResetRectanglesClicked (object sender, EventArgs e) { } protected void OnBtnNextImgClicked (object sender, EventArgs e) { try { NodeIdx = (NodeIdx + 1) % Nodes.Count; SetNode (Nodes [NodeIdx]); } catch (Exception ex) { } } protected void OnEntryLeftLineEditingDone (object sender, EventArgs e) { this.QueueDraw (); } protected void OnEntryRightLineEditingDone (object sender, EventArgs e) { this.QueueDraw (); } protected void OnKeyPressEvent (object sender, KeyPressEventArgs e) { pressedKeys.Add (e.Event.Key); } protected void OnKeyReleaseEvent (object sender, KeyReleaseEventArgs e) { if (pressedKeys.Contains (e.Event.Key)) { pressedKeys.Remove (e.Event.Key); Console.WriteLine (e.Event.Key.ToString ()); } } protected void OnScaleLeftLineValueChanged (object sender, EventArgs e) { LeftLine = (float)(scaleLeftLine.Value / 100.0) * ScaledPixelBuffer.Width; CurrentNode.OnLeftSideChanged ((int)LeftLine); this.QueueDraw (); } protected void OnScaleRightLineValueChanged (object sender, EventArgs e) { RightLine = (float)(scaleRightLine.Value / 100.0) * ScaledPixelBuffer.Width; CurrentNode.OnRightSideChanged ((int)RightLine); this.QueueDraw (); } protected void OnDeleteEvent (object sender, DeleteEventArgs args) { // Prevent window from closing args.RetVal = true; } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the ec2-2015-10-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.EC2.Model { /// <summary> /// Describes a Reserved Instance. /// </summary> public partial class ReservedInstances { private string _availabilityZone; private CurrencyCodeValues _currencyCode; private long? _duration; private DateTime? _end; private float? _fixedPrice; private int? _instanceCount; private Tenancy _instanceTenancy; private InstanceType _instanceType; private OfferingTypeValues _offeringType; private RIProductDescription _productDescription; private List<RecurringCharge> _recurringCharges = new List<RecurringCharge>(); private string _reservedInstancesId; private DateTime? _start; private ReservedInstanceState _state; private List<Tag> _tags = new List<Tag>(); private float? _usagePrice; /// <summary> /// Gets and sets the property AvailabilityZone. /// <para> /// The Availability Zone in which the Reserved Instance can be used. /// </para> /// </summary> public string AvailabilityZone { get { return this._availabilityZone; } set { this._availabilityZone = value; } } // Check to see if AvailabilityZone property is set internal bool IsSetAvailabilityZone() { return this._availabilityZone != null; } /// <summary> /// Gets and sets the property CurrencyCode. /// <para> /// The currency of the Reserved Instance. It's specified using ISO 4217 standard currency /// codes. At this time, the only supported currency is <code>USD</code>. /// </para> /// </summary> public CurrencyCodeValues CurrencyCode { get { return this._currencyCode; } set { this._currencyCode = value; } } // Check to see if CurrencyCode property is set internal bool IsSetCurrencyCode() { return this._currencyCode != null; } /// <summary> /// Gets and sets the property Duration. /// <para> /// The duration of the Reserved Instance, in seconds. /// </para> /// </summary> public long Duration { get { return this._duration.GetValueOrDefault(); } set { this._duration = value; } } // Check to see if Duration property is set internal bool IsSetDuration() { return this._duration.HasValue; } /// <summary> /// Gets and sets the property End. /// <para> /// The time when the Reserved Instance expires. /// </para> /// </summary> public DateTime End { get { return this._end.GetValueOrDefault(); } set { this._end = value; } } // Check to see if End property is set internal bool IsSetEnd() { return this._end.HasValue; } /// <summary> /// Gets and sets the property FixedPrice. /// <para> /// The purchase price of the Reserved Instance. /// </para> /// </summary> public float FixedPrice { get { return this._fixedPrice.GetValueOrDefault(); } set { this._fixedPrice = value; } } // Check to see if FixedPrice property is set internal bool IsSetFixedPrice() { return this._fixedPrice.HasValue; } /// <summary> /// Gets and sets the property InstanceCount. /// <para> /// The number of Reserved Instances purchased. /// </para> /// </summary> public int InstanceCount { get { return this._instanceCount.GetValueOrDefault(); } set { this._instanceCount = value; } } // Check to see if InstanceCount property is set internal bool IsSetInstanceCount() { return this._instanceCount.HasValue; } /// <summary> /// Gets and sets the property InstanceTenancy. /// <para> /// The tenancy of the reserved instance. /// </para> /// </summary> public Tenancy InstanceTenancy { get { return this._instanceTenancy; } set { this._instanceTenancy = value; } } // Check to see if InstanceTenancy property is set internal bool IsSetInstanceTenancy() { return this._instanceTenancy != null; } /// <summary> /// Gets and sets the property InstanceType. /// <para> /// The instance type on which the Reserved Instance can be used. /// </para> /// </summary> public InstanceType InstanceType { get { return this._instanceType; } set { this._instanceType = value; } } // Check to see if InstanceType property is set internal bool IsSetInstanceType() { return this._instanceType != null; } /// <summary> /// Gets and sets the property OfferingType. /// <para> /// The Reserved Instance offering type. /// </para> /// </summary> public OfferingTypeValues OfferingType { get { return this._offeringType; } set { this._offeringType = value; } } // Check to see if OfferingType property is set internal bool IsSetOfferingType() { return this._offeringType != null; } /// <summary> /// Gets and sets the property ProductDescription. /// <para> /// The Reserved Instance product platform description. /// </para> /// </summary> public RIProductDescription ProductDescription { get { return this._productDescription; } set { this._productDescription = value; } } // Check to see if ProductDescription property is set internal bool IsSetProductDescription() { return this._productDescription != null; } /// <summary> /// Gets and sets the property RecurringCharges. /// <para> /// The recurring charge tag assigned to the resource. /// </para> /// </summary> public List<RecurringCharge> RecurringCharges { get { return this._recurringCharges; } set { this._recurringCharges = value; } } // Check to see if RecurringCharges property is set internal bool IsSetRecurringCharges() { return this._recurringCharges != null && this._recurringCharges.Count > 0; } /// <summary> /// Gets and sets the property ReservedInstancesId. /// <para> /// The ID of the Reserved Instance. /// </para> /// </summary> public string ReservedInstancesId { get { return this._reservedInstancesId; } set { this._reservedInstancesId = value; } } // Check to see if ReservedInstancesId property is set internal bool IsSetReservedInstancesId() { return this._reservedInstancesId != null; } /// <summary> /// Gets and sets the property Start. /// <para> /// The date and time the Reserved Instance started. /// </para> /// </summary> public DateTime Start { get { return this._start.GetValueOrDefault(); } set { this._start = value; } } // Check to see if Start property is set internal bool IsSetStart() { return this._start.HasValue; } /// <summary> /// Gets and sets the property State. /// <para> /// The state of the Reserved Instance purchase. /// </para> /// </summary> public ReservedInstanceState State { get { return this._state; } set { this._state = value; } } // Check to see if State property is set internal bool IsSetState() { return this._state != null; } /// <summary> /// Gets and sets the property Tags. /// <para> /// Any tags assigned to the resource. /// </para> /// </summary> public List<Tag> Tags { get { return this._tags; } set { this._tags = value; } } // Check to see if Tags property is set internal bool IsSetTags() { return this._tags != null && this._tags.Count > 0; } /// <summary> /// Gets and sets the property UsagePrice. /// <para> /// The usage price of the Reserved Instance, per hour. /// </para> /// </summary> public float UsagePrice { get { return this._usagePrice.GetValueOrDefault(); } set { this._usagePrice = value; } } // Check to see if UsagePrice property is set internal bool IsSetUsagePrice() { return this._usagePrice.HasValue; } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.Common.Authentication.Models; using Microsoft.Azure.Commands.Sql.Database.Model; using Microsoft.Azure.Commands.Sql.Database.Services; using Microsoft.Azure.Commands.Sql.FailoverGroup.Model; using Microsoft.Azure.Commands.Sql.Server.Adapter; using Microsoft.Azure.Commands.Sql.Services; using Microsoft.Azure.Management.Sql.LegacySdk.Models; using System.Collections.Generic; using System.Linq; using Microsoft.Azure.Commands.Common.Authentication.Abstractions; namespace Microsoft.Azure.Commands.Sql.FailoverGroup.Services { /// <summary> /// Adapter for FailoverGroup operations /// </summary> public class AzureSqlFailoverGroupAdapter { /// <summary> /// Gets or sets the AzureEndpointsCommunicator which has all the needed management clients /// </summary> private AzureSqlFailoverGroupCommunicator Communicator { get; set; } /// <summary> /// Gets or sets the Azure profile /// </summary> public IAzureContext Context { get; set; } /// <summary> /// Gets or sets the Azure Subscription /// </summary> private IAzureSubscription _subscription { get; set; } /// <summary> /// Constructs a database adapter /// </summary> /// <param name="profile">The current azure profile</param> /// <param name="subscription">The current azure subscription</param> public AzureSqlFailoverGroupAdapter(IAzureContext context) { _subscription = context.Subscription; Context = context; Communicator = new AzureSqlFailoverGroupCommunicator(Context); } /// <summary> /// Gets an Azure Sql Database FailoverGroup by name. /// </summary> /// <param name="resourceGroupName">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="failoverGroupName">The name of the Azure Sql Database FailoverGroup</param> /// <returns>The Azure Sql Database FailoverGroup object</returns> internal AzureSqlFailoverGroupModel GetFailoverGroup(string resourceGroupName, string serverName, string failoverGroupName) { var resp = Communicator.Get(resourceGroupName, serverName, failoverGroupName); return CreateFailoverGroupModelFromResponse(resp); } /// <summary> /// Gets a list of Azure Sql Databases FailoverGroup. /// </summary> /// <param name="resourceGroupName">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <returns>A list of database objects</returns> internal ICollection<AzureSqlFailoverGroupModel> ListFailoverGroups(string resourceGroupName, string serverName) { var resp = Communicator.List(resourceGroupName, serverName); return resp.Select((db) => { return CreateFailoverGroupModelFromResponse(db); }).ToList(); } /// <summary> /// Creates or updates an Azure Sql Database FailoverGroup. /// </summary> /// <param name="resourceGroup">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="model">The input parameters for the create/update operation</param> /// <returns>The upserted Azure Sql Database FailoverGroup</returns> internal AzureSqlFailoverGroupModel UpsertFailoverGroup(AzureSqlFailoverGroupModel model) { List < FailoverGroupPartnerServer > partnerServers = new List<FailoverGroupPartnerServer>(); FailoverGroupPartnerServer partnerServer = new FailoverGroupPartnerServer(); partnerServer.Id = string.Format( AzureSqlFailoverGroupModel.PartnerServerIdTemplate, _subscription.Id.ToString(), model.PartnerResourceGroupName, model.PartnerServerName); partnerServers.Add(partnerServer); ReadOnlyEndpoint readOnlyEndpoint = new ReadOnlyEndpoint(); readOnlyEndpoint.FailoverPolicy = model.ReadOnlyFailoverPolicy; ReadWriteEndpoint readWriteEndpoint = new ReadWriteEndpoint(); readWriteEndpoint.FailoverPolicy = model.ReadWriteFailoverPolicy; if (model.FailoverWithDataLossGracePeriodHours.HasValue) { readWriteEndpoint.FailoverWithDataLossGracePeriodMinutes = checked(model.FailoverWithDataLossGracePeriodHours * 60); } var resp = Communicator.CreateOrUpdate(model.ResourceGroupName, model.ServerName, model.FailoverGroupName, new FailoverGroupCreateOrUpdateParameters() { Location = model.Location, Properties = new FailoverGroupCreateOrUpdateProperties() { PartnerServers = partnerServers, ReadOnlyEndpoint = readOnlyEndpoint, ReadWriteEndpoint = readWriteEndpoint, } }); return CreateFailoverGroupModelFromResponse(resp); } /// <summary> /// Patch updates an Azure Sql Database FailoverGroup. /// </summary> /// <param name="resourceGroup">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="model">The input parameters for the create/update operation</param> /// <returns>The upserted Azure Sql Database FailoverGroup</returns> internal AzureSqlFailoverGroupModel PatchUpdateFailoverGroup(AzureSqlFailoverGroupModel model) { ReadOnlyEndpoint readOnlyEndpoint = new ReadOnlyEndpoint(); readOnlyEndpoint.FailoverPolicy = model.ReadOnlyFailoverPolicy; ReadWriteEndpoint readWriteEndpoint = new ReadWriteEndpoint(); readWriteEndpoint.FailoverPolicy = model.ReadWriteFailoverPolicy; if (model.FailoverWithDataLossGracePeriodHours.HasValue) { readWriteEndpoint.FailoverWithDataLossGracePeriodMinutes = checked(model.FailoverWithDataLossGracePeriodHours * 60); } var resp = Communicator.PatchUpdate(model.ResourceGroupName, model.ServerName, model.FailoverGroupName, new FailoverGroupPatchUpdateParameters() { Location = model.Location, Properties = new FailoverGroupPatchUpdateProperties() { ReadOnlyEndpoint = readOnlyEndpoint, ReadWriteEndpoint = readWriteEndpoint, } }); return CreateFailoverGroupModelFromResponse(resp); } /// <summary> /// Deletes a failvoer group /// </summary> /// <param name="resourceGroupName">The resource group the server is in</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="failvoerGroupName">The name of the Azure SQL Database Failover Group to delete</param> public void RemoveFailoverGroup(string resourceGroupName, string serverName, string failoverGroupName) { Communicator.Remove(resourceGroupName, serverName, failoverGroupName); } /// <summary> /// Gets a list of Azure Sql Databases in a secondary server. /// </summary> /// <param name="resourceGroupName">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <returns>A list of database objects</returns> internal ICollection<AzureSqlDatabaseModel> ListDatabasesOnServer(string resourceGroupName, string serverName) { var resp = Communicator.ListDatabasesOnServer(resourceGroupName, serverName); return resp.Select((db) => { return AzureSqlDatabaseAdapter.CreateDatabaseModelFromResponse(resourceGroupName, serverName, db); }).ToList(); } /// <summary> /// Patch updates an Azure Sql Database FailoverGroup. /// </summary> /// <param name="resourceGroup">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="model">The input parameters for the create/update operation</param> /// <returns>The updated Azure Sql Database FailoverGroup</returns> internal AzureSqlFailoverGroupModel AddOrRemoveDatabaseToFailoverGroup(string resourceGroupName, string serverName, string failoverGroupName, AzureSqlFailoverGroupModel model) { var resp = Communicator.PatchUpdate(resourceGroupName, serverName, failoverGroupName, new FailoverGroupPatchUpdateParameters() { Location = model.Location, Properties = new FailoverGroupPatchUpdateProperties() { Databases = model.Databases, } }); return CreateFailoverGroupModelFromResponse(resp); } /// <summary> /// Finds and removes the Secondary Link by the secondary resource group and Azure SQL Server /// </summary> /// <param name="resourceGroupName">The name of the Resource Group containing the primary database</param> /// <param name="serverName">The name of the Azure SQL Server containing the primary database</param> /// <param name="databaseName">The name of primary database</param> /// <param name="partnerResourceGroupName">The name of the Resource Group containing the secondary database</param> /// <param name="partnerServerName">The name of the Azure SQL Server containing the secondary database</param> /// <param name="allowDataLoss">Whether the failover operation will allow data loss</param> /// <returns>The Azure SQL Database ReplicationLink object</returns> internal AzureSqlFailoverGroupModel Failover(string resourceGroupName, string serverName, string failoverGroupName, bool allowDataLoss) { if (!allowDataLoss) { Communicator.Failover(resourceGroupName, serverName, failoverGroupName); } else { Communicator.ForceFailoverAllowDataLoss(resourceGroupName, serverName, failoverGroupName); } return null; } /// <summary> /// Gets the Location of the server. /// </summary> /// <param name="resourceGroupName">The resource group the server is in</param> /// <param name="serverName">The name of the server</param> /// <returns></returns> public string GetServerLocation(string resourceGroupName, string serverName) { AzureSqlServerAdapter serverAdapter = new AzureSqlServerAdapter(Context); var server = serverAdapter.GetServer(resourceGroupName, serverName); return server.Location; } /// <summary> /// Converts the response from the service to a powershell database object /// </summary> /// <param name="resourceGroupName">The resource group the server is in</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="pool">The service response</param> /// <returns>The converted model</returns> private AzureSqlFailoverGroupModel CreateFailoverGroupModelFromResponse(Management.Sql.LegacySdk.Models.FailoverGroup failoverGroup) { AzureSqlFailoverGroupModel model = new AzureSqlFailoverGroupModel(); model.FailoverGroupName = failoverGroup.Name; model.Databases = failoverGroup.Properties.Databases; model.ReadOnlyFailoverPolicy = failoverGroup.Properties.ReadOnlyEndpoint.FailoverPolicy; model.ReadWriteFailoverPolicy = failoverGroup.Properties.ReadWriteEndpoint.FailoverPolicy; model.ReplicationRole = failoverGroup.Properties.ReplicationRole; model.ReplicationState = failoverGroup.Properties.ReplicationState; model.PartnerServers = failoverGroup.Properties.PartnerServers; model.FailoverWithDataLossGracePeriodHours = failoverGroup.Properties.ReadWriteEndpoint.FailoverWithDataLossGracePeriodMinutes == null ? null : failoverGroup.Properties.ReadWriteEndpoint.FailoverWithDataLossGracePeriodMinutes / 60; model.Id = failoverGroup.Id; model.Location = failoverGroup.Location; model.DatabaseNames = failoverGroup.Properties.Databases .Select(dbId => GetUriSegment(dbId, 10)) .ToList(); model.ResourceGroupName = GetUriSegment(failoverGroup.Id, 4); model.ServerName = GetUriSegment(failoverGroup.Id, 8); FailoverGroupPartnerServer partnerServer = failoverGroup.Properties.PartnerServers.FirstOrDefault(); if (partnerServer != null) { model.PartnerResourceGroupName = GetUriSegment(partnerServer.Id, 4); model.PartnerServerName = GetUriSegment(partnerServer.Id, 8); model.PartnerLocation = partnerServer.Location; } return model; } private string GetUriSegment(string uri, int segmentNum) { if (uri != null) { var segments = uri.Split('/'); if (segments.Length > segmentNum) { return segments[segmentNum]; } } return null; } } }
using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Drawing; using System.Threading; using System.IO; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Serialization; using OpenMetaverse; using OpenMetaverse.Http; using OpenMetaverse.Imaging; using OpenMetaverse.ImportExport; using OpenMetaverse.StructuredData; namespace OpenMetaverse.ImportExport { /// <summary> /// Implements mesh upload communications with the simulator /// </summary> public class cmdModelUploader { public GridClient Client; public List<cmdModelPrim> Prims; public List<byte[]> Images; public List<string> ImageNames; public Dictionary<string, int> ImgIndex; public string InvName = "NewMesh"; public string InvDescription = ""; public UUID InvAssetFolderUUID, InvTextureFolderUUID; public bool UploadTextures; public int Debug; public UUID ReturnedMeshUUID; public UUID ReturnedMeshInvUUID; public float TextureScale = 1.0f; /// <summary> /// Inlcude stub convex hull physics, required for uploading to Second Life /// </summary> public bool IncludePhysicsStub; /// <summary> /// Use the same mesh used for geometry as the physical mesh upload /// </summary> public bool UseModelAsPhysics; /// <summary> /// Callback for mesh upload operations /// </summary> /// <param name="result">null on failure, result from server on success</param> public delegate void ModelUploadCallback(OSD result); /// <summary> /// Creates instance of the mesh uploader /// </summary> /// <param name="client">GridClient instance to communicate with the simulator</param> /// <param name="prims">List of ModelPrimitive objects to upload as a linkset</param> public cmdModelUploader(GridClient client, List<cmdModelPrim> prims) { this.Client = client; this.Prims = prims; } /// <summary> /// Performs model upload in one go, without first checking for the price /// </summary> /// <param name="callback">Callback that will be invoke upon completion of the upload. Null is sent on request failure</param> public void Upload(ModelUploadCallback callback) { PrepareUpload((result => { if (result == null && callback != null) { callback(null); return; } if (result is OSDMap) { var res = (OSDMap)result; Uri uploader = new Uri(res["uploader"]); PerformUpload(uploader, (contents => { if (contents != null) { var reply = (OSDMap)contents; if (reply.ContainsKey("new_inventory_item") && reply.ContainsKey("new_asset")) { // Request full update on the item in order to update the local store Client.Inventory.RequestFetchInventory(reply["new_inventory_item"].AsUUID(), Client.Self.AgentID); ReturnedMeshUUID = reply["new_asset"].AsUUID(); ReturnedMeshInvUUID = reply["new_inventory_item"].AsUUID(); } } if (callback != null) callback(contents); })); } })); } /// <summary> /// Ask server for details of cost and impact of the mesh upload /// </summary> /// <param name="callback">Callback that will be invoke upon completion of the upload. Null is sent on request failure</param> public void PrepareUpload(ModelUploadCallback callback) { Console.WriteLine("Preparing Upload..."); Uri url = null; if (Client.Network.CurrentSim == null || Client.Network.CurrentSim.Caps == null || null == (url = Client.Network.CurrentSim.Caps.CapabilityURI("NewFileAgentInventory"))) { Console.WriteLine("Cannot upload mesh, no connection or NewFileAgentInventory not available"); if (callback != null) callback(null); return; } Images = new List<byte[]>(); ImageNames = new List<string>(); ImgIndex = new Dictionary<string, int>(); OSDMap req = new OSDMap(); req["name"] = InvName; req["description"] = InvDescription; req["asset_resources"] = AssetResources(UploadTextures, UseModelAsPhysics); req["asset_type"] = "mesh"; req["inventory_type"] = "object"; req["folder_id"] = InvAssetFolderUUID; req["texture_folder_id"] = InvTextureFolderUUID; req["everyone_mask"] = (int)PermissionMask.All; req["group_mask"] = (int)PermissionMask.All; ; req["next_owner_mask"] = (int)PermissionMask.All; CapsClient request = new CapsClient(url); request.OnComplete += (client, result, error) => { if (error != null || result == null || result.Type != OSDType.Map) { Console.WriteLine("Mesh upload request failure: {0}", error.Message); if (callback != null) callback(null); return; } OSDMap res = (OSDMap)result; if (res["state"] != "upload") { OSDMap err = (OSDMap)res["error"]; Console.WriteLine("Mesh upload failure: {0}", err["message"]); if (callback != null) callback(null); return; } Console.WriteLine("Done."); if (Debug > 2) Console.WriteLine("Response from mesh upload prepare:\n{0}", OSDParser.SerializeLLSDNotationFormatted(result)); if (callback != null) callback(result); }; Console.WriteLine("Sending Request Resources ({0} bytes) to server...", OSDParser.SerializeLLSDXmlBytes(req).LongLength); if (Debug > 2) Console.WriteLine("{0}", OSDParser.SerializeLLSDNotationFormatted(req)); request.BeginGetResponse(req, OSDFormat.Xml, 1200 * 1000); } OSD AssetResources(bool upload, bool physicsFromMesh) { OSDArray instanceList = new OSDArray(); List<byte[]> meshes = new List<byte[]>(); //List<byte[]> textures = new List<byte[]>(); foreach (var prim in Prims) { OSDMap primMap = new OSDMap(); OSDArray faceList = new OSDArray(); foreach (var face in prim.Faces) { OSDMap faceMap = new OSDMap(); faceMap["diffuse_color"] = face.Material.DiffuseColor; faceMap["fullbright"] = false; if (face.Material.TextureData != null) { int index; if (ImgIndex.ContainsKey(face.Material.Texture)) { index = ImgIndex[face.Material.Texture]; } else { index = Images.Count; ImgIndex[face.Material.Texture] = index; Images.Add(face.Material.TextureData); ImageNames.Add(face.Material.Texture); } faceMap["image"] = index; faceMap["scales"] = TextureScale; faceMap["scalet"] = TextureScale; faceMap["offsets"] = 0.0f; faceMap["offsett"] = 0.0f; faceMap["imagerot"] = 0.0f; } faceList.Add(faceMap); } primMap["face_list"] = faceList; primMap["position"] = prim.Position; primMap["rotation"] = prim.Rotation; primMap["scale"] = prim.Scale; //I don't think Opensim honours these selections at present.... :( primMap["material"] = (int)Material.Wood; // always sent as "wood" material if (physicsFromMesh) primMap["physics_shape_type"] = (int)PhysicsShapeType.Prim; else primMap["physics_shape_type"] = (int)PhysicsShapeType.ConvexHull; primMap["mesh"] = meshes.Count; meshes.Add(prim.Asset); instanceList.Add(primMap); } OSDMap resources = new OSDMap(); resources["instance_list"] = instanceList; OSDArray meshList = new OSDArray(); foreach (var mesh in meshes) { meshList.Add(OSD.FromBinary(mesh)); } resources["mesh_list"] = meshList; OSDArray textureList = new OSDArray(); for (int i = 0; i < Images.Count; i++) { if (upload) { textureList.Add(new OSDBinary(Images[i])); } else { textureList.Add(new OSDBinary(Utils.EmptyBytes)); } } resources["texture_list"] = textureList; resources["metric"] = "MUT_Unspecified"; return resources; } /// <summary> /// Performas actual mesh and image upload /// </summary> /// <param name="uploader">Uri recieved in the upload prepare stage</param> /// <param name="callback">Callback that will be invoke upon completion of the upload. Null is sent on request failure</param> public void PerformUpload(Uri uploader, ModelUploadCallback callback) { CapsClient request = new CapsClient(uploader); request.OnComplete += (client, result, error) => { if (error != null || result == null || result.Type != OSDType.Map) { Console.WriteLine("Mesh upload request failure {0}", error.Message); if (callback != null) callback(null); return; } OSDMap res = (OSDMap)result; Console.WriteLine("Done."); if (Debug > 2) Console.WriteLine("Response from mesh upload perform:\n{0}", OSDParser.SerializeLLSDNotationFormatted(result)); if (callback != null) callback(res); }; OSD resources = AssetResources(UploadTextures, UseModelAsPhysics); Console.WriteLine("Sending Request Resources ({0} bytes) to server...", OSDParser.SerializeLLSDXmlBytes(resources).LongLength); if (Debug > 2) Console.WriteLine("{0}", OSDParser.SerializeLLSDNotationFormatted(resources)); request.BeginGetResponse(resources, OSDFormat.Xml, 1200 * 1000); } } }
/*------------------------------------------------------------------------ * (The MIT License) * * Copyright (c) 2008-2011 Rhomobile, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * http://rhomobile.com *------------------------------------------------------------------------*/ using System; using System.Collections; using System.Collections.Generic; //using System.Data; using System.Globalization; using System.Reflection; //using System.Reflection.Emit; using System.Text; using rho; namespace fastJSON { /// <summary> /// This class encodes and decodes JSON strings. /// Spec. details, see http://www.json.org/ /// /// JSON uses Arrays and Objects. These correspond here to the datatypes ArrayList and Hashtable. /// All numbers are parsed to doubles. /// </summary> internal class RJSONTokener { static CRhoRuby RhoRuby { get { return CRhoRuby.Instance; } } private const int TOKEN_NONE = 0; private const int TOKEN_CURLY_OPEN = 1; private const int TOKEN_CURLY_CLOSE = 2; private const int TOKEN_SQUARED_OPEN = 3; private const int TOKEN_SQUARED_CLOSE = 4; private const int TOKEN_COLON = 5; private const int TOKEN_COMMA = 6; private const int TOKEN_STRING = 7; private const int TOKEN_NUMBER = 8; private const int TOKEN_TRUE = 9; private const int TOKEN_FALSE = 10; private const int TOKEN_NULL = 11; /// <summary> /// Parses the string json into a value /// </summary> /// <param name="json">A JSON string.</param> /// <returns>An ArrayList, a dictionary, a double, a string, null, true, or false</returns> internal static object JsonDecode(string json) { bool success = true; return JsonDecode(json, ref success); } /// <summary> /// Parses the string json into a value; and fills 'success' with the successfullness of the parse. /// </summary> /// <param name="json">A JSON string.</param> /// <param name="success">Successful parse?</param> /// <returns>An ArrayList, a Hashtable, a double, a string, null, true, or false</returns> private static object JsonDecode(string json, ref bool success) { success = true; if (json != null) { char[] charArray = json.ToCharArray(); int index = 0; object value = ParseValue(charArray, ref index, ref success); return value; } else { return null; } } protected static IronRuby.Builtins.Hash ParseObject(char[] json, ref int index, ref bool success) { IronRuby.Builtins.Hash table = RhoRuby.createHash(); int token; // { NextToken(json, ref index); bool done = false; while (!done) { token = LookAhead(json, index); if (token == TOKEN_NONE) { success = false; return null; } else if (token == TOKEN_COMMA) { NextToken(json, ref index); } else if (token == TOKEN_CURLY_CLOSE) { NextToken(json, ref index); return table; } else { // name object name = ParseString(json, ref index, ref success); if (!success) { success = false; return null; } // : token = NextToken(json, ref index); if (token != TOKEN_COLON) { success = false; return null; } // value object value = ParseValue(json, ref index, ref success); if (!success) { success = false; return null; } table[name] = value; } } return table; } protected static IronRuby.Builtins.RubyArray ParseArray(char[] json, ref int index, ref bool success) { IronRuby.Builtins.RubyArray array = RhoRuby.createArray(); NextToken(json, ref index); bool done = false; while (!done) { int token = LookAhead(json, index); if (token == TOKEN_NONE) { success = false; return null; } else if (token == TOKEN_COMMA) { NextToken(json, ref index); } else if (token == TOKEN_SQUARED_CLOSE) { NextToken(json, ref index); break; } else { object value = ParseValue(json, ref index, ref success); if (!success) { return null; } array.Add(value); } } return array; } protected static object ParseValue(char[] json, ref int index, ref bool success) { switch (LookAhead(json, index)) { case TOKEN_NUMBER: return ParseNumber(json, ref index, ref success); case TOKEN_STRING: return ParseString(json, ref index, ref success); case TOKEN_CURLY_OPEN: return ParseObject(json, ref index, ref success); case TOKEN_SQUARED_OPEN: return ParseArray(json, ref index, ref success); case TOKEN_TRUE: NextToken(json, ref index); return true; case TOKEN_FALSE: NextToken(json, ref index); return false; case TOKEN_NULL: NextToken(json, ref index); return null; case TOKEN_NONE: break; } success = false; return null; } protected static object ParseString(char[] json, ref int index, ref bool success) { StringBuilder s = new StringBuilder(); char c; EatWhitespace(json, ref index); // " c = json[index++]; bool complete = false; while (!complete) { if (index == json.Length) { break; } c = json[index++]; if (c == '"') { complete = true; break; } else if (c == '\\') { if (index == json.Length) { break; } c = json[index++]; if (c == '"') { s.Append('"'); } else if (c == '\\') { s.Append('\\'); } else if (c == '/') { s.Append('/'); } else if (c == 'b') { s.Append('\b'); } else if (c == 'f') { s.Append('\f'); } else if (c == 'n') { s.Append('\n'); } else if (c == 'r') { s.Append('\r'); } else if (c == 't') { s.Append('\t'); } else if (c == 'u') { int remainingLength = json.Length - index; if (remainingLength >= 4) { // parse the 32 bit hex into an integer codepoint uint codePoint; if (!(success = UInt32.TryParse(new string(json, index, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out codePoint))) { return ""; } // convert the integer codepoint to a unicode char and add to string //s.Append(Char.ConvertFromUtf32((int)codePoint)); s.Append(codePoint); // skip 4 chars index += 4; } else { break; } } } else { s.Append(c); } } if (!complete) { success = false; return null; } return RhoRuby.createString(s.ToString()); } protected static object ParseNumber(char[] json, ref int index, ref bool success) { EatWhitespace(json, ref index); int lastIndex = GetLastIndexOfNumber(json, index); int charLength = (lastIndex - index) + 1; string number = new string(json,index,charLength); success = true; index = lastIndex + 1; return RhoRuby.createString(number); } protected static int GetLastIndexOfNumber(char[] json, int index) { int lastIndex; for (lastIndex = index; lastIndex < json.Length; lastIndex++) { if ("0123456789+-.eE".IndexOf(json[lastIndex]) == -1) { break; } } return lastIndex - 1; } protected static void EatWhitespace(char[] json, ref int index) { for (; index < json.Length; index++) { if (" \t\n\r".IndexOf(json[index]) == -1) { break; } } } protected static int LookAhead(char[] json, int index) { int saveIndex = index; return NextToken(json, ref saveIndex); } protected static int NextToken(char[] json, ref int index) { EatWhitespace(json, ref index); if (index == json.Length) { return TOKEN_NONE; } char c = json[index]; index++; switch (c) { case '{': return TOKEN_CURLY_OPEN; case '}': return TOKEN_CURLY_CLOSE; case '[': return TOKEN_SQUARED_OPEN; case ']': return TOKEN_SQUARED_CLOSE; case ',': return TOKEN_COMMA; case '"': return TOKEN_STRING; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': return TOKEN_NUMBER; case ':': return TOKEN_COLON; } index--; int remainingLength = json.Length - index; // false if (remainingLength >= 5) { if (json[index] == 'f' && json[index + 1] == 'a' && json[index + 2] == 'l' && json[index + 3] == 's' && json[index + 4] == 'e') { index += 5; return TOKEN_FALSE; } } // true if (remainingLength >= 4) { if (json[index] == 't' && json[index + 1] == 'r' && json[index + 2] == 'u' && json[index + 3] == 'e') { index += 4; return TOKEN_TRUE; } } // null if (remainingLength >= 4) { if (json[index] == 'n' && json[index + 1] == 'u' && json[index + 2] == 'l' && json[index + 3] == 'l') { index += 4; return TOKEN_NULL; } } return TOKEN_NONE; } public static object SerializeString(string aString) { StringBuilder builder = new StringBuilder(); builder.Append("\""); char[] charArray = aString.ToCharArray(); for (int i = 0; i < charArray.Length; i++) { char c = charArray[i]; if (c == '"') { builder.Append("\\\""); } else if (c == '\\') { builder.Append("\\\\"); } else if (c == '\b') { builder.Append("\\b"); } else if (c == '\f') { builder.Append("\\f"); } else if (c == '\n') { builder.Append("\\n"); } else if (c == '\r') { builder.Append("\\r"); } else if (c == '\t') { builder.Append("\\t"); } else { int codepoint = Convert.ToInt32(c); if ((codepoint >= 32) && (codepoint <= 126)) { builder.Append(c); } else { builder.Append("\\u" + Convert.ToString(codepoint, 16).PadLeft(4, '0')); } } } builder.Append("\""); return RhoRuby.createString(builder.ToString()); } protected static bool IsNumeric(object o) { double result; return (o == null) ? false : Double.TryParse(o.ToString(), out result); } } }
using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using DotVVM.Framework.Binding; using DotVVM.Framework.Configuration; using DotVVM.Framework.Controls.Infrastructure; using DotVVM.Framework.Hosting; using DotVVM.Framework.Runtime.Filters; using DotVVM.Framework.Security; using DotVVM.Framework.ViewModel; using DotVVM.Framework.Utils; using DotVVM.Framework.ResourceManagement; using DotVVM.Framework.Controls; using System.IO; namespace DotVVM.Framework.Runtime { public class DefaultViewModelSerializer : IViewModelSerializer { private CommandResolver commandResolver = new CommandResolver(); private readonly IViewModelProtector viewModelProtector; public bool SendDiff { get; set; } public Formatting JsonFormatting { get; set; } /// <summary> /// Initializes a new instance of the <see cref="DefaultViewModelSerializer"/> class. /// </summary> public DefaultViewModelSerializer(DotvvmConfiguration configuration) { this.viewModelProtector = configuration.ServiceLocator.GetService<IViewModelProtector>(); this.JsonFormatting = configuration.Debug ? Formatting.Indented : Formatting.None; } /// <summary> /// Initializes a new instance of the <see cref="DefaultViewModelSerializer"/> class. /// </summary> public DefaultViewModelSerializer(IViewModelProtector viewModelProtector) { this.viewModelProtector = viewModelProtector; } /// <summary> /// Serializes the view model. /// </summary> public string SerializeViewModel(DotvvmRequestContext context) { if (SendDiff && context.ReceivedViewModelJson != null && context.ViewModelJson["viewModel"] != null) { bool changed; context.ViewModelJson["viewModelDiff"] = JsonUtils.Diff((JObject)context.ReceivedViewModelJson["viewModel"], (JObject)context.ViewModelJson["viewModel"], out changed, true); if (!changed) context.ViewModelJson.Remove("viewModelDiff"); context.ViewModelJson.Remove("viewModel"); } return context.ViewModelJson.ToString(JsonFormatting); } /// <summary> /// Builds the view model for the client. /// </summary> public void BuildViewModel(DotvvmRequestContext context, DotvvmView view) { // serialize the ViewModel var serializer = CreateJsonSerializer(); var viewModelConverter = new ViewModelJsonConverter() { EncryptedValues = new JArray(), UsedSerializationMaps = new HashSet<ViewModelSerializationMap>() }; serializer.Converters.Add(viewModelConverter); var writer = new JTokenWriter(); serializer.Serialize(writer, context.ViewModel); // persist CSRF token writer.Token["$csrfToken"] = context.CsrfToken; // persist encrypted values if (viewModelConverter.EncryptedValues.Count > 0) writer.Token["$encryptedValues"] = viewModelProtector.Protect(viewModelConverter.EncryptedValues.ToString(Formatting.None), context); // serialize validation rules var validationRules = SerializeValidationRules(viewModelConverter); // create result object var result = new JObject(); result["viewModel"] = writer.Token; result["url"] = context.OwinContext.Request.Uri.PathAndQuery; result["virtualDirectory"] = DotvvmMiddleware.GetVirtualDirectory(context.OwinContext); if (context.IsPostBack || context.IsSpaRequest) { result["action"] = "successfulCommand"; var renderedResources = new HashSet<string>(context.ReceivedViewModelJson?["renderedResources"]?.Values<string>() ?? new string[] { }); result["resources"] = BuildResourcesJson(context, rn => !renderedResources.Contains(rn)); } else { result["renderedResources"] = JArray.FromObject(context.ResourceManager.RequiredResources); } // TODO: do not send on postbacks if (validationRules.Count > 0) result["validationRules"] = validationRules; context.ViewModelJson = result; } protected virtual JsonSerializer CreateJsonSerializer() { return new JsonSerializer() { DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind }; } public JObject BuildResourcesJson(DotvvmRequestContext context, Func<string, bool> predicate) { var manager = context.ResourceManager; var resourceObj = new JObject(); foreach(var resource in manager.GetNamedResourcesInOrder()) { if (predicate(resource.Name)) { using (var str = new StringWriter()) { var w = new HtmlWriter(str, context); resource.Resource.Render(w); resourceObj[resource.Name] = JValue.CreateString(str.ToString()); } } } return resourceObj; } /// <summary> /// Serializes the validation rules. /// </summary> private JObject SerializeValidationRules(ViewModelJsonConverter viewModelConverter) { var validationRules = new JObject(); foreach (var map in viewModelConverter.UsedSerializationMaps) { var rule = new JObject(); foreach (var property in map.Properties.Where(p => p.ClientValidationRules.Any())) { rule[property.Name] = JToken.FromObject(property.ClientValidationRules); } if (rule.Count > 0) validationRules[map.Type.ToString()] = rule; } return validationRules; } /// <summary> /// Serializes the redirect action. /// </summary> public static string GenerateRedirectActionResponse(string url) { // create result object var result = new JObject(); result["url"] = url; result["action"] = "redirect"; return result.ToString(Formatting.None); } /// <summary> /// Serializes the validation errors in case the viewmodel was not valid. /// </summary> public string SerializeModelState(DotvvmRequestContext context) { // create result object var result = new JObject(); result["modelState"] = JArray.FromObject(context.ModelState.Errors); result["action"] = "validationErrors"; return result.ToString(JsonFormatting); } /// <summary> /// Populates the view model from the data received from the request. /// </summary> /// <returns></returns> public void PopulateViewModel(DotvvmRequestContext context, DotvvmView view, string serializedPostData) { var viewModelConverter = new ViewModelJsonConverter(); // get properties var data = context.ReceivedViewModelJson = JObject.Parse(serializedPostData); var viewModelToken = (JObject)data["viewModel"]; // load CSRF token context.CsrfToken = viewModelToken["$csrfToken"].Value<string>(); if (viewModelToken["$encryptedValues"] != null) { // load encrypted values var encryptedValuesString = viewModelToken["$encryptedValues"].Value<string>(); viewModelConverter.EncryptedValues = JArray.Parse(viewModelProtector.Unprotect(encryptedValuesString, context)); } else viewModelConverter.EncryptedValues = new JArray(); // get validation path context.ModelState.ValidationTargetPath = data["validationTargetPath"].Value<string>(); // populate the ViewModel var serializer = CreateJsonSerializer(); serializer.Converters.Add(viewModelConverter); viewModelConverter.Populate(viewModelToken, serializer, context.ViewModel); } /// <summary> /// Resolves the command for the specified post data. /// </summary> public void ResolveCommand(DotvvmRequestContext context, DotvvmView view, string serializedPostData, out ActionInfo actionInfo) { // get properties var data = JObject.Parse(serializedPostData); var path = data["currentPath"].Values<string>().ToArray(); var command = data["command"].Value<string>(); var controlUniqueId = data["controlUniqueId"].Value<string>(); if (string.IsNullOrEmpty(command)) { // empty command actionInfo = null; } else { // find the command target if (!string.IsNullOrEmpty(controlUniqueId)) { var target = view.FindControl(controlUniqueId); if (target == null) { throw new Exception(string.Format("The control with ID '{0}' was not found!", controlUniqueId)); } actionInfo = commandResolver.GetFunction(target, view, context, path, command); } else { actionInfo = commandResolver.GetFunction(view, context, path, command); } } } /// <summary> /// Adds the post back updated controls. /// </summary> public void AddPostBackUpdatedControls(DotvvmRequestContext context) { var result = new JObject(); foreach (var control in context.PostBackUpdatedControls) { result[control.Key] = JValue.CreateString(control.Value); } context.ViewModelJson["updatedControls"] = result; } } }
/* * Exchange Web Services Managed API * * Copyright (c) Microsoft Corporation * All rights reserved. * * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ namespace Microsoft.Exchange.WebServices.Data { using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using DefaultPropertySetDictionary = LazyMember<System.Collections.Generic.Dictionary<BasePropertySet, string>>; /// <summary> /// Represents a set of item or folder properties. Property sets are used to indicate what properties of an item or /// folder should be loaded when binding to an existing item or folder or when loading an item or folder's properties. /// </summary> public sealed class PropertySet : ISelfValidate, IEnumerable<PropertyDefinitionBase> { /// <summary> /// Returns a predefined property set that only includes the Id property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable instance")] public static readonly PropertySet IdOnly = PropertySet.CreateReadonlyPropertySet(BasePropertySet.IdOnly); /// <summary> /// Returns a predefined property set that includes the first class properties of an item or folder. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable instance")] public static readonly PropertySet FirstClassProperties = PropertySet.CreateReadonlyPropertySet(BasePropertySet.FirstClassProperties); /// <summary> /// Maps BasePropertySet values to EWS's BaseShape values. /// </summary> private static DefaultPropertySetDictionary defaultPropertySetMap = new DefaultPropertySetDictionary( delegate() { Dictionary<BasePropertySet, string> result = new Dictionary<BasePropertySet, string>(); result.Add(BasePropertySet.IdOnly, "IdOnly"); result.Add(BasePropertySet.FirstClassProperties, "AllProperties"); return result; }); /// <summary> /// The base property set this property set is based upon. /// </summary> private BasePropertySet basePropertySet; /// <summary> /// The list of additional properties included in this property set. /// </summary> private List<PropertyDefinitionBase> additionalProperties = new List<PropertyDefinitionBase>(); /// <summary> /// The requested body type for get and find operations. If null, the "best body" is returned. /// </summary> private BodyType? requestedBodyType; /// <summary> /// The requested unique body type for get and find operations. If null, the should return the same value as body type. /// </summary> private BodyType? requestedUniqueBodyType; /// <summary> /// The requested normalized body type for get and find operations. If null, the should return the same value as body type. /// </summary> private BodyType? requestedNormalizedBodyType; /// <summary> /// Value indicating whether or not the server should filter HTML content. /// </summary> private bool? filterHtml; /// <summary> /// Value indicating whether or not the server should convert HTML code page to UTF8. /// </summary> private bool? convertHtmlCodePageToUTF8; /// <summary> /// Value of the URL template to use for the src attribute of inline IMG elements. /// </summary> private string inlineImageUrlTemplate; /// <summary> /// Value indicating whether or not the server should block references to external images. /// </summary> private bool? blockExternalImages; /// <summary> /// Value indicating whether or not to add a blank target attribute to anchor links. /// </summary> private bool? addTargetToLinks; /// <summary> /// Value indicating whether or not this PropertySet can be modified. /// </summary> private bool isReadOnly; /// <summary> /// Value indicating the maximum body size to retrieve. /// </summary> private int? maximumBodySize; /// <summary> /// Initializes a new instance of PropertySet. /// </summary> /// <param name="basePropertySet">The base property set to base the property set upon.</param> /// <param name="additionalProperties">Additional properties to include in the property set. Property definitions are available as static members from schema classes (for example, EmailMessageSchema.Subject, AppointmentSchema.Start, ContactSchema.GivenName, etc.)</param> public PropertySet(BasePropertySet basePropertySet, params PropertyDefinitionBase[] additionalProperties) : this(basePropertySet, (IEnumerable<PropertyDefinitionBase>)additionalProperties) { } /// <summary> /// Initializes a new instance of PropertySet. /// </summary> /// <param name="basePropertySet">The base property set to base the property set upon.</param> /// <param name="additionalProperties">Additional properties to include in the property set. Property definitions are available as static members from schema classes (for example, EmailMessageSchema.Subject, AppointmentSchema.Start, ContactSchema.GivenName, etc.)</param> public PropertySet(BasePropertySet basePropertySet, IEnumerable<PropertyDefinitionBase> additionalProperties) { this.basePropertySet = basePropertySet; if (additionalProperties != null) { this.additionalProperties.AddRange(additionalProperties); } } /// <summary> /// Initializes a new instance of PropertySet based upon BasePropertySet.IdOnly. /// </summary> public PropertySet() : this(BasePropertySet.IdOnly, null) { } /// <summary> /// Initializes a new instance of PropertySet. /// </summary> /// <param name="basePropertySet">The base property set to base the property set upon.</param> public PropertySet(BasePropertySet basePropertySet) : this(basePropertySet, null) { } /// <summary> /// Initializes a new instance of PropertySet based upon BasePropertySet.IdOnly. /// </summary> /// <param name="additionalProperties">Additional properties to include in the property set. Property definitions are available as static members from schema classes (for example, EmailMessageSchema.Subject, AppointmentSchema.Start, ContactSchema.GivenName, etc.)</param> public PropertySet(params PropertyDefinitionBase[] additionalProperties) : this(BasePropertySet.IdOnly, additionalProperties) { } /// <summary> /// Initializes a new instance of PropertySet based upon BasePropertySet.IdOnly. /// </summary> /// <param name="additionalProperties">Additional properties to include in the property set. Property definitions are available as static members from schema classes (for example, EmailMessageSchema.Subject, AppointmentSchema.Start, ContactSchema.GivenName, etc.)</param> public PropertySet(IEnumerable<PropertyDefinitionBase> additionalProperties) : this(BasePropertySet.IdOnly, additionalProperties) { } /// <summary> /// Implements an implicit conversion between PropertySet and BasePropertySet. /// </summary> /// <param name="basePropertySet">The BasePropertySet value to convert from.</param> /// <returns>A PropertySet instance based on the specified base property set.</returns> public static implicit operator PropertySet(BasePropertySet basePropertySet) { return new PropertySet(basePropertySet); } /// <summary> /// Adds the specified property to the property set. /// </summary> /// <param name="property">The property to add.</param> public void Add(PropertyDefinitionBase property) { this.ThrowIfReadonly(); EwsUtilities.ValidateParam(property, "property"); if (!this.additionalProperties.Contains(property)) { this.additionalProperties.Add(property); } } /// <summary> /// Adds the specified properties to the property set. /// </summary> /// <param name="properties">The properties to add.</param> public void AddRange(IEnumerable<PropertyDefinitionBase> properties) { this.ThrowIfReadonly(); EwsUtilities.ValidateParamCollection(properties, "properties"); foreach (PropertyDefinitionBase property in properties) { this.Add(property); } } /// <summary> /// Remove all explicitly added properties from the property set. /// </summary> public void Clear() { this.ThrowIfReadonly(); this.additionalProperties.Clear(); } /// <summary> /// Creates a read-only PropertySet. /// </summary> /// <param name="basePropertySet">The base property set.</param> /// <returns>PropertySet</returns> private static PropertySet CreateReadonlyPropertySet(BasePropertySet basePropertySet) { PropertySet propertySet = new PropertySet(basePropertySet); propertySet.isReadOnly = true; return propertySet; } /// <summary> /// Gets the name of the shape. /// </summary> /// <param name="serviceObjectType">Type of the service object.</param> /// <returns>Shape name.</returns> private static string GetShapeName(ServiceObjectType serviceObjectType) { switch (serviceObjectType) { case ServiceObjectType.Item: return XmlElementNames.ItemShape; case ServiceObjectType.Folder: return XmlElementNames.FolderShape; case ServiceObjectType.Conversation: return XmlElementNames.ConversationShape; case ServiceObjectType.Persona: return XmlElementNames.PersonaShape; default: EwsUtilities.Assert( false, "PropertySet.GetShapeName", string.Format("An unexpected object type {0} for property shape. This code path should never be reached.", serviceObjectType)); return string.Empty; } } /// <summary> /// Throws if readonly property set. /// </summary> private void ThrowIfReadonly() { if (this.isReadOnly) { throw new System.NotSupportedException(Strings.PropertySetCannotBeModified); } } /// <summary> /// Determines whether the specified property has been explicitly added to this property set using the Add or AddRange methods. /// </summary> /// <param name="property">The property.</param> /// <returns> /// <c>true</c> if this property set contains the specified propert]; otherwise, <c>false</c>. /// </returns> public bool Contains(PropertyDefinitionBase property) { return this.additionalProperties.Contains(property); } /// <summary> /// Removes the specified property from the set. /// </summary> /// <param name="property">The property to remove.</param> /// <returns>true if the property was successfully removed, false otherwise.</returns> public bool Remove(PropertyDefinitionBase property) { this.ThrowIfReadonly(); return this.additionalProperties.Remove(property); } /// <summary> /// Gets or sets the base property set the property set is based upon. /// </summary> public BasePropertySet BasePropertySet { get { return this.basePropertySet; } set { this.ThrowIfReadonly(); this.basePropertySet = value; } } /// <summary> /// Gets or sets type of body that should be loaded on items. If RequestedBodyType is null, body is returned as HTML if available, plain text otherwise. /// </summary> public BodyType? RequestedBodyType { get { return this.requestedBodyType; } set { this.ThrowIfReadonly(); this.requestedBodyType = value; } } /// <summary> /// Gets or sets type of body that should be loaded on items. If null, the should return the same value as body type. /// </summary> public BodyType? RequestedUniqueBodyType { get { return this.requestedUniqueBodyType; } set { this.ThrowIfReadonly(); this.requestedUniqueBodyType = value; } } /// <summary> /// Gets or sets type of normalized body that should be loaded on items. If null, the should return the same value as body type. /// </summary> public BodyType? RequestedNormalizedBodyType { get { return this.requestedNormalizedBodyType; } set { this.ThrowIfReadonly(); this.requestedNormalizedBodyType = value; } } /// <summary> /// Gets the number of explicitly added properties in this set. /// </summary> public int Count { get { return this.additionalProperties.Count; } } /// <summary> /// Gets or sets value indicating whether or not to filter potentially unsafe HTML content from message bodies. /// </summary> public bool? FilterHtmlContent { get { return this.filterHtml; } set { this.ThrowIfReadonly(); this.filterHtml = value; } } /// <summary> /// Gets or sets value indicating whether or not to convert HTML code page to UTF8 encoding. /// </summary> public bool? ConvertHtmlCodePageToUTF8 { get { return this.convertHtmlCodePageToUTF8; } set { this.ThrowIfReadonly(); this.convertHtmlCodePageToUTF8 = value; } } /// <summary> /// Gets or sets a value of the URL template to use for the src attribute of inline IMG elements. /// </summary> public string InlineImageUrlTemplate { get { return this.inlineImageUrlTemplate; } set { this.ThrowIfReadonly(); this.inlineImageUrlTemplate = value; } } /// <summary> /// Gets or sets value indicating whether or not to convert inline images to data URLs. /// </summary> public bool? BlockExternalImages { get { return this.blockExternalImages; } set { this.ThrowIfReadonly(); this.blockExternalImages = value; } } /// <summary> /// Gets or sets value indicating whether or not to add blank target attribute to anchor links. /// </summary> public bool? AddBlankTargetToLinks { get { return this.addTargetToLinks; } set { this.ThrowIfReadonly(); this.addTargetToLinks = value; } } /// <summary> /// Gets or sets the maximum size of the body to be retrieved. /// </summary> /// <value> /// The maximum size of the body to be retrieved. /// </value> public int? MaximumBodySize { get { return this.maximumBodySize; } set { this.ThrowIfReadonly(); this.maximumBodySize = value; } } /// <summary> /// Gets the <see cref="Microsoft.Exchange.WebServices.Data.PropertyDefinitionBase"/> at the specified index. /// </summary> /// <param name="index">Index.</param> public PropertyDefinitionBase this[int index] { get { return this.additionalProperties[index]; } } /// <summary> /// Implements ISelfValidate.Validate. Validates this property set. /// </summary> void ISelfValidate.Validate() { this.InternalValidate(); } /// <summary> /// Maps BasePropertySet values to EWS's BaseShape values. /// </summary> internal static DefaultPropertySetDictionary DefaultPropertySetMap { get { return PropertySet.defaultPropertySetMap; } } /// <summary> /// Writes additonal properties to XML. /// </summary> /// <param name="writer">The writer to write to.</param> /// <param name="propertyDefinitions">The property definitions to write.</param> internal static void WriteAdditionalPropertiesToXml( EwsServiceXmlWriter writer, IEnumerable<PropertyDefinitionBase> propertyDefinitions) { writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.AdditionalProperties); foreach (PropertyDefinitionBase propertyDefinition in propertyDefinitions) { propertyDefinition.WriteToXml(writer); } writer.WriteEndElement(); } /// <summary> /// Validates this property set. /// </summary> internal void InternalValidate() { for (int i = 0; i < this.additionalProperties.Count; i++) { if (this.additionalProperties[i] == null) { throw new ServiceValidationException(string.Format(Strings.AdditionalPropertyIsNull, i)); } } } /// <summary> /// Validates this property set instance for request to ensure that: /// 1. Properties are valid for the request server version. /// 2. If only summary properties are legal for this request (e.g. FindItem) then only summary properties were specified. /// </summary> /// <param name="request">The request.</param> /// <param name="summaryPropertiesOnly">if set to <c>true</c> then only summary properties are allowed.</param> internal void ValidateForRequest(ServiceRequestBase request, bool summaryPropertiesOnly) { foreach (PropertyDefinitionBase propDefBase in this.additionalProperties) { PropertyDefinition propertyDefinition = propDefBase as PropertyDefinition; if (propertyDefinition != null) { if (propertyDefinition.Version > request.Service.RequestedServerVersion) { throw new ServiceVersionException( string.Format( Strings.PropertyIncompatibleWithRequestVersion, propertyDefinition.Name, propertyDefinition.Version)); } if (summaryPropertiesOnly && !propertyDefinition.HasFlag(PropertyDefinitionFlags.CanFind, request.Service.RequestedServerVersion)) { throw new ServiceValidationException( string.Format( Strings.NonSummaryPropertyCannotBeUsed, propertyDefinition.Name, request.GetXmlElementName())); } } } if (this.FilterHtmlContent.HasValue) { if (request.Service.RequestedServerVersion < ExchangeVersion.Exchange2010) { throw new ServiceVersionException( string.Format( Strings.PropertyIncompatibleWithRequestVersion, "FilterHtmlContent", ExchangeVersion.Exchange2010)); } } if (this.ConvertHtmlCodePageToUTF8.HasValue) { if (request.Service.RequestedServerVersion < ExchangeVersion.Exchange2010_SP1) { throw new ServiceVersionException( string.Format( Strings.PropertyIncompatibleWithRequestVersion, "ConvertHtmlCodePageToUTF8", ExchangeVersion.Exchange2010_SP1)); } } if (!string.IsNullOrEmpty(this.InlineImageUrlTemplate)) { if (request.Service.RequestedServerVersion < ExchangeVersion.Exchange2013) { throw new ServiceVersionException( string.Format( Strings.PropertyIncompatibleWithRequestVersion, "InlineImageUrlTemplate", ExchangeVersion.Exchange2013)); } } if (this.BlockExternalImages.HasValue) { if (request.Service.RequestedServerVersion < ExchangeVersion.Exchange2013) { throw new ServiceVersionException( string.Format( Strings.PropertyIncompatibleWithRequestVersion, "BlockExternalImages", ExchangeVersion.Exchange2013)); } } if (this.AddBlankTargetToLinks.HasValue) { if (request.Service.RequestedServerVersion < ExchangeVersion.Exchange2013) { throw new ServiceVersionException( string.Format( Strings.PropertyIncompatibleWithRequestVersion, "AddTargetToLinks", ExchangeVersion.Exchange2013)); } } if (this.MaximumBodySize.HasValue) { if (request.Service.RequestedServerVersion < ExchangeVersion.Exchange2013) { throw new ServiceVersionException( string.Format( Strings.PropertyIncompatibleWithRequestVersion, "MaximumBodySize", ExchangeVersion.Exchange2013)); } } } /// <summary> /// Writes the property set to XML. /// </summary> /// <param name="writer">The writer to write to.</param> /// <param name="serviceObjectType">The type of service object the property set is emitted for.</param> internal void WriteToXml(EwsServiceXmlWriter writer, ServiceObjectType serviceObjectType) { string shapeElementName = GetShapeName(serviceObjectType); writer.WriteStartElement( XmlNamespace.Messages, shapeElementName); writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.BaseShape, defaultPropertySetMap.Member[this.BasePropertySet]); if (serviceObjectType == ServiceObjectType.Item) { if (this.RequestedBodyType.HasValue) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.BodyType, this.RequestedBodyType.Value); } if (this.RequestedUniqueBodyType.HasValue) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.UniqueBodyType, this.RequestedUniqueBodyType.Value); } if (this.RequestedNormalizedBodyType.HasValue) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.NormalizedBodyType, this.RequestedNormalizedBodyType.Value); } if (this.FilterHtmlContent.HasValue) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.FilterHtmlContent, this.FilterHtmlContent.Value); } if (this.ConvertHtmlCodePageToUTF8.HasValue && writer.Service.RequestedServerVersion >= ExchangeVersion.Exchange2010_SP1) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.ConvertHtmlCodePageToUTF8, this.ConvertHtmlCodePageToUTF8.Value); } if (!string.IsNullOrEmpty(this.InlineImageUrlTemplate) && writer.Service.RequestedServerVersion >= ExchangeVersion.Exchange2013) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.InlineImageUrlTemplate, this.InlineImageUrlTemplate); } if (this.BlockExternalImages.HasValue && writer.Service.RequestedServerVersion >= ExchangeVersion.Exchange2013) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.BlockExternalImages, this.BlockExternalImages.Value); } if (this.AddBlankTargetToLinks.HasValue && writer.Service.RequestedServerVersion >= ExchangeVersion.Exchange2013) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.AddBlankTargetToLinks, this.AddBlankTargetToLinks.Value); } if (this.MaximumBodySize.HasValue && writer.Service.RequestedServerVersion >= ExchangeVersion.Exchange2013) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.MaximumBodySize, this.MaximumBodySize.Value); } } if (this.additionalProperties.Count > 0) { WriteAdditionalPropertiesToXml(writer, this.additionalProperties); } writer.WriteEndElement(); // Item/FolderShape } #region IEnumerable<PropertyDefinitionBase> Members /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection. /// </returns> public IEnumerator<PropertyDefinitionBase> GetEnumerator() { return this.additionalProperties.GetEnumerator(); } #endregion #region IEnumerable Members /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection. /// </returns> System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.additionalProperties.GetEnumerator(); } #endregion } }
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 Tests.ApiHarness.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 the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <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 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 objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <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 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> /// 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> /// 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> /// 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); } 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 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; } [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 object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace Contoso.Core.JavaScriptCustomization.AppWeb { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #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.Data.Common; using System.Data.SqlClient; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using System.Transactions; namespace System.Data.ProviderBase { internal abstract class DbConnectionInternal { internal static readonly StateChangeEventArgs StateChangeClosed = new StateChangeEventArgs(ConnectionState.Open, ConnectionState.Closed); internal static readonly StateChangeEventArgs StateChangeOpen = new StateChangeEventArgs(ConnectionState.Closed, ConnectionState.Open); private readonly bool _allowSetConnectionString; private readonly bool _hidePassword; private readonly ConnectionState _state; private readonly WeakReference _owningObject = new WeakReference(null, false); // [usage must be thread safe] the owning object, when not in the pool. (both Pooled and Non-Pooled connections) private DbConnectionPool _connectionPool; // the pooler that the connection came from (Pooled connections only) private DbReferenceCollection _referenceCollection; // collection of objects that we need to notify in some way when we're being deactivated private int _pooledCount; // [usage must be thread safe] the number of times this object has been pushed into the pool less the number of times it's been popped (0 != inPool) private bool _connectionIsDoomed; // true when the connection should no longer be used. private bool _cannotBePooled; // true when the connection should no longer be pooled. private bool _isInStasis; private DateTime _createTime; // when the connection was created. private Transaction _enlistedTransaction; // [usage must be thread-safe] the transaction that we're enlisted in, either manually or automatically // _enlistedTransaction is a clone, so that transaction information can be queried even if the original transaction object is disposed. // However, there are times when we need to know if the original transaction object was disposed, so we keep a reference to it here. // This field should only be assigned a value at the same time _enlistedTransaction is updated. // Also, this reference should not be disposed, since we aren't taking ownership of it. private Transaction _enlistedTransactionOriginal; #if DEBUG private int _activateCount; // debug only counter to verify activate/deactivates are in sync. #endif //DEBUG protected DbConnectionInternal() : this(ConnectionState.Open, true, false) { } // Constructor for internal connections internal DbConnectionInternal(ConnectionState state, bool hidePassword, bool allowSetConnectionString) { _allowSetConnectionString = allowSetConnectionString; _hidePassword = hidePassword; _state = state; } internal bool AllowSetConnectionString { get { return _allowSetConnectionString; } } internal bool CanBePooled { get { bool flag = (!_connectionIsDoomed && !_cannotBePooled && !_owningObject.IsAlive); return flag; } } protected internal Transaction EnlistedTransaction { get { return _enlistedTransaction; } set { Transaction currentEnlistedTransaction = _enlistedTransaction; if (((null == currentEnlistedTransaction) && (null != value)) || ((null != currentEnlistedTransaction) && !currentEnlistedTransaction.Equals(value))) { // WebData 20000024 // Pay attention to the order here: // 1) defect from any notifications // 2) replace the transaction // 3) re-enlist in notifications for the new transaction // SQLBUDT #230558 we need to use a clone of the transaction // when we store it, or we'll end up keeping it past the // duration of the using block of the TransactionScope Transaction valueClone = null; Transaction previousTransactionClone = null; try { if (null != value) { valueClone = value.Clone(); } // NOTE: rather than take locks around several potential round- // trips to the server, and/or virtual function calls, we simply // presume that you aren't doing something illegal from multiple // threads, and check once we get around to finalizing things // inside a lock. lock (this) { // NOTE: There is still a race condition here, when we are // called from EnlistTransaction (which cannot re-enlist) // instead of EnlistDistributedTransaction (which can), // however this should have been handled by the outer // connection which checks to ensure that it's OK. The // only case where we have the race condition is multiple // concurrent enlist requests to the same connection, which // is a bit out of line with something we should have to // support. // enlisted transaction can be nullified in Dispose call without lock previousTransactionClone = Interlocked.Exchange(ref _enlistedTransaction, valueClone); _enlistedTransactionOriginal = value; value = valueClone; valueClone = null; // we've stored it, don't dispose it. } } finally { // we really need to dispose our clones; they may have // native resources and GC may not happen soon enough. // VSDevDiv 479564: don't dispose if still holding reference in _enlistedTransaction if (null != previousTransactionClone && !Object.ReferenceEquals(previousTransactionClone, _enlistedTransaction)) { previousTransactionClone.Dispose(); } if (null != valueClone && !Object.ReferenceEquals(valueClone, _enlistedTransaction)) { valueClone.Dispose(); } } // I don't believe that we need to lock to protect the actual // enlistment in the transaction; it would only protect us // against multiple concurrent calls to enlist, which really // isn't supported anyway. if (null != value) { TransactionOutcomeEnlist(value); } } } } /// <summary> /// Get boolean value that indicates whether the enlisted transaction has been disposed. /// </summary> /// <value> /// True if there is an enlisted transaction, and it has been disposed. /// False if there is an enlisted transaction that has not been disposed, or if the transaction reference is null. /// </value> /// <remarks> /// This method must be called while holding a lock on the DbConnectionInternal instance. /// </remarks> protected bool EnlistedTransactionDisposed { get { // Until the Transaction.Disposed property is public it is necessary to access a member // that throws if the object is disposed to determine if in fact the transaction is disposed. try { bool disposed; Transaction currentEnlistedTransactionOriginal = _enlistedTransactionOriginal; if (currentEnlistedTransactionOriginal != null) { disposed = currentEnlistedTransactionOriginal.TransactionInformation == null; } else { // Don't expect to get here in the general case, // Since this getter is called by CheckEnlistedTransactionBinding // after checking for a non-null enlisted transaction (and it does so under lock). disposed = false; } return disposed; } catch (ObjectDisposedException) { return true; } } } internal bool IsTxRootWaitingForTxEnd { get { return _isInStasis; } } virtual protected bool UnbindOnTransactionCompletion { get { return true; } } // Is this a connection that must be put in stasis (or is already in stasis) pending the end of it's transaction? virtual protected internal bool IsNonPoolableTransactionRoot { get { return false; // if you want to have delegated transactions that are non-poolable, you better override this... } } virtual internal bool IsTransactionRoot { get { return false; // if you want to have delegated transactions, you better override this... } } protected internal bool IsConnectionDoomed { get { return _connectionIsDoomed; } } internal bool IsEmancipated { get { // NOTE: There are race conditions between PrePush, PostPop and this // property getter -- only use this while this object is locked; // (DbConnectionPool.Clear and ReclaimEmancipatedObjects // do this for us) // The functionality is as follows: // // _pooledCount is incremented when the connection is pushed into the pool // _pooledCount is decremented when the connection is popped from the pool // _pooledCount is set to -1 when the connection is not pooled (just in case...) // // That means that: // // _pooledCount > 1 connection is in the pool multiple times (This should not happen) // _pooledCount == 1 connection is in the pool // _pooledCount == 0 connection is out of the pool // _pooledCount == -1 connection is not a pooled connection; we shouldn't be here for non-pooled connections. // _pooledCount < -1 connection out of the pool multiple times // // Now, our job is to return TRUE when the connection is out // of the pool and it's owning object is no longer around to // return it. bool value = (_pooledCount < 1) && !_owningObject.IsAlive; return value; } } internal bool IsInPool { get { Debug.Assert(_pooledCount <= 1 && _pooledCount >= -1, "Pooled count for object is invalid"); return (_pooledCount == 1); } } protected internal object Owner { // We use a weak reference to the owning object so we can identify when // it has been garbage collected without thowing exceptions. get { return _owningObject.Target; } } internal DbConnectionPool Pool { get { return _connectionPool; } } virtual protected bool ReadyToPrepareTransaction { get { return true; } } protected internal DbReferenceCollection ReferenceCollection { get { return _referenceCollection; } } abstract public string ServerVersion { get; } // this should be abstract but until it is added to all the providers virtual will have to do virtual public string ServerVersionNormalized { get { throw ADP.NotSupported(); } } public bool ShouldHidePassword { get { return _hidePassword; } } public ConnectionState State { get { return _state; } } abstract protected void Activate(Transaction transaction); internal void ActivateConnection(Transaction transaction) { // Internal method called from the connection pooler so we don't expose // the Activate method publicly. Activate(transaction); } internal void AddWeakReference(object value, int tag) { if (null == _referenceCollection) { _referenceCollection = CreateReferenceCollection(); if (null == _referenceCollection) { throw ADP.InternalError(ADP.InternalErrorCode.CreateReferenceCollectionReturnedNull); } } _referenceCollection.Add(value, tag); } abstract public DbTransaction BeginTransaction(IsolationLevel il); virtual public void ChangeDatabase(string value) { throw ADP.MethodNotImplemented(); } internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFactory connectionFactory) { // The implementation here is the implementation required for the // "open" internal connections, since our own private "closed" // singleton internal connection objects override this method to // prevent anything funny from happening (like disposing themselves // or putting them into a connection pool) // // Derived class should override DbConnectionInternal.Deactivate and DbConnectionInternal.Dispose // for cleaning up after DbConnection.Close // protected override void Deactivate() { // override DbConnectionInternal.Close // // do derived class connection deactivation for both pooled & non-pooled connections // } // public override void Dispose() { // override DbConnectionInternal.Close // // do derived class cleanup // base.Dispose(); // } // // overriding DbConnection.Close is also possible, but must provider for their own synchronization // public override void Close() { // override DbConnection.Close // base.Close(); // // do derived class outer connection for both pooled & non-pooled connections // // user must do their own synchronization here // } // // if the DbConnectionInternal derived class needs to close the connection it should // delegate to the DbConnection if one exists or directly call dispose // DbConnection owningObject = (DbConnection)Owner; // if (null != owningObject) { // owningObject.Close(); // force the closed state on the outer object. // } // else { // Dispose(); // } // //////////////////////////////////////////////////////////////// // DON'T MESS WITH THIS CODE UNLESS YOU KNOW WHAT YOU'RE DOING! //////////////////////////////////////////////////////////////// Debug.Assert(null != owningObject, "null owningObject"); Debug.Assert(null != connectionFactory, "null connectionFactory"); // if an exception occurs after the state change but before the try block // the connection will be stuck in OpenBusy state. The commented out try-catch // block doesn't really help because a ThreadAbort during the finally block // would just revert the connection to a bad state. // Open->Closed: guarantee internal connection is returned to correct pool if (connectionFactory.SetInnerConnectionFrom(owningObject, DbConnectionOpenBusy.SingletonInstance, this)) { // Lock to prevent race condition with cancellation lock (this) { object lockToken = ObtainAdditionalLocksForClose(); try { PrepareForCloseConnection(); DbConnectionPool connectionPool = Pool; // Detach from enlisted transactions that are no longer active on close DetachCurrentTransactionIfEnded(); // The singleton closed classes won't have owners and // connection pools, and we won't want to put them back // into the pool. if (null != connectionPool) { connectionPool.PutObject(this, owningObject); // PutObject calls Deactivate for us... // NOTE: Before we leave the PutObject call, another // thread may have already popped the connection from // the pool, so don't expect to be able to verify it. } else { Deactivate(); // ensure we de-activate non-pooled connections, or the data readers and transactions may not get cleaned up... // To prevent an endless recursion, we need to clear // the owning object before we call dispose so that // we can't get here a second time... Ordinarily, I // would call setting the owner to null a hack, but // this is safe since we're about to dispose the // object and it won't have an owner after that for // certain. _owningObject.Target = null; if (IsTransactionRoot) { SetInStasis(); } else { Dispose(); } } } finally { ReleaseAdditionalLocksForClose(lockToken); // if a ThreadAbort puts us here then its possible the outer connection will not reference // this and this will be orphaned, not reclaimed by object pool until outer connection goes out of scope. connectionFactory.SetInnerConnectionEvent(owningObject, DbConnectionClosedPreviouslyOpened.SingletonInstance); } } } } virtual internal void PrepareForReplaceConnection() { // By default, there is no preparation required } virtual protected void PrepareForCloseConnection() { // By default, there is no preparation required } virtual protected object ObtainAdditionalLocksForClose() { return null; // no additional locks in default implementation } virtual protected void ReleaseAdditionalLocksForClose(object lockToken) { // no additional locks in default implementation } virtual protected DbReferenceCollection CreateReferenceCollection() { throw ADP.InternalError(ADP.InternalErrorCode.AttemptingToConstructReferenceCollectionOnStaticObject); } abstract protected void Deactivate(); internal void DeactivateConnection() { // Internal method called from the connection pooler so we don't expose // the Deactivate method publicly. #if DEBUG int activateCount = Interlocked.Decrement(ref _activateCount); #endif // DEBUG if (!_connectionIsDoomed && Pool.UseLoadBalancing) { // If we're not already doomed, check the connection's lifetime and // doom it if it's lifetime has elapsed. DateTime now = DateTime.UtcNow; if ((now.Ticks - _createTime.Ticks) > Pool.LoadBalanceTimeout.Ticks) { DoNotPoolThisConnection(); } } Deactivate(); } virtual internal void DelegatedTransactionEnded() { // Called by System.Transactions when the delegated transaction has // completed. We need to make closed connections that are in stasis // available again, or disposed closed/leaked non-pooled connections. // IMPORTANT NOTE: You must have taken a lock on the object before // you call this method to prevent race conditions with Clear and // ReclaimEmancipatedObjects. if (1 == _pooledCount) { // When _pooledCount is 1, it indicates a closed, pooled, // connection so it is ready to put back into the pool for // general use. TerminateStasis(true); Deactivate(); // call it one more time just in case DbConnectionPool pool = Pool; if (null == pool) { throw ADP.InternalError(ADP.InternalErrorCode.PooledObjectWithoutPool); // pooled connection does not have a pool } pool.PutObjectFromTransactedPool(this); } else if (-1 == _pooledCount && !_owningObject.IsAlive) { // When _pooledCount is -1 and the owning object no longer exists, // it indicates a closed (or leaked), non-pooled connection so // it is safe to dispose. TerminateStasis(false); Deactivate(); // call it one more time just in case // it's a non-pooled connection, we need to dispose of it // once and for all, or the server will have fits about us // leaving connections open until the client-side GC kicks // in. Dispose(); } // When _pooledCount is 0, the connection is a pooled connection // that is either open (if the owning object is alive) or leaked (if // the owning object is not alive) In either case, we can't muck // with the connection here. } public virtual void Dispose() { _connectionPool = null; _connectionIsDoomed = true; _enlistedTransactionOriginal = null; // should not be disposed // Dispose of the _enlistedTransaction since it is a clone // of the original reference. // VSDD 780271 - _enlistedTransaction can be changed by another thread (TX end event) Transaction enlistedTransaction = Interlocked.Exchange(ref _enlistedTransaction, null); if (enlistedTransaction != null) { enlistedTransaction.Dispose(); } } protected internal void DoNotPoolThisConnection() { _cannotBePooled = true; } /// <devdoc>Ensure that this connection cannot be put back into the pool.</devdoc> protected internal void DoomThisConnection() { _connectionIsDoomed = true; } abstract public void EnlistTransaction(Transaction transaction); protected internal virtual DataTable GetSchema(DbConnectionFactory factory, DbConnectionPoolGroup poolGroup, DbConnection outerConnection, string collectionName, string[] restrictions) { Debug.Assert(outerConnection != null, "outerConnection may not be null."); DbMetaDataFactory metaDataFactory = factory.GetMetaDataFactory(poolGroup, this); Debug.Assert(metaDataFactory != null, "metaDataFactory may not be null."); return metaDataFactory.GetSchema(outerConnection, collectionName, restrictions); } internal void MakeNonPooledObject(object owningObject) { // Used by DbConnectionFactory to indicate that this object IS NOT part of // a connection pool. _connectionPool = null; _owningObject.Target = owningObject; _pooledCount = -1; } internal void MakePooledConnection(DbConnectionPool connectionPool) { // Used by DbConnectionFactory to indicate that this object IS part of // a connection pool. _createTime = DateTime.UtcNow; _connectionPool = connectionPool; } internal void NotifyWeakReference(int message) { DbReferenceCollection referenceCollection = ReferenceCollection; if (null != referenceCollection) { referenceCollection.Notify(message); } } internal virtual void OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) { if (!TryOpenConnection(outerConnection, connectionFactory, null, null)) { throw ADP.InternalError(ADP.InternalErrorCode.SynchronousConnectReturnedPending); } } /// <devdoc>The default implementation is for the open connection objects, and /// it simply throws. Our private closed-state connection objects /// override this and do the correct thing.</devdoc> // User code should either override DbConnectionInternal.Activate when it comes out of the pool // or override DbConnectionFactory.CreateConnection when the connection is created for non-pooled connections internal virtual bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions) { throw ADP.ConnectionAlreadyOpen(State); } internal virtual bool TryReplaceConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions) { throw ADP.MethodNotImplemented(); } protected bool TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions) { // ?->Connecting: prevent set_ConnectionString during Open if (connectionFactory.SetInnerConnectionFrom(outerConnection, DbConnectionClosedConnecting.SingletonInstance, this)) { DbConnectionInternal openConnection = null; try { connectionFactory.PermissionDemand(outerConnection); if (!connectionFactory.TryGetConnection(outerConnection, retry, userOptions, this, out openConnection)) { return false; } } catch { // This should occur for all exceptions, even ADP.UnCatchableExceptions. connectionFactory.SetInnerConnectionTo(outerConnection, this); throw; } if (null == openConnection) { connectionFactory.SetInnerConnectionTo(outerConnection, this); throw ADP.InternalConnectionError(ADP.ConnectionError.GetConnectionReturnsNull); } connectionFactory.SetInnerConnectionEvent(outerConnection, openConnection); } return true; } internal void PrePush(object expectedOwner) { // Called by DbConnectionPool when we're about to be put into it's pool, we // take this opportunity to ensure ownership and pool counts are legit. // IMPORTANT NOTE: You must have taken a lock on the object before // you call this method to prevent race conditions with Clear and // ReclaimEmancipatedObjects. //3 // The following tests are retail assertions of things we can't allow to happen. if (null == expectedOwner) { if (null != _owningObject.Target) { throw ADP.InternalError(ADP.InternalErrorCode.UnpooledObjectHasOwner); // new unpooled object has an owner } } else if (_owningObject.Target != expectedOwner) { throw ADP.InternalError(ADP.InternalErrorCode.UnpooledObjectHasWrongOwner); // unpooled object has incorrect owner } if (0 != _pooledCount) { throw ADP.InternalError(ADP.InternalErrorCode.PushingObjectSecondTime); // pushing object onto stack a second time } _pooledCount++; _owningObject.Target = null; // NOTE: doing this and checking for InternalError.PooledObjectHasOwner degrades the close by 2% } internal void PostPop(object newOwner) { // Called by DbConnectionPool right after it pulls this from it's pool, we // take this opportunity to ensure ownership and pool counts are legit. Debug.Assert(!IsEmancipated, "pooled object not in pool"); // When another thread is clearing this pool, it // will doom all connections in this pool without prejudice which // causes the following assert to fire, which really mucks up stress // against checked bits. The assert is benign, so we're commenting // it out. //Debug.Assert(CanBePooled, "pooled object is not poolable"); // IMPORTANT NOTE: You must have taken a lock on the object before // you call this method to prevent race conditions with Clear and // ReclaimEmancipatedObjects. if (null != _owningObject.Target) { throw ADP.InternalError(ADP.InternalErrorCode.PooledObjectHasOwner); // pooled connection already has an owner! } _owningObject.Target = newOwner; _pooledCount--; //3 // The following tests are retail assertions of things we can't allow to happen. if (null != Pool) { if (0 != _pooledCount) { throw ADP.InternalError(ADP.InternalErrorCode.PooledObjectInPoolMoreThanOnce); // popping object off stack with multiple pooledCount } } else if (-1 != _pooledCount) { throw ADP.InternalError(ADP.InternalErrorCode.NonPooledObjectUsedMoreThanOnce); // popping object off stack with multiple pooledCount } } internal void RemoveWeakReference(object value) { DbReferenceCollection referenceCollection = ReferenceCollection; if (null != referenceCollection) { referenceCollection.Remove(value); } } // Cleanup connection's transaction-specific structures (currently used by Delegated transaction). // This is a separate method because cleanup can be triggered in multiple ways for a delegated // transaction. virtual protected void CleanupTransactionOnCompletion(Transaction transaction) { } internal void DetachCurrentTransactionIfEnded() { Transaction enlistedTransaction = EnlistedTransaction; if (enlistedTransaction != null) { bool transactionIsDead; try { transactionIsDead = (TransactionStatus.Active != enlistedTransaction.TransactionInformation.Status); } catch (TransactionException) { // If the transaction is being processed (i.e. is part way through a rollback\commit\etc then TransactionInformation.Status will throw an exception) transactionIsDead = true; } if (transactionIsDead) { DetachTransaction(enlistedTransaction, true); } } } // Detach transaction from connection. internal void DetachTransaction(Transaction transaction, bool isExplicitlyReleasing) { // potentially a multi-threaded event, so lock the connection to make sure we don't enlist in a new // transaction between compare and assignment. No need to short circuit outside of lock, since failed comparisons should // be the exception, not the rule. lock (this) { // Detach if detach-on-end behavior, or if outer connection was closed DbConnection owner = (DbConnection)Owner; if (isExplicitlyReleasing || UnbindOnTransactionCompletion || null == owner) { Transaction currentEnlistedTransaction = _enlistedTransaction; if (currentEnlistedTransaction != null && transaction.Equals(currentEnlistedTransaction)) { EnlistedTransaction = null; if (IsTxRootWaitingForTxEnd) { DelegatedTransactionEnded(); } } } } } // Handle transaction detach, pool cleanup and other post-transaction cleanup tasks associated with internal void CleanupConnectionOnTransactionCompletion(Transaction transaction) { DetachTransaction(transaction, false); DbConnectionPool pool = Pool; if (null != pool) { pool.TransactionEnded(transaction, this); } } void TransactionCompletedEvent(object sender, TransactionEventArgs e) { Transaction transaction = e.Transaction; CleanupTransactionOnCompletion(transaction); CleanupConnectionOnTransactionCompletion(transaction); } // TODO: Review whether we need the unmanaged code permission when we have the new object model available. // [SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.UnmanagedCode)] private void TransactionOutcomeEnlist(Transaction transaction) { transaction.TransactionCompleted += new TransactionCompletedEventHandler(TransactionCompletedEvent); } internal void SetInStasis() { _isInStasis = true; } private void TerminateStasis(bool returningToPool) { _isInStasis = false; } /// <summary> /// When overridden in a derived class, will check if the underlying connection is still actually alive /// </summary> /// <param name="throwOnException">If true an exception will be thrown if the connection is dead instead of returning true\false /// (this allows the caller to have the real reason that the connection is not alive (e.g. network error, etc))</param> /// <returns>True if the connection is still alive, otherwise false (If not overridden, then always true)</returns> internal virtual bool IsConnectionAlive(bool throwOnException = false) { return true; } } }
using System; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Localization; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; using Newtonsoft.Json.Linq; using Orchard.DisplayManagement.Notify; using Orchard.Lucene.Services; using Orchard.Lucene.ViewModels; using Orchard.Mvc.Utilities; using Orchard.Tokens.Services; namespace Orchard.Lucene.Controllers { public class AdminController : Controller { private readonly LuceneIndexManager _luceneIndexManager; private readonly LuceneIndexingService _luceneIndexingService; private readonly IAuthorizationService _authorizationService; private readonly INotifier _notifier; private readonly LuceneAnalyzerManager _luceneAnalyzerManager; private readonly ILuceneQueryService _queryService; public AdminController( LuceneIndexManager luceneIndexManager, LuceneIndexingService luceneIndexingService, IAuthorizationService authorizationService, LuceneAnalyzerManager luceneAnalyzerManager, ILuceneQueryService queryService, INotifier notifier, IStringLocalizer<AdminController> s, IHtmlLocalizer<AdminController> h, ILogger<AdminController> logger) { _luceneIndexManager = luceneIndexManager; _luceneIndexingService = luceneIndexingService; _authorizationService = authorizationService; _luceneAnalyzerManager = luceneAnalyzerManager; _queryService = queryService; _notifier = notifier; S = s; H = h; Logger = logger; } public ILogger Logger { get; } public IStringLocalizer S { get; } public IHtmlLocalizer H { get; } public ActionResult Index() { var viewModel = new AdminIndexViewModel(); viewModel.Indexes = _luceneIndexManager.List().Select(s => new IndexViewModel { Name = s }).ToArray(); return View(viewModel); } public async Task<ActionResult> Create() { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageIndexes)) { return Unauthorized(); } var model = new AdminEditViewModel { IndexName = "", }; return View(model); } [HttpPost, ActionName("Create")] public async Task<ActionResult> CreatePOST(AdminEditViewModel model) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageIndexes)) { return Unauthorized(); } ValidateModel(model); if (_luceneIndexManager.Exists(model.IndexName)) { ModelState.AddModelError(nameof(AdminEditViewModel.IndexName), S["An index named {0} already exists."]); } if (!ModelState.IsValid) { return View(model); } try { // We call Rebuild in order to reset the index state cursor too in case the same index // name was also used previously. _luceneIndexingService.RebuildIndex(model.IndexName); await _luceneIndexingService.ProcessContentItemsAsync(); } catch (Exception e) { _notifier.Error(H["An error occurred while creating the index"]); Logger.LogError("An error occurred while creating an index", e); return View(model); } _notifier.Success(H["Index <em>{0}</em> created successfully", model.IndexName]); return RedirectToAction("Index"); } [HttpPost] public async Task<ActionResult> Reset(string id) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageIndexes)) { return Unauthorized(); } if (!_luceneIndexManager.Exists(id)) { return NotFound(); } _luceneIndexingService.ResetIndex(id); await _luceneIndexingService.ProcessContentItemsAsync(); _notifier.Success(H["Index <em>{0}</em> resetted successfully", id]); return RedirectToAction("Index"); } [HttpPost] public async Task<ActionResult> Rebuild(string id) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageIndexes)) { return Unauthorized(); } if (!_luceneIndexManager.Exists(id)) { return NotFound(); } _luceneIndexingService.RebuildIndex(id); await _luceneIndexingService.ProcessContentItemsAsync(); _notifier.Success(H["Index <em>{0}</em> rebuilt successfully", id]); return RedirectToAction("Index"); } [HttpPost] public async Task<ActionResult> Delete(AdminEditViewModel model) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageIndexes)) { return Unauthorized(); } if (!_luceneIndexManager.Exists(model.IndexName)) { return NotFound(); } try { _luceneIndexManager.DeleteIndex(model.IndexName); _notifier.Success(H["Index <em>{0}</em> deleted successfully", model.IndexName]); } catch(Exception e) { _notifier.Error(H["An error occurred while deleting the index"]); Logger.LogError("An error occurred while deleting the index " + model.IndexName, e); } return RedirectToAction("Index"); } public Task<IActionResult> Query(string indexName, string query, [FromServices] ITokenizer tokenizer) { query = String.IsNullOrWhiteSpace(query) ? "" : System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(query)); return Query(new AdminQueryViewModel { IndexName = indexName, DecodedQuery = query }, tokenizer); } [HttpPost] public async Task<IActionResult> Query(AdminQueryViewModel model, [FromServices] ITokenizer tokenizer) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageIndexes)) { return Unauthorized(); } model.Indices = _luceneIndexManager.List().ToArray(); // Can't query if there are no indices if (model.Indices.Length == 0) { return RedirectToAction("Index"); } if (String.IsNullOrEmpty(model.IndexName)) { model.IndexName = model.Indices[0]; } if (!_luceneIndexManager.Exists(model.IndexName)) { return NotFound(); } if (String.IsNullOrWhiteSpace(model.DecodedQuery)) { return View(model); } if (String.IsNullOrEmpty(model.Parameters)) { model.Parameters = "{ }"; } var luceneSettings = await _luceneIndexingService.GetLuceneSettingsAsync(); var stopwatch = new Stopwatch(); stopwatch.Start(); await _luceneIndexManager.SearchAsync(model.IndexName, async searcher => { var analyzer = _luceneAnalyzerManager.CreateAnalyzer("standardanalyzer"); var context = new LuceneQueryContext(searcher, LuceneSettings.DefaultVersion, analyzer); var tokenizedContent = tokenizer.Tokenize(model.DecodedQuery, JObject.Parse(model.Parameters)); try { var parameterizedQuery = JObject.Parse(tokenizedContent); var docs = await _queryService.SearchAsync(context, parameterizedQuery); model.Documents = docs.ScoreDocs.Select(hit => searcher.Doc(hit.Doc)).ToList(); } catch(Exception e) { Logger.LogError("Error while executing query: {0}", e.Message); ModelState.AddModelError(nameof(model.DecodedQuery), "Invalid query"); } stopwatch.Stop(); model.Elapsed = stopwatch.Elapsed; }); return View(model); } private void ValidateModel(AdminEditViewModel model) { if (String.IsNullOrWhiteSpace(model.IndexName)) { ModelState.AddModelError(nameof(AdminEditViewModel.IndexName), S["The index name is required."]); } else if (model.IndexName.ToSafeName() != model.IndexName) { ModelState.AddModelError(nameof(AdminEditViewModel.IndexName), S["The index name contains unallowed chars."]); } } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.Synchronization { using System; using System.Runtime.CompilerServices; public sealed class WaitingRecord { // // HACK: We have a bug in the liveness of multi-pointer structure. We have to use a class instead. // //// public struct Holder : IDisposable public class Holder : IDisposable { // // State // ThreadImpl m_thread; Synchronization.WaitableObject m_waitableObject; SchedulerTime m_timeout; WaitingRecord m_wr; // // Constructor Methods // internal Holder() { } //// public Holder( ThreadImpl thread , //// Synchronization.WaitableObject waitableObject , //// SchedulerTime timeout ) //// { //// m_thread = thread; //// m_waitableObject = waitableObject; //// m_timeout = timeout; //// m_wr = null; //// } // // Helper Methods // public void Dispose() { if(m_wr != null) { using(SmartHandles.InterruptState.Disable()) { m_wr.Recycle(); m_thread = null; m_waitableObject = null; m_wr = null; } } } // // HACK: We have a bug in the liveness of multi-pointer structure. We have to use a class instead. Use this instead of the parametrized constructor. // public static Holder Get( ThreadImpl thread , Synchronization.WaitableObject waitableObject , SchedulerTime timeout ) { Holder hld = thread.m_holder; hld.m_thread = thread; hld.m_waitableObject = waitableObject; hld.m_timeout = timeout; hld.m_wr = null; return hld; } // // Access Methods // public bool ShouldTryToAcquire { get { return m_wr == null || m_wr.Processed == false; } } public bool RequestProcessed { get { // // We do two passes through the acquire phase. // // On the first pass, we don't allocate a WaitingRecord, we just try to acquire the resource. // If that fails, we allocate a WaitingRecord, connect it and // // On the second pass, we retry to acquire the resource and if that fails, we simply wait. // if(m_wr == null) { m_wr = WaitingRecord.GetInstance( m_thread, m_waitableObject, m_timeout ); using(SmartHandles.InterruptState.Disable()) { m_wr.Connect(); } return false; } else { m_wr.Wait(); return m_wr.Processed; } } } public bool RequestFulfilled { get { return m_wr.RequestFulfilled; } } } // // State // const int RecycleLimit = 32; static KernelList< WaitingRecord > s_recycledList; static int s_recycledCount; KernelNode< WaitingRecord > m_linkTowardSource; KernelNode< WaitingRecord > m_linkTowardTarget; ThreadImpl m_source; WaitableObject m_target; SchedulerTime m_timeout; bool m_processed; bool m_fulfilled; // // Constructor Methods // static WaitingRecord() { s_recycledList = new KernelList< WaitingRecord >(); while(s_recycledCount < RecycleLimit) { WaitingRecord wr = new WaitingRecord(); wr.Recycle(); } } private WaitingRecord() { m_linkTowardSource = new KernelNode< WaitingRecord >( this ); m_linkTowardTarget = new KernelNode< WaitingRecord >( this ); } // // Helper Methods // static WaitingRecord GetInstance( ThreadImpl source , WaitableObject target , SchedulerTime timeout ) { BugCheck.AssertInterruptsOn(); WaitingRecord wr = null; if(s_recycledCount > 0) { using(SmartHandles.InterruptState.Disable()) { KernelNode< WaitingRecord > node = s_recycledList.ExtractFirstNode(); if(node != null) { wr = node.Target; s_recycledCount--; } } } if(wr == null) { wr = new WaitingRecord(); } wr.m_source = source; wr.m_target = target; wr.m_timeout = timeout; return wr; } void Connect() { BugCheck.AssertInterruptsOff(); m_target.RegisterWait( m_linkTowardTarget ); m_source.RegisterWait( m_linkTowardSource ); } void Wait() { ThreadManager.Instance.SwitchToWait( this ); } void Recycle() { BugCheck.AssertInterruptsOff(); Disconnect(); if(s_recycledCount < RecycleLimit) { m_processed = false; s_recycledCount++; s_recycledList.InsertAtTail( m_linkTowardTarget ); } } void Disconnect() { BugCheck.AssertInterruptsOff(); if(m_linkTowardSource.IsLinked) { m_source.UnregisterWait( m_linkTowardSource ); } if(m_linkTowardTarget.IsLinked) { m_target.UnregisterWait( m_linkTowardTarget ); } m_target = null; m_source = null; } // // Access Methods // public ThreadImpl Source { get { return m_source; } } public WaitableObject Target { get { return m_target; } } public SchedulerTime Timeout { get { return m_timeout; } } public bool Processed { get { return m_processed; } } public bool RequestFulfilled { get { return m_fulfilled; } set { if(m_processed == false) { m_fulfilled = value; m_processed = true; Disconnect(); } } } } }
// Copyright (c) MOSA Project. Licensed under the New BSD License. using System; using System.Collections; using System.Collections.Generic; namespace Mosa.Compiler.Framework { /// <summary> /// Container class used to define the pipeline of a compiler. /// </summary> public sealed class CompilerPipeline : IEnumerable { #region Data members /// <summary> /// The stages in the compiler pipeline. /// </summary> private List<IPipelineStage> pipeline; #endregion Data members #region Construction /// <summary> /// Initializes a new instance of the <see cref="CompilerPipeline"/> class. /// </summary> public CompilerPipeline() { pipeline = new List<IPipelineStage>(); } #endregion Construction #region Properties /// <summary> /// Returns the number of stages in the compiler pipeline. /// </summary> public int Count { get { return pipeline.Count; } } /// <summary> /// Retrieves the indexed compilation stage. /// </summary> /// <param name="index">The index of the compilation stage to return.</param> /// <returns>The compilation stage at the requested index.</returns> public IPipelineStage this[int index] { get { return pipeline[index]; } } #endregion Properties #region Methods /// <summary> /// Adds the specified stage. /// </summary> /// <param name="stage">The stage.</param> public void Add(IPipelineStage stage) { if (stage == null) throw new ArgumentNullException(@"stage"); pipeline.Add(stage); } /// <summary> /// Inserts the stage after StageType /// </summary> /// <typeparam name="StageType">The type of stage.</typeparam> /// <param name="stage">The stage.</param> public void InsertAfterFirst<StageType>(IPipelineStage stage) where StageType : class, IPipelineStage { if (stage == null) throw new ArgumentNullException(@"stage"); for (int i = 0; i < pipeline.Count; i++) { StageType result = pipeline[i] as StageType; if (result != null) { pipeline.Insert(i + 1, stage); return; } } throw new ArgumentNullException(@"missing stage to insert at"); } /// <summary> /// Inserts the stage after StageType /// </summary> /// <typeparam name="StageType">The type of stage.</typeparam> /// <param name="stage">The stage.</param> public void InsertAfterLast<StageType>(IPipelineStage stage) where StageType : class, IPipelineStage { if (stage == null) throw new ArgumentNullException(@"stage"); for (int i = pipeline.Count - 1; i >= 0; i--) { StageType result = pipeline[i] as StageType; if (result != null) { pipeline.Insert(i + 1, stage); return; } } throw new ArgumentNullException(@"missing stage to insert at"); } /// <summary> /// Inserts the stage after StageType /// </summary> /// <typeparam name="StageType">The type of stage.</typeparam> /// <param name="stages">The stages.</param> public void InsertAfterLast<StageType>(IEnumerable<IPipelineStage> stages) where StageType : class, IPipelineStage { if (stages == null) throw new ArgumentNullException(@"stage"); for (int i = pipeline.Count - 1; i >= 0; i--) { StageType result = pipeline[i] as StageType; if (result != null) { pipeline.InsertRange(i + 1, stages); return; } } throw new ArgumentNullException(@"missing stage to insert at"); } /// <summary> /// Inserts the stage before StageType /// </summary> /// <typeparam name="StageType">The type of stage.</typeparam> /// <param name="stage">The stage.</param> public void InsertBefore<StageType>(IPipelineStage stage) where StageType : class, IPipelineStage { if (stage == null) throw new ArgumentNullException(@"stage"); for (int i = 0; i < pipeline.Count; i++) { StageType result = pipeline[i] as StageType; if (result != null) { pipeline.Insert(i, stage); return; } } throw new ArgumentNullException(@"missing stage to insert before"); } /// <summary> /// Adds the specified stages. /// </summary> /// <param name="stages">The stages.</param> /// <exception cref="System.ArgumentNullException">@stages</exception> public void Add(IEnumerable<IPipelineStage> stages) { if (stages == null) throw new ArgumentNullException(@"stages"); foreach (var stage in stages) if (stage != null) Add(stage); } /// <summary> /// Clears this instance. /// </summary> public void Clear() { pipeline.Clear(); } /// <summary> /// Removes the specified stage. /// </summary> /// <param name="stage">The stage.</param> public void Remove(IPipelineStage stage) { if (stage == null) throw new ArgumentNullException(@"stage"); pipeline.Remove(stage); } /// <summary> /// Gets the position. /// </summary> /// <param name="stage">The stage.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">@stage</exception> public int GetPosition(IPipelineStage stage) { if (stage == null) throw new ArgumentNullException(@"stage"); for (int i = 0; i < pipeline.Count; i++) { if (object.ReferenceEquals(pipeline[i], stage)) return i; } throw new ArgumentNullException(@"missing stage to insert before"); } #endregion Methods #region IEnumerable members /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection. /// </returns> System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return pipeline.GetEnumerator(); } #endregion IEnumerable members /// <summary> /// Finds this instance. /// </summary> /// <typeparam name="StageType">The type of the tage type.</typeparam> /// <returns></returns> public StageType FindFirst<StageType>() where StageType : class { StageType result = default(StageType); foreach (object o in pipeline) { result = o as StageType; if (result != null) break; } return result; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //----------------------------------------------------------------------- // <copyright file="IntrinsicFunctions.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <summary>Definition of functions which can be accessed from MSBuild files.</summary> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Text; using Microsoft.Build.BuildEngine.Shared; using Microsoft.Win32; using System.IO; namespace Microsoft.Build.BuildEngine { /// <summary> /// The Intrinsic class provides static methods that can be accessed from MSBuild's /// property functions using $([MSBuild]::Function(x,y)) /// </summary> internal static class IntrinsicFunctions { /// <summary> /// Add two doubles /// </summary> internal static double Add(double a, double b) { return a + b; } /// <summary> /// Add two longs /// </summary> internal static long Add(long a, long b) { return a + b; } /// <summary> /// Subtract two doubles /// </summary> internal static double Subtract(double a, double b) { return a - b; } /// <summary> /// Subtract two longs /// </summary> internal static long Subtract(long a, long b) { return a - b; } /// <summary> /// Multiply two doubles /// </summary> internal static double Multiply(double a, double b) { return a * b; } /// <summary> /// Multiply two longs /// </summary> internal static long Multiply(long a, long b) { return a * b; } /// <summary> /// Divide two doubles /// </summary> internal static double Divide(double a, double b) { return a / b; } /// <summary> /// Divide two longs /// </summary> internal static long Divide(long a, long b) { return a / b; } /// <summary> /// Modulo two doubles /// </summary> internal static double Modulo(double a, double b) { return a % b; } /// <summary> /// Modulo two longs /// </summary> internal static long Modulo(long a, long b) { return a % b; } /// <summary> /// Escape the string according to MSBuild's escaping rules /// </summary> internal static string Escape(string unescaped) { return EscapingUtilities.Escape(unescaped); } /// <summary> /// Unescape the string according to MSBuild's escaping rules /// </summary> internal static string Unescape(string escaped) { return EscapingUtilities.UnescapeAll(escaped); } /// <summary> /// Perform a bitwise OR on the first and second (first | second) /// </summary> internal static int BitwiseOr(int first, int second) { return first | second; } /// <summary> /// Perform a bitwise AND on the first and second (first &amp; second) /// </summary> internal static int BitwiseAnd(int first, int second) { return first & second; } /// <summary> /// Perform a bitwise XOR on the first and second (first ^ second) /// </summary> internal static int BitwiseXor(int first, int second) { return first ^ second; } /// <summary> /// Perform a bitwise NOT on the first and second (~first) /// </summary> internal static int BitwiseNot(int first) { return ~first; } /// <summary> /// Get the value of the registry key and value, default value is null /// </summary> internal static object GetRegistryValue(string keyName, string valueName) { return Registry.GetValue(keyName, valueName, null /* null to match the $(Regsitry:XYZ@ZBC) behaviour */); } /// <summary> /// Get the value of the registry key and value /// </summary> internal static object GetRegistryValue(string keyName, string valueName, object defaultValue) { return Registry.GetValue(keyName, valueName, defaultValue); } /// <summary> /// Get the value of the registry key from one of the RegistryView's specified /// </summary> internal static object GetRegistryValueFromView(string keyName, string valueName, object defaultValue, params object[] views) { string subKeyName; // We will take on handing of default value // A we need to act on the null return from the GetValue call below // so we can keep searching other registry views object result = defaultValue; // If we haven't been passed any views, then we'll just use the default view if (views == null || views.Length == 0) { views = new object[] { RegistryView.Default }; } foreach (object viewObject in views) { string viewAsString = viewObject as string; if (viewAsString != null) { string typeLeafName = typeof(RegistryView).Name + "."; string typeFullName = typeof(RegistryView).FullName + "."; // We'll allow the user to specify the leaf or full type name on the RegistryView enum viewAsString = viewAsString.Replace(typeFullName, "").Replace(typeLeafName, ""); // This may throw - and that's fine as the user will receive a controlled version // of that error. RegistryView view = (RegistryView)Enum.Parse(typeof(RegistryView), viewAsString, true); using (RegistryKey key = GetBaseKeyFromKeyName(keyName, view, out subKeyName)) { if (key != null) { using (RegistryKey subKey = key.OpenSubKey(subKeyName, false)) { // If we managed to retrieve the subkey, then move onto locating the value if (subKey != null) { result = subKey.GetValue(valueName); } // We've found a value, so stop looking if (result != null) { break; } } } } } } // We will have either found a result or defaultValue if one wasn't found at this point return result; } /// <summary> /// Given the absolute location of a file, and a disc location, returns relative file path to that disk location. /// Throws UriFormatException. /// </summary> /// <param name="basePath"> /// The base path we want to relativize to. Must be absolute. /// Should <i>not</i> include a filename as the last segment will be interpreted as a directory. /// </param> /// <param name="path"> /// The path we need to make relative to basePath. The path can be either absolute path or a relative path in which case it is relative to the base path. /// If the path cannot be made relative to the base path (for example, it is on another drive), it is returned verbatim. /// </param> /// <returns>relative path (can be the full path)</returns> internal static string MakeRelative(string basePath, string path) { string result = FileUtilities.MakeRelative(basePath, path); return result; } /// <summary> /// Locate a file in either the directory specified or a location in the /// direcorty structure above that directory. /// </summary> internal static string GetDirectoryNameOfFileAbove(string startingDirectory, string fileName) { // Canonicalize our starting location string lookInDirectory = Path.GetFullPath(startingDirectory); do { // Construct the path that we will use to test against string possibleFileDirectory = Path.Combine(lookInDirectory, fileName); // If we successfully locate the file in the directory that we're // looking in, simply return that location. Otherwise we'll // keep moving up the tree. if (File.Exists(possibleFileDirectory)) { // We've found the file, return the directory we found it in return lookInDirectory; } else { // GetDirectoryName will return null when we reach the root // terminating our search lookInDirectory = Path.GetDirectoryName(lookInDirectory); } } while (lookInDirectory != null); // When we didn't find the location, then return an empty string return String.Empty; } /// <summary> /// Return the string in parameter 'defaultValue' only if parameter 'conditionValue' is empty /// else, return the value conditionValue /// </summary> internal static string ValueOrDefault(string conditionValue, string defaultValue) { if (String.IsNullOrEmpty(conditionValue)) { return defaultValue; } else { return conditionValue; } } /// <summary> /// Returns true if a task host exists that can service the requested runtime and architecture /// values, and false otherwise. /// </summary> /// <comments> /// The old engine ignores the concept of the task host entirely, so it shouldn't really /// matter what we return. So we return "true" because regardless of the task host parameters, /// the task will be successfully run (in-proc). /// </comments> internal static bool DoesTaskHostExist(string runtime, string architecture) { return true; } #region Debug only intrinsics /// <summary> /// returns if the string contains escaped wildcards /// </summary> internal static List<string> __GetListTest() { return new List<string> { "A", "B", "C", "D" }; } #endregion /// <summary> /// Following function will parse a keyName and returns the basekey for it. /// It will also store the subkey name in the out parameter. /// If the keyName is not valid, we will throw ArgumentException. /// The return value shouldn't be null. /// Taken from: \ndp\clr\src\BCL\Microsoft\Win32\Registry.cs /// </summary> private static RegistryKey GetBaseKeyFromKeyName(string keyName, RegistryView view, out string subKeyName) { if (keyName == null) { throw new ArgumentNullException("keyName"); } string basekeyName; int i = keyName.IndexOf('\\'); if (i != -1) { basekeyName = keyName.Substring(0, i).ToUpper(System.Globalization.CultureInfo.InvariantCulture); } else { basekeyName = keyName.ToUpper(System.Globalization.CultureInfo.InvariantCulture); } RegistryKey basekey = null; switch (basekeyName) { case "HKEY_CURRENT_USER": basekey = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, view); break; case "HKEY_LOCAL_MACHINE": basekey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, view); break; case "HKEY_CLASSES_ROOT": basekey = RegistryKey.OpenBaseKey(RegistryHive.ClassesRoot, view); break; case "HKEY_USERS": basekey = RegistryKey.OpenBaseKey(RegistryHive.Users, view); break; case "HKEY_PERFORMANCE_DATA": basekey = RegistryKey.OpenBaseKey(RegistryHive.PerformanceData, view); break; case "HKEY_CURRENT_CONFIG": basekey = RegistryKey.OpenBaseKey(RegistryHive.CurrentConfig, view); break; case "HKEY_DYN_DATA": basekey = RegistryKey.OpenBaseKey(RegistryHive.DynData, view); break; default: ErrorUtilities.ThrowArgument(keyName); break; } if (i == -1 || i == keyName.Length) { subKeyName = string.Empty; } else { subKeyName = keyName.Substring(i + 1, keyName.Length - i - 1); } return basekey; } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.VpcAccess.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedVpcAccessServiceClientTest { [xunit::FactAttribute] public void GetConnectorRequestObject() { moq::Mock<VpcAccessService.VpcAccessServiceClient> mockGrpcClient = new moq::Mock<VpcAccessService.VpcAccessServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetConnectorRequest request = new GetConnectorRequest { ConnectorName = ConnectorName.FromProjectLocationConnector("[PROJECT]", "[LOCATION]", "[CONNECTOR]"), }; Connector expectedResponse = new Connector { ConnectorName = ConnectorName.FromProjectLocationConnector("[PROJECT]", "[LOCATION]", "[CONNECTOR]"), Network = "networkd22ce091", IpCidrRange = "ip_cidr_range745a04d3", State = Connector.Types.State.Unspecified, MinThroughput = -1306078102, MaxThroughput = 1609945563, ConnectedProjects = { "connected_projects7e2fb014", }, Subnet = new Connector.Types.Subnet(), }; mockGrpcClient.Setup(x => x.GetConnector(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); VpcAccessServiceClient client = new VpcAccessServiceClientImpl(mockGrpcClient.Object, null); Connector response = client.GetConnector(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetConnectorRequestObjectAsync() { moq::Mock<VpcAccessService.VpcAccessServiceClient> mockGrpcClient = new moq::Mock<VpcAccessService.VpcAccessServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetConnectorRequest request = new GetConnectorRequest { ConnectorName = ConnectorName.FromProjectLocationConnector("[PROJECT]", "[LOCATION]", "[CONNECTOR]"), }; Connector expectedResponse = new Connector { ConnectorName = ConnectorName.FromProjectLocationConnector("[PROJECT]", "[LOCATION]", "[CONNECTOR]"), Network = "networkd22ce091", IpCidrRange = "ip_cidr_range745a04d3", State = Connector.Types.State.Unspecified, MinThroughput = -1306078102, MaxThroughput = 1609945563, ConnectedProjects = { "connected_projects7e2fb014", }, Subnet = new Connector.Types.Subnet(), }; mockGrpcClient.Setup(x => x.GetConnectorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Connector>(stt::Task.FromResult(expectedResponse), null, null, null, null)); VpcAccessServiceClient client = new VpcAccessServiceClientImpl(mockGrpcClient.Object, null); Connector responseCallSettings = await client.GetConnectorAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Connector responseCancellationToken = await client.GetConnectorAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetConnector() { moq::Mock<VpcAccessService.VpcAccessServiceClient> mockGrpcClient = new moq::Mock<VpcAccessService.VpcAccessServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetConnectorRequest request = new GetConnectorRequest { ConnectorName = ConnectorName.FromProjectLocationConnector("[PROJECT]", "[LOCATION]", "[CONNECTOR]"), }; Connector expectedResponse = new Connector { ConnectorName = ConnectorName.FromProjectLocationConnector("[PROJECT]", "[LOCATION]", "[CONNECTOR]"), Network = "networkd22ce091", IpCidrRange = "ip_cidr_range745a04d3", State = Connector.Types.State.Unspecified, MinThroughput = -1306078102, MaxThroughput = 1609945563, ConnectedProjects = { "connected_projects7e2fb014", }, Subnet = new Connector.Types.Subnet(), }; mockGrpcClient.Setup(x => x.GetConnector(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); VpcAccessServiceClient client = new VpcAccessServiceClientImpl(mockGrpcClient.Object, null); Connector response = client.GetConnector(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetConnectorAsync() { moq::Mock<VpcAccessService.VpcAccessServiceClient> mockGrpcClient = new moq::Mock<VpcAccessService.VpcAccessServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetConnectorRequest request = new GetConnectorRequest { ConnectorName = ConnectorName.FromProjectLocationConnector("[PROJECT]", "[LOCATION]", "[CONNECTOR]"), }; Connector expectedResponse = new Connector { ConnectorName = ConnectorName.FromProjectLocationConnector("[PROJECT]", "[LOCATION]", "[CONNECTOR]"), Network = "networkd22ce091", IpCidrRange = "ip_cidr_range745a04d3", State = Connector.Types.State.Unspecified, MinThroughput = -1306078102, MaxThroughput = 1609945563, ConnectedProjects = { "connected_projects7e2fb014", }, Subnet = new Connector.Types.Subnet(), }; mockGrpcClient.Setup(x => x.GetConnectorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Connector>(stt::Task.FromResult(expectedResponse), null, null, null, null)); VpcAccessServiceClient client = new VpcAccessServiceClientImpl(mockGrpcClient.Object, null); Connector responseCallSettings = await client.GetConnectorAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Connector responseCancellationToken = await client.GetConnectorAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetConnectorResourceNames() { moq::Mock<VpcAccessService.VpcAccessServiceClient> mockGrpcClient = new moq::Mock<VpcAccessService.VpcAccessServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetConnectorRequest request = new GetConnectorRequest { ConnectorName = ConnectorName.FromProjectLocationConnector("[PROJECT]", "[LOCATION]", "[CONNECTOR]"), }; Connector expectedResponse = new Connector { ConnectorName = ConnectorName.FromProjectLocationConnector("[PROJECT]", "[LOCATION]", "[CONNECTOR]"), Network = "networkd22ce091", IpCidrRange = "ip_cidr_range745a04d3", State = Connector.Types.State.Unspecified, MinThroughput = -1306078102, MaxThroughput = 1609945563, ConnectedProjects = { "connected_projects7e2fb014", }, Subnet = new Connector.Types.Subnet(), }; mockGrpcClient.Setup(x => x.GetConnector(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); VpcAccessServiceClient client = new VpcAccessServiceClientImpl(mockGrpcClient.Object, null); Connector response = client.GetConnector(request.ConnectorName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetConnectorResourceNamesAsync() { moq::Mock<VpcAccessService.VpcAccessServiceClient> mockGrpcClient = new moq::Mock<VpcAccessService.VpcAccessServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetConnectorRequest request = new GetConnectorRequest { ConnectorName = ConnectorName.FromProjectLocationConnector("[PROJECT]", "[LOCATION]", "[CONNECTOR]"), }; Connector expectedResponse = new Connector { ConnectorName = ConnectorName.FromProjectLocationConnector("[PROJECT]", "[LOCATION]", "[CONNECTOR]"), Network = "networkd22ce091", IpCidrRange = "ip_cidr_range745a04d3", State = Connector.Types.State.Unspecified, MinThroughput = -1306078102, MaxThroughput = 1609945563, ConnectedProjects = { "connected_projects7e2fb014", }, Subnet = new Connector.Types.Subnet(), }; mockGrpcClient.Setup(x => x.GetConnectorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Connector>(stt::Task.FromResult(expectedResponse), null, null, null, null)); VpcAccessServiceClient client = new VpcAccessServiceClientImpl(mockGrpcClient.Object, null); Connector responseCallSettings = await client.GetConnectorAsync(request.ConnectorName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Connector responseCancellationToken = await client.GetConnectorAsync(request.ConnectorName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
/* * 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.Reflection; using NUnit.Framework; using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Region.Framework.Scenes; using OpenSim.Tests.Common; using OpenSim.Tests.Common.Mock; using OpenSim.Tests.Common.Setup; using log4net; namespace OpenSim.Region.Framework.Scenes.Tests { /// <summary> /// Linking tests /// </summary> [TestFixture] public class SceneObjectLinkingTests { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); [Test] public void TestLinkDelink2SceneObjects() { TestHelper.InMethod(); bool debugtest = false; Scene scene = SceneSetupHelpers.SetupScene(); SceneObjectPart part1 = SceneSetupHelpers.AddSceneObject(scene); SceneObjectGroup grp1 = part1.ParentGroup; SceneObjectPart part2 = SceneSetupHelpers.AddSceneObject(scene); SceneObjectGroup grp2 = part2.ParentGroup; grp1.AbsolutePosition = new Vector3(10, 10, 10); grp2.AbsolutePosition = Vector3.Zero; // <90,0,0> grp1.Rotation = (Quaternion.CreateFromEulers(90 * Utils.DEG_TO_RAD, 0, 0)); // <180,0,0> grp2.UpdateGroupRotationR(Quaternion.CreateFromEulers(180 * Utils.DEG_TO_RAD, 0, 0)); // Required for linking grp1.RootPart.UpdateFlag = 0; grp2.RootPart.UpdateFlag = 0; // Link grp2 to grp1. part2 becomes child prim to grp1. grp2 is eliminated. grp1.LinkToGroup(grp2); // FIXME: Can't do this test yet since group 2 still has its root part! We can't yet null this since // it might cause SOG.ProcessBackup() to fail due to the race condition. This really needs to be fixed. Assert.That(grp2.IsDeleted, "SOG 2 was not registered as deleted after link."); Assert.That(grp2.Children.Count, Is.EqualTo(0), "Group 2 still contained children after delink."); Assert.That(grp1.Children.Count == 2); if (debugtest) { m_log.Debug("parts: " + grp1.Children.Count); m_log.Debug("Group1: Pos:"+grp1.AbsolutePosition+", Rot:"+grp1.Rotation); m_log.Debug("Group1: Prim1: OffsetPosition:"+ part1.OffsetPosition+", OffsetRotation:"+part1.RotationOffset); m_log.Debug("Group1: Prim2: OffsetPosition:"+part2.OffsetPosition+", OffsetRotation:"+part2.RotationOffset); } // root part should have no offset position or rotation Assert.That(part1.OffsetPosition == Vector3.Zero && part1.RotationOffset == Quaternion.Identity, "root part should have no offset position or rotation"); // offset position should be root part position - part2.absolute position. Assert.That(part2.OffsetPosition == new Vector3(-10, -10, -10), "offset position should be root part position - part2.absolute position."); float roll = 0; float pitch = 0; float yaw = 0; // There's a euler anomoly at 180, 0, 0 so expect 180 to turn into -180. part1.RotationOffset.GetEulerAngles(out roll, out pitch, out yaw); Vector3 rotEuler1 = new Vector3(roll * Utils.RAD_TO_DEG, pitch * Utils.RAD_TO_DEG, yaw * Utils.RAD_TO_DEG); if (debugtest) m_log.Debug(rotEuler1); part2.RotationOffset.GetEulerAngles(out roll, out pitch, out yaw); Vector3 rotEuler2 = new Vector3(roll * Utils.RAD_TO_DEG, pitch * Utils.RAD_TO_DEG, yaw * Utils.RAD_TO_DEG); if (debugtest) m_log.Debug(rotEuler2); Assert.That(rotEuler2.ApproxEquals(new Vector3(-180, 0, 0), 0.001f) || rotEuler2.ApproxEquals(new Vector3(180, 0, 0), 0.001f), "Not exactly sure what this is asserting..."); // Delink part 2 grp1.DelinkFromGroup(part2.LocalId); if (debugtest) m_log.Debug("Group2: Prim2: OffsetPosition:" + part2.AbsolutePosition + ", OffsetRotation:" + part2.RotationOffset); Assert.That(grp1.Children.Count, Is.EqualTo(1), "Group 1 still contained part2 after delink."); Assert.That(part2.AbsolutePosition == Vector3.Zero, "The absolute position should be zero"); } [Test] public void TestLinkDelink2groups4SceneObjects() { TestHelper.InMethod(); bool debugtest = false; Scene scene = SceneSetupHelpers.SetupScene(); SceneObjectPart part1 = SceneSetupHelpers.AddSceneObject(scene); SceneObjectGroup grp1 = part1.ParentGroup; SceneObjectPart part2 = SceneSetupHelpers.AddSceneObject(scene); SceneObjectGroup grp2 = part2.ParentGroup; SceneObjectPart part3 = SceneSetupHelpers.AddSceneObject(scene); SceneObjectGroup grp3 = part3.ParentGroup; SceneObjectPart part4 = SceneSetupHelpers.AddSceneObject(scene); SceneObjectGroup grp4 = part4.ParentGroup; grp1.AbsolutePosition = new Vector3(10, 10, 10); grp2.AbsolutePosition = Vector3.Zero; grp3.AbsolutePosition = new Vector3(20, 20, 20); grp4.AbsolutePosition = new Vector3(40, 40, 40); // <90,0,0> grp1.Rotation = (Quaternion.CreateFromEulers(90 * Utils.DEG_TO_RAD, 0, 0)); // <180,0,0> grp2.UpdateGroupRotationR(Quaternion.CreateFromEulers(180 * Utils.DEG_TO_RAD, 0, 0)); // <270,0,0> grp3.Rotation = (Quaternion.CreateFromEulers(270 * Utils.DEG_TO_RAD, 0, 0)); // <0,90,0> grp4.UpdateGroupRotationR(Quaternion.CreateFromEulers(0, 90 * Utils.DEG_TO_RAD, 0)); // Required for linking grp1.RootPart.UpdateFlag = 0; grp2.RootPart.UpdateFlag = 0; grp3.RootPart.UpdateFlag = 0; grp4.RootPart.UpdateFlag = 0; // Link grp2 to grp1. part2 becomes child prim to grp1. grp2 is eliminated. grp1.LinkToGroup(grp2); // Link grp4 to grp3. grp3.LinkToGroup(grp4); // At this point we should have 4 parts total in two groups. Assert.That(grp1.Children.Count == 2, "Group1 children count should be 2"); Assert.That(grp2.IsDeleted, "Group 2 was not registered as deleted after link."); Assert.That(grp2.Children.Count, Is.EqualTo(0), "Group 2 still contained parts after delink."); Assert.That(grp3.Children.Count == 2, "Group3 children count should be 2"); Assert.That(grp4.IsDeleted, "Group 4 was not registered as deleted after link."); Assert.That(grp4.Children.Count, Is.EqualTo(0), "Group 4 still contained parts after delink."); if (debugtest) { m_log.Debug("--------After Link-------"); m_log.Debug("Group1: parts:" + grp1.Children.Count); m_log.Debug("Group1: Pos:"+grp1.AbsolutePosition+", Rot:"+grp1.Rotation); m_log.Debug("Group1: Prim1: OffsetPosition:" + part1.OffsetPosition + ", OffsetRotation:" + part1.RotationOffset); m_log.Debug("Group1: Prim2: OffsetPosition:"+part2.OffsetPosition+", OffsetRotation:"+ part2.RotationOffset); m_log.Debug("Group3: parts:"+grp3.Children.Count); m_log.Debug("Group3: Pos:"+grp3.AbsolutePosition+", Rot:"+grp3.Rotation); m_log.Debug("Group3: Prim1: OffsetPosition:"+part3.OffsetPosition+", OffsetRotation:"+part3.RotationOffset); m_log.Debug("Group3: Prim2: OffsetPosition:"+part4.OffsetPosition+", OffsetRotation:"+part4.RotationOffset); } // Required for linking grp1.RootPart.UpdateFlag = 0; grp3.RootPart.UpdateFlag = 0; // root part should have no offset position or rotation Assert.That(part1.OffsetPosition == Vector3.Zero && part1.RotationOffset == Quaternion.Identity, "root part should have no offset position or rotation (again)"); // offset position should be root part position - part2.absolute position. Assert.That(part2.OffsetPosition == new Vector3(-10, -10, -10), "offset position should be root part position - part2.absolute position (again)"); float roll = 0; float pitch = 0; float yaw = 0; // There's a euler anomoly at 180, 0, 0 so expect 180 to turn into -180. part1.RotationOffset.GetEulerAngles(out roll, out pitch, out yaw); Vector3 rotEuler1 = new Vector3(roll * Utils.RAD_TO_DEG, pitch * Utils.RAD_TO_DEG, yaw * Utils.RAD_TO_DEG); if (debugtest) m_log.Debug(rotEuler1); part2.RotationOffset.GetEulerAngles(out roll, out pitch, out yaw); Vector3 rotEuler2 = new Vector3(roll * Utils.RAD_TO_DEG, pitch * Utils.RAD_TO_DEG, yaw * Utils.RAD_TO_DEG); if (debugtest) m_log.Debug(rotEuler2); Assert.That(rotEuler2.ApproxEquals(new Vector3(-180, 0, 0), 0.001f) || rotEuler2.ApproxEquals(new Vector3(180, 0, 0), 0.001f), "Not sure what this assertion is all about..."); // Now we're linking the first group to the third group. This will make the first group child parts of the third one. grp3.LinkToGroup(grp1); // Delink parts 2 and 3 grp3.DelinkFromGroup(part2.LocalId); grp3.DelinkFromGroup(part3.LocalId); if (debugtest) { m_log.Debug("--------After De-Link-------"); m_log.Debug("Group1: parts:" + grp1.Children.Count); m_log.Debug("Group1: Pos:" + grp1.AbsolutePosition + ", Rot:" + grp1.Rotation); m_log.Debug("Group1: Prim1: OffsetPosition:" + part1.OffsetPosition + ", OffsetRotation:" + part1.RotationOffset); m_log.Debug("Group1: Prim2: OffsetPosition:" + part2.OffsetPosition + ", OffsetRotation:" + part2.RotationOffset); m_log.Debug("Group3: parts:" + grp3.Children.Count); m_log.Debug("Group3: Pos:" + grp3.AbsolutePosition + ", Rot:" + grp3.Rotation); m_log.Debug("Group3: Prim1: OffsetPosition:" + part3.OffsetPosition + ", OffsetRotation:" + part3.RotationOffset); m_log.Debug("Group3: Prim2: OffsetPosition:" + part4.OffsetPosition + ", OffsetRotation:" + part4.RotationOffset); } Assert.That(part2.AbsolutePosition == Vector3.Zero, "Badness 1"); Assert.That(part4.OffsetPosition == new Vector3(20, 20, 20), "Badness 2"); Quaternion compareQuaternion = new Quaternion(0, 0.7071068f, 0, 0.7071068f); Assert.That((part4.RotationOffset.X - compareQuaternion.X < 0.00003) && (part4.RotationOffset.Y - compareQuaternion.Y < 0.00003) && (part4.RotationOffset.Z - compareQuaternion.Z < 0.00003) && (part4.RotationOffset.W - compareQuaternion.W < 0.00003), "Badness 3"); } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using IdSharp.Common.Utils; namespace IdSharp.Tagging.VorbisComment { /// <summary> /// Vorbis Comment /// </summary> public class VorbisComment : IVorbisComment { private static readonly byte[] FLAC_MARKER = Encoding.ASCII.GetBytes("fLaC"); private readonly NameValueList _items = new NameValueList(); private string _vendor = string.Empty; private List<FlacMetaDataBlock> _metaDataBlockList; private class InternalInfo { public int OrigVorbisCommentSize = 0; public int OrigPaddingSize = 0; public FileType? FileType = null; public string Vendor = null; public IEnumerable<FlacMetaDataBlock> MetaDataBlockList = null; } private enum FileType { OggVorbis, Flac } /// <summary> /// Initializes a new instance of the <see cref="VorbisComment"/> class. /// </summary> /// <param name="path">The path of the file.</param> public VorbisComment(string path) { if (string.IsNullOrEmpty(path)) throw new ArgumentNullException("path"); Read(path); } /// <summary> /// Initializes a new instance of the <see cref="VorbisComment"/> class. /// </summary> /// <param name="stream">The stream.</param> public VorbisComment(Stream stream) { if (stream == null) throw new ArgumentNullException("stream"); Read(stream); } private VorbisComment() { } /// <summary> /// Gets the vendor specified in the Vorbis Comment header. /// </summary> /// <value>The vendor specified in the Vorbis Comment header..</value> public string Vendor { get { return _vendor; } } /// <summary> /// Gets or sets the artist. /// </summary> /// <value>The artist.</value> public string Artist { get { return _items.GetValue("ARTIST"); } set { _items.SetValue("ARTIST", value); } } /// <summary> /// Gets or sets the album. /// </summary> /// <value>The album.</value> public string Album { get { return _items.GetValue("ALBUM"); } set { _items.SetValue("ALBUM", value); } } /// <summary> /// Gets or sets the title. /// </summary> /// <value>The title.</value> public string Title { get { return _items.GetValue("TITLE"); } set { _items.SetValue("TITLE", value); } } /// <summary> /// Gets or sets the year. /// </summary> /// <value>The year.</value> public string Year { get { string value = _items.GetValue("DATE"); if (string.IsNullOrEmpty(value)) value = _items.GetValue("YEAR"); return value; } set { _items.SetValue("DATE", value); } } /// <summary> /// Gets or sets the genre. /// </summary> /// <value>The genre.</value> public string Genre { get { return _items.GetValue("GENRE"); } set { _items.SetValue("GENRE", value); } } /// <summary> /// Gets or sets the track number. /// </summary> /// <value>The track number.</value> public string TrackNumber { get { return _items.GetValue("TRACKNUMBER"); } set { _items.SetValue("TRACKNUMBER", value); } } /// <summary> /// Gets or sets the comment. /// </summary> /// <value>The comment.</value> public string Comment { get { return _items.GetValue("COMMENT"); } set { _items.SetValue("COMMENT", value); } } /// <summary> /// Gets the Name/Value item list. /// </summary> /// <value>The Name/Value item list.</value> public NameValueList Items { get { return _items; } } /// <summary> /// Writes the tag. /// </summary> /// <param name="path">The path.</param> public void Save(string path) { VorbisComment vorbisComment = new VorbisComment(); InternalInfo info; using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { info = vorbisComment.ReadTagInternal(fs); } _vendor = info.Vendor; // keep the vendor of the original file, don't copy it from another source if (string.IsNullOrEmpty(_vendor)) { _vendor = "idsharp library"; } if (info.FileType == FileType.Flac) { WriteTagFlac(path, info); } /*else if (info.FileType == FileType.OggVorbis) { }*/ else { throw new InvalidDataException(String.Format("File '{0}' is not a valid FLAC or Ogg-Vorbis file", path)); } } /// <summary> /// Reads the tag. /// </summary> /// <param name="path">The path.</param> public void Read(string path) { try { using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { Read(fs); } } catch (InvalidDataException ex) { throw new InvalidDataException(String.Format("Cannot read '{0}'", path), ex); } } /// <summary> /// Reads the tag. /// </summary> /// <param name="stream">The stream.</param> public void Read(Stream stream) { ReadTagInternal(stream); } private void WriteTagFlac(string path, InternalInfo targetFile) { // This will store the metadata blocks we're actually going to write List<FlacMetaDataBlock> myMetaDataBlocks = new List<FlacMetaDataBlock>(); // Get byte array of new vorbis comment block byte[] newTagArray; using (MemoryStream newTag = new MemoryStream()) { // Write vendor byte[] vendorBytes = Encoding.UTF8.GetBytes(_vendor); newTag.WriteInt32LittleEndian(vendorBytes.Length); newTag.Write(vendorBytes); // Remove dead items and replace commonly misnamed items foreach (NameValueItem item in new List<NameValueItem>(_items)) { if (string.IsNullOrEmpty(item.Value)) { _items.Remove(item); } else if (string.Compare(item.Name, "YEAR", true) == 0) { if (string.IsNullOrEmpty(_items.GetValue("DATE"))) _items.SetValue("DATE", item.Value); _items.Remove(item); } } // Write item count newTag.WriteInt32LittleEndian(_items.Count); // Write items foreach (NameValueItem item in _items) { if (string.IsNullOrEmpty(item.Value)) continue; byte[] keyBytes = Encoding.ASCII.GetBytes(item.Name); byte[] valueBytes = Encoding.UTF8.GetBytes(item.Value); newTag.WriteInt32LittleEndian(keyBytes.Length + 1 + valueBytes.Length); newTag.Write(keyBytes); newTag.WriteByte((byte)'='); newTag.Write(valueBytes); } newTagArray = newTag.ToArray(); } // 1. Get old size of metadata blocks. // 2. Find StreamInfo, SeekTable, and Padding blocks. // These blocks should occur only once. If not, an exception is thrown. The padding // block we don't really care about so no exception is thrown if it's duplicated. FlacMetaDataBlock paddingBlock = null; FlacMetaDataBlock streamInfoBlock = null; FlacMetaDataBlock seekTableBlock = null; long origMetaDataSize = 0; foreach (FlacMetaDataBlock metaDataBlock in targetFile.MetaDataBlockList) { origMetaDataSize += 4; // Identifier + Size origMetaDataSize += metaDataBlock.Size; if (metaDataBlock.BlockType == FlacMetaDataBlockType.Padding) { paddingBlock = metaDataBlock; } else if (metaDataBlock.BlockType == FlacMetaDataBlockType.StreamInfo) { if (streamInfoBlock != null) throw new InvalidDataException("Multiple stream info blocks"); streamInfoBlock = metaDataBlock; } else if (metaDataBlock.BlockType == FlacMetaDataBlockType.SeekTable) { if (seekTableBlock != null) throw new InvalidDataException("Multiple seek tables"); seekTableBlock = metaDataBlock; } } // No Padding block found, create one if (paddingBlock == null) { paddingBlock = new FlacMetaDataBlock(FlacMetaDataBlockType.Padding); paddingBlock.SetBlockDataZeroed(2000); } // Padding block found, adjust size else { // TODO: This is not entirely accurate, since we may be reading from one file // and writing to another. The other blocks need to be accounted for, however for // same file read/write this works. Not high priority. int adjustPadding = targetFile.OrigVorbisCommentSize - newTagArray.Length; int newSize = paddingBlock.Size + adjustPadding; if (newSize < 10) paddingBlock.SetBlockDataZeroed(2000); else paddingBlock.SetBlockDataZeroed(newSize); } // Set Vorbis-Comment block data FlacMetaDataBlock vorbisCommentBlock = new FlacMetaDataBlock(FlacMetaDataBlockType.VorbisComment); vorbisCommentBlock.SetBlockData(newTagArray); // Create list of blocks to write myMetaDataBlocks.Add(streamInfoBlock); // StreamInfo MUST be first if (seekTableBlock != null) myMetaDataBlocks.Add(seekTableBlock); // Add other blocks we read from the original file. foreach (FlacMetaDataBlock metaDataBlock in _metaDataBlockList) { if (metaDataBlock.BlockType == FlacMetaDataBlockType.Application || metaDataBlock.BlockType == FlacMetaDataBlockType.CueSheet || metaDataBlock.BlockType == FlacMetaDataBlockType.Picture) { myMetaDataBlocks.Add(metaDataBlock); } } // Add our new vorbis comment and padding blocks myMetaDataBlocks.Add(vorbisCommentBlock); myMetaDataBlocks.Add(paddingBlock); // Get new size of metadata blocks long newMetaDataSize = 0; foreach (FlacMetaDataBlock metaDataBlock in myMetaDataBlocks) { newMetaDataSize += 4; // Identifier + Size newMetaDataSize += metaDataBlock.Size; } // If the new metadata size is less than the original, increase the padding if (newMetaDataSize != origMetaDataSize) { int newPaddingSize = paddingBlock.Size + (int)(origMetaDataSize - newMetaDataSize); if (newPaddingSize > 0) { paddingBlock.SetBlockDataZeroed(newPaddingSize); // Get new size of metadata blocks newMetaDataSize = 0; foreach (FlacMetaDataBlock metaDataBlock in myMetaDataBlocks) { newMetaDataSize += 4; // Identifier + Size newMetaDataSize += metaDataBlock.Size; } } } string tempFilename = null; // no rewrite necessary if (newMetaDataSize == origMetaDataSize) { // } // rewrite necessary - grab a snickers. else if (newMetaDataSize > origMetaDataSize) { // rename tempFilename = PathUtils.GetTemporaryFileNameBasedOnFileName(path); File.Move(path, tempFilename); // open for read, open for write using (FileStream fsRead = File.Open(tempFilename, FileMode.Open, FileAccess.Read, FileShare.None)) using (FileStream fsWrite = File.Open(path, FileMode.CreateNew, FileAccess.Write, FileShare.None)) { // copy ID3v2 tag.. technically there shouldn't be one, but we don't want to destroy data int tmpID3v2TagSize = ID3v2.ID3v2Tag.GetTagSize(fsRead); if (tmpID3v2TagSize != 0) { byte[] id3v2 = fsRead.Read(tmpID3v2TagSize); fsWrite.Write(id3v2); } fsWrite.Write(FLAC_MARKER); // create blankspace byte[] blankSpace = new Byte[newMetaDataSize]; fsWrite.Write(blankSpace); fsRead.Seek(4 + origMetaDataSize, SeekOrigin.Current); byte[] buf = new byte[32768]; int bytesRead = fsRead.Read(buf, 0, 32768); while (bytesRead != 0) { fsWrite.Write(buf, 0, bytesRead); bytesRead = fsRead.Read(buf, 0, 32768); } } } // newMetaDataSize < origMetaDataSize is an error else { throw new Exception(String.Format("Internal Error: newMetaDataSize ({0}) < origMetaDataSize ({1})", newMetaDataSize, origMetaDataSize)); } using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) { // skip fLaC marker and ID3v2 tag size int tmpID3v2TagSize = ID3v2.ID3v2Tag.GetTagSize(fs); fs.Position = tmpID3v2TagSize + 4; byte blockType; foreach (FlacMetaDataBlock metaDataBlock in myMetaDataBlocks) { // always write padding last if (metaDataBlock == paddingBlock) continue; blockType = (byte)metaDataBlock.BlockType; fs.WriteByte(blockType); fs.WriteInt24(metaDataBlock.Size); fs.Write(metaDataBlock.BlockData); } // write padding, add stop bit to block type blockType = (byte)(paddingBlock.BlockType + 0x80); fs.WriteByte(blockType); fs.WriteInt24(paddingBlock.Size); fs.Write(paddingBlock.BlockData); } if (!string.IsNullOrEmpty(tempFilename)) File.Delete(tempFilename); } /*else if (mAudioFileTrack == AUDIO_OGG) { unsigned char *vc = new unsigned char[TagSize+10]; // Vendor size, Vendor sprintf(vc, "%c%c%c%c%s%c%c%c%c", mVendor.Length() & 0xFF, (mVendor.Length() >> 8) & 0xFF, (mVendor.Length() >> 16) & 0xFF, (mVendor.Length() >> 24) & 0xFF, mVendor.c_str(), \ elements & 0xFF, (elements >> 8) & 0xFF, (elements >> 16) & 0xFF, (elements >> 24) & 0xFF); unsigned long offset = 4 + mVendor.Length() + 4; if (Field != NULL) { Rewind(); do { String Vector = Field->ItemKey + "=" + Field->ItemValue; // Vector size, Vector vc[offset++] = Vector.Length() & 0xFF; vc[offset++] = (Vector.Length() >> 8) & 0xFF; vc[offset++] = (Vector.Length() >> 16) & 0xFF; vc[offset++] = (Vector.Length() >> 24) & 0xFF; for (i=0; i<Vector.Length(); i++) { vc[offset++] = Vector.c_str()[i]; } } while (this->NextField()); } if (NewPaddingSize > 3) { NewPaddingSize -= 1; fseek(fp, mvcoffset, SEEK_SET); fwrite(vc, offset, 1, fp); fputc(0x01, fp); for (i=0; i<NewPaddingSize; i++) fputc(0x00, fp); } else { fclose(fp); sprintf(buf, "%s__tmpaudio%lu", DirTrunc(Filename), releasetotalcount+16); if (rename(Filename.c_str(), buf) != 0) { String msg = ""; fp = fopen(buf, "rb"); if (fp != NULL) { fclose(fp); msg = String((char *)buf) + " exists; "; throw Exception(String(msg + "rename(\"" + FilenameTrunc(Filename) + "\", \"" + String(FilenameTrunc((char *)buf)) + "\"); failed").c_str()); } else { msg = String((char *)buf) + " does not exist; "; fp = fopen(buf, "wb"); if (fp == NULL) { msg = "cant open " + String((char *)buf) + "; "; throw Exception(String(msg + "rename(\"" + FilenameTrunc(Filename) + "\", \"" + String(FilenameTrunc((char *)buf)) + "\"); failed").c_str()); } FILE *ren = fopen(Filename.c_str(), "rb"); if (ren == NULL) { msg = Filename + " does not exist; "; throw Exception(String(msg + "rename(\"" + FilenameTrunc(Filename) + "\", \"" + String(FilenameTrunc((char *)buf)) + "\"); failed").c_str()); } iRead = fread(buf, 1, cuiReadBufSize, ren); while (iRead) { fwrite(buf, iRead, 1, fp); iRead = fread(buf, 1, cuiReadBufSize, ren); } fclose(fp); fclose(ren); } sprintf(buf, "%s__tmpaudio%lu", DirTrunc(Filename), releasetotalcount+16); } fp = fopen(buf, "rb"); out = fopen(Filename.c_str(), "wb+"); unsigned long curpos = 0; step = "initial read"; iRead = fread(buf, 1, cuiReadBufSize, fp); while (iRead) { curpos += iRead; if (curpos > lSPageStart) { iRead -= (curpos - lSPageStart); fwrite(buf, iRead, 1, out); break; } else { fwrite(buf, iRead, 1, out); iRead = fread(buf, 1, cuiReadBufSize, fp); } } step = "read second page header"; fseek(fp, lSPageStart, SEEK_SET); fread(buf, 1, 27, fp); buf[22] = 0; // clear CRC buf[23] = 0; buf[24] = 0; buf[25] = 0; step = "set up new lace vals"; int origlace = ((mOrigVorbisCommentSize + mOrigPaddingSize + 7) / 255) + 1; int newlace = ((offset + 1000 + 8) / 255) + 1; int oldlace = buf[26]; buf[26] += (newlace - origlace); step = "output header"; fwrite(buf, 27, 1, out); step = "output new lacing vals"; int toffset = offset + 1000 + 8; // 0x03 + 'vorbis' + 0x01 while (toffset >= 0) { fputc((toffset >= 255 ? 255 : toffset) & 0xFF, out); toffset -= 255; } step = "skip old lacing vals"; fread(buf, 1, origlace, fp); step = "output last lacing vals"; for (i=origlace; i<oldlace; i++) { fputc(fgetc(fp), out); } sprintf(buf, "%cvorbis", 0x03); fwrite(buf, 7, 1, out); step = "write vorbis comment"; fwrite(vc, offset, 1, out); int a = FileSize/cuiReadBufSize / 21; int b = a, x, y; if (Progress != NULL) { Progress->SetVisible(); } // write stop bit fputc(1, out); for (i=0; i<1000; i++) fputc(0x00, out); // seek past vorbis comment fseek(fp, mvcoffset + mOrigVorbisCommentSize + mOrigPaddingSize, SEEK_SET); // copy rest of file iRead = fread(buf, 1, cuiReadBufSize, fp); while (iRead) { fwrite(buf, iRead, 1, out); iRead = fread(buf, 1, cuiReadBufSize, fp); } fclose(fp); fclose(out); sprintf(buf, "%s__tmpaudio%lu", DirTrunc(Filename), releasetotalcount+16); unlink(buf); fp = fopen(Filename.c_str(), "rb+"); } delete[] vc; // crc: clear current crc fseek(fp, lSPageStart+22, SEEK_SET); fputc(0x00, fp); fputc(0x00, fp); fputc(0x00, fp); fputc(0x00, fp); // crc: reseek fseek(fp, lSPageStart+26, SEEK_SET); int lacings = fgetc(fp); unsigned char LacingSize[255]; step = "crc: get lacings (" + String(lacings) + ")"; for (i=0; i<lacings; i++) { LacingSize[i] = fgetc(fp); } // Go to start of 2nd page unsigned long iCRC = 0x00; unsigned long iRead; unsigned long count; unsigned char uiOffset; // crc: go to 2nd page start fseek(fp, lSPageStart, SEEK_SET); // crc: fread begin iRead = count = fread(buf, 1, 27+lacings, fp); do { uiOffset = ((iCRC >> 24) & 0xFF) ^ buf[iRead - count]; iCRC = (iCRC << 8) ^ VCCRCTAB[uiOffset]; } while (--count); for (i=0; i<lacings; i++) { if (LacingSize[i]) { step = "crc: fread(" + String(LacingSize[i]) + ")"; iRead = count = fread(buf, 1, LacingSize[i], fp); do { uiOffset = ((iCRC >> 24) & 0xFF) ^ buf[iRead - count]; iCRC = (iCRC << 8) ^ VCCRCTAB[uiOffset]; } while (--count); } } // crc: parse crc unsigned char a = (iCRC >> 24) & 0xFF; unsigned char b = (iCRC >> 16) & 0xFF; unsigned char c = (iCRC >> 8) & 0xFF; unsigned char d = iCRC & 0xFF; // crc: seek to write pos fseek(fp, lSPageStart+22, SEEK_SET); fputc(d, fp); fputc(c, fp); fputc(b, fp); fputc(a, fp); // crc: close file fclose(fp); } }*/ private InternalInfo ReadTagInternal(Stream stream) { InternalInfo info = new InternalInfo(); info.OrigPaddingSize = 0; info.OrigVorbisCommentSize = 0; // Skip ID3v2 tag int id3v2TagSize = ID3v2.ID3v2Tag.GetTagSize(stream); stream.Seek(id3v2TagSize, SeekOrigin.Begin); if (IsFlac(stream)) { ReadTag_FLAC(stream, info); } /*else if (mAudioFileTrack == AUDIO_OGG) { return ReadTag_OGG(fp); }*/ else { throw new InvalidDataException("FLAC marker not found"); //throw new InvalidDataException(String.Format("File '{0}' is not a valid FLAC or Ogg-Vorbis file", path)); } info.Vendor = _vendor; return info; } private void ReadTag_VorbisComment(Stream stream) { _items.Clear(); int size = stream.ReadInt32LittleEndian(); _vendor = stream.ReadUTF8(size); int elements = stream.ReadInt32LittleEndian(); for (; elements > 0; elements--) { size = stream.ReadInt32LittleEndian(); string text = stream.ReadUTF8(size); string[] nameValue = text.Split("=".ToCharArray(), 2, StringSplitOptions.RemoveEmptyEntries); if (nameValue.Length == 2) { string name = nameValue[0]; string value = nameValue[1]; _items.Add(new NameValueItem(name, value)); } } } private void ReadTag_FLAC(Stream stream, InternalInfo info) { info.FileType = FileType.Flac; // Skip "fLaC" marker stream.Seek(4, SeekOrigin.Current); bool isLastMetaDataBlock; List<FlacMetaDataBlock> metaDataBlockList = new List<FlacMetaDataBlock>(); do { int c = stream.ReadByte(); isLastMetaDataBlock = (((c >> 7) & 0x01) == 1); int blocksize = stream.ReadInt24(); FlacMetaDataBlockType blockType = (FlacMetaDataBlockType)(c & 0x07); if (blockType == FlacMetaDataBlockType.VorbisComment) // Vorbis comment { info.OrigVorbisCommentSize = blocksize; long mvcoffset = stream.Position - 4; ReadTag_VorbisComment(stream); stream.Seek(mvcoffset + 4, SeekOrigin.Begin); } FlacMetaDataBlock metaDataBlock = new FlacMetaDataBlock(blockType); metaDataBlock.SetBlockData(stream, blocksize); metaDataBlockList.Add(metaDataBlock); } while (isLastMetaDataBlock == false); info.MetaDataBlockList = metaDataBlockList; _metaDataBlockList = metaDataBlockList; } /*private void ReadTag_OGG(FILE *fp) { info.FileType = FileType.OggVorbis; unsigned char buf[30]; unsigned long curpos; curpos = ftell(fp); fread(buf, 1, 27, fp); buf[4] = 0; if (strcmp(buf, "OggS")) { throw Exception("No OggS marker found"); } // Add segments + skip parameters vorbis-header (0x01 + 'vorbis') curpos += 27 + buf[26] + 30; fseek(fp, curpos, SEEK_SET); lSPageStart = ftell(fp); fread(buf, 1, 27, fp); buf[4] = 0; if (strcmp(buf, "OggS")) { throw Exception("No second OggS marker found"); } // Seek to 0x03 + 'vorbis' curpos += 27 + buf[26]; fseek(fp, curpos, SEEK_SET); // Read 0x03 + 'vorbis' fread(buf, 1, 7, fp); mvcoffset = ftell(fp); ReadTag_VorbisComment(fp); mOrigVorbisCommentSize = ftell(fp) - mvcoffset + 1; if (fgetc(fp) == 0x01) // check stop bit { mOrigPaddingSize = 0; while (fgetc(fp) == 0x00) mOrigPaddingSize++; } }*/ internal static bool IsFlac(string path) { using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { return IsFlac(fs); } } internal static bool IsFlac(Stream stream) { // Read flac marker byte[] flacMarker = new byte[4]; stream.Read(flacMarker, 0, 4); stream.Seek(-4, SeekOrigin.Current); return ByteUtils.Compare(flacMarker, FLAC_MARKER); } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.MetaData { using System; // MetaDataBits // // definitions for various bit-level flags, masks // derived from //urtdist/builds/src/2727/Lightning/Src/inc/CorHdr.h public enum NativeTypes : byte { END = 0x00, //DEPRECATED VOID = 0x01, //DEPRECATED BOOLEAN = 0x02, // (4 byte boolean value: TRUE = non-zero, FALSE = 0) I1 = 0x03, U1 = 0x04, I2 = 0x05, U2 = 0x06, I4 = 0x07, U4 = 0x08, I8 = 0x09, U8 = 0x0A, R4 = 0x0B, R8 = 0x0C, SYSCHAR = 0x0D, //DEPRECATED VARIANT = 0x0E, //DEPRECATED CURRENCY = 0x0F, PTR = 0x10, //DEPRECATED DECIMAL = 0x11, //DEPRECATED DATE = 0x12, //DEPRECATED BSTR = 0x13, LPSTR = 0x14, LPWSTR = 0x15, LPTSTR = 0x16, FIXEDSYSSTRING = 0x17, OBJECTREF = 0x18, //DEPRECATED IUNKNOWN = 0x19, IDISPATCH = 0x1A, STRUCT = 0x1B, INTF = 0x1C, SAFEARRAY = 0x1D, FIXEDARRAY = 0x1E, INT = 0x1F, UINT = 0x20, //////////////////////////@todo: sync up the spec NESTEDSTRUCT = 0x21, //DEPRECATED (use STRUCT) BYVALSTR = 0x22, ANSIBSTR = 0x23, TBSTR = 0x24, // select BSTR or ANSIBSTR depending on platform VARIANTBOOL = 0x25, // (2-byte boolean value: TRUE = -1, FALSE = 0) FUNC = 0x26, ASANY = 0x28, ARRAY = 0x2A, LPSTRUCT = 0x2B, CUSTOMMARSHALER = 0x2C, // Custom marshaler native type. This must be followed ////////////////////////// by a string of the following format: ////////////////////////// "Native type name/0Custom marshaler type name/0Optional cookie/0" ////////////////////////// Or ////////////////////////// "{Native type GUID}/0Custom marshaler type name/0Optional cookie/0" ERROR = 0x2D, // This native type coupled with ELEMENT_TYPE_I4 will map to VT_HRESULT MAX = 0x50 // first invalid element type } public enum VariantTypes { VT_EMPTY = 0, VT_NULL = 1, VT_I2 = 2, VT_I4 = 3, VT_R4 = 4, VT_R8 = 5, VT_CY = 6, VT_DATE = 7, VT_BSTR = 8, VT_DISPATCH = 9, VT_ERROR = 10, VT_BOOL = 11, VT_VARIANT = 12, VT_UNKNOWN = 13, VT_DECIMAL = 14, VT_I1 = 16, VT_UI1 = 17, VT_UI2 = 18, VT_UI4 = 19, VT_I8 = 20, VT_UI8 = 21, VT_INT = 22, VT_UINT = 23, VT_VOID = 24, VT_HRESULT = 25, VT_PTR = 26, VT_SAFEARRAY = 27, VT_CARRAY = 28, VT_USERDEFINED = 29, VT_LPSTR = 30, VT_LPWSTR = 31, VT_RECORD = 36, VT_FILETIME = 64, VT_BLOB = 65, VT_STREAM = 66, VT_STORAGE = 67, VT_STREAMED_OBJECT = 68, VT_STORED_OBJECT = 69, VT_BLOB_OBJECT = 70, VT_CF = 71, VT_CLSID = 72, VT_BSTR_BLOB = 0x0FFF, VT_VECTOR = 0x1000, VT_ARRAY = 0x2000, VT_BYREF = 0x4000, VT_RESERVED = 0x8000, VT_ILLEGAL = 0xFFFF, VT_ILLEGALMASKED = 0x0FFF, VT_TYPEMASK = 0x0FFF }; public enum TokenType : byte { Module = 0x00, TypeRef = 0x01, TypeDef = 0x02, FieldPtr = 0x03, // Not Supported Field = 0x04, MethodPtr = 0x05, // Not Supported Method = 0x06, ParamPtr = 0x07, // Not Supported Param = 0x08, InterfaceImpl = 0x09, MemberRef = 0x0A, Constant = 0x0B, CustomAttribute = 0x0C, FieldMarshal = 0x0D, DeclSecurity = 0x0E, ClassLayout = 0x0F, FieldLayout = 0x10, StandAloneSig = 0x11, EventMap = 0x12, EventPtr = 0x13, // Not Supported Event = 0x14, PropertyMap = 0x15, PropertyPtr = 0x16, // Not Supported Property = 0x17, MethodSemantics = 0x18, MethodImpl = 0x19, ModuleRef = 0x1A, TypeSpec = 0x1B, ImplMap = 0x1C, FieldRVA = 0x1D, ENCLog = 0x1E, // Not Supported ENCMap = 0x1F, // Not Supported Assembly = 0x20, AssemblyProcessor = 0x21, // Ignored AssemblyOS = 0x22, // Ignored AssemblyRef = 0x23, AssemblyRefProcessor = 0x24, // Ignored AssemblyRefOS = 0x25, // Ignored File = 0x26, ExportedType = 0x27, // Not Supported ManifestResource = 0x28, NestedClass = 0x29, GenericParam = 0x2A, MethodSpec = 0x2B, GenericParamConstraint = 0x2C, Count = GenericParamConstraint + 1, // Common synonyms. FieldDef = Field, MethodDef = Method, ParamDef = Param, Permission = DeclSecurity, Signature = StandAloneSig, String = 0x70, Illegal = 0xFF, } //--// // // Section 23.1.1 of ECMA spec, Partition II // public enum HashAlgorithmID { None = 0x0000, MD5 = 0x8003, SHA1 = 0x8004 } // // Section 23.1.2 of ECMA spec, Partition II // [Flags] public enum AssemblyFlags { PublicKey = 0x0001, // The assembly ref holds the full (unhashed) public key. CompatibilityMask = 0x0070, SideBySideCompatible = 0x0000, // The assembly is side by side compatible. NonSideBySideAppDomain = 0x0010, // The assembly cannot execute with other versions if they are executing in the same application domain. NonSideBySideProcess = 0x0020, // The assembly cannot execute with other versions if they are executing in the same process. NonSideBySideMachine = 0x0030, // The assembly cannot execute with other versions if they are executing on the same machine. EnableJITcompileTracking = 0x8000, // From "DebuggableAttribute". DisableJITcompileOptimizer = 0x4000 // From "DebuggableAttribute". } // // Section 23.1.4 of ECMA spec, Partition II // [Flags] public enum EventAttributes : ushort { SpecialName = 0x0200, // Event is special. Name describes how. ReservedMask = 0x0400, // Reserved flags for Runtime use only. RTSpecialName = 0x0400 // Runtime (metadata internal APIs) should check name encoding. } // // Section 23.1.5 of ECMA spec, Partition II // [Flags] public enum FieldAttributes : ushort { FieldAccessMask = 0x0007, // member access mask - Use this mask to retrieve accessibility information. PrivateScope = 0x0000, // Member not referenceable. Private = 0x0001, // Accessible only by the parent type. FamANDAssem = 0x0002, // Accessible by sub-types only in this Assembly. Assembly = 0x0003, // Accessibly by anyone in the Assembly. Family = 0x0004, // Accessible only by type and sub-types. FamORAssem = 0x0005, // Accessibly by sub-types anywhere, plus anyone in assembly. Public = 0x0006, // Accessibly by anyone who has visibility to this scope. // end member access mask // field contract attributes. Static = 0x0010, // Defined on type, else per instance. InitOnly = 0x0020, // Field may only be initialized, not written to after init. Literal = 0x0040, // Value is compile time constant. NotSerialized = 0x0080, // Field does not have to be serialized when type is remoted. SpecialName = 0x0200, // field is special. Name describes how. // interop attributes PinvokeImpl = 0x2000, // Implementation is forwarded through pinvoke. // Reserved flags for runtime use only. ReservedMask = 0x9500, RTSpecialName = 0x0400, // Runtime(metadata internal APIs) should check name encoding. HasFieldMarshal = 0x1000, // Field has marshalling information. HasDefault = 0x8000, // Field has default. HasFieldRVA = 0x0100 // Field has RVA. } // // Section 23.1.6 of ECMA spec, Partition II // [Flags] public enum FileAttributes { ContainsMetaData = 0x0000, // This is not a resource file, ContainsNoMetaData = 0x0001 // This is a resource file or other non-metadata-containing file } // // Section 23.1.7 of ECMA spec, Partition II // [Flags] public enum GenericParameterAttributes : ushort { VarianceMask = 0x0003, NonVariant = 0x0000, // The generic parameter is non-variant Covariant = 0x0001, // The generic parameter is covariant Contravariant = 0x0002, // The generic parameter is contravariant SpecialConstraintMask = 0x001C, ReferenceTypeConstraint = 0x0004, // The generic parameter has the class special constraint NotNullableValueTypeConstraint = 0x0008, // The generic parameter has the valuetype special constraint DefaultConstructorConstraint = 0x0010, // The generic parameter has the .ctor special constraint } // // Section 23.1.8 of ECMA spec, Partition II // [Flags] public enum ImplementationMapAttributes : ushort { NoMangle = 0x0001, // Pinvoke is to use the member name as specified. // Character set flags CharSetMask = 0x0006, // Use this mask to retrieve the CharSet information. CharSetNotSpec = 0x0000, CharSetAnsi = 0x0002, CharSetUnicode = 0x0004, CharSetAuto = 0x0006, SupportsLastError = 0x0040, // Information about target function. Not relevant for fields. // None of the calling convention flags is relevant for fields. CallConvMask = 0x0700, CallConvWinapi = 0x0100, // Pinvoke will use native callconv appropriate to target windows platform. CallConvCdecl = 0x0200, CallConvStdcall = 0x0300, CallConvThiscall = 0x0400, // In M9, pinvoke will raise exception. CallConvFastcall = 0x0500 } // // Section 23.1.9 of ECMA spec, Partition II // [Flags] public enum ManifestResourceAttributes { VisibilityMask = 0x0007, Public = 0x0001, // The Resource is exported from the Assembly. Private = 0x0002 // The Resource is private to the Assembly. } // // Section 23.1.10 of ECMA spec, Partition II // [Flags] public enum MethodAttributes : ushort { // member access attributes MemberAccessMask = 0x0007, // Use this mask to retrieve accessibility information. PrivateScope = 0x0000, // Member not referenceable. Private = 0x0001, // Accessible only by the parent type. FamANDAssem = 0x0002, // Accessible by sub-types only in this Assembly. Assem = 0x0003, // Accessibly by anyone in the Assembly. Family = 0x0004, // Accessible only by type and sub-types. FamORAssem = 0x0005, // Accessibly by sub-types anywhere, plus anyone in assembly. Public = 0x0006, // Accessibly by anyone who has visibility to this scope. // method contract attributes. Static = 0x0010, // Defined on type, else per instance. Final = 0x0020, // Method may not be overridden. Virtual = 0x0040, // Method virtual. HideBySig = 0x0080, // Method hides by name+sig, else just by name. // vtable layout mask - Use this mask to retrieve vtable attributes. VtableLayoutMask = 0x0100, ReuseSlot = 0x0000, // The default. NewSlot = 0x0100, // Method always gets a new slot in the vtable. Strict = 0x0200, // method implementation attributes. Abstract = 0x0400, // Method does not provide an implementation. SpecialName = 0x0800, // Method is special. Name describes how. // interop attributes PinvokeImpl = 0x2000, // Implementation is forwarded through pinvoke. UnmanagedExport = 0x0008, // Managed method exported via thunk to unmanaged code. // Reserved flags for runtime use only. ReservedMask = 0xD000, RTSpecialName = 0x1000, // Runtime should check name encoding. HasSecurity = 0x4000, // Method has security associate with it. RequireSecObject = 0x8000 // Method calls another method containing security code. } // // Section 23.1.11 of ECMA spec, Partition II // [Flags] public enum MethodImplAttributes : ushort { // code impl mask CodeTypeMask = 0x0003, // Flags about code type. IL = 0x0000, // Method impl is IL. Native = 0x0001, // Method impl is native. OPTIL = 0x0002, // Method impl is OPTIL Runtime = 0x0003, // Method impl is provided by the runtime. // managed mask ManagedMask = 0x0004, // Flags specifying whether the code is managed or unmanaged. Unmanaged = 0x0004, // Method impl is unmanaged, otherwise managed. Managed = 0x0000, // Method impl is managed. // implementation info and interop ForwardRef = 0x0010, // Indicates method is defined; used primarily in merge scenarios. PreserveSig = 0x0080, // Indicates method sig is not to be mangled to do HRESULT conversion. InternalCall = 0x1000, // Reserved for internal use. Synchronized = 0x0020, // Method is single threaded through the body. NoInlining = 0x0008, // Method may not be inlined. MaxMethodImplVal = 0xFFFF // Range check value } // // Section 23.1.12 of ECMA spec, Partition II // [Flags] public enum MethodSemanticAttributes : ushort { Setter = 0x0001, // Setter for property Getter = 0x0002, // Getter for property Other = 0x0004, // other method for property or event AddOn = 0x0008, // AddOn method for event RemoveOn = 0x0010, // RemoveOn method for event Fire = 0x0020 // Fire method for event } // // Section 23.1.13 of ECMA spec, Partition II // [Flags] public enum ParamAttributes : ushort { In = 0x0001, // Param is [In] Out = 0x0002, // Param is [out] Optional = 0x0010, // Param is optional // Reserved flags for Runtime use only. ReservedMask = 0xF000, HasDefault = 0x1000, // Param has default value. HasFieldMarshal = 0x2000, // Param has FieldMarshal. Unused = 0xCFE0 } // // Section 23.1.14 of ECMA spec, Partition II // [Flags] public enum PropertyAttributes : ushort { SpecialName = 0x0200, // property is special. Name describes how. // Reserved flags for Runtime use only. ReservedMask = 0xF400, RTSpecialName = 0x0400, // Runtime(metadata internal APIs) should check name encoding. HasDefault = 0x1000, // Property has default Unused = 0xE9FF } // // Section 23.1.15 of ECMA spec, Partition II // [Flags] public enum TypeAttributes { VisibilityMask = 0x00000007, NotPublic = 0x00000000, // Class is not public scope. Public = 0x00000001, // Class is public scope. NestedPublic = 0x00000002, // Class is nested with public visibility. NestedPrivate = 0x00000003, // Class is nested with private visibility. NestedFamily = 0x00000004, // Class is nested with family visibility. NestedAssembly = 0x00000005, // Class is nested with assembly visibility. NestedFamANDAssem = 0x00000006, // Class is nested with family and assembly visibility. NestedFamORAssem = 0x00000007, // Class is nested with family or assembly visibility. // Use this mask to retrieve class layout informaiton // 0 is AutoLayout, 0x2 is SequentialLayout, 4 is ExplicitLayout LayoutMask = 0x00000018, AutoLayout = 0x00000000, // Class fields are auto-laid out SequentialLayout = 0x00000008, // Class fields are laid out sequentially ExplicitLayout = 0x00000010, // Layout is supplied explicitly // end layout mask // Use this mask to distinguish a type declaration as a Class, ValueType or Interface ClassSemanticsMask = 0x00000020, Class = 0x00000000, // Type is a class. Interface = 0x00000020, // Type is an interface. // Special semantics in addition to class semantics. Abstract = 0x00000080, // Class is abstract Sealed = 0x00000100, // Class is concrete and may not be extended SpecialName = 0x00000400, // Class name is special. Name describes how. // Implementation attributes. Import = 0x00001000, // Class / interface is imported Serializable = 0x00002000, // The class is Serializable. // Use tdStringFormatMask to retrieve string information for native interop StringFormatMask = 0x00030000, AnsiClass = 0x00000000, // LPTSTR is interpreted as ANSI in this class UnicodeClass = 0x00010000, // LPTSTR is interpreted as UNICODE AutoClass = 0x00020000, // LPTSTR is interpreted automatically CustomFormatClass = 0x00030000, // A non-standard encoding specified by CustomFormatMask CustomFormatMask = 0x00C00000, // Use this mask to retrieve non-standard encoding information for native interop. The meaning of the values of these 2 bits is unspecified. // end string format mask BeforeFieldInit = 0x00100000, // Initialize the class any time before first static field access. // Flags reserved for runtime use. ReservedMask = 0x00040800, RTSpecialName = 0x00000800, // Runtime should check name encoding. HasSecurity = 0x00040000, // Class has security associate with it. } // // Section 23.1.16 of ECMA spec, Partition II // public enum ElementTypes : byte { END = 0x00, VOID = 0x01, BOOLEAN = 0x02, CHAR = 0x03, I1 = 0x04, U1 = 0x05, I2 = 0x06, U2 = 0x07, I4 = 0x08, U4 = 0x09, I8 = 0x0A, U8 = 0x0B, R4 = 0x0C, R8 = 0x0D, STRING = 0x0E, ///////////////////////// every type above PTR will be simple type PTR = 0x0F, // PTR <type> BYREF = 0x10, // BYREF <type> ///////////////////////// Please use VALUETYPE. VALUECLASS is deprecated. VALUETYPE = 0x11, // VALUETYPE <class Token> CLASS = 0x12, // CLASS <class Token> VAR = 0x13, // a class type variable VAR <U1> ARRAY = 0x14, // MDARRAY <type> <rank> <bcount> <bound1> ... <lbcount> <lb1> ... GENERICINST = 0x15, // instantiated type TYPEDBYREF = 0x16, // This is a simple type. I = 0x18, // native integer size U = 0x19, // native unsigned integer size FNPTR = 0x1B, // FNPTR <complete sig for the function including calling convention> OBJECT = 0x1C, // Shortcut for System.Object SZARRAY = 0x1D, // Shortcut for single dimension zero lower bound array ///////////////////////// SZARRAY <type> ///////////////////////// This is only for binding MVAR = 0x1E, // a method type variable MVAR <U1> CMOD_REQD = 0x1F, // required C modifier : E_T_CMOD_REQD <mdTypeRef/mdTypeDef> CMOD_OPT = 0x20, // optional C modifier : E_T_CMOD_OPT <mdTypeRef/mdTypeDef> ///////////////////////// This is for signatures generated internally (which will not be persisted in any way). INTERNAL = 0x21, // INTERNAL <typehandle> ///////////////////////// Note that this is the max of base type excluding modifiers MAX = 0x22, // first invalid element type MODIFIER = 0x40, SENTINEL = 0x01 | MODIFIER, // sentinel for varargs PINNED = 0x05 | MODIFIER } public enum SerializationTypes { BOOLEAN = ElementTypes.BOOLEAN, CHAR = ElementTypes.CHAR, I1 = ElementTypes.I1, U1 = ElementTypes.U1, I2 = ElementTypes.I2, U2 = ElementTypes.U2, I4 = ElementTypes.I4, U4 = ElementTypes.U4, I8 = ElementTypes.I8, U8 = ElementTypes.U8, R4 = ElementTypes.R4, R8 = ElementTypes.R8, STRING = ElementTypes.STRING, OBJECT = ElementTypes.OBJECT, SZARRAY = ElementTypes.SZARRAY, // Shortcut for single dimension zero lower bound array TYPE = 0x50, TAGGED_OBJECT = 0x51, FIELD = 0x53, PROPERTY = 0x54, ENUM = 0x55 } }
namespace zenQuery { partial class frmMdi { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region 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() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmMdi)); this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); this.panmenu = new System.Windows.Forms.Panel(); this.ts = new System.Windows.Forms.ToolStrip(); this.tsConnect = new System.Windows.Forms.ToolStripButton(); this.tsDisconnect = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator15 = new System.Windows.Forms.ToolStripSeparator(); this.tsNew = new System.Windows.Forms.ToolStripButton(); this.tsOpen = new System.Windows.Forms.ToolStripButton(); this.tsSave = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator16 = new System.Windows.Forms.ToolStripSeparator(); this.tsExecute = new System.Windows.Forms.ToolStripButton(); this.tsCancel = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator17 = new System.Windows.Forms.ToolStripSeparator(); this.tsResult = new System.Windows.Forms.ToolStripComboBox(); this.tsHideResults = new System.Windows.Forms.ToolStripButton(); this.tsHideBrowser = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator18 = new System.Windows.Forms.ToolStripSeparator(); this.tsBeautyCode = new System.Windows.Forms.ToolStripButton(); this.tsSnippets = new System.Windows.Forms.ToolStripButton(); this.tsQueryHistory = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator19 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.menuStripMain = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.newToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator11 = new System.Windows.Forms.ToolStripSeparator(); this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveAsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveAllStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator = new System.Windows.Forms.ToolStripSeparator(); this.closeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator12 = new System.Windows.Forms.ToolStripSeparator(); this.printToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.printPreviewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.editToolStripMenu = new System.Windows.Forms.ToolStripMenuItem(); this.undoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.redoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator(); this.cutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.pasteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator(); this.selectAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator(); this.findAndReplaceStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.findToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.replaceToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.goToToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator(); this.bookmarksToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toggleBookmarkToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.previosBookmarkToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.nextBookmarkToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.clearBookmarsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.advancedToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.makeUpperCaseToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.makeLowerCaseToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.commentStreamToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.commentLineToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.uncommentLineToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator(); this.snippetsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.insertSnippetToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.surroundWithToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.viewStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.whiteSpaceToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.wordWrapToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.endOfLineToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator9 = new System.Windows.Forms.ToolStripSeparator(); this.zoomInToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.zoomOutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.resetZoomToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator10 = new System.Windows.Forms.ToolStripSeparator(); this.lineNumbersToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.windowStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator8 = new System.Windows.Forms.ToolStripSeparator(); this.closeToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.closeAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.panSearch = new System.Windows.Forms.Panel(); this.dockPanel = new WeifenLuo.WinFormsUI.Docking.DockPanel(); this.panel1 = new System.Windows.Forms.Panel(); this.chkobjecttext = new System.Windows.Forms.CheckBox(); this.btnsearch = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.txtsearch = new System.Windows.Forms.TextBox(); this.chkobjectname = new System.Windows.Forms.CheckBox(); this.panmenu.SuspendLayout(); this.ts.SuspendLayout(); this.menuStripMain.SuspendLayout(); this.panel1.SuspendLayout(); this.SuspendLayout(); // // openFileDialog // this.openFileDialog.DefaultExt = "sql"; this.openFileDialog.Filter = "SQL (*.sql)|*.sql|All files (*.*)|*.*"; // // panmenu // this.panmenu.Controls.Add(this.ts); this.panmenu.Controls.Add(this.menuStripMain); this.panmenu.Dock = System.Windows.Forms.DockStyle.Top; this.panmenu.Location = new System.Drawing.Point(0, 0); this.panmenu.Name = "panmenu"; this.panmenu.Size = new System.Drawing.Size(1028, 62); this.panmenu.TabIndex = 18; // // ts // this.ts.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224))))); this.ts.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.ts.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.tsConnect, this.tsDisconnect, this.toolStripSeparator15, this.tsNew, this.tsOpen, this.tsSave, this.toolStripSeparator16, this.tsExecute, this.tsCancel, this.toolStripSeparator17, this.tsResult, this.tsHideResults, this.tsHideBrowser, this.toolStripSeparator18, this.tsBeautyCode, this.tsSnippets, this.tsQueryHistory, this.toolStripSeparator19, this.toolStripButton1}); this.ts.Location = new System.Drawing.Point(0, 24); this.ts.Name = "ts"; this.ts.Size = new System.Drawing.Size(1028, 36); this.ts.TabIndex = 15; this.ts.Text = "te"; // // tsConnect // this.tsConnect.Image = global::img.Resources.connect; this.tsConnect.ImageTransparentColor = System.Drawing.Color.Magenta; this.tsConnect.Name = "tsConnect"; this.tsConnect.Size = new System.Drawing.Size(51, 33); this.tsConnect.Text = "Connect"; this.tsConnect.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText; this.tsConnect.Click += new System.EventHandler(this.tsConnect_Click); // // tsDisconnect // this.tsDisconnect.Image = global::img.Resources.disconnect; this.tsDisconnect.ImageTransparentColor = System.Drawing.Color.Magenta; this.tsDisconnect.Name = "tsDisconnect"; this.tsDisconnect.Size = new System.Drawing.Size(63, 33); this.tsDisconnect.Text = "Disconnect"; this.tsDisconnect.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText; this.tsDisconnect.Click += new System.EventHandler(this.tsDisconnect_Click); // // toolStripSeparator15 // this.toolStripSeparator15.Name = "toolStripSeparator15"; this.toolStripSeparator15.Size = new System.Drawing.Size(6, 36); // // tsNew // this.tsNew.Image = global::img.Resources.newwindow; this.tsNew.ImageTransparentColor = System.Drawing.Color.Magenta; this.tsNew.Name = "tsNew"; this.tsNew.Size = new System.Drawing.Size(71, 33); this.tsNew.Text = "New window"; this.tsNew.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText; this.tsNew.Click += new System.EventHandler(this.tsNew_Click); // // tsOpen // this.tsOpen.Image = global::img.Resources.open; this.tsOpen.ImageTransparentColor = System.Drawing.Color.Magenta; this.tsOpen.Name = "tsOpen"; this.tsOpen.Size = new System.Drawing.Size(37, 33); this.tsOpen.Text = "Open"; this.tsOpen.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText; this.tsOpen.Click += new System.EventHandler(this.tsOpen_Click); // // tsSave // this.tsSave.Image = global::img.Resources.save; this.tsSave.ImageTransparentColor = System.Drawing.Color.Magenta; this.tsSave.Name = "tsSave"; this.tsSave.Size = new System.Drawing.Size(35, 33); this.tsSave.Text = "Save"; this.tsSave.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText; this.tsSave.Click += new System.EventHandler(this.tsSave_Click); // // toolStripSeparator16 // this.toolStripSeparator16.Name = "toolStripSeparator16"; this.toolStripSeparator16.Size = new System.Drawing.Size(6, 36); // // tsExecute // this.tsExecute.Image = global::img.Resources.execute; this.tsExecute.ImageTransparentColor = System.Drawing.Color.Magenta; this.tsExecute.Name = "tsExecute"; this.tsExecute.Size = new System.Drawing.Size(104, 33); this.tsExecute.Text = "Execute query [F5]"; this.tsExecute.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText; this.tsExecute.ToolTipText = "shortcut: F5 key"; this.tsExecute.Click += new System.EventHandler(this.tsExecute_Click); // // tsCancel // this.tsCancel.Image = global::img.Resources.cancel; this.tsCancel.ImageTransparentColor = System.Drawing.Color.Magenta; this.tsCancel.Name = "tsCancel"; this.tsCancel.Size = new System.Drawing.Size(43, 33); this.tsCancel.Text = "Cancel"; this.tsCancel.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText; this.tsCancel.Click += new System.EventHandler(this.tsCancel_Click); // // toolStripSeparator17 // this.toolStripSeparator17.Name = "toolStripSeparator17"; this.toolStripSeparator17.Size = new System.Drawing.Size(6, 36); // // tsResult // this.tsResult.Items.AddRange(new object[] { "Result Text", "Result Text Pretty", "Result Grid", "Result Grid Trans."}); this.tsResult.Name = "tsResult"; this.tsResult.Size = new System.Drawing.Size(121, 36); this.tsResult.Text = "Result Grid"; this.tsResult.SelectedIndexChanged += new System.EventHandler(this.tsResult_SelectedIndexChanged); // // tsHideResults // this.tsHideResults.Image = global::img.Resources.hide; this.tsHideResults.ImageTransparentColor = System.Drawing.Color.Magenta; this.tsHideResults.Name = "tsHideResults"; this.tsHideResults.Size = new System.Drawing.Size(65, 33); this.tsHideResults.Text = "Hide Result"; this.tsHideResults.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText; this.tsHideResults.Click += new System.EventHandler(this.tsHideResults_Click); // // tsHideBrowser // this.tsHideBrowser.Image = global::img.Resources.hide; this.tsHideBrowser.ImageTransparentColor = System.Drawing.Color.Magenta; this.tsHideBrowser.Name = "tsHideBrowser"; this.tsHideBrowser.Size = new System.Drawing.Size(74, 33); this.tsHideBrowser.Text = "Hide Browser"; this.tsHideBrowser.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText; this.tsHideBrowser.Click += new System.EventHandler(this.tsHideBrowser_Click); // // toolStripSeparator18 // this.toolStripSeparator18.Name = "toolStripSeparator18"; this.toolStripSeparator18.Size = new System.Drawing.Size(6, 36); // // tsBeautyCode // this.tsBeautyCode.Image = global::img.Resources.favicon; this.tsBeautyCode.ImageTransparentColor = System.Drawing.Color.Magenta; this.tsBeautyCode.Name = "tsBeautyCode"; this.tsBeautyCode.Size = new System.Drawing.Size(96, 33); this.tsBeautyCode.Text = "Beauty Code [F3]"; this.tsBeautyCode.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText; this.tsBeautyCode.ToolTipText = "shortcut: F3 key"; this.tsBeautyCode.Click += new System.EventHandler(this.tsBeautyCode_Click); // // tsSnippets // this.tsSnippets.Image = global::img.Resources.snippets; this.tsSnippets.ImageTransparentColor = System.Drawing.Color.Magenta; this.tsSnippets.Name = "tsSnippets"; this.tsSnippets.Size = new System.Drawing.Size(46, 33); this.tsSnippets.Text = "Actions"; this.tsSnippets.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText; this.tsSnippets.Click += new System.EventHandler(this.tsSnippets_Click); // // tsQueryHistory // this.tsQueryHistory.Image = global::img.Resources.history; this.tsQueryHistory.ImageTransparentColor = System.Drawing.Color.Magenta; this.tsQueryHistory.Name = "tsQueryHistory"; this.tsQueryHistory.Size = new System.Drawing.Size(78, 33); this.tsQueryHistory.Text = "Query History"; this.tsQueryHistory.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText; this.tsQueryHistory.Click += new System.EventHandler(this.tsQueryHistory_Click); // // toolStripSeparator19 // this.toolStripSeparator19.Name = "toolStripSeparator19"; this.toolStripSeparator19.Size = new System.Drawing.Size(6, 36); // // toolStripButton1 // this.toolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton1.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton1.Image"))); this.toolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton1.Name = "toolStripButton1"; this.toolStripButton1.Size = new System.Drawing.Size(23, 33); this.toolStripButton1.Text = "Template"; this.toolStripButton1.Visible = false; // // menuStripMain // this.menuStripMain.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224))))); this.menuStripMain.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem, this.editToolStripMenu, this.viewStripMenuItem, this.windowStripMenuItem, this.helpToolStripMenuItem}); this.menuStripMain.Location = new System.Drawing.Point(0, 0); this.menuStripMain.MdiWindowListItem = this.windowStripMenuItem; this.menuStripMain.Name = "menuStripMain"; this.menuStripMain.Padding = new System.Windows.Forms.Padding(4, 2, 0, 2); this.menuStripMain.Size = new System.Drawing.Size(1028, 24); this.menuStripMain.TabIndex = 3; // // fileToolStripMenuItem // this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.newToolStripMenuItem, this.openToolStripMenuItem, this.toolStripSeparator11, this.saveToolStripMenuItem, this.saveAsToolStripMenuItem, this.saveAllStripMenuItem, this.toolStripSeparator, this.closeToolStripMenuItem, this.toolStripSeparator12, this.printToolStripMenuItem, this.printPreviewToolStripMenuItem, this.toolStripSeparator1, this.exitToolStripMenuItem}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Size = new System.Drawing.Size(35, 20); this.fileToolStripMenuItem.Text = "&File"; // // newToolStripMenuItem // this.newToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("newToolStripMenuItem.Image"))); this.newToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta; this.newToolStripMenuItem.Name = "newToolStripMenuItem"; this.newToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N))); this.newToolStripMenuItem.Size = new System.Drawing.Size(191, 22); this.newToolStripMenuItem.Text = "&New"; this.newToolStripMenuItem.Click += new System.EventHandler(this.newToolStripMenuItem_Click); // // openToolStripMenuItem // this.openToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("openToolStripMenuItem.Image"))); this.openToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta; this.openToolStripMenuItem.Name = "openToolStripMenuItem"; this.openToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O))); this.openToolStripMenuItem.Size = new System.Drawing.Size(191, 22); this.openToolStripMenuItem.Text = "&Open"; this.openToolStripMenuItem.Click += new System.EventHandler(this.openToolStripMenuItem_Click); // // toolStripSeparator11 // this.toolStripSeparator11.Name = "toolStripSeparator11"; this.toolStripSeparator11.Size = new System.Drawing.Size(188, 6); // // saveToolStripMenuItem // this.saveToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("saveToolStripMenuItem.Image"))); this.saveToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta; this.saveToolStripMenuItem.Name = "saveToolStripMenuItem"; this.saveToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S))); this.saveToolStripMenuItem.Size = new System.Drawing.Size(191, 22); this.saveToolStripMenuItem.Text = "&Save"; this.saveToolStripMenuItem.Click += new System.EventHandler(this.saveToolStripMenuItem_Click); // // saveAsToolStripMenuItem // this.saveAsToolStripMenuItem.Name = "saveAsToolStripMenuItem"; this.saveAsToolStripMenuItem.Size = new System.Drawing.Size(191, 22); this.saveAsToolStripMenuItem.Text = "Save &As"; this.saveAsToolStripMenuItem.Click += new System.EventHandler(this.saveAsToolStripMenuItem_Click); // // saveAllStripMenuItem // this.saveAllStripMenuItem.Name = "saveAllStripMenuItem"; this.saveAllStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)(((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Shift) | System.Windows.Forms.Keys.S))); this.saveAllStripMenuItem.Size = new System.Drawing.Size(191, 22); this.saveAllStripMenuItem.Text = "Save A&ll"; this.saveAllStripMenuItem.Click += new System.EventHandler(this.saveAllStripMenuItem_Click); // // toolStripSeparator // this.toolStripSeparator.Name = "toolStripSeparator"; this.toolStripSeparator.Size = new System.Drawing.Size(188, 6); // // closeToolStripMenuItem // this.closeToolStripMenuItem.Name = "closeToolStripMenuItem"; this.closeToolStripMenuItem.Size = new System.Drawing.Size(191, 22); this.closeToolStripMenuItem.Text = "&Close"; this.closeToolStripMenuItem.Click += new System.EventHandler(this.closeToolStripMenuItem_Click); // // toolStripSeparator12 // this.toolStripSeparator12.Name = "toolStripSeparator12"; this.toolStripSeparator12.Size = new System.Drawing.Size(188, 6); // // printToolStripMenuItem // this.printToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("printToolStripMenuItem.Image"))); this.printToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta; this.printToolStripMenuItem.Name = "printToolStripMenuItem"; this.printToolStripMenuItem.Size = new System.Drawing.Size(191, 22); this.printToolStripMenuItem.Text = "&Print"; this.printToolStripMenuItem.Click += new System.EventHandler(this.printToolStripMenuItem_Click); // // printPreviewToolStripMenuItem // this.printPreviewToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("printPreviewToolStripMenuItem.Image"))); this.printPreviewToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta; this.printPreviewToolStripMenuItem.Name = "printPreviewToolStripMenuItem"; this.printPreviewToolStripMenuItem.Size = new System.Drawing.Size(191, 22); this.printPreviewToolStripMenuItem.Text = "Print Pre&view"; this.printPreviewToolStripMenuItem.Click += new System.EventHandler(this.printPreviewToolStripMenuItem_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(188, 6); // // exitToolStripMenuItem // this.exitToolStripMenuItem.Name = "exitToolStripMenuItem"; this.exitToolStripMenuItem.Size = new System.Drawing.Size(191, 22); this.exitToolStripMenuItem.Text = "E&xit"; this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click); // // editToolStripMenu // this.editToolStripMenu.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.undoToolStripMenuItem, this.redoToolStripMenuItem, this.toolStripSeparator3, this.cutToolStripMenuItem, this.copyToolStripMenuItem, this.pasteToolStripMenuItem, this.toolStripSeparator4, this.selectAllToolStripMenuItem, this.toolStripSeparator6, this.findAndReplaceStripMenuItem, this.goToToolStripMenuItem, this.toolStripSeparator7, this.bookmarksToolStripMenuItem, this.advancedToolStripMenuItem, this.toolStripSeparator5, this.snippetsToolStripMenuItem}); this.editToolStripMenu.Name = "editToolStripMenu"; this.editToolStripMenu.Size = new System.Drawing.Size(37, 20); this.editToolStripMenu.Text = "&Edit"; // // undoToolStripMenuItem // this.undoToolStripMenuItem.Name = "undoToolStripMenuItem"; this.undoToolStripMenuItem.Size = new System.Drawing.Size(167, 22); this.undoToolStripMenuItem.Text = "&Undo"; this.undoToolStripMenuItem.Click += new System.EventHandler(this.undoToolStripMenuItem_Click); // // redoToolStripMenuItem // this.redoToolStripMenuItem.Name = "redoToolStripMenuItem"; this.redoToolStripMenuItem.Size = new System.Drawing.Size(167, 22); this.redoToolStripMenuItem.Text = "&Redo"; this.redoToolStripMenuItem.Click += new System.EventHandler(this.redoToolStripMenuItem_Click); // // toolStripSeparator3 // this.toolStripSeparator3.Name = "toolStripSeparator3"; this.toolStripSeparator3.Size = new System.Drawing.Size(164, 6); // // cutToolStripMenuItem // this.cutToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("cutToolStripMenuItem.Image"))); this.cutToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta; this.cutToolStripMenuItem.Name = "cutToolStripMenuItem"; this.cutToolStripMenuItem.Size = new System.Drawing.Size(167, 22); this.cutToolStripMenuItem.Text = "Cu&t"; this.cutToolStripMenuItem.Click += new System.EventHandler(this.cutToolStripMenuItem_Click); // // copyToolStripMenuItem // this.copyToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("copyToolStripMenuItem.Image"))); this.copyToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta; this.copyToolStripMenuItem.Name = "copyToolStripMenuItem"; this.copyToolStripMenuItem.Size = new System.Drawing.Size(167, 22); this.copyToolStripMenuItem.Text = "&Copy"; this.copyToolStripMenuItem.Click += new System.EventHandler(this.copyToolStripMenuItem_Click); // // pasteToolStripMenuItem // this.pasteToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("pasteToolStripMenuItem.Image"))); this.pasteToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta; this.pasteToolStripMenuItem.Name = "pasteToolStripMenuItem"; this.pasteToolStripMenuItem.Size = new System.Drawing.Size(167, 22); this.pasteToolStripMenuItem.Text = "&Paste"; this.pasteToolStripMenuItem.Click += new System.EventHandler(this.pasteToolStripMenuItem_Click); // // toolStripSeparator4 // this.toolStripSeparator4.Name = "toolStripSeparator4"; this.toolStripSeparator4.Size = new System.Drawing.Size(164, 6); // // selectAllToolStripMenuItem // this.selectAllToolStripMenuItem.Name = "selectAllToolStripMenuItem"; this.selectAllToolStripMenuItem.Size = new System.Drawing.Size(167, 22); this.selectAllToolStripMenuItem.Text = "Select &All"; this.selectAllToolStripMenuItem.Click += new System.EventHandler(this.selectAllToolStripMenuItem_Click); // // toolStripSeparator6 // this.toolStripSeparator6.Name = "toolStripSeparator6"; this.toolStripSeparator6.Size = new System.Drawing.Size(164, 6); // // findAndReplaceStripMenuItem // this.findAndReplaceStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.findToolStripMenuItem, this.replaceToolStripMenuItem}); this.findAndReplaceStripMenuItem.Name = "findAndReplaceStripMenuItem"; this.findAndReplaceStripMenuItem.Size = new System.Drawing.Size(167, 22); this.findAndReplaceStripMenuItem.Text = "&Find and Replace"; // // findToolStripMenuItem // this.findToolStripMenuItem.Name = "findToolStripMenuItem"; this.findToolStripMenuItem.Size = new System.Drawing.Size(123, 22); this.findToolStripMenuItem.Text = "&Find"; this.findToolStripMenuItem.Click += new System.EventHandler(this.findToolStripMenuItem_Click); // // replaceToolStripMenuItem // this.replaceToolStripMenuItem.Name = "replaceToolStripMenuItem"; this.replaceToolStripMenuItem.Size = new System.Drawing.Size(123, 22); this.replaceToolStripMenuItem.Text = "&Replace"; this.replaceToolStripMenuItem.Click += new System.EventHandler(this.replaceToolStripMenuItem_Click); // // goToToolStripMenuItem // this.goToToolStripMenuItem.Name = "goToToolStripMenuItem"; this.goToToolStripMenuItem.Size = new System.Drawing.Size(167, 22); this.goToToolStripMenuItem.Text = "&Go To"; this.goToToolStripMenuItem.Click += new System.EventHandler(this.goToToolStripMenuItem_Click); // // toolStripSeparator7 // this.toolStripSeparator7.Name = "toolStripSeparator7"; this.toolStripSeparator7.Size = new System.Drawing.Size(164, 6); // // bookmarksToolStripMenuItem // this.bookmarksToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toggleBookmarkToolStripMenuItem, this.previosBookmarkToolStripMenuItem, this.nextBookmarkToolStripMenuItem, this.clearBookmarsToolStripMenuItem}); this.bookmarksToolStripMenuItem.Name = "bookmarksToolStripMenuItem"; this.bookmarksToolStripMenuItem.Size = new System.Drawing.Size(167, 22); this.bookmarksToolStripMenuItem.Text = "Boo&kmarks"; // // toggleBookmarkToolStripMenuItem // this.toggleBookmarkToolStripMenuItem.Name = "toggleBookmarkToolStripMenuItem"; this.toggleBookmarkToolStripMenuItem.Size = new System.Drawing.Size(175, 22); this.toggleBookmarkToolStripMenuItem.Text = "&Toggle Bookmark"; this.toggleBookmarkToolStripMenuItem.Click += new System.EventHandler(this.toggleBookmarkToolStripMenuItem_Click); // // previosBookmarkToolStripMenuItem // this.previosBookmarkToolStripMenuItem.Name = "previosBookmarkToolStripMenuItem"; this.previosBookmarkToolStripMenuItem.Size = new System.Drawing.Size(175, 22); this.previosBookmarkToolStripMenuItem.Text = "&Previous Bookmark"; this.previosBookmarkToolStripMenuItem.Click += new System.EventHandler(this.previosBookmarkToolStripMenuItem_Click); // // nextBookmarkToolStripMenuItem // this.nextBookmarkToolStripMenuItem.Name = "nextBookmarkToolStripMenuItem"; this.nextBookmarkToolStripMenuItem.Size = new System.Drawing.Size(175, 22); this.nextBookmarkToolStripMenuItem.Text = "Next &Bookmark"; this.nextBookmarkToolStripMenuItem.Click += new System.EventHandler(this.nextBookmarkToolStripMenuItem_Click); // // clearBookmarsToolStripMenuItem // this.clearBookmarsToolStripMenuItem.Name = "clearBookmarsToolStripMenuItem"; this.clearBookmarsToolStripMenuItem.Size = new System.Drawing.Size(175, 22); this.clearBookmarsToolStripMenuItem.Text = "&Clear Bookmarks"; this.clearBookmarsToolStripMenuItem.Click += new System.EventHandler(this.clearBookmarsToolStripMenuItem_Click); // // advancedToolStripMenuItem // this.advancedToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.makeUpperCaseToolStripMenuItem, this.makeLowerCaseToolStripMenuItem, this.commentStreamToolStripMenuItem, this.commentLineToolStripMenuItem, this.uncommentLineToolStripMenuItem}); this.advancedToolStripMenuItem.Name = "advancedToolStripMenuItem"; this.advancedToolStripMenuItem.Size = new System.Drawing.Size(167, 22); this.advancedToolStripMenuItem.Text = "Ad&vanced"; // // makeUpperCaseToolStripMenuItem // this.makeUpperCaseToolStripMenuItem.Name = "makeUpperCaseToolStripMenuItem"; this.makeUpperCaseToolStripMenuItem.Size = new System.Drawing.Size(175, 22); this.makeUpperCaseToolStripMenuItem.Text = "Make &Upper Case"; this.makeUpperCaseToolStripMenuItem.Click += new System.EventHandler(this.makeUpperCaseToolStripMenuItem_Click); // // makeLowerCaseToolStripMenuItem // this.makeLowerCaseToolStripMenuItem.Name = "makeLowerCaseToolStripMenuItem"; this.makeLowerCaseToolStripMenuItem.Size = new System.Drawing.Size(175, 22); this.makeLowerCaseToolStripMenuItem.Text = "Make &Lower Case"; this.makeLowerCaseToolStripMenuItem.Click += new System.EventHandler(this.makeLowerCaseToolStripMenuItem_Click); // // commentStreamToolStripMenuItem // this.commentStreamToolStripMenuItem.Name = "commentStreamToolStripMenuItem"; this.commentStreamToolStripMenuItem.Size = new System.Drawing.Size(175, 22); this.commentStreamToolStripMenuItem.Text = "Comment (&Stream)"; this.commentStreamToolStripMenuItem.Click += new System.EventHandler(this.commentStreamToolStripMenuItem_Click); // // commentLineToolStripMenuItem // this.commentLineToolStripMenuItem.Name = "commentLineToolStripMenuItem"; this.commentLineToolStripMenuItem.Size = new System.Drawing.Size(175, 22); this.commentLineToolStripMenuItem.Text = "&Comment (Line)"; this.commentLineToolStripMenuItem.Click += new System.EventHandler(this.commentLineToolStripMenuItem_Click); // // uncommentLineToolStripMenuItem // this.uncommentLineToolStripMenuItem.Name = "uncommentLineToolStripMenuItem"; this.uncommentLineToolStripMenuItem.Size = new System.Drawing.Size(175, 22); this.uncommentLineToolStripMenuItem.Text = "&Uncomment (Line)"; this.uncommentLineToolStripMenuItem.Click += new System.EventHandler(this.uncommentLineToolStripMenuItem_Click); // // toolStripSeparator5 // this.toolStripSeparator5.Name = "toolStripSeparator5"; this.toolStripSeparator5.Size = new System.Drawing.Size(164, 6); // // snippetsToolStripMenuItem // this.snippetsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.insertSnippetToolStripMenuItem, this.surroundWithToolStripMenuItem}); this.snippetsToolStripMenuItem.Name = "snippetsToolStripMenuItem"; this.snippetsToolStripMenuItem.Size = new System.Drawing.Size(167, 22); this.snippetsToolStripMenuItem.Text = "&Snippets"; // // insertSnippetToolStripMenuItem // this.insertSnippetToolStripMenuItem.Name = "insertSnippetToolStripMenuItem"; this.insertSnippetToolStripMenuItem.Size = new System.Drawing.Size(154, 22); this.insertSnippetToolStripMenuItem.Text = "&Insert Snippet"; this.insertSnippetToolStripMenuItem.Click += new System.EventHandler(this.insertSnippetToolStripMenuItem_Click); // // surroundWithToolStripMenuItem // this.surroundWithToolStripMenuItem.Name = "surroundWithToolStripMenuItem"; this.surroundWithToolStripMenuItem.Size = new System.Drawing.Size(154, 22); this.surroundWithToolStripMenuItem.Text = "&Surround With"; this.surroundWithToolStripMenuItem.Click += new System.EventHandler(this.surroundWithToolStripMenuItem_Click); // // viewStripMenuItem // this.viewStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.whiteSpaceToolStripMenuItem, this.wordWrapToolStripMenuItem, this.endOfLineToolStripMenuItem, this.toolStripSeparator9, this.zoomInToolStripMenuItem, this.zoomOutToolStripMenuItem, this.resetZoomToolStripMenuItem, this.toolStripSeparator10, this.lineNumbersToolStripMenuItem}); this.viewStripMenuItem.Name = "viewStripMenuItem"; this.viewStripMenuItem.Size = new System.Drawing.Size(41, 20); this.viewStripMenuItem.Text = "&View"; // // whiteSpaceToolStripMenuItem // this.whiteSpaceToolStripMenuItem.Name = "whiteSpaceToolStripMenuItem"; this.whiteSpaceToolStripMenuItem.Size = new System.Drawing.Size(149, 22); this.whiteSpaceToolStripMenuItem.Text = "W&hite Space"; this.whiteSpaceToolStripMenuItem.Click += new System.EventHandler(this.whiteSpaceToolStripMenuItem_Click); // // wordWrapToolStripMenuItem // this.wordWrapToolStripMenuItem.Name = "wordWrapToolStripMenuItem"; this.wordWrapToolStripMenuItem.Size = new System.Drawing.Size(149, 22); this.wordWrapToolStripMenuItem.Text = "&Word Wrap"; this.wordWrapToolStripMenuItem.Click += new System.EventHandler(this.wordWrapToolStripMenuItem_Click); // // endOfLineToolStripMenuItem // this.endOfLineToolStripMenuItem.Name = "endOfLineToolStripMenuItem"; this.endOfLineToolStripMenuItem.Size = new System.Drawing.Size(149, 22); this.endOfLineToolStripMenuItem.Text = "&End of Line"; this.endOfLineToolStripMenuItem.Click += new System.EventHandler(this.endOfLineToolStripMenuItem_Click); // // toolStripSeparator9 // this.toolStripSeparator9.Name = "toolStripSeparator9"; this.toolStripSeparator9.Size = new System.Drawing.Size(146, 6); // // zoomInToolStripMenuItem // this.zoomInToolStripMenuItem.Name = "zoomInToolStripMenuItem"; this.zoomInToolStripMenuItem.Size = new System.Drawing.Size(149, 22); this.zoomInToolStripMenuItem.Text = "Zoom &In"; this.zoomInToolStripMenuItem.Click += new System.EventHandler(this.zoomInToolStripMenuItem_Click); // // zoomOutToolStripMenuItem // this.zoomOutToolStripMenuItem.Name = "zoomOutToolStripMenuItem"; this.zoomOutToolStripMenuItem.Size = new System.Drawing.Size(149, 22); this.zoomOutToolStripMenuItem.Text = "Zoom &Out"; this.zoomOutToolStripMenuItem.Click += new System.EventHandler(this.zoomOutToolStripMenuItem_Click); // // resetZoomToolStripMenuItem // this.resetZoomToolStripMenuItem.Name = "resetZoomToolStripMenuItem"; this.resetZoomToolStripMenuItem.Size = new System.Drawing.Size(149, 22); this.resetZoomToolStripMenuItem.Text = "Reset &Zoom"; this.resetZoomToolStripMenuItem.Click += new System.EventHandler(this.resetZoomToolStripMenuItem_Click); // // toolStripSeparator10 // this.toolStripSeparator10.Name = "toolStripSeparator10"; this.toolStripSeparator10.Size = new System.Drawing.Size(146, 6); // // lineNumbersToolStripMenuItem // this.lineNumbersToolStripMenuItem.Name = "lineNumbersToolStripMenuItem"; this.lineNumbersToolStripMenuItem.Size = new System.Drawing.Size(149, 22); this.lineNumbersToolStripMenuItem.Text = "Line Nu&mbers"; this.lineNumbersToolStripMenuItem.Click += new System.EventHandler(this.lineNumbersToolStripMenuItem_Click); // // windowStripMenuItem // this.windowStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripSeparator8, this.closeToolStripMenuItem1, this.closeAllToolStripMenuItem}); this.windowStripMenuItem.Name = "windowStripMenuItem"; this.windowStripMenuItem.Size = new System.Drawing.Size(57, 20); this.windowStripMenuItem.Text = "&Window"; // // toolStripSeparator8 // this.toolStripSeparator8.Name = "toolStripSeparator8"; this.toolStripSeparator8.Size = new System.Drawing.Size(122, 6); // // closeToolStripMenuItem1 // this.closeToolStripMenuItem1.Name = "closeToolStripMenuItem1"; this.closeToolStripMenuItem1.Size = new System.Drawing.Size(125, 22); this.closeToolStripMenuItem1.Text = "&Close"; // // closeAllToolStripMenuItem // this.closeAllToolStripMenuItem.Name = "closeAllToolStripMenuItem"; this.closeAllToolStripMenuItem.Size = new System.Drawing.Size(125, 22); this.closeAllToolStripMenuItem.Text = "C&lose All"; // // helpToolStripMenuItem // this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.aboutToolStripMenuItem}); this.helpToolStripMenuItem.Name = "helpToolStripMenuItem"; this.helpToolStripMenuItem.Size = new System.Drawing.Size(40, 20); this.helpToolStripMenuItem.Text = "&Help"; // // aboutToolStripMenuItem // this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem"; this.aboutToolStripMenuItem.Size = new System.Drawing.Size(126, 22); this.aboutToolStripMenuItem.Text = "&About..."; this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutToolStripMenuItem_Click); // // panSearch // this.panSearch.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); this.panSearch.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224))))); this.panSearch.Location = new System.Drawing.Point(461, 0); this.panSearch.Name = "panSearch"; this.panSearch.Size = new System.Drawing.Size(564, 34); this.panSearch.TabIndex = 21; // // dockPanel // this.dockPanel.ActiveAutoHideContent = null; this.dockPanel.AllowEndUserNestedDocking = false; this.dockPanel.AutoSize = true; this.dockPanel.BackColor = System.Drawing.SystemColors.Control; this.dockPanel.Dock = System.Windows.Forms.DockStyle.Fill; this.dockPanel.Font = new System.Drawing.Font("Tahoma", 14F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.World); this.dockPanel.Location = new System.Drawing.Point(0, 62); this.dockPanel.Margin = new System.Windows.Forms.Padding(2); this.dockPanel.Name = "dockPanel"; this.dockPanel.Size = new System.Drawing.Size(1028, 451); this.dockPanel.TabIndex = 23; this.dockPanel.ActiveDocumentChanged += new System.EventHandler(this.dockPanel_ActiveDocumentChanged_1); // // panel1 // this.panel1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224))))); this.panel1.Controls.Add(this.chkobjecttext); this.panel1.Controls.Add(this.btnsearch); this.panel1.Controls.Add(this.panSearch); this.panel1.Controls.Add(this.label1); this.panel1.Controls.Add(this.txtsearch); this.panel1.Controls.Add(this.chkobjectname); this.panel1.Dock = System.Windows.Forms.DockStyle.Bottom; this.panel1.Location = new System.Drawing.Point(0, 513); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(1028, 34); this.panel1.TabIndex = 29; // // chkobjecttext // this.chkobjecttext.AutoSize = true; this.chkobjecttext.Location = new System.Drawing.Point(266, 9); this.chkobjecttext.Name = "chkobjecttext"; this.chkobjecttext.Size = new System.Drawing.Size(43, 17); this.chkobjecttext.TabIndex = 32; this.chkobjecttext.Text = "text"; this.chkobjecttext.UseVisualStyleBackColor = true; this.chkobjecttext.CheckedChanged += new System.EventHandler(this.chkobjecttext_CheckedChanged); // // btnsearch // this.btnsearch.Location = new System.Drawing.Point(315, 6); this.btnsearch.Name = "btnsearch"; this.btnsearch.Size = new System.Drawing.Size(40, 23); this.btnsearch.TabIndex = 29; this.btnsearch.Text = "Go"; this.btnsearch.UseVisualStyleBackColor = true; this.btnsearch.Click += new System.EventHandler(this.btnsearch_Click); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(3, 13); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(76, 13); this.label1.TabIndex = 30; this.label1.Text = "Search object:"; // // txtsearch // this.txtsearch.Location = new System.Drawing.Point(85, 8); this.txtsearch.Name = "txtsearch"; this.txtsearch.Size = new System.Drawing.Size(118, 20); this.txtsearch.TabIndex = 28; // // chkobjectname // this.chkobjectname.AutoSize = true; this.chkobjectname.Checked = true; this.chkobjectname.CheckState = System.Windows.Forms.CheckState.Checked; this.chkobjectname.Location = new System.Drawing.Point(209, 9); this.chkobjectname.Name = "chkobjectname"; this.chkobjectname.Size = new System.Drawing.Size(52, 17); this.chkobjectname.TabIndex = 31; this.chkobjectname.Text = "name"; this.chkobjectname.UseVisualStyleBackColor = true; this.chkobjectname.CheckedChanged += new System.EventHandler(this.chkobjectname_CheckedChanged); // // frmMdi // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1028, 547); this.Controls.Add(this.dockPanel); this.Controls.Add(this.panel1); this.Controls.Add(this.panmenu); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.IsMdiContainer = true; this.MainMenuStrip = this.menuStripMain; this.Name = "frmMdi"; this.Load += new System.EventHandler(this.frmMdi_Load); this.panmenu.ResumeLayout(false); this.panmenu.PerformLayout(); this.ts.ResumeLayout(false); this.ts.PerformLayout(); this.menuStripMain.ResumeLayout(false); this.menuStripMain.PerformLayout(); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.OpenFileDialog openFileDialog; private System.Windows.Forms.Panel panmenu; private System.Windows.Forms.ToolStripButton tsConnect; private System.Windows.Forms.ToolStripButton tsDisconnect; private System.Windows.Forms.ToolStripSeparator toolStripSeparator15; private System.Windows.Forms.ToolStripButton tsNew; private System.Windows.Forms.ToolStripButton tsOpen; private System.Windows.Forms.ToolStripButton tsSave; private System.Windows.Forms.ToolStripSeparator toolStripSeparator16; private System.Windows.Forms.ToolStripButton tsExecute; private System.Windows.Forms.ToolStripButton tsCancel; private System.Windows.Forms.ToolStripSeparator toolStripSeparator17; private System.Windows.Forms.ToolStripComboBox tsResult; private System.Windows.Forms.ToolStripButton tsHideResults; private System.Windows.Forms.ToolStripButton tsHideBrowser; private System.Windows.Forms.ToolStripSeparator toolStripSeparator18; private System.Windows.Forms.ToolStripButton tsBeautyCode; private System.Windows.Forms.ToolStripButton tsSnippets; private System.Windows.Forms.ToolStripButton tsQueryHistory; private System.Windows.Forms.ToolStripSeparator toolStripSeparator19; private System.Windows.Forms.ToolStrip ts; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem newToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator11; private System.Windows.Forms.ToolStripMenuItem saveToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem saveAsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem saveAllStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator; private System.Windows.Forms.ToolStripMenuItem closeToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator12; private System.Windows.Forms.ToolStripMenuItem printToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem printPreviewToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem editToolStripMenu; private System.Windows.Forms.ToolStripMenuItem undoToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem redoToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator3; private System.Windows.Forms.ToolStripMenuItem cutToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem pasteToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator4; private System.Windows.Forms.ToolStripMenuItem selectAllToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator6; private System.Windows.Forms.ToolStripMenuItem findAndReplaceStripMenuItem; private System.Windows.Forms.ToolStripMenuItem findToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem replaceToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem goToToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator7; private System.Windows.Forms.ToolStripMenuItem bookmarksToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem toggleBookmarkToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem previosBookmarkToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem nextBookmarkToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem clearBookmarsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem advancedToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem makeUpperCaseToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem makeLowerCaseToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem commentStreamToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem commentLineToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem uncommentLineToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator5; private System.Windows.Forms.ToolStripMenuItem snippetsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem insertSnippetToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem surroundWithToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem viewStripMenuItem; private System.Windows.Forms.ToolStripMenuItem whiteSpaceToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem wordWrapToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem endOfLineToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator9; private System.Windows.Forms.ToolStripMenuItem zoomInToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem zoomOutToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem resetZoomToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator10; private System.Windows.Forms.ToolStripMenuItem lineNumbersToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem windowStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator8; private System.Windows.Forms.ToolStripMenuItem closeToolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem closeAllToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem; private System.Windows.Forms.MenuStrip menuStripMain; private System.Windows.Forms.ToolStripButton toolStripButton1; private System.Windows.Forms.Panel panSearch; private WeifenLuo.WinFormsUI.Docking.DockPanel dockPanel; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.CheckBox chkobjecttext; private System.Windows.Forms.CheckBox chkobjectname; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox txtsearch; private System.Windows.Forms.Button btnsearch; } }
using System; namespace Lucene.Net.Search { using Lucene.Net.Util; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using IBits = Lucene.Net.Util.IBits; using BytesRef = Lucene.Net.Util.BytesRef; using FieldInvertState = Lucene.Net.Index.FieldInvertState; using Similarity = Lucene.Net.Search.Similarities.Similarity; using Terms = Lucene.Net.Index.Terms; using TermsEnum = Lucene.Net.Index.TermsEnum; /// <summary> /// Holds all implementations of classes in the o.a.l.search package as a /// back-compatibility test. It does not run any tests per-se, however if /// someone adds a method to an interface or abstract method to an abstract /// class, one of the implementations here will fail to compile and so we know /// back-compat policy was violated. /// </summary> internal sealed class JustCompileSearch { private const string UNSUPPORTED_MSG = "unsupported: used for back-compat testing only !"; internal sealed class JustCompileCollector : ICollector { public void Collect(int doc) { throw new System.NotSupportedException(UNSUPPORTED_MSG); } public void SetNextReader(AtomicReaderContext context) { throw new System.NotSupportedException(UNSUPPORTED_MSG); } public void SetScorer(Scorer scorer) { throw new System.NotSupportedException(UNSUPPORTED_MSG); } public bool AcceptsDocsOutOfOrder { get { throw new System.NotSupportedException(UNSUPPORTED_MSG); } } } internal sealed class JustCompileDocIdSet : DocIdSet { public override DocIdSetIterator GetIterator() { throw new System.NotSupportedException(UNSUPPORTED_MSG); } } internal sealed class JustCompileDocIdSetIterator : DocIdSetIterator { public override int DocID { get { throw new System.NotSupportedException(UNSUPPORTED_MSG); } } public override int NextDoc() { throw new System.NotSupportedException(UNSUPPORTED_MSG); } public override int Advance(int target) { throw new System.NotSupportedException(UNSUPPORTED_MSG); } public override long GetCost() { throw new System.NotSupportedException(UNSUPPORTED_MSG); } } internal sealed class JustCompileExtendedFieldCacheLongParser : FieldCache.IInt64Parser { /// <summary> /// NOTE: This was parseLong() in Lucene /// </summary> public long ParseInt64(BytesRef @string) { throw new System.NotSupportedException(UNSUPPORTED_MSG); } public TermsEnum TermsEnum(Terms terms) { throw new System.NotSupportedException(UNSUPPORTED_MSG); } } internal sealed class JustCompileExtendedFieldCacheDoubleParser : FieldCache.IDoubleParser { public double ParseDouble(BytesRef term) { throw new System.NotSupportedException(UNSUPPORTED_MSG); } public TermsEnum TermsEnum(Terms terms) { throw new System.NotSupportedException(UNSUPPORTED_MSG); } } internal sealed class JustCompileFieldComparer : FieldComparer<object> { public override int Compare(int slot1, int slot2) { throw new System.NotSupportedException(UNSUPPORTED_MSG); } public override int CompareBottom(int doc) { throw new System.NotSupportedException(UNSUPPORTED_MSG); } public override void Copy(int slot, int doc) { throw new System.NotSupportedException(UNSUPPORTED_MSG); } public override void SetBottom(int slot) { throw new System.NotSupportedException(UNSUPPORTED_MSG); } public override void SetTopValue(object value) { throw new System.NotSupportedException(UNSUPPORTED_MSG); } public override FieldComparer SetNextReader(AtomicReaderContext context) { throw new System.NotSupportedException(UNSUPPORTED_MSG); } // LUCENENET NOTE: This was value(int) in Lucene. public override IComparable this[int slot] { get { throw new System.NotSupportedException(UNSUPPORTED_MSG); } } public override int CompareTop(int doc) { throw new System.NotSupportedException(UNSUPPORTED_MSG); } } internal sealed class JustCompileFieldComparerSource : FieldComparerSource { public override FieldComparer NewComparer(string fieldname, int numHits, int sortPos, bool reversed) { throw new System.NotSupportedException(UNSUPPORTED_MSG); } } internal sealed class JustCompileFilter : Filter { // Filter is just an abstract class with no abstract methods. However it is // still added here in case someone will add abstract methods in the future. public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs) { return null; } } internal sealed class JustCompileFilteredDocIdSet : FilteredDocIdSet { public JustCompileFilteredDocIdSet(DocIdSet innerSet) : base(innerSet) { } protected override bool Match(int docid) { throw new System.NotSupportedException(UNSUPPORTED_MSG); } } internal sealed class JustCompileFilteredDocIdSetIterator : FilteredDocIdSetIterator { public JustCompileFilteredDocIdSetIterator(DocIdSetIterator innerIter) : base(innerIter) { } protected override bool Match(int doc) { throw new System.NotSupportedException(UNSUPPORTED_MSG); } public override long GetCost() { throw new System.NotSupportedException(UNSUPPORTED_MSG); } } internal sealed class JustCompileQuery : Query { public override string ToString(string field) { throw new System.NotSupportedException(UNSUPPORTED_MSG); } } internal sealed class JustCompileScorer : Scorer { internal JustCompileScorer(Weight weight) : base(weight) { } public override float GetScore() { throw new System.NotSupportedException(UNSUPPORTED_MSG); } public override int Freq { get { throw new System.NotSupportedException(UNSUPPORTED_MSG); } } public override int DocID { get { throw new System.NotSupportedException(UNSUPPORTED_MSG); } } public override int NextDoc() { throw new System.NotSupportedException(UNSUPPORTED_MSG); } public override int Advance(int target) { throw new System.NotSupportedException(UNSUPPORTED_MSG); } public override long GetCost() { throw new System.NotSupportedException(UNSUPPORTED_MSG); } } internal sealed class JustCompileSimilarity : Similarity { public override SimWeight ComputeWeight(float queryBoost, CollectionStatistics collectionStats, params TermStatistics[] termStats) { throw new System.NotSupportedException(UNSUPPORTED_MSG); } public override SimScorer GetSimScorer(SimWeight stats, AtomicReaderContext context) { throw new System.NotSupportedException(UNSUPPORTED_MSG); } public override long ComputeNorm(FieldInvertState state) { throw new System.NotSupportedException(UNSUPPORTED_MSG); } } internal sealed class JustCompileTopDocsCollector : TopDocsCollector<ScoreDoc> { internal JustCompileTopDocsCollector(PriorityQueue<ScoreDoc> pq) : base(pq) { } public override void Collect(int doc) { throw new System.NotSupportedException(UNSUPPORTED_MSG); } public override void SetNextReader(AtomicReaderContext context) { throw new System.NotSupportedException(UNSUPPORTED_MSG); } public override void SetScorer(Scorer scorer) { throw new System.NotSupportedException(UNSUPPORTED_MSG); } public override bool AcceptsDocsOutOfOrder { get { throw new System.NotSupportedException(UNSUPPORTED_MSG); } } public override TopDocs GetTopDocs() { throw new System.NotSupportedException(UNSUPPORTED_MSG); } public override TopDocs GetTopDocs(int start) { throw new System.NotSupportedException(UNSUPPORTED_MSG); } public override TopDocs GetTopDocs(int start, int end) { throw new System.NotSupportedException(UNSUPPORTED_MSG); } } internal sealed class JustCompileWeight : Weight { public override Explanation Explain(AtomicReaderContext context, int doc) { throw new System.NotSupportedException(UNSUPPORTED_MSG); } public override Query Query { get { throw new System.NotSupportedException(UNSUPPORTED_MSG); } } public override void Normalize(float norm, float topLevelBoost) { throw new System.NotSupportedException(UNSUPPORTED_MSG); } public override float GetValueForNormalization() { throw new System.NotSupportedException(UNSUPPORTED_MSG); } public override Scorer GetScorer(AtomicReaderContext context, IBits acceptDocs) { throw new System.NotSupportedException(UNSUPPORTED_MSG); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using GitVersion.Common; using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.Model.Configuration; namespace GitVersion.Configuration { public class BranchConfigurationCalculator : IBranchConfigurationCalculator { private const string FallbackConfigName = "Fallback"; private readonly ILog log; private readonly IRepositoryStore repositoryStore; public BranchConfigurationCalculator(ILog log, IRepositoryStore repositoryStore) { this.log = log ?? throw new ArgumentNullException(nameof(log)); this.repositoryStore = repositoryStore ?? throw new ArgumentNullException(nameof(repositoryStore)); } /// <summary> /// Gets the <see cref="BranchConfig"/> for the current commit. /// </summary> public BranchConfig GetBranchConfiguration(IBranch targetBranch, ICommit currentCommit, Config configuration, IList<IBranch> excludedInheritBranches = null) { var matchingBranches = configuration.GetConfigForBranch(targetBranch.Name.WithoutRemote); if (matchingBranches == null) { log.Info($"No branch configuration found for branch {targetBranch}, falling back to default configuration"); matchingBranches = BranchConfig.CreateDefaultBranchConfig(FallbackConfigName) .Apply(new BranchConfig { Regex = "", VersioningMode = configuration.VersioningMode, Increment = configuration.Increment ?? IncrementStrategy.Inherit, }); } if (matchingBranches.Increment == IncrementStrategy.Inherit) { matchingBranches = InheritBranchConfiguration(targetBranch, matchingBranches, currentCommit, configuration, excludedInheritBranches); if (matchingBranches.Name.IsEquivalentTo(FallbackConfigName) && matchingBranches.Increment == IncrementStrategy.Inherit) { // We tried, and failed to inherit, just fall back to patch matchingBranches.Increment = IncrementStrategy.Patch; } } return matchingBranches; } // TODO I think we need to take a fresh approach to this.. it's getting really complex with heaps of edge cases private BranchConfig InheritBranchConfiguration(IBranch targetBranch, BranchConfig branchConfiguration, ICommit currentCommit, Config configuration, IList<IBranch> excludedInheritBranches) { using (log.IndentLog("Attempting to inherit branch configuration from parent branch")) { var excludedBranches = new[] { targetBranch }; // Check if we are a merge commit. If so likely we are a pull request var parentCount = currentCommit.Parents.Count(); if (parentCount == 2) { excludedBranches = CalculateWhenMultipleParents(currentCommit, ref targetBranch, excludedBranches); } excludedInheritBranches ??= repositoryStore.GetExcludedInheritBranches(configuration).ToList(); excludedBranches = excludedBranches.Where(b => excludedInheritBranches.All(bte => !b.Equals(bte))).ToArray(); // Add new excluded branches. foreach (var excludedBranch in excludedBranches) { excludedInheritBranches.Add(excludedBranch); } var branchesToEvaluate = repositoryStore.ExcludingBranches(excludedInheritBranches).ToList(); var branchPoint = repositoryStore .FindCommitBranchWasBranchedFrom(targetBranch, configuration, excludedInheritBranches.ToArray()); List<IBranch> possibleParents; if (branchPoint == BranchCommit.Empty) { possibleParents = repositoryStore.GetBranchesContainingCommit(targetBranch.Tip, branchesToEvaluate) // It fails to inherit Increment branch configuration if more than 1 parent; // therefore no point to get more than 2 parents .Take(2) .ToList(); } else { var branches = repositoryStore.GetBranchesContainingCommit(branchPoint.Commit, branchesToEvaluate).ToList(); if (branches.Count > 1) { var currentTipBranches = repositoryStore.GetBranchesContainingCommit(currentCommit, branchesToEvaluate).ToList(); possibleParents = branches.Except(currentTipBranches).ToList(); } else { possibleParents = branches; } } log.Info("Found possible parent branches: " + string.Join(", ", possibleParents.Select(p => p.ToString()))); if (possibleParents.Count == 1) { var branchConfig = GetBranchConfiguration(possibleParents[0], currentCommit, configuration, excludedInheritBranches); // If we have resolved a fallback config we should not return that we have got config if (branchConfig.Name != FallbackConfigName) { return new BranchConfig(branchConfiguration) { Increment = branchConfig.Increment, PreventIncrementOfMergedBranchVersion = branchConfig.PreventIncrementOfMergedBranchVersion, // If we are inheriting from develop then we should behave like develop TracksReleaseBranches = branchConfig.TracksReleaseBranches }; } } // If we fail to inherit it is probably because the branch has been merged and we can't do much. So we will fall back to develop's config // if develop exists and main if not var errorMessage = possibleParents.Count == 0 ? "Failed to inherit Increment branch configuration, no branches found." : "Failed to inherit Increment branch configuration, ended up with: " + string.Join(", ", possibleParents.Select(p => p.ToString())); var chosenBranch = repositoryStore.GetChosenBranch(configuration); if (chosenBranch == null) { // TODO We should call the build server to generate this exception, each build server works differently // for fetch issues and we could give better warnings. throw new InvalidOperationException("Could not find a 'develop' or 'main' branch, neither locally nor remotely."); } log.Warning($"{errorMessage}{System.Environment.NewLine}Falling back to {chosenBranch} branch config"); // To prevent infinite loops, make sure that a new branch was chosen. if (targetBranch.Equals(chosenBranch)) { var developOrMainConfig = ChooseMainOrDevelopIncrementStrategyIfTheChosenBranchIsOneOfThem( chosenBranch, branchConfiguration, configuration); if (developOrMainConfig != null) { return developOrMainConfig; } log.Warning("Fallback branch wants to inherit Increment branch configuration from itself. Using patch increment instead."); return new BranchConfig(branchConfiguration) { Increment = IncrementStrategy.Patch }; } var inheritingBranchConfig = GetBranchConfiguration(chosenBranch, currentCommit, configuration, excludedInheritBranches); var configIncrement = inheritingBranchConfig.Increment; if (inheritingBranchConfig.Name.IsEquivalentTo(FallbackConfigName) && configIncrement == IncrementStrategy.Inherit) { log.Warning("Fallback config inherits by default, dropping to patch increment"); configIncrement = IncrementStrategy.Patch; } return new BranchConfig(branchConfiguration) { Increment = configIncrement, PreventIncrementOfMergedBranchVersion = inheritingBranchConfig.PreventIncrementOfMergedBranchVersion, // If we are inheriting from develop then we should behave like develop TracksReleaseBranches = inheritingBranchConfig.TracksReleaseBranches }; } } private IBranch[] CalculateWhenMultipleParents(ICommit currentCommit, ref IBranch currentBranch, IBranch[] excludedBranches) { var parents = currentCommit.Parents.ToArray(); var branches = repositoryStore.GetBranchesForCommit(parents[1]).ToList(); if (branches.Count == 1) { var branch = branches[0]; excludedBranches = new[] { currentBranch, branch }; currentBranch = branch; } else if (branches.Count > 1) { currentBranch = branches.FirstOrDefault(b => b.Name.WithoutRemote == Config.MainBranchKey) ?? branches.First(); } else { var possibleTargetBranches = repositoryStore.GetBranchesForCommit(parents[0]).ToList(); if (possibleTargetBranches.Count > 1) { currentBranch = possibleTargetBranches.FirstOrDefault(b => b.Name.WithoutRemote == Config.MainBranchKey) ?? possibleTargetBranches.First(); } else { currentBranch = possibleTargetBranches.FirstOrDefault() ?? currentBranch; } } log.Info($"HEAD is merge commit, this is likely a pull request using {currentBranch} as base"); return excludedBranches; } private static BranchConfig ChooseMainOrDevelopIncrementStrategyIfTheChosenBranchIsOneOfThem(IBranch chosenBranch, BranchConfig branchConfiguration, Config config) { BranchConfig mainOrDevelopConfig = null; var developBranchRegex = config.Branches[Config.DevelopBranchKey].Regex; var mainBranchRegex = config.Branches[Config.MainBranchKey].Regex; if (Regex.IsMatch(chosenBranch.Name.Friendly, developBranchRegex, RegexOptions.IgnoreCase)) { // Normally we would not expect this to happen but for safety we add a check if (config.Branches[Config.DevelopBranchKey].Increment != IncrementStrategy.Inherit) { mainOrDevelopConfig = new BranchConfig(branchConfiguration) { Increment = config.Branches[Config.DevelopBranchKey].Increment }; } } else if (Regex.IsMatch(chosenBranch.Name.Friendly, mainBranchRegex, RegexOptions.IgnoreCase)) { // Normally we would not expect this to happen but for safety we add a check if (config.Branches[Config.MainBranchKey].Increment != IncrementStrategy.Inherit) { mainOrDevelopConfig = new BranchConfig(branchConfiguration) { Increment = config.Branches[Config.DevelopBranchKey].Increment }; } } return mainOrDevelopConfig; } } }
/* * 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.Net; using System.Collections.Generic; using Nini.Config; using OpenMetaverse; using OpenSim.Data.Null; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Framework.Console; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Physics.Manager; using OpenSim.Region.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.CoreModules.Avatar.Gods; using OpenSim.Region.CoreModules.Asset; using OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset; using OpenSim.Region.CoreModules.ServiceConnectorsOut.Authentication; using OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory; using OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid; using OpenSim.Region.CoreModules.ServiceConnectorsOut.UserAccounts; using OpenSim.Region.CoreModules.ServiceConnectorsOut.Presence; using OpenSim.Services.Interfaces; using OpenSim.Tests.Common.Mock; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace OpenSim.Tests.Common { /// <summary> /// Helpers for setting up scenes. /// </summary> public class SceneHelpers { /// <summary> /// We need a scene manager so that test clients can retrieve a scene when performing teleport tests. /// </summary> public SceneManager SceneManager { get; private set; } public ISimulationDataService SimDataService { get; private set; } private AgentCircuitManager m_acm = new AgentCircuitManager(); private IEstateDataService m_estateDataService = null; private LocalAssetServicesConnector m_assetService; private LocalAuthenticationServicesConnector m_authenticationService; private LocalInventoryServicesConnector m_inventoryService; private LocalGridServicesConnector m_gridService; private LocalUserAccountServicesConnector m_userAccountService; private LocalPresenceServicesConnector m_presenceService; private CoreAssetCache m_cache; public SceneHelpers() : this(null) {} public SceneHelpers(CoreAssetCache cache) { SceneManager = new SceneManager(); m_assetService = StartAssetService(cache); m_authenticationService = StartAuthenticationService(); m_inventoryService = StartInventoryService(); m_gridService = StartGridService(); m_userAccountService = StartUserAccountService(); m_presenceService = StartPresenceService(); m_inventoryService.PostInitialise(); m_assetService.PostInitialise(); m_userAccountService.PostInitialise(); m_presenceService.PostInitialise(); m_cache = cache; SimDataService = OpenSim.Server.Base.ServerUtils.LoadPlugin<ISimulationDataService>("OpenSim.Tests.Common.dll", null); } /// <summary> /// Set up a test scene /// </summary> /// <remarks> /// Automatically starts services, as would the normal runtime. /// </remarks> /// <returns></returns> public TestScene SetupScene() { return SetupScene("Unit test region", UUID.Random(), 1000, 1000); } public TestScene SetupScene(string name, UUID id, uint x, uint y) { return SetupScene(name, id, x, y, new IniConfigSource()); } public TestScene SetupScene(string name, UUID id, uint x, uint y, IConfigSource configSource) { return SetupScene(name, id, x, y, Constants.RegionSize, Constants.RegionSize, configSource); } /// <summary> /// Set up a scene. /// </summary> /// <param name="name">Name of the region</param> /// <param name="id">ID of the region</param> /// <param name="x">X co-ordinate of the region</param> /// <param name="y">Y co-ordinate of the region</param> /// <param name="sizeX">X size of scene</param> /// <param name="sizeY">Y size of scene</param> /// <param name="configSource"></param> /// <returns></returns> public TestScene SetupScene( string name, UUID id, uint x, uint y, uint sizeX, uint sizeY, IConfigSource configSource) { Console.WriteLine("Setting up test scene {0}", name); // We must set up a console otherwise setup of some modules may fail MainConsole.Instance = new MockConsole(); RegionInfo regInfo = new RegionInfo(x, y, new IPEndPoint(IPAddress.Loopback, 9000), "127.0.0.1"); regInfo.RegionName = name; regInfo.RegionID = id; regInfo.RegionSizeX = sizeX; regInfo.RegionSizeY = sizeY; SceneCommunicationService scs = new SceneCommunicationService(); TestScene testScene = new TestScene( regInfo, m_acm, scs, SimDataService, m_estateDataService, configSource, null); INonSharedRegionModule godsModule = new GodsModule(); godsModule.Initialise(new IniConfigSource()); godsModule.AddRegion(testScene); // Add scene to services m_assetService.AddRegion(testScene); if (m_cache != null) { m_cache.AddRegion(testScene); m_cache.RegionLoaded(testScene); testScene.AddRegionModule(m_cache.Name, m_cache); } m_assetService.RegionLoaded(testScene); testScene.AddRegionModule(m_assetService.Name, m_assetService); m_authenticationService.AddRegion(testScene); m_authenticationService.RegionLoaded(testScene); testScene.AddRegionModule(m_authenticationService.Name, m_authenticationService); m_inventoryService.AddRegion(testScene); m_inventoryService.RegionLoaded(testScene); testScene.AddRegionModule(m_inventoryService.Name, m_inventoryService); m_gridService.AddRegion(testScene); m_gridService.RegionLoaded(testScene); testScene.AddRegionModule(m_gridService.Name, m_gridService); m_userAccountService.AddRegion(testScene); m_userAccountService.RegionLoaded(testScene); testScene.AddRegionModule(m_userAccountService.Name, m_userAccountService); m_presenceService.AddRegion(testScene); m_presenceService.RegionLoaded(testScene); testScene.AddRegionModule(m_presenceService.Name, m_presenceService); testScene.RegionInfo.EstateSettings.EstateOwner = UUID.Random(); testScene.SetModuleInterfaces(); testScene.LandChannel = new TestLandChannel(testScene); testScene.LoadWorldMap(); PhysicsPluginManager physicsPluginManager = new PhysicsPluginManager(); physicsPluginManager.LoadPluginsFromAssembly("Physics/OpenSim.Region.Physics.BasicPhysicsPlugin.dll"); Vector3 regionExtent = new Vector3( regInfo.RegionSizeX, regInfo.RegionSizeY, regInfo.RegionSizeZ); testScene.PhysicsScene = physicsPluginManager.GetPhysicsScene("basicphysics", "ZeroMesher", new IniConfigSource(), "test", regionExtent); testScene.RegionInfo.EstateSettings = new EstateSettings(); testScene.LoginsEnabled = true; testScene.RegisterRegionWithGrid(); SceneManager.Add(testScene); return testScene; } private static LocalAssetServicesConnector StartAssetService(CoreAssetCache cache) { IConfigSource config = new IniConfigSource(); config.AddConfig("Modules"); config.Configs["Modules"].Set("AssetServices", "LocalAssetServicesConnector"); config.AddConfig("AssetService"); config.Configs["AssetService"].Set("LocalServiceModule", "OpenSim.Services.AssetService.dll:AssetService"); config.Configs["AssetService"].Set("StorageProvider", "OpenSim.Tests.Common.dll"); LocalAssetServicesConnector assetService = new LocalAssetServicesConnector(); assetService.Initialise(config); if (cache != null) { IConfigSource cacheConfig = new IniConfigSource(); cacheConfig.AddConfig("Modules"); cacheConfig.Configs["Modules"].Set("AssetCaching", "CoreAssetCache"); cacheConfig.AddConfig("AssetCache"); cache.Initialise(cacheConfig); } return assetService; } private static LocalAuthenticationServicesConnector StartAuthenticationService() { IConfigSource config = new IniConfigSource(); config.AddConfig("Modules"); config.AddConfig("AuthenticationService"); config.Configs["Modules"].Set("AuthenticationServices", "LocalAuthenticationServicesConnector"); config.Configs["AuthenticationService"].Set( "LocalServiceModule", "OpenSim.Services.AuthenticationService.dll:PasswordAuthenticationService"); config.Configs["AuthenticationService"].Set("StorageProvider", "OpenSim.Data.Null.dll"); LocalAuthenticationServicesConnector service = new LocalAuthenticationServicesConnector(); service.Initialise(config); return service; } private static LocalInventoryServicesConnector StartInventoryService() { IConfigSource config = new IniConfigSource(); config.AddConfig("Modules"); config.AddConfig("InventoryService"); config.Configs["Modules"].Set("InventoryServices", "LocalInventoryServicesConnector"); config.Configs["InventoryService"].Set("LocalServiceModule", "OpenSim.Services.InventoryService.dll:XInventoryService"); config.Configs["InventoryService"].Set("StorageProvider", "OpenSim.Tests.Common.dll"); LocalInventoryServicesConnector inventoryService = new LocalInventoryServicesConnector(); inventoryService.Initialise(config); return inventoryService; } private static LocalGridServicesConnector StartGridService() { IConfigSource config = new IniConfigSource(); config.AddConfig("Modules"); config.AddConfig("GridService"); config.Configs["Modules"].Set("GridServices", "LocalGridServicesConnector"); config.Configs["GridService"].Set("StorageProvider", "OpenSim.Data.Null.dll:NullRegionData"); config.Configs["GridService"].Set("LocalServiceModule", "OpenSim.Services.GridService.dll:GridService"); config.Configs["GridService"].Set("ConnectionString", "!static"); LocalGridServicesConnector gridService = new LocalGridServicesConnector(); gridService.Initialise(config); return gridService; } /// <summary> /// Start a user account service /// </summary> /// <param name="testScene"></param> /// <returns></returns> private static LocalUserAccountServicesConnector StartUserAccountService() { IConfigSource config = new IniConfigSource(); config.AddConfig("Modules"); config.AddConfig("UserAccountService"); config.Configs["Modules"].Set("UserAccountServices", "LocalUserAccountServicesConnector"); config.Configs["UserAccountService"].Set("StorageProvider", "OpenSim.Data.Null.dll"); config.Configs["UserAccountService"].Set( "LocalServiceModule", "OpenSim.Services.UserAccountService.dll:UserAccountService"); LocalUserAccountServicesConnector userAccountService = new LocalUserAccountServicesConnector(); userAccountService.Initialise(config); return userAccountService; } /// <summary> /// Start a presence service /// </summary> /// <param name="testScene"></param> private static LocalPresenceServicesConnector StartPresenceService() { // Unfortunately, some services share data via statics, so we need to null every time to stop interference // between tests. // This is a massive non-obvious pita. NullPresenceData.Instance = null; IConfigSource config = new IniConfigSource(); config.AddConfig("Modules"); config.AddConfig("PresenceService"); config.Configs["Modules"].Set("PresenceServices", "LocalPresenceServicesConnector"); config.Configs["PresenceService"].Set("StorageProvider", "OpenSim.Data.Null.dll"); config.Configs["PresenceService"].Set( "LocalServiceModule", "OpenSim.Services.PresenceService.dll:PresenceService"); LocalPresenceServicesConnector presenceService = new LocalPresenceServicesConnector(); presenceService.Initialise(config); return presenceService; } /// <summary> /// Setup modules for a scene using their default settings. /// </summary> /// <param name="scene"></param> /// <param name="modules"></param> public static void SetupSceneModules(Scene scene, params object[] modules) { SetupSceneModules(scene, new IniConfigSource(), modules); } /// <summary> /// Setup modules for a scene. /// </summary> /// <remarks> /// If called directly, then all the modules must be shared modules. /// </remarks> /// <param name="scenes"></param> /// <param name="config"></param> /// <param name="modules"></param> public static void SetupSceneModules(Scene scene, IConfigSource config, params object[] modules) { SetupSceneModules(new Scene[] { scene }, config, modules); } /// <summary> /// Setup modules for a scene using their default settings. /// </summary> /// <param name="scenes"></param> /// <param name="modules"></param> public static void SetupSceneModules(Scene[] scenes, params object[] modules) { SetupSceneModules(scenes, new IniConfigSource(), modules); } /// <summary> /// Setup modules for scenes. /// </summary> /// <remarks> /// If called directly, then all the modules must be shared modules. /// /// We are emulating here the normal calls made to setup region modules /// (Initialise(), PostInitialise(), AddRegion, RegionLoaded()). /// TODO: Need to reuse normal runtime module code. /// </remarks> /// <param name="scenes"></param> /// <param name="config"></param> /// <param name="modules"></param> public static void SetupSceneModules(Scene[] scenes, IConfigSource config, params object[] modules) { List<IRegionModuleBase> newModules = new List<IRegionModuleBase>(); foreach (object module in modules) { IRegionModuleBase m = (IRegionModuleBase)module; // Console.WriteLine("MODULE {0}", m.Name); m.Initialise(config); newModules.Add(m); } foreach (IRegionModuleBase module in newModules) { if (module is ISharedRegionModule) ((ISharedRegionModule)module).PostInitialise(); } foreach (IRegionModuleBase module in newModules) { foreach (Scene scene in scenes) { module.AddRegion(scene); scene.AddRegionModule(module.Name, module); } } // RegionLoaded is fired after all modules have been appropriately added to all scenes foreach (IRegionModuleBase module in newModules) foreach (Scene scene in scenes) module.RegionLoaded(scene); foreach (Scene scene in scenes) { scene.SetModuleInterfaces(); } } /// <summary> /// Generate some standard agent connection data. /// </summary> /// <param name="agentId"></param> /// <returns></returns> public static AgentCircuitData GenerateAgentData(UUID agentId) { AgentCircuitData acd = GenerateCommonAgentData(); acd.AgentID = agentId; acd.firstname = "testfirstname"; acd.lastname = "testlastname"; acd.ServiceURLs = new Dictionary<string, object>(); return acd; } /// <summary> /// Generate some standard agent connection data. /// </summary> /// <param name="agentId"></param> /// <returns></returns> public static AgentCircuitData GenerateAgentData(UserAccount ua) { AgentCircuitData acd = GenerateCommonAgentData(); acd.AgentID = ua.PrincipalID; acd.firstname = ua.FirstName; acd.lastname = ua.LastName; acd.ServiceURLs = ua.ServiceURLs; return acd; } private static AgentCircuitData GenerateCommonAgentData() { AgentCircuitData acd = new AgentCircuitData(); // XXX: Sessions must be unique, otherwise one presence can overwrite another in NullPresenceData. acd.SessionID = UUID.Random(); acd.SecureSessionID = UUID.Random(); acd.circuitcode = 123; acd.BaseFolder = UUID.Zero; acd.InventoryFolder = UUID.Zero; acd.startpos = Vector3.Zero; acd.CapsPath = "http://wibble.com"; acd.Appearance = new AvatarAppearance(); return acd; } /// <summary> /// Add a root agent where the details of the agent connection (apart from the id) are unimportant for the test /// </summary> /// <remarks> /// XXX: Use the version of this method that takes the UserAccount structure wherever possible - this will /// make the agent circuit data (e.g. first, lastname) consistent with the user account data. /// </remarks> /// <param name="scene"></param> /// <param name="agentId"></param> /// <returns></returns> public static ScenePresence AddScenePresence(Scene scene, UUID agentId) { return AddScenePresence(scene, GenerateAgentData(agentId)); } /// <summary> /// Add a root agent. /// </summary> /// <param name="scene"></param> /// <param name="ua"></param> /// <returns></returns> public static ScenePresence AddScenePresence(Scene scene, UserAccount ua) { return AddScenePresence(scene, GenerateAgentData(ua)); } /// <summary> /// Add a root agent. /// </summary> /// <remarks> /// This function /// /// 1) Tells the scene that an agent is coming. Normally, the login service (local if standalone, from the /// userserver if grid) would give initial login data back to the client and separately tell the scene that the /// agent was coming. /// /// 2) Connects the agent with the scene /// /// This function performs actions equivalent with notifying the scene that an agent is /// coming and then actually connecting the agent to the scene. The one step missed out is the very first /// </remarks> /// <param name="scene"></param> /// <param name="agentData"></param> /// <returns></returns> public static ScenePresence AddScenePresence(Scene scene, AgentCircuitData agentData) { return AddScenePresence(scene, new TestClient(agentData, scene), agentData); } /// <summary> /// Add a root agent. /// </summary> /// <remarks> /// This function /// /// 1) Tells the scene that an agent is coming. Normally, the login service (local if standalone, from the /// userserver if grid) would give initial login data back to the client and separately tell the scene that the /// agent was coming. /// /// 2) Connects the agent with the scene /// /// This function performs actions equivalent with notifying the scene that an agent is /// coming and then actually connecting the agent to the scene. The one step missed out is the very first /// </remarks> /// <param name="scene"></param> /// <param name="agentData"></param> /// <returns></returns> public static ScenePresence AddScenePresence( Scene scene, IClientAPI client, AgentCircuitData agentData) { // We emulate the proper login sequence here by doing things in four stages // Stage 0: login // We need to punch through to the underlying service because scene will not, correctly, let us call it // through it's reference to the LPSC LocalPresenceServicesConnector lpsc = (LocalPresenceServicesConnector)scene.PresenceService; lpsc.m_PresenceService.LoginAgent(agentData.AgentID.ToString(), agentData.SessionID, agentData.SecureSessionID); // Stages 1 & 2 ScenePresence sp = IntroduceClientToScene(scene, client, agentData, TeleportFlags.ViaLogin); // Stage 3: Complete the entrance into the region. This converts the child agent into a root agent. sp.CompleteMovement(sp.ControllingClient, true); return sp; } /// <summary> /// Introduce an agent into the scene by adding a new client. /// </summary> /// <returns>The scene presence added</returns> /// <param name='scene'></param> /// <param name='testClient'></param> /// <param name='agentData'></param> /// <param name='tf'></param> private static ScenePresence IntroduceClientToScene( Scene scene, IClientAPI client, AgentCircuitData agentData, TeleportFlags tf) { string reason; // Stage 1: tell the scene to expect a new user connection if (!scene.NewUserConnection(agentData, (uint)tf, null, out reason)) Console.WriteLine("NewUserConnection failed: " + reason); // Stage 2: add the new client as a child agent to the scene scene.AddNewAgent(client, PresenceType.User); return scene.GetScenePresence(client.AgentId); } public static ScenePresence AddChildScenePresence(Scene scene, UUID agentId) { return AddChildScenePresence(scene, GenerateAgentData(agentId)); } public static ScenePresence AddChildScenePresence(Scene scene, AgentCircuitData acd) { acd.child = true; // XXX: ViaLogin may not be correct for child agents TestClient client = new TestClient(acd, scene); return IntroduceClientToScene(scene, client, acd, TeleportFlags.ViaLogin); } /// <summary> /// Add a test object /// </summary> /// <param name="scene"></param> /// <returns></returns> public static SceneObjectGroup AddSceneObject(Scene scene) { return AddSceneObject(scene, "Test Object", UUID.Zero); } /// <summary> /// Add a test object /// </summary> /// <param name="scene"></param> /// <param name="name"></param> /// <param name="ownerId"></param> /// <returns></returns> public static SceneObjectGroup AddSceneObject(Scene scene, string name, UUID ownerId) { SceneObjectGroup so = new SceneObjectGroup(CreateSceneObjectPart(name, UUID.Random(), ownerId)); //part.UpdatePrimFlags(false, false, true); //part.ObjectFlags |= (uint)PrimFlags.Phantom; scene.AddNewSceneObject(so, false); return so; } /// <summary> /// Add a test object /// </summary> /// <param name="scene"></param> /// <param name="parts"> /// The number of parts that should be in the scene object /// </param> /// <param name="ownerId"></param> /// <param name="partNamePrefix"> /// The prefix to be given to part names. This will be suffixed with "Part<part no>" /// (e.g. mynamePart1 for the root part) /// </param> /// <param name="uuidTail"> /// The hexadecimal last part of the UUID for parts created. A UUID of the form "00000000-0000-0000-0000-{0:XD12}" /// will be given to the root part, and incremented for each part thereafter. /// </param> /// <returns></returns> public static SceneObjectGroup AddSceneObject(Scene scene, int parts, UUID ownerId, string partNamePrefix, int uuidTail) { SceneObjectGroup so = CreateSceneObject(parts, ownerId, partNamePrefix, uuidTail); scene.AddNewSceneObject(so, false); return so; } /// <summary> /// Create a scene object part. /// </summary> /// <param name="name"></param> /// <param name="id"></param> /// <param name="ownerId"></param> /// <returns></returns> public static SceneObjectPart CreateSceneObjectPart(string name, UUID id, UUID ownerId) { return new SceneObjectPart( ownerId, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero) { Name = name, UUID = id, Scale = new Vector3(1, 1, 1) }; } /// <summary> /// Create a scene object but do not add it to the scene. /// </summary> /// <remarks> /// UUID always starts at 00000000-0000-0000-0000-000000000001. For some purposes, (e.g. serializing direct /// to another object's inventory) we do not need a scene unique ID. So it would be better to add the /// UUID when we actually add an object to a scene rather than on creation. /// </remarks> /// <param name="parts">The number of parts that should be in the scene object</param> /// <param name="ownerId"></param> /// <returns></returns> public static SceneObjectGroup CreateSceneObject(int parts, UUID ownerId) { return CreateSceneObject(parts, ownerId, 0x1); } /// <summary> /// Create a scene object but do not add it to the scene. /// </summary> /// <param name="parts">The number of parts that should be in the scene object</param> /// <param name="ownerId"></param> /// <param name="uuidTail"> /// The hexadecimal last part of the UUID for parts created. A UUID of the form "00000000-0000-0000-0000-{0:XD12}" /// will be given to the root part, and incremented for each part thereafter. /// </param> /// <returns></returns> public static SceneObjectGroup CreateSceneObject(int parts, UUID ownerId, int uuidTail) { return CreateSceneObject(parts, ownerId, "", uuidTail); } /// <summary> /// Create a scene object but do not add it to the scene. /// </summary> /// <param name="parts"> /// The number of parts that should be in the scene object /// </param> /// <param name="ownerId"></param> /// <param name="partNamePrefix"> /// The prefix to be given to part names. This will be suffixed with "Part<part no>" /// (e.g. mynamePart1 for the root part) /// </param> /// <param name="uuidTail"> /// The hexadecimal last part of the UUID for parts created. A UUID of the form "00000000-0000-0000-0000-{0:XD12}" /// will be given to the root part, and incremented for each part thereafter. /// </param> /// <returns></returns> public static SceneObjectGroup CreateSceneObject(int parts, UUID ownerId, string partNamePrefix, int uuidTail) { string rawSogId = string.Format("00000000-0000-0000-0000-{0:X12}", uuidTail); SceneObjectGroup sog = new SceneObjectGroup( CreateSceneObjectPart(string.Format("{0}Part1", partNamePrefix), new UUID(rawSogId), ownerId)); if (parts > 1) for (int i = 2; i <= parts; i++) sog.AddPart( CreateSceneObjectPart( string.Format("{0}Part{1}", partNamePrefix, i), new UUID(string.Format("00000000-0000-0000-0000-{0:X12}", uuidTail + i - 1)), ownerId)); return sog; } } }
body { font-family: "Helvetica Neue", arial, sans-serif; font-size: 14px; line-height: 1.6; padding-top: 10px; padding-bottom: 10px; background-color: white; padding: 30px; color: #333; border: 1px solid #aaa; max-width: 900px; margin: 20px auto; } body > *:first-child { margin-top: 0 !important; } body > *:last-child { margin-bottom: 0 !important; } a { color: #4183C4; text-decoration: none; } a.absent { color: #cc0000; } a.anchor { display: block; padding-left: 30px; margin-left: -30px; cursor: pointer; position: absolute; top: 0; left: 0; bottom: 0; } h1, h2, h3, h4, h5, h6 { margin: 20px 0 10px; padding: 0; font-weight: bold; -webkit-font-smoothing: antialiased; cursor: text; position: relative; } h2:first-child, h1:first-child, h1:first-child + h2, h3:first-child, h4:first-child, h5:first-child, h6:first-child { margin-top: 0; padding-top: 0; } h1:hover a.anchor, h2:hover a.anchor, h3:hover a.anchor, h4:hover a.anchor, h5:hover a.anchor, h6:hover a.anchor { text-decoration: none; } h1 tt, h1 code { font-size: inherit; } h2 tt, h2 code { font-size: inherit; } h3 tt, h3 code { font-size: inherit; } h4 tt, h4 code { font-size: inherit; } h5 tt, h5 code { font-size: inherit; } h6 tt, h6 code { font-size: inherit; } h1 { font-size: 28px; color: black; } h2 { font-size: 24px; border-bottom: 1px solid #cccccc; color: black; } h3 { font-size: 18px; } h4 { font-size: 16px; } h5 { font-size: 14px; } h6 { color: #777777; font-size: 14px; } p, blockquote, ul, ol, dl, li, table, pre { margin: 3px 0; } hr { background: transparent url("http://tinyurl.com/bq5kskr") repeat-x 0 0; border: 0 none; color: #cccccc; height: 4px; padding: 0; } body > h2:first-child { margin-top: 0; padding-top: 0; } body > h1:first-child { margin-top: 0; padding-top: 0; } body > h1:first-child + h2 { margin-top: 0; padding-top: 0; } body > h3:first-child, body > h4:first-child, body > h5:first-child, body > h6:first-child { margin-top: 0; padding-top: 0; } a:first-child h1, a:first-child h2, a:first-child h3, a:first-child h4, a:first-child h5, a:first-child h6 { margin-top: 0; padding-top: 0; } h1 p, h2 p, h3 p, h4 p, h5 p, h6 p { margin-top: 0; } li p.first { display: inline-block; } ul, ol { padding-left: 30px; } ul :first-child, ol :first-child { margin-top: 0; } ul :last-child, ol :last-child { margin-bottom: 0; } dl { padding: 0; } dl dt { font-size: 14px; font-weight: bold; font-style: italic; padding: 0; margin: 15px 0 5px; } dl dt:first-child { padding: 0; } dl dt > :first-child { margin-top: 0; } dl dt > :last-child { margin-bottom: 0; } dl dd { margin: 0 0 15px; padding: 0 15px; } dl dd > :first-child { margin-top: 0; } dl dd > :last-child { margin-bottom: 0; } blockquote { border-left: 4px solid #dddddd; padding: 0 15px; color: #777777; } blockquote > :first-child { margin-top: 0; } blockquote > :last-child { margin-bottom: 0; } table { padding: 0; } table tr { border-top: 1px solid #cccccc; background-color: white; margin: 0; padding: 0; } table tr:nth-child(2n) { background-color: #f8f8f8; } table tr th { font-weight: bold; border: 1px solid #cccccc; text-align: left; margin: 0; padding: 6px 13px; } table tr td { border: 1px solid #cccccc; text-align: left; margin: 0; padding: 6px 13px; } table tr th :first-child, table tr td :first-child { margin-top: 0; } table tr th :last-child, table tr td :last-child { margin-bottom: 0; } img { max-width: 100%; } span.frame { display: block; overflow: hidden; } span.frame > span { border: 1px solid #dddddd; display: block; float: left; overflow: hidden; margin: 13px 0 0; padding: 7px; width: auto; } span.frame span img { display: block; float: left; } span.frame span span { clear: both; color: #333333; display: block; padding: 5px 0 0; } span.align-center { display: block; overflow: hidden; clear: both; } span.align-center > span { display: block; overflow: hidden; margin: 13px auto 0; text-align: center; } span.align-center span img { margin: 0 auto; text-align: center; } span.align-right { display: block; overflow: hidden; clear: both; } span.align-right > span { display: block; overflow: hidden; margin: 13px 0 0; text-align: right; } span.align-right span img { margin: 0; text-align: right; } span.float-left { display: block; margin-right: 13px; overflow: hidden; float: left; } span.float-left span { margin: 13px 0 0; } span.float-right { display: block; margin-left: 13px; overflow: hidden; float: right; } span.float-right > span { display: block; overflow: hidden; margin: 13px auto 0; text-align: right; } code, tt { font-family: "Lucida Console", "Courier New", courier; font-size: 12px; margin: 0 2px; padding: 3px 5px; white-space: nowrap; border: 1px solid #eaeaea; background-color: #f8f8f8; border-radius: 3px; } pre code { margin: 0; padding: 0; white-space: pre; border: none; background: transparent; } .highlight pre { background-color: #f8f8f8; border: 1px solid #cccccc; font-size: 13px; line-height: 19px; overflow: auto; padding: 6px 10px; border-radius: 3px; } pre { background-color: #f8f8f8; border: 1px solid #cccccc; font-size: 13px; line-height: 19px; overflow: auto; padding: 6px 10px; border-radius: 3px; } pre code, pre tt { background-color: transparent; border: none; } span.line-numbers { margin-right: 10px; } img.logo { display: block; margin: 10px auto; } h1.logo { text-align: center; font-size: 40px; }
// <copyright file="Cookie.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.Globalization; using Newtonsoft.Json; using OpenQA.Selenium.Internal; namespace OpenQA.Selenium { /// <summary> /// Represents a cookie in the browser. /// </summary> [Serializable] [JsonObject(MemberSerialization = MemberSerialization.OptIn)] public class Cookie { private string cookieName; private string cookieValue; private string cookiePath; private string cookieDomain; private DateTime? cookieExpiry; /// <summary> /// Initializes a new instance of the <see cref="Cookie"/> class with a specific name, /// value, domain, path and expiration date. /// </summary> /// <param name="name">The name of the cookie.</param> /// <param name="value">The value of the cookie.</param> /// <param name="domain">The domain of the cookie.</param> /// <param name="path">The path of the cookie.</param> /// <param name="expiry">The expiration date of the cookie.</param> /// <exception cref="ArgumentException">If the name is <see langword="null"/> or an empty string, /// or if it contains a semi-colon.</exception> /// <exception cref="ArgumentNullException">If the value is <see langword="null"/>.</exception> public Cookie(string name, string value, string domain, string path, DateTime? expiry) { if (string.IsNullOrEmpty(name)) { throw new ArgumentException("Cookie name cannot be null or empty string", "name"); } if (value == null) { throw new ArgumentNullException("value", "Cookie value cannot be null"); } if (name.IndexOf(';') != -1) { throw new ArgumentException("Cookie names cannot contain a ';': " + name, "name"); } this.cookieName = name; this.cookieValue = value; if (!string.IsNullOrEmpty(path)) { this.cookiePath = path; } this.cookieDomain = StripPort(domain); if (expiry != null) { this.cookieExpiry = expiry; } } /// <summary> /// Initializes a new instance of the <see cref="Cookie"/> class with a specific name, /// value, path and expiration date. /// </summary> /// <param name="name">The name of the cookie.</param> /// <param name="value">The value of the cookie.</param> /// <param name="path">The path of the cookie.</param> /// <param name="expiry">The expiration date of the cookie.</param> /// <exception cref="ArgumentException">If the name is <see langword="null"/> or an empty string, /// or if it contains a semi-colon.</exception> /// <exception cref="ArgumentNullException">If the value is <see langword="null"/>.</exception> public Cookie(string name, string value, string path, DateTime? expiry) : this(name, value, null, path, expiry) { } /// <summary> /// Initializes a new instance of the <see cref="Cookie"/> class with a specific name, /// value, and path. /// </summary> /// <param name="name">The name of the cookie.</param> /// <param name="value">The value of the cookie.</param> /// <param name="path">The path of the cookie.</param> /// <exception cref="ArgumentException">If the name is <see langword="null"/> or an empty string, /// or if it contains a semi-colon.</exception> /// <exception cref="ArgumentNullException">If the value is <see langword="null"/>.</exception> public Cookie(string name, string value, string path) : this(name, value, path, null) { } /// <summary> /// Initializes a new instance of the <see cref="Cookie"/> class with a specific name and value. /// </summary> /// <param name="name">The name of the cookie.</param> /// <param name="value">The value of the cookie.</param> /// <exception cref="ArgumentException">If the name is <see langword="null"/> or an empty string, /// or if it contains a semi-colon.</exception> /// <exception cref="ArgumentNullException">If the value is <see langword="null"/>.</exception> public Cookie(string name, string value) : this(name, value, null, null) { } /// <summary> /// Gets the name of the cookie. /// </summary> [JsonProperty("name")] public string Name { get { return this.cookieName; } } /// <summary> /// Gets the value of the cookie. /// </summary> [JsonProperty("value")] public string Value { get { return this.cookieValue; } } /// <summary> /// Gets the domain of the cookie. /// </summary> [JsonProperty("domain", NullValueHandling = NullValueHandling.Ignore)] public string Domain { get { return this.cookieDomain; } } /// <summary> /// Gets the path of the cookie. /// </summary> [JsonProperty("path", NullValueHandling = NullValueHandling.Ignore)] public virtual string Path { get { return this.cookiePath; } } /// <summary> /// Gets a value indicating whether the cookie is secure. /// </summary> [JsonProperty("secure")] public virtual bool Secure { get { return false; } } /// <summary> /// Gets a value indicating whether the cookie is an HTTP-only cookie. /// </summary> [JsonProperty("httpOnly")] public virtual bool IsHttpOnly { get { return false; } } /// <summary> /// Gets the expiration date of the cookie. /// </summary> public DateTime? Expiry { get { return this.cookieExpiry; } } /// <summary> /// Gets the cookie expiration date in seconds from the defined zero date (01 January 1970 00:00:00 UTC). /// </summary> /// <remarks>This property only exists so that the JSON serializer can serialize a /// cookie without resorting to a custom converter.</remarks> [JsonProperty("expiry", NullValueHandling = NullValueHandling.Ignore)] internal long? ExpirySeconds { get { if (this.cookieExpiry == null) { return null; } DateTime zeroDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); TimeSpan span = this.cookieExpiry.Value.ToUniversalTime().Subtract(zeroDate); long totalSeconds = Convert.ToInt64(span.TotalSeconds); return totalSeconds; } } /// <summary> /// Converts a Dictionary to a Cookie. /// </summary> /// <param name="rawCookie">The Dictionary object containing the cookie parameters.</param> /// <returns>A <see cref="Cookie"/> object with the proper parameters set.</returns> public static Cookie FromDictionary(Dictionary<string, object> rawCookie) { if (rawCookie == null) { throw new ArgumentNullException("rawCookie", "Dictionary cannot be null"); } string name = rawCookie["name"].ToString(); string value = string.Empty; if (rawCookie["value"] != null) { value = rawCookie["value"].ToString(); } string path = "/"; if (rawCookie.ContainsKey("path") && rawCookie["path"] != null) { path = rawCookie["path"].ToString(); } string domain = string.Empty; if (rawCookie.ContainsKey("domain") && rawCookie["domain"] != null) { domain = rawCookie["domain"].ToString(); } DateTime? expires = null; if (rawCookie.ContainsKey("expiry") && rawCookie["expiry"] != null) { double seconds = 0; if (double.TryParse(rawCookie["expiry"].ToString(), NumberStyles.Number, CultureInfo.InvariantCulture, out seconds)) { try { expires = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(seconds).ToLocalTime(); } catch (ArgumentOutOfRangeException) { expires = DateTime.MaxValue.ToLocalTime(); } } } bool secure = false; if (rawCookie.ContainsKey("secure") && rawCookie["secure"] != null) { secure = bool.Parse(rawCookie["secure"].ToString()); } bool isHttpOnly = false; if (rawCookie.ContainsKey("httpOnly") && rawCookie["httpOnly"] != null) { isHttpOnly = bool.Parse(rawCookie["httpOnly"].ToString()); } return new ReturnedCookie(name, value, domain, path, expires, secure, isHttpOnly); } /// <summary> /// Creates and returns a string representation of the cookie. /// </summary> /// <returns>A string representation of the cookie.</returns> public override string ToString() { return this.cookieName + "=" + this.cookieValue + (this.cookieExpiry == null ? string.Empty : "; expires=" + this.cookieExpiry.Value.ToUniversalTime().ToString("ddd MM dd yyyy hh:mm:ss UTC", CultureInfo.InvariantCulture)) + (string.IsNullOrEmpty(this.cookiePath) ? string.Empty : "; path=" + this.cookiePath) + (string.IsNullOrEmpty(this.cookieDomain) ? string.Empty : "; domain=" + this.cookieDomain); } /// <summary> /// Determines whether the specified <see cref="object">Object</see> is equal /// to the current <see cref="object">Object</see>. /// </summary> /// <param name="obj">The <see cref="object">Object</see> to compare with the /// current <see cref="object">Object</see>.</param> /// <returns><see langword="true"/> if the specified <see cref="object">Object</see> /// is equal to the current <see cref="object">Object</see>; otherwise, /// <see langword="false"/>.</returns> public override bool Equals(object obj) { // Two cookies are equal if the name and value match Cookie cookie = obj as Cookie; if (this == obj) { return true; } if (cookie == null) { return false; } if (!this.cookieName.Equals(cookie.cookieName)) { return false; } return !(this.cookieValue != null ? !this.cookieValue.Equals(cookie.cookieValue) : cookie.Value != null); } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns>A hash code for the current <see cref="object">Object</see>.</returns> public override int GetHashCode() { return this.cookieName.GetHashCode(); } private static string StripPort(string domain) { return string.IsNullOrEmpty(domain) ? null : domain.Split(':')[0]; } } }
using System; using System.Collections.Generic; using System.Globalization; using AllReady.Areas.Admin.ViewModels.Validators; using AllReady.Areas.Admin.ViewModels.Validators.Task; using AllReady.Controllers; using AllReady.DataAccess; using AllReady.Hangfire; using AllReady.Hangfire.Jobs; using AllReady.Models; using AllReady.Providers; using AllReady.Providers.ExternalUserInformationProviders; using AllReady.Providers.ExternalUserInformationProviders.Providers; using AllReady.Security; using AllReady.Services; using Autofac; using Autofac.Extensions.DependencyInjection; using Autofac.Features.Variance; using MediatR; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.PlatformAbstractions; using AllReady.Security.Middleware; using Newtonsoft.Json.Serialization; using Microsoft.AspNetCore.Cors.Infrastructure; using Geocoding; using Geocoding.Google; using Hangfire; using Hangfire.SqlServer; using AllReady.ModelBinding; using Microsoft.AspNetCore.Localization; using Microsoft.Extensions.Options; using AllReady.Services.Routing; namespace AllReady { public class Startup { public Startup(IHostingEnvironment env) { // Setup configuration sources. var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("version.json") .AddJsonFile("config.json") .AddJsonFile($"config.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); if (env.IsDevelopment()) { // This reads the configuration keys from the secret store. // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709 builder.AddUserSecrets(); // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately. //builder.AddApplicationInsightsSettings(developerMode: true); builder.AddApplicationInsightsSettings(developerMode: false); } else if (env.IsStaging() || env.IsProduction()) { // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately. builder.AddApplicationInsightsSettings(developerMode: false); } Configuration = builder.Build(); Configuration["version"] = new ApplicationEnvironment().ApplicationVersion; // version in project.json } public IConfiguration Configuration { get; set; } // This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { //Add CORS support. // Must be first to avoid OPTIONS issues when calling from Angular/Browser var corsBuilder = new CorsPolicyBuilder(); corsBuilder.AllowAnyHeader(); corsBuilder.AllowAnyMethod(); corsBuilder.AllowAnyOrigin(); corsBuilder.AllowCredentials(); services.AddCors(options => { options.AddPolicy("allReady", corsBuilder.Build()); }); // Add Application Insights data collection services to the services container. services.AddApplicationInsightsTelemetry(Configuration); // Add Entity Framework services to the services container. services.AddDbContext<AllReadyContext>(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"])); services.Configure<AzureStorageSettings>(Configuration.GetSection("Data:Storage")); services.Configure<DatabaseSettings>(Configuration.GetSection("Data:DefaultConnection")); services.Configure<EmailSettings>(Configuration.GetSection("Email")); services.Configure<SampleDataSettings>(Configuration.GetSection("SampleData")); services.Configure<GeneralSettings>(Configuration.GetSection("General")); services.Configure<TwitterAuthenticationSettings>(Configuration.GetSection("Authentication:Twitter")); services.Configure<MappingSettings>(Configuration.GetSection("Mapping")); // Add Identity services to the services container. services.AddIdentity<ApplicationUser, IdentityRole>(options => { options.Password.RequiredLength = 10; options.Password.RequireNonAlphanumeric = false; options.Password.RequireDigit = true; options.Password.RequireUppercase = false; options.Cookies.ApplicationCookie.AccessDeniedPath = new PathString("/Home/AccessDenied"); }) .AddEntityFrameworkStores<AllReadyContext>() .AddDefaultTokenProviders(); // Add Authorization rules for the app services.AddAuthorization(options => { options.AddPolicy("OrgAdmin", b => b.RequireClaim(Security.ClaimTypes.UserType, "OrgAdmin", "SiteAdmin")); options.AddPolicy("SiteAdmin", b => b.RequireClaim(Security.ClaimTypes.UserType, "SiteAdmin")); }); services.AddLocalization(); //Currently AllReady only supports en-US culture. This forces datetime and number formats to the en-US culture regardless of local culture var usCulture = new CultureInfo("en-US"); var supportedCultures = new[] { usCulture }; services.Configure<RequestLocalizationOptions>(options => { options.DefaultRequestCulture = new RequestCulture(usCulture, usCulture); options.SupportedCultures = supportedCultures; options.SupportedUICultures = supportedCultures; }); // Add MVC services to the services container. // config add to get passed Angular failing on Options request when logging in. services.AddMvc(config => { config.ModelBinderProviders.Insert(0, new AdjustToTimezoneModelBinderProvider()); }) .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver()); //Hangfire services.AddHangfire(configuration => configuration.UseSqlServerStorage(Configuration["Data:HangfireConnection:ConnectionString"])); // configure IoC support var container = CreateIoCContainer(services); return container.Resolve<IServiceProvider>(); } private IContainer CreateIoCContainer(IServiceCollection services) { // todo: move these to a proper autofac module // Register application services. services.AddSingleton((x) => Configuration); services.AddTransient<IEmailSender, AuthMessageSender>(); services.AddTransient<ISmsSender, AuthMessageSender>(); services.AddTransient<IDetermineIfATaskIsEditable, DetermineIfATaskIsEditable>(); services.AddTransient<IValidateEventEditViewModels, EventEditViewModelValidator>(); services.AddTransient<ITaskEditViewModelValidator, TaskEditViewModelValidator>(); services.AddTransient<IItineraryEditModelValidator, ItineraryEditModelValidator>(); services.AddTransient<IOrganizationEditModelValidator, OrganizationEditModelValidator>(); services.AddTransient<IRedirectAccountControllerRequests, RedirectAccountControllerRequests>(); services.AddSingleton<IImageService, ImageService>(); services.AddTransient<ISendRequestConfirmationMessagesSevenDaysBeforeAnItineraryDate, SendRequestConfirmationMessagesSevenDaysBeforeAnItineraryDate>(); services.AddTransient<ISendRequestConfirmationMessagesADayBeforeAnItineraryDate, SendRequestConfirmationMessagesADayBeforeAnItineraryDate>(); services.AddTransient<ISendRequestConfirmationMessagesTheDayOfAnItineraryDate, SendRequestConfirmationMessagesTheDayOfAnItineraryDate>(); services.AddTransient<SampleDataGenerator>(); if (Configuration["Geocoding:EnableGoogleGeocodingService"] == "true") { //This setting is false by default. To enable Google geocoding you will //need to override this setting in your user secrets or env vars. //Visit https://developers.google.com/maps/documentation/geocoding/get-api-key to get a free standard usage API key services.AddSingleton<IGeocoder>(new GoogleGeocoder(Configuration["Geocoding:GoogleGeocodingApiKey"])); } else { //implement null object pattern to protect against IGeocoder not being passed a legit reference at runtime b/c of the above conditional services.AddSingleton<IGeocoder>(new NullObjectGeocoder()); } if (Configuration["Data:Storage:EnableAzureQueueService"] == "true") { // This setting is false by default. To enable queue processing you will // need to override the setting in your user secrets or env vars. services.AddTransient<IQueueStorageService, QueueStorageService>(); } else { // this writer service will just write to the default logger services.AddTransient<IQueueStorageService, FakeQueueWriterService>(); //services.AddTransient<IQueueStorageService, SmtpEmailSender>(); } var containerBuilder = new ContainerBuilder(); containerBuilder.RegisterSource(new ContravariantRegistrationSource()); containerBuilder.RegisterAssemblyTypes(typeof(IMediator).Assembly).AsImplementedInterfaces(); containerBuilder.RegisterAssemblyTypes(typeof(Startup).Assembly).AsImplementedInterfaces(); containerBuilder.Register<SingleInstanceFactory>(ctx => { var c = ctx.Resolve<IComponentContext>(); return t => c.Resolve(t); }); containerBuilder.Register<MultiInstanceFactory>(ctx => { var c = ctx.Resolve<IComponentContext>(); return t => (IEnumerable<object>)c.Resolve(typeof(IEnumerable<>).MakeGenericType(t)); }); //ExternalUserInformationProviderFactory registration containerBuilder.RegisterType<TwitterExternalUserInformationProvider>().Named<IProvideExternalUserInformation>("Twitter"); containerBuilder.RegisterType<GoogleExternalUserInformationProvider>().Named<IProvideExternalUserInformation>("Google"); containerBuilder.RegisterType<MicrosoftAndFacebookExternalUserInformationProvider>().Named<IProvideExternalUserInformation>("Microsoft"); containerBuilder.RegisterType<MicrosoftAndFacebookExternalUserInformationProvider>().Named<IProvideExternalUserInformation>("Facebook"); containerBuilder.RegisterType<ExternalUserInformationProviderFactory>().As<IExternalUserInformationProviderFactory>(); //Hangfire containerBuilder.Register(icomponentcontext => new BackgroundJobClient(new SqlServerStorage(Configuration["Data:HangfireConnection:ConnectionString"]))) .As<IBackgroundJobClient>(); containerBuilder.RegisterType<GoogleOptimizeRouteService>().As<IOptimizeRouteService>().SingleInstance(); //Populate the container with services that were previously registered containerBuilder.Populate(services); var container = containerBuilder.Build(); return container; } // Configure is called after ConfigureServices is called. public async void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, SampleDataGenerator sampleData, AllReadyContext context, IConfiguration configuration) { // Put first to avoid issues with OPTIONS when calling from Angular/Browser. app.UseCors("allReady"); // todo: in RC update we can read from a logging.json config file loggerFactory.AddConsole((category, level) => { if (category.StartsWith("Microsoft.")) { return level >= LogLevel.Information; } return true; }); if (env.IsDevelopment()) { // this will go to the VS output window loggerFactory.AddDebug((category, level) => { if (category.StartsWith("Microsoft.")) { return level >= LogLevel.Information; } return true; }); } // Add Application Insights to the request pipeline to track HTTP request telemetry data. app.UseApplicationInsightsRequestTelemetry(); // Add the following to the request pipeline only in development environment. if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else if (env.IsStaging()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { // Add Error handling middleware which catches all application specific errors and // sends the request to the following path or controller action. app.UseExceptionHandler("/Home/Error"); } // Track data about exceptions from the application. Should be configured after all error handling middleware in the request pipeline. app.UseApplicationInsightsExceptionTelemetry(); // Add static files to the request pipeline. app.UseStaticFiles(); app.UseRequestLocalization(); // Add cookie-based authentication to the request pipeline. app.UseIdentity(); // Add token-based protection to the request inject pipeline app.UseTokenProtection(new TokenProtectedResourceOptions { Path = "/api/request", PolicyName = "api-request-injest" }); // Add authentication middleware to the request pipeline. You can configure options such as Id and Secret in the ConfigureServices method. // For more information see http://go.microsoft.com/fwlink/?LinkID=532715 if (Configuration["Authentication:Facebook:AppId"] != null) { var options = new FacebookOptions { AppId = Configuration["Authentication:Facebook:AppId"], AppSecret = Configuration["Authentication:Facebook:AppSecret"], BackchannelHttpHandler = new FacebookBackChannelHandler(), UserInformationEndpoint = "https://graph.facebook.com/v2.5/me?fields=id,name,email,first_name,last_name" }; options.Scope.Add("email"); app.UseFacebookAuthentication(options); } if (Configuration["Authentication:MicrosoftAccount:ClientId"] != null) { var options = new MicrosoftAccountOptions { ClientId = Configuration["Authentication:MicrosoftAccount:ClientId"], ClientSecret = Configuration["Authentication:MicrosoftAccount:ClientSecret"] }; app.UseMicrosoftAccountAuthentication(options); } //http://www.bigbrainintelligence.com/Post/get-users-email-address-from-twitter-oauth-ap if (Configuration["Authentication:Twitter:ConsumerKey"] != null) { var options = new TwitterOptions { ConsumerKey = Configuration["Authentication:Twitter:ConsumerKey"], ConsumerSecret = Configuration["Authentication:Twitter:ConsumerSecret"] }; app.UseTwitterAuthentication(options); } if (Configuration["Authentication:Google:ClientId"] != null) { var options = new GoogleOptions { ClientId = Configuration["Authentication:Google:ClientId"], ClientSecret = Configuration["Authentication:Google:ClientSecret"] }; app.UseGoogleAuthentication(options); } //call Migrate here to force the creation of the AllReady database so Hangfire can create its schema under it if (!env.IsProduction()) { context.Database.Migrate(); } //Hangfire app.UseHangfireDashboard("/hangfire", new DashboardOptions { Authorization = new[] { new HangireDashboardAuthorizationFilter() } }); app.UseHangfireServer(); // Add MVC to the request pipeline. app.UseMvc(routes => { routes.MapRoute(name: "areaRoute", template: "{area:exists}/{controller}/{action=Index}/{id?}"); routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); // Add sample data and test admin accounts if specified in Config.Json. // for production applications, this should either be set to false or deleted. if (Configuration["SampleData:InsertSampleData"] == "true") { sampleData.InsertTestData(); } if (Configuration["SampleData:InsertTestUsers"] == "true") { await sampleData.CreateAdminUser(); } } } }
using System; using Sodium; using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using Windows.Security.Cryptography.Core; namespace Test { [TestClass] public class KDFTest { [TestCategory("PBKDF2")] [TestMethod] public void PBKDF2Test() { // Directly compare to other known pbkdf2 implementations with known value and output // Output is derived from php:hash_pbkdf2 var salt = Convert.FromBase64String("iszDKigtU8NhOSY5Dz8m3uw2Bpdcyjc436kLiqTYjxU="); var expected = Convert.FromBase64String("PFjtIDyW8JV9IZ7D19EGuUlSTLvJePc+PfeZEDYSM88="); var password = "correct horse battery staple"; var result = Sodium.KDF.PBKDF2(KeyDerivationAlgorithmNames.Pbkdf2Sha256, password, salt, 10000, 32); Assert.AreEqual(Convert.ToBase64String(expected), Convert.ToBase64String(result)); } // RFC6070 outlines the following test cases // https://www.ietf.org/rfc/rfc6070.txt [TestCategory("PBKDF2")] [TestMethod] public void RFC6070A1Test() { var p = "password"; var s = System.Text.Encoding.ASCII.GetBytes("salt"); var c = 1; var dkLen = 20; var result = Sodium.KDF.PBKDF2(KeyDerivationAlgorithmNames.Pbkdf2Sha1, p, s, c, dkLen); var expected = new byte[] { 0x0c, 0x60, 0xc8, 0x0f, 0x96, 0x1f, 0x0e, 0x71, 0xf3, 0xa9, 0xb5, 0x24, 0xaf, 0x60, 0x12, 0x06, 0x2f, 0xe0, 0x37, 0xa6 }; Assert.AreEqual(Convert.ToBase64String(expected), Convert.ToBase64String(result)); } [TestCategory("PBKDF2")] [TestMethod] public void RFC6070A2Test() { var p = "password"; var s = System.Text.Encoding.ASCII.GetBytes("salt"); var c = 2; var dkLen = 20; var result = Sodium.KDF.PBKDF2(KeyDerivationAlgorithmNames.Pbkdf2Sha1, p, s, c, dkLen); var expected = new byte[] { 0xea, 0x6c, 0x01, 0x4d, 0xc7, 0x2d, 0x6f, 0x8c, 0xcd, 0x1e, 0xd9, 0x2a, 0xce, 0x1d, 0x41, 0xf0, 0xd8, 0xde, 0x89, 0x57 }; Assert.AreEqual(Convert.ToBase64String(expected), Convert.ToBase64String(result)); } [TestCategory("PBKDF2")] [TestMethod] public void RFC6070A3Test() { var p = "password"; var s = System.Text.Encoding.ASCII.GetBytes("salt"); var c = 4096; var dkLen = 20; var result = Sodium.KDF.PBKDF2(KeyDerivationAlgorithmNames.Pbkdf2Sha1, p, s, c, dkLen); var expected = new byte[] { 0x4b, 0x00, 0x79, 0x01, 0xb7, 0x65, 0x48, 0x9a, 0xbe, 0xad, 0x49, 0xd9, 0x26, 0xf7, 0x21, 0xd0, 0x65, 0xa4, 0x29, 0xc1 }; Assert.AreEqual(Convert.ToBase64String(expected), Convert.ToBase64String(result)); } [TestCategory("PBKDF2")] [TestMethod] public void RFC6070A4Test() { var p = "password"; var s = System.Text.Encoding.ASCII.GetBytes("salt"); var c = 16777216; var dkLen = 20; var result = Sodium.KDF.PBKDF2(KeyDerivationAlgorithmNames.Pbkdf2Sha1, p, s, c, dkLen); var expected = new byte[] { 0xee, 0xfe, 0x3d, 0x61, 0xcd, 0x4d, 0xa4, 0xe4, 0xe9, 0x94, 0x5b, 0x3d, 0x6b, 0xa2, 0x15, 0x8c, 0x26, 0x34, 0xe9, 0x84 }; Assert.AreEqual(Convert.ToBase64String(expected), Convert.ToBase64String(result)); } [TestCategory("PBKDF2")] [TestMethod] public void RFC6070A5Test() { var p = "passwordPASSWORDpassword"; var s = System.Text.Encoding.ASCII.GetBytes("saltSALTsaltSALTsaltSALTsaltSALTsalt"); var c = 4096; var dkLen = 25; var result = Sodium.KDF.PBKDF2(KeyDerivationAlgorithmNames.Pbkdf2Sha1, p, s, c, dkLen); var expected = new byte[] { 0x3d, 0x2e, 0xec, 0x4f, 0xe4, 0x1c, 0x84, 0x9b, 0x80, 0xc8, 0xd8, 0x36, 0x62, 0xc0, 0xe4, 0x4a, 0x8b, 0x29, 0x1a, 0x96, 0x4c, 0xf2, 0xf0, 0x70, 0x38 }; Assert.AreEqual(Convert.ToBase64String(expected), Convert.ToBase64String(result)); } [TestCategory("PBKDF2")] [TestMethod] public void RFC6070A6Test() { var p = "pass\0word"; var s = System.Text.Encoding.ASCII.GetBytes("sa\0lt"); var c = 4096; var dkLen = 16; var result = Sodium.KDF.PBKDF2(KeyDerivationAlgorithmNames.Pbkdf2Sha1, p, s, c, dkLen); var expected = new byte[] { 0x56, 0xfa, 0x6a, 0xa7, 0x55, 0x48, 0x09, 0x9d, 0xcc, 0x37, 0xd7, 0xf0, 0x34, 0x25, 0xe0, 0xc3 }; Assert.AreEqual(Convert.ToBase64String(expected), Convert.ToBase64String(result)); } [TestCategory("HKDF")] [TestMethod] public void HKDFTest() { // salt and ikm are 32 random bytes, base46 encoded var salt = Convert.FromBase64String("hsXKrSfNu/9qMc3j6sohQuSymsrkL6URwRkthQM4+yI="); var ikm = Convert.FromBase64String("XC+Ph8miNDofAtYDrsyOoPFN6ofTmmA6z+BsjNgjIC0="); // The expected result is calculated from a known working HKDF implementation, base64 encoded var expected = Convert.FromBase64String("uP5Uvdmamdg1uzEbh/Tvg+BYsHXHcwAg/VRGJ5yPj3Y="); var algorithm = MacAlgorithmNames.HmacSha256; var authInfo = System.Text.Encoding.UTF8.GetBytes("test"); var result = Sodium.KDF.HKDF(algorithm, ikm, salt, authInfo, 32); Assert.AreEqual(Convert.ToBase64String(expected), Convert.ToBase64String(result)); // This should be the same, because outputLength will transform to 32 result = Sodium.KDF.HKDF(algorithm, ikm, salt, authInfo, 0); Assert.AreEqual(Convert.ToBase64String(expected), Convert.ToBase64String(result)); } // Test vectors derived from https://tools.ietf.org/html/rfc5869 // NOTE: values are base64 encodings of their hexidecimal representation in the RFC. // This is done to reduce typing. The values are equivalent [TestCategory("HKDF")] [TestMethod] public void RFC5869A1Test() { var ikm = Convert.FromBase64String("CwsLCwsLCwsLCwsLCwsLCwsLCwsLCw=="); var salt = Convert.FromBase64String("AAECAwQFBgcICQoLDA=="); var info = Convert.FromBase64String("8PHy8/T19vf4+Q=="); var expected = Convert.FromBase64String("PLJfJfqs1XqQQ09k0DYvKi0tCpDPGlpMXbAtVuzExb80AHII1biHGFhl"); int l = 42; var algorithm = MacAlgorithmNames.HmacSha256; var result = Sodium.KDF.HKDF(algorithm, ikm, salt, info, l); Assert.AreEqual(Convert.ToBase64String(expected), Convert.ToBase64String(result)); Assert.IsTrue(result.Length == l); } [TestCategory("HKDF")] [TestMethod] public void RFC5869A2Test() { var ikm = Convert.FromBase64String("AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk8="); var salt = Convert.FromBase64String("YGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq8="); var info = Convert.FromBase64String("sLGys7S1tre4ubq7vL2+v8DBwsPExcbHyMnKy8zNzs/Q0dLT1NXW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+Pn6+/z9/v8="); var expected = Convert.FromBase64String("sR45jcgDJ6HI5/eMWWpJNE8BLtotTvrYoFDMTBmvqXxZBFqZyseCcnHLQcZeWQ4J2jJ1YAwvCbg2d5OprKPbccwwxYF57D6HwUwB1cHzQ08dhw=="); int l = 82; var algorithm = MacAlgorithmNames.HmacSha256; var result = Sodium.KDF.HKDF(algorithm, ikm, salt, info, l); Assert.AreEqual(Convert.ToBase64String(expected), Convert.ToBase64String(result)); Assert.IsTrue(result.Length == l); } [TestCategory("HKDF")] [TestMethod] public void RFC5869A3Test() { var ikm = Convert.FromBase64String("CwsLCwsLCwsLCwsLCwsLCwsLCwsLCw=="); var salt = new byte[] { }; var info = new byte[] { }; var expected = Convert.FromBase64String("jaTndaVjwY9xX4AqBjxaMbihH1xe4Yeew0VOXzxzjS2dIBOV+qS2GpbI"); int l = 42; var algorithm = MacAlgorithmNames.HmacSha256; var result = Sodium.KDF.HKDF(algorithm, ikm, salt, info, l); Assert.AreEqual(Convert.ToBase64String(expected), Convert.ToBase64String(result)); Assert.IsTrue(result.Length == l); } [TestCategory("HKDF")] [TestMethod] public void RFC5869A4Test() { var ikm = Convert.FromBase64String("CwsLCwsLCwsLCws="); var salt = Convert.FromBase64String("AAECAwQFBgcICQoLDA=="); var info = Convert.FromBase64String("8PHy8/T19vf4+Q=="); var expected = Convert.FromBase64String("CFoB6hsQ82kzBotW76WtgaTxS4IvWwkVaKnN1PFV/aLCLkIkeNMF8/iW"); int l = 42; var algorithm = MacAlgorithmNames.HmacSha1; var result = Sodium.KDF.HKDF(algorithm, ikm, salt, info, l); Assert.AreEqual(Convert.ToBase64String(expected), Convert.ToBase64String(result)); Assert.IsTrue(result.Length == l); } [TestCategory("HKDF")] [TestMethod] public void RFC5869A5Test() { var ikm = Convert.FromBase64String("AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk8="); var salt = Convert.FromBase64String("YGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq8="); var info = Convert.FromBase64String("sLGys7S1tre4ubq7vL2+v8DBwsPExcbHyMnKy8zNzs/Q0dLT1NXW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+Pn6+/z9/v8="); var expected = Convert.FromBase64String("C9dwp00RYPfJ8SzVkSoG6/9q3K6JnZIZH+QwVnO6L/6Po/Gk5a158/M0s7ICshc8SG6jfOPTl+0DTH+d/rFcXpJzNtBEH0xDAOLP8NCQC1LTtA=="); int l = 82; var algorithm = MacAlgorithmNames.HmacSha1; var result = Sodium.KDF.HKDF(algorithm, ikm, salt, info, l); Assert.IsTrue(result.Length == l); } [TestCategory("HKDF")] [TestMethod] public void RFC5869A6Test() { var ikm = Convert.FromBase64String("CwsLCwsLCwsLCwsLCwsLCwsLCwsLCw=="); var salt = new byte[] { }; var info = new byte[] { }; var expected = Convert.FromBase64String("CsGvcAKz12HR5VKY2p0FBrmuUgVyIKMG4Htrh+jfIdDqAAM94DmE00kY"); int l = 42; var algorithm = MacAlgorithmNames.HmacSha1; var result = Sodium.KDF.HKDF(algorithm, ikm, salt, info, l); Assert.AreEqual(Convert.ToBase64String(expected), Convert.ToBase64String(result)); Assert.IsTrue(result.Length == l); } [TestCategory("HKDF")] [TestMethod] public void RFC5869A7Test() { var ikm = Convert.FromBase64String("DAwMDAwMDAwMDAwMDAwMDAwMDAwMDA=="); var salt = new byte[] { }; var info = new byte[] { }; var expected = Convert.FromBase64String("LJERcgTXRfNQDWNqYvZPCrO65UiqU9QjsNHyfrum9eVnOggdcMznrPxI"); int l = 42; var algorithm = MacAlgorithmNames.HmacSha1; var result = Sodium.KDF.HKDF(algorithm, ikm, salt, info, l); Assert.AreEqual(Convert.ToBase64String(expected), Convert.ToBase64String(result)); Assert.IsTrue(result.Length == l); } [TestCategory("HSalsa20")] [TestMethod] public void HSalsa20Test() { var shared = new byte[] { 0x4a,0x5d,0x9d,0x5b,0xa4,0xce,0x2d,0xe1 ,0x72,0x8e,0x3b,0xf4,0x80,0x35,0x0f,0x25 ,0xe0,0x7e,0x21,0xc9,0x47,0xd1,0x9e,0x33 ,0x76,0xf0,0x9b,0x3c,0x1e,0x16,0x17,0x42 }; var zero = new byte[32]; var c = new byte[] { 0x65,0x78,0x70,0x61,0x6e,0x64,0x20,0x33 ,0x32,0x2d,0x62,0x79,0x74,0x65,0x20,0x6b }; var expected = new byte[] { 0x1b,0x27,0x55,0x64,0x73,0xe9,0x85,0xd4 ,0x62,0xcd,0x51,0x19,0x7a,0x9a,0x46,0xc7 ,0x60,0x09,0x54,0x9e,0xac,0x64,0x74,0xf2 ,0x06,0xc4,0xee,0x08,0x44,0xf6,0x83,0x89 }; var result = Sodium.KDF.HSalsa20(zero, shared, c); Assert.AreEqual(Convert.ToBase64String(expected), Convert.ToBase64String(result)); Assert.IsTrue(result.Length == 32); var nonceprefix = new byte[] { 0x69,0x69,0x6e,0xe9,0x55,0xb6,0x2b,0x73 ,0xcd,0x62,0xbd,0xa8,0x75,0xfc,0x73,0xd6 }; c = new byte[] { 0x65,0x78,0x70,0x61,0x6e,0x64,0x20,0x33 ,0x32,0x2d,0x62,0x79,0x74,0x65,0x20,0x6b }; expected = new byte[] { 0xdc,0x90,0x8d,0xda,0x0b,0x93,0x44,0xa9 ,0x53,0x62,0x9b,0x73,0x38,0x20,0x77,0x88 ,0x80,0xf3,0xce,0xb4,0x21,0xbb,0x61,0xb9 ,0x1c,0xbd,0x4c,0x3e,0x66,0x25,0x6c,0xe4 }; result = Sodium.KDF.HSalsa20(nonceprefix, result, c); Assert.AreEqual(Convert.ToBase64String(expected), Convert.ToBase64String(result)); Assert.IsTrue(result.Length == 32); } [TestCategory("Argon2i")] [TestMethod] public void Argon2iTest() { string password = "correct horse battery staple"; var options = PasswordHash.CreateOptions(1 << 8, 3); var result = Sodium.KDF.Argon2i(password, options); Assert.AreEqual(32, result.Length); var salt = Sodium.Core.GetRandomBytes(16); result = Sodium.KDF.Argon2i(password, salt, options); Assert.AreEqual(32, result.Length); } [TestCategory("Scrypt")] [TestMethod] public void ScryptTest() { string password = "correct horse battery staple"; var options = PasswordHash.CreateOptions(1 << 8, 3); var result = Sodium.KDF.Scrypt(password, options); Assert.AreEqual(32, result.Length); var salt = Sodium.Core.GetRandomBytes(32); result = Sodium.KDF.Scrypt(password, salt, options); Assert.AreEqual(32, result.Length); } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace TestCases.SS.Formula.Functions { using System; using NUnit.Framework; using NPOI.SS.Formula.Eval; using TestCases.SS.Formula.Functions; using NPOI.SS.Formula.Functions; /** * Test cases for MATCH() * * @author Josh Micich */ [TestFixture] public class TestMatch { /** less than or equal to */ private static NumberEval MATCH_LARGEST_LTE = new NumberEval(1); private static NumberEval MATCH_EXACT = new NumberEval(0); /** greater than or equal to */ private static NumberEval MATCH_SMALLEST_GTE = new NumberEval(-1); private static ValueEval invokeMatch(ValueEval Lookup_value, ValueEval Lookup_array, ValueEval match_type) { ValueEval[] args = { Lookup_value, Lookup_array, match_type, }; return new Match().Evaluate(args, -1, (short)-1); } private static void ConfirmInt(int expected, ValueEval actualEval) { if (!(actualEval is NumericValueEval)) { Assert.Fail("Expected numeric result"); } NumericValueEval nve = (NumericValueEval)actualEval; Assert.AreEqual(expected, nve.NumberValue, 0); } [Test] public void TestSimpleNumber() { ValueEval[] values = { new NumberEval(4), new NumberEval(5), new NumberEval(10), new NumberEval(10), new NumberEval(25), }; AreaEval ae = EvalFactory.CreateAreaEval("A1:A5", values); ConfirmInt(2, invokeMatch(new NumberEval(5), ae, MATCH_LARGEST_LTE)); ConfirmInt(2, invokeMatch(new NumberEval(5), ae, MATCH_EXACT)); ConfirmInt(4, invokeMatch(new NumberEval(10), ae, MATCH_LARGEST_LTE)); ConfirmInt(3, invokeMatch(new NumberEval(10), ae, MATCH_EXACT)); ConfirmInt(4, invokeMatch(new NumberEval(20), ae, MATCH_LARGEST_LTE)); Assert.AreEqual(ErrorEval.NA, invokeMatch(new NumberEval(20), ae, MATCH_EXACT)); } [Test] public void TestReversedNumber() { ValueEval[] values = { new NumberEval(25), new NumberEval(10), new NumberEval(10), new NumberEval(10), new NumberEval(4), }; AreaEval ae = EvalFactory.CreateAreaEval("A1:A5", values); ConfirmInt(2, invokeMatch(new NumberEval(10), ae, MATCH_SMALLEST_GTE)); ConfirmInt(2, invokeMatch(new NumberEval(10), ae, MATCH_EXACT)); ConfirmInt(4, invokeMatch(new NumberEval(9), ae, MATCH_SMALLEST_GTE)); ConfirmInt(1, invokeMatch(new NumberEval(20), ae, MATCH_SMALLEST_GTE)); Assert.AreEqual(ErrorEval.NA, invokeMatch(new NumberEval(20), ae, MATCH_EXACT)); Assert.AreEqual(ErrorEval.NA, invokeMatch(new NumberEval(26), ae, MATCH_SMALLEST_GTE)); } [Test] public void TestSimpleString() { ValueEval[] values = { new StringEval("Albert"), new StringEval("Charles"), new StringEval("Ed"), new StringEval("Greg"), new StringEval("Ian"), }; AreaEval ae = EvalFactory.CreateAreaEval("A1:A5", values); // Note String comparisons are case insensitive ConfirmInt(3, invokeMatch(new StringEval("Ed"), ae, MATCH_LARGEST_LTE)); ConfirmInt(3, invokeMatch(new StringEval("eD"), ae, MATCH_LARGEST_LTE)); ConfirmInt(3, invokeMatch(new StringEval("Ed"), ae, MATCH_EXACT)); ConfirmInt(3, invokeMatch(new StringEval("ed"), ae, MATCH_EXACT)); ConfirmInt(4, invokeMatch(new StringEval("Hugh"), ae, MATCH_LARGEST_LTE)); Assert.AreEqual(ErrorEval.NA, invokeMatch(new StringEval("Hugh"), ae, MATCH_EXACT)); } [Test] public void TestSimpleBoolean() { ValueEval[] values = { BoolEval.FALSE, BoolEval.FALSE, BoolEval.TRUE, BoolEval.TRUE, }; AreaEval ae = EvalFactory.CreateAreaEval("A1:A4", values); // Note String comparisons are case insensitive ConfirmInt(2, invokeMatch(BoolEval.FALSE, ae, MATCH_LARGEST_LTE)); ConfirmInt(1, invokeMatch(BoolEval.FALSE, ae, MATCH_EXACT)); ConfirmInt(4, invokeMatch(BoolEval.TRUE, ae, MATCH_LARGEST_LTE)); ConfirmInt(3, invokeMatch(BoolEval.TRUE, ae, MATCH_EXACT)); } [Test] public void TestHeterogeneous() { ValueEval[] values = { new NumberEval(4), BoolEval.FALSE, new NumberEval(5), new StringEval("Albert"), BoolEval.FALSE, BoolEval.TRUE, new NumberEval(10), new StringEval("Charles"), new StringEval("Ed"), new NumberEval(10), new NumberEval(25), BoolEval.TRUE, new StringEval("Ed"), }; AreaEval ae = EvalFactory.CreateAreaEval("A1:A13", values); Assert.AreEqual(ErrorEval.NA, invokeMatch(new StringEval("Aaron"), ae, MATCH_LARGEST_LTE)); ConfirmInt(5, invokeMatch(BoolEval.FALSE, ae, MATCH_LARGEST_LTE)); ConfirmInt(2, invokeMatch(BoolEval.FALSE, ae, MATCH_EXACT)); ConfirmInt(3, invokeMatch(new NumberEval(5), ae, MATCH_LARGEST_LTE)); ConfirmInt(3, invokeMatch(new NumberEval(5), ae, MATCH_EXACT)); ConfirmInt(8, invokeMatch(new StringEval("CHARLES"), ae, MATCH_EXACT)); ConfirmInt(4, invokeMatch(new StringEval("Ben"), ae, MATCH_LARGEST_LTE)); ConfirmInt(13, invokeMatch(new StringEval("ED"), ae, MATCH_LARGEST_LTE)); ConfirmInt(9, invokeMatch(new StringEval("ED"), ae, MATCH_EXACT)); ConfirmInt(13, invokeMatch(new StringEval("Hugh"), ae, MATCH_LARGEST_LTE)); Assert.AreEqual(ErrorEval.NA, invokeMatch(new StringEval("Hugh"), ae, MATCH_EXACT)); ConfirmInt(11, invokeMatch(new NumberEval(30), ae, MATCH_LARGEST_LTE)); ConfirmInt(12, invokeMatch(BoolEval.TRUE, ae, MATCH_LARGEST_LTE)); } /** * Ensures that the match_type argument can be an <c>AreaEval</c>.<br/> * Bugzilla 44421 */ [Test] public void TestMatchArgTypeArea() { ValueEval[] values = { new NumberEval(4), new NumberEval(5), new NumberEval(10), new NumberEval(10), new NumberEval(25), }; AreaEval ae = EvalFactory.CreateAreaEval("A1:A5", values); AreaEval matchAE = EvalFactory.CreateAreaEval("C1:C1", new ValueEval[] { MATCH_LARGEST_LTE, }); try { ConfirmInt(4, invokeMatch(new NumberEval(10), ae, matchAE)); } catch (Exception e) { if (e.Message.StartsWith("Unexpected match_type type")) { // identified bug 44421 Assert.Fail(e.Message); } // some other error ?? throw e; } } } }
// 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. // // // Adding tests for BoolArrayMarshaler code coverage // //Rule for Passing Value // Reverse Pinvoke //M--->N true,true,true,true,true //N----M true,false,true,false,true using System; using System.Text; using System.Security; using System.Runtime.InteropServices; using TestLibrary; public class MarshalBoolArray { #region"variable" const int SIZE = 5; #endregion #region "Reverse PInvoke" #region "Bool Array" [DllImport("MarshalBoolArrayNative")] private static extern bool DoCallBackIn(CallBackIn callback); private delegate bool CallBackIn([In]int size, [In, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I1, SizeConst = SIZE)] bool[] array); private static bool TestMethod_CallBackIn(int size, bool[] array) { bool retVal = true; //Check the Input if (SIZE != size) { retVal = false; //TestFramework.LogError("001","Failed on the Managed Side:TestMethod_CallBackIn:Parameter Size is wrong"); } for (int i = 0; i < SIZE; ++i) //Reverse PInvoke, true,false,true false,true { if ((0 == i % 2) && !array[i]) { retVal = false; //TestFramework.LogError("002","Failed on the Managed Side:TestMethod_CallBackIn. The " + (i + 1) + "st Item failed"); } else if ((1 == i % 2) && array[i]) { retVal = false; //TestFramework.LogError("003","Failed on the Managed Side:TestMethod_CallBackIn. The " + (i + 1) + "st Item failed"); } } return retVal; } [DllImport("MarshalBoolArrayNative")] private static extern bool DoCallBackOut(CallBackOut callback); private delegate bool CallBackOut([In]int size, [Out, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U1, SizeConst = SIZE)] bool[] array); private static bool TestMethod_CallBackOut(int size, bool[] array) { bool retVal = true; //Check the Input if (SIZE != size) { retVal = false; //TestFramework.LogError("004","Failed on the Managed Side:TestMethod_CallBackOut:Parameter Size is wrong"); } for (int i = 0; i < SIZE; ++i) //Reverse PInvoke, true,true,true true,true { array[i] = true; } return retVal; } [DllImport("MarshalBoolArrayNative")] private static extern bool DoCallBackInOut(CallBackInOut callback); private delegate bool CallBackInOut([In]int size, [In, Out, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I1, SizeConst = SIZE)] bool[] array); private static bool TestMethod_CallBackInOut(int size, bool[] array) { bool retVal = true; //Check the Input if (SIZE != size) { retVal = false; //TestFramework.LogError("005","Failed on the Managed Side:TestMethod_CallBackInOut:Parameter Size is wrong"); } for (int i = 0; i < SIZE; ++i) //Reverse PInvoke, true,false,true false,true { if ((0 == i % 2) && !array[i]) { retVal = false; TestFramework.LogError("006","Failed on the Managed Side:TestMethod_CallBackInOut. The " + (i + 1) + "st Item failed"); } else if ((1 == i % 2) && array[i]) { retVal = false; //TestFramework.LogError("007","Failed on the Managed Side:TestMethod_CallBackInOut. The " + (i + 1) + "st Item failed"); } } //Check the output for (int i = 0; i < size; ++i) //Reverse PInvoke, true,true,true true,true { array[i] = true; } return retVal; } #endregion #region"Bool Array Reference" [DllImport("MarshalBoolArrayNative")] private static extern bool DoCallBackRefIn(CallBackRefIn callback); private delegate bool CallBackRefIn([In]int size, [In, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U1)] ref bool[] array); private static bool TestMethod_CallBackRefIn(int size, ref bool[] array) { bool retVal = true; //Check the Input if (SIZE != size) { retVal = false; //TestFramework.LogError("008","Failed on the Managed Side:TestMethod_CallBackRefIn:Parameter Size is wrong"); } //TODO: UnComment these line if the SizeConst attributes is support //Since now the sizeconst doesnt support on ref,so only check the first item instead. //Unhandled Exception: System.Runtime.InteropServices.MarshalDirectiveException: Cannot marshal 'parameter #2': Cannot use SizeParamIndex for ByRef array parameters. //for (int i = 0; i < size; ++i) //Reverse PInvoke, true,false,true false,true //{ // if ((0 == i % 2) && !array[i]) // { // ReportFailure("Failed on the Managed Side:TestMethod_CallBackRefIn. The " + (i + 1) + "st Item failed", true.ToString(), false.ToString()); // } // else if ((1 == i % 2) && array[i]) // { // ReportFailure("Failed on the Managed Side:TestMethod_CallBackRefIn. The " + (i + 1) + "st Item failed", false.ToString(), true.ToString()); // } // } if (!array[0]) { retVal = false; //TestFramework.LogError("009","Failed on the Managed Side:TestMethod_CallBackRefIn. The first Item failed"); } return retVal; } [DllImport("MarshalBoolArrayNative")] private static extern bool DoCallBackRefOut(CallBackRefOut callback); private delegate bool CallBackRefOut([In]int size, [Out, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.I1)] out bool[] array); private static bool TestMethod_CallBackRefOut(int size, out bool[] array) { bool retVal = true; //Check the Input if (size != SIZE) { retVal = false; //TestFramework.LogError("010","Failed on the Managed Side:TestMethod_CallBackRefOut:Parameter Size is wrong"); } array = new bool[SIZE]; for (int i = 0; i < SIZE; ++i) //Reverse PInvoke, true,true,true true,true { array[i] = true; } return retVal; } [DllImport("MarshalBoolArrayNative")] private static extern bool DoCallBackRefInOut(CallBackRefInOut callback); private delegate bool CallBackRefInOut([In]int size, [In, Out, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U1)] ref bool[] array); private static bool TestMethod_CallBackRefInOut(int size, ref bool[] array) { bool retVal = true; //Check the Input if (SIZE != size) { retVal = false; //TestFramework.LogError("011","Failed on the Managed Side:TestMethod_CallBackRefInOut:Parameter Size is wrong"); } //TODO: UnComment these line if the SizeConst attributes is support //Since now the sizeconst doesnt support on ref,so only check the first item instead. //Unhandled Exception: System.Runtime.InteropServices.MarshalDirectiveException: Cannot marshal 'parameter #2': Cannot use SizeParamIndex for ByRef array parameters. //for (int i = 0; i < size; ++i) //Reverse PInvoke, true,false,true false,true //{ // if ((0 == i % 2) && !array[i]) // { // ReportFailure("Failed on the Managed Side:TestMethod_CallBackRefInOut. The " + (i + 1) + "st Item failed", true.ToString(), false.ToString()); // } // else if ((1 == i % 2) && array[i]) // { // ReportFailure("Failed on the Managed Side:TestMethod_CallBackRefInOut. The " + (i + 1) + "st Item failed", false.ToString(), true.ToString()); // } // } if (!array[0]) { retVal = false; //TestFramework.LogError("012","Failed on the Managed Side:TestMethod_CallBackRefInOut. The first Item failed"); } //Output array = new bool[SIZE]; for (int i = 0; i < size; ++i) //Reverse PInvoke, true,true,true true,true { array[i] = true; } return retVal; } #endregion #endregion [System.Security.SecuritySafeCritical] static int Main() { bool retVal = true; //TestFramework.BeginScenario("Reverse PInvoke with In attribute"); if (!DoCallBackIn(new CallBackIn(TestMethod_CallBackIn))) { retVal = false; //TestFramework.LogError("013","Error happens in Native side:DoCallBackIn"); } //TestFramework.BeginScenario("Reverse PInvoke with Out attribute"); if (!DoCallBackOut(new CallBackOut(TestMethod_CallBackOut))) { retVal = false; //TestFramework.LogError("014","Error happens in Native side:DoCallBackOut"); } // TestFramework.BeginScenario("Reverse PInvoke with InOut attribute"); if (!DoCallBackInOut(new CallBackInOut(TestMethod_CallBackInOut))) { retVal = false; TestFramework.LogError("015","Error happens in Native side:DoCallBackInOut"); } // TestFramework.BeginScenario("Reverse PInvoke Reference In"); if (!DoCallBackRefIn(new CallBackRefIn(TestMethod_CallBackRefIn))) { retVal = false; //TestFramework.LogError("016","Error happens in Native side:DoCallBackRefIn"); } // TestFramework.BeginScenario("Reverse PInvoke Reference Out"); if (!DoCallBackRefOut(new CallBackRefOut(TestMethod_CallBackRefOut))) { retVal = false; //TestFramework.LogError("017","Error happens in Native side:DoCallBackRefOut"); } //TestFramework.BeginScenario("Reverse PInvoke Reference InOut"); if (!DoCallBackRefInOut(new CallBackRefInOut(TestMethod_CallBackRefInOut))) { retVal = false; //TestFramework.LogError("019","Error happens in Native side:DoCallBackRefInOut"); } if(retVal) { //Console.WriteLine("Succeeded!"); return 100; } throw new Exception("Failed"); // return 101; } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System.Collections.Generic; using Aurora.Framework; using OpenMetaverse; using OpenMetaverse.StructuredData; namespace OpenSim.Services.Interfaces { /// <summary> /// Callback used when a user's inventory is received from the inventory service /// </summary> public delegate void InventoryReceiptCallback( ICollection<InventoryFolderImpl> folders, ICollection<InventoryItemBase> items); public interface IExternalInventoryService : IInventoryService { //This is the same as the normal inventory interface, but it is used to load the inventory service for external transactions (outside of this simulator/grid) } public interface IInventoryService { /// <summary> /// Create the entire inventory for a given user (local only) /// </summary> /// <param name = "user"></param> /// <returns></returns> bool CreateUserInventory(UUID user, bool createDefaultItems); /// <summary> /// Create the entire inventory for a given user (local only) /// </summary> /// <param name = "user"></param> /// <returns></returns> bool CreateUserInventory(UUID user, bool createDefaultItems, out List<InventoryItemBase> defaultInventoryItems); /// <summary> /// Gets the skeleton of the inventory -- folders only (local only) /// </summary> /// <param name = "userId"></param> /// <returns></returns> List<InventoryFolderBase> GetInventorySkeleton(UUID userId); /// <summary> /// Retrieve the root inventory folder for the given user. /// </summary> /// <param name = "userID"></param> /// <returns>null if no root folder was found</returns> InventoryFolderBase GetRootFolder(UUID userID); /// <summary> /// Gets a folder by name for the given user /// </summary> /// <param name="userID"></param> /// <param name="FolderName"></param> /// <returns></returns> InventoryFolderBase GetFolderByOwnerAndName(UUID userID, string FolderName); /// <summary> /// Retrieve the root inventory folder for the given user. - local only /// </summary> /// <param name = "userID"></param> /// <returns>null if no root folder was found</returns> List<InventoryFolderBase> GetRootFolders(UUID userID); /// <summary> /// Gets the user folder for the given folder-type /// </summary> /// <param name = "userID"></param> /// <param name = "invType"></param> /// <param name = "type"></param> /// <returns></returns> InventoryFolderBase GetFolderForType(UUID userID, InventoryType invType, AssetType type); /// <summary> /// Gets everything (folders and items) inside a folder /// </summary> /// <param name = "userId"></param> /// <param name = "folderID"></param> /// <returns></returns> InventoryCollection GetFolderContent(UUID userID, UUID folderID); /// <summary> /// Gets the folders inside a folder (local only) /// </summary> /// <param name = "userID"></param> /// <param name = "folderID"></param> /// <returns></returns> List<InventoryFolderBase> GetFolderFolders(UUID userID, UUID folderID); /// <summary> /// Gets the items inside a folder - local only /// </summary> /// <param name = "userID"></param> /// <param name = "folderID"></param> /// <returns></returns> List<InventoryItemBase> GetFolderItems(UUID userID, UUID folderID); /// <summary> /// Add a new folder to the user's inventory /// </summary> /// <param name = "folder"></param> /// <returns>true if the folder was successfully added</returns> bool AddFolder(InventoryFolderBase folder); /// <summary> /// Update a folder in the user's inventory /// </summary> /// <param name = "folder"></param> /// <returns>true if the folder was successfully updated</returns> bool UpdateFolder(InventoryFolderBase folder); /// <summary> /// Move an inventory folder to a new location /// </summary> /// <param name = "folder">A folder containing the details of the new location</param> /// <returns>true if the folder was successfully moved</returns> bool MoveFolder(InventoryFolderBase folder); /// <summary> /// Delete an item from the user's inventory /// </summary> /// <param name = "item"></param> /// <returns>true if the item was successfully deleted</returns> bool DeleteFolders(UUID userID, List<UUID> folderIDs); /// <summary> /// Force Deletes a folder (LOCAL ONLY) /// </summary> /// <param name = "folder"></param> /// <returns></returns> bool ForcePurgeFolder(InventoryFolderBase folder); /// <summary> /// Purge an inventory folder of all its items and subfolders. /// </summary> /// <param name = "folder"></param> /// <returns>true if the folder was successfully purged</returns> bool PurgeFolder(InventoryFolderBase folder); /// <summary> /// Add a new item to the user's inventory /// </summary> /// <param name = "item"> /// The item to be added. If item.FolderID == UUID.Zero then the item is added to the most suitable system /// folder. If there is no suitable folder then the item is added to the user's root inventory folder. /// </param> /// <returns>true if the item was successfully added, false if it was not</returns> bool AddItem(InventoryItemBase item); /// <summary> /// Update an item in the user's inventory /// </summary> /// <param name = "item"></param> /// <returns>true if the item was successfully updated</returns> bool UpdateItem(InventoryItemBase item); /// <summary> /// Update the assetID for the given item /// </summary> /// <param name="itemID"></param> /// <param name="assetID"></param> /// <returns></returns> bool UpdateAssetIDForItem(UUID itemID, UUID assetID); /// <summary> /// Move the given items to the folder given in the inventory item /// </summary> /// <param name = "ownerID"></param> /// <param name = "items"></param> /// <returns></returns> bool MoveItems(UUID ownerID, List<InventoryItemBase> items); /// <summary> /// Delete an item from the user's inventory /// </summary> /// <param name = "item"></param> /// <returns>true if the item was successfully deleted</returns> bool DeleteItems(UUID userID, List<UUID> itemIDs); /// <summary> /// Get an item, given by its UUID /// </summary> /// <param name = "item"></param> /// <returns></returns> InventoryItemBase GetItem(InventoryItemBase item); /// <summary> /// Get a folder, given by its UUID /// </summary> /// <param name = "folder"></param> /// <returns></returns> InventoryFolderBase GetFolder(InventoryFolderBase folder); /// <summary> /// Get the active gestures of the agent. /// </summary> /// <param name = "userId"></param> /// <returns></returns> List<InventoryItemBase> GetActiveGestures(UUID userId); /// <summary> /// Gives an inventory item to another user (LOCAL ONLY) /// </summary> /// <param name="recipient"></param> /// <param name="senderId"></param> /// <param name="item"></param> /// <param name="recipientFolderId"></param> /// <param name="doOwnerCheck"></param> /// <returns></returns> InventoryItemBase InnerGiveInventoryItem(UUID recipient, UUID senderId, InventoryItemBase item, UUID recipientFolderId, bool doOwnerCheck); #region OSD methods /// <summary> /// Get an OSDArray of the items in the given folder - local only /// </summary> /// <param name = "principalID"></param> /// <param name = "folderID"></param> /// <returns></returns> OSDArray GetLLSDFolderItems(UUID principalID, UUID folderID); /// <summary> /// Get the item serialized as an OSDArray - local only /// </summary> /// <param name = "itemID"></param> /// <returns></returns> OSDArray GetItem(UUID avatarID, UUID itemID); #endregion #region Async methods /// <summary> /// Adds a new item to the user's inventory asynchronously /// </summary> /// <param name="item"></param> /// <param name="success"></param> void AddItemAsync(InventoryItemBase item, NoParam success); /// <summary> /// Moves multiple items to a new folder in the user's inventory /// </summary> /// <param name="agentID"></param> /// <param name="items"></param> /// <param name="success"></param> void MoveItemsAsync(UUID agentID, List<InventoryItemBase> items, NoParam success); /// <summary> /// Gives an inventory item to another user asychronously /// </summary> /// <param name="recipient"></param> /// <param name="senderId"></param> /// <param name="itemId"></param> /// <param name="recipientFolderId"></param> /// <param name="doOwnerCheck"></param> /// <param name="success"></param> void GiveInventoryItemAsync(UUID recipient, UUID senderId, UUID itemId, UUID recipientFolderId, bool doOwnerCheck, GiveItemParam success); /// <summary> /// Gives an entire inventory folder to another user asynchronously /// </summary> /// <param name="recipientId"></param> /// <param name="senderId"></param> /// <param name="folderId"></param> /// <param name="recipientParentFolderId"></param> /// <param name="success"></param> void GiveInventoryFolderAsync( UUID recipientId, UUID senderId, UUID folderId, UUID recipientParentFolderId, GiveFolderParam success); #endregion } public delegate void GiveFolderParam(InventoryFolderBase folder); public delegate void GiveItemParam(InventoryItemBase item); public interface IInventoryData : IAuroraDataPlugin { List<InventoryFolderBase> GetFolders(string[] fields, string[] vals); List<InventoryItemBase> GetItems(UUID avatarID, string[] fields, string[] vals); OSDArray GetLLSDItems(string[] fields, string[] vals); bool HasAssetForUser(UUID userID, UUID assetID); string GetItemNameByAsset(UUID assetID); bool StoreFolder(InventoryFolderBase folder); bool StoreItem(InventoryItemBase item); bool UpdateAssetIDForItem(UUID itemID, UUID assetID); bool DeleteFolders(string field, string val, bool safe); bool DeleteItems(string field, string val); bool MoveItem(string id, string newParent); InventoryItemBase[] GetActiveGestures(UUID principalID); byte[] FetchInventoryReply(OSDArray fetchRequest, UUID AgentID, UUID forceOwnerID, UUID libraryOwnerID); void IncrementFolder(UUID folderID); void IncrementFolderByItem(UUID folderID); } }