context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the apigateway-2015-07-09.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.APIGateway.Model { /// <summary> /// Represents a unique identifier for a version of a deployed <a>RestApi</a> that is /// callable by users. /// </summary> public partial class GetStageResponse : AmazonWebServiceResponse { private bool? _cacheClusterEnabled; private CacheClusterSize _cacheClusterSize; private CacheClusterStatus _cacheClusterStatus; private string _clientCertificateId; private DateTime? _createdDate; private string _deploymentId; private string _description; private DateTime? _lastUpdatedDate; private Dictionary<string, MethodSetting> _methodSettings = new Dictionary<string, MethodSetting>(); private string _stageName; private Dictionary<string, string> _variables = new Dictionary<string, string>(); /// <summary> /// Gets and sets the property CacheClusterEnabled. /// <para> /// Specifies whether a cache cluster is enabled for the stage. /// </para> /// </summary> public bool CacheClusterEnabled { get { return this._cacheClusterEnabled.GetValueOrDefault(); } set { this._cacheClusterEnabled = value; } } // Check to see if CacheClusterEnabled property is set internal bool IsSetCacheClusterEnabled() { return this._cacheClusterEnabled.HasValue; } /// <summary> /// Gets and sets the property CacheClusterSize. /// <para> /// The size of the cache cluster for the stage, if enabled. /// </para> /// </summary> public CacheClusterSize CacheClusterSize { get { return this._cacheClusterSize; } set { this._cacheClusterSize = value; } } // Check to see if CacheClusterSize property is set internal bool IsSetCacheClusterSize() { return this._cacheClusterSize != null; } /// <summary> /// Gets and sets the property CacheClusterStatus. /// <para> /// The status of the cache cluster for the stage, if enabled. /// </para> /// </summary> public CacheClusterStatus CacheClusterStatus { get { return this._cacheClusterStatus; } set { this._cacheClusterStatus = value; } } // Check to see if CacheClusterStatus property is set internal bool IsSetCacheClusterStatus() { return this._cacheClusterStatus != null; } /// <summary> /// Gets and sets the property ClientCertificateId. /// </summary> public string ClientCertificateId { get { return this._clientCertificateId; } set { this._clientCertificateId = value; } } // Check to see if ClientCertificateId property is set internal bool IsSetClientCertificateId() { return this._clientCertificateId != null; } /// <summary> /// Gets and sets the property CreatedDate. /// <para> /// The date and time that the stage was created, in <a target="_blank" href="http://www.iso.org/iso/home/standards/iso8601.htm">ISO /// 8601 format</a>. /// </para> /// </summary> public DateTime CreatedDate { get { return this._createdDate.GetValueOrDefault(); } set { this._createdDate = value; } } // Check to see if CreatedDate property is set internal bool IsSetCreatedDate() { return this._createdDate.HasValue; } /// <summary> /// Gets and sets the property DeploymentId. /// <para> /// The identifier of the <a>Deployment</a> that the stage points to. /// </para> /// </summary> public string DeploymentId { get { return this._deploymentId; } set { this._deploymentId = value; } } // Check to see if DeploymentId property is set internal bool IsSetDeploymentId() { return this._deploymentId != null; } /// <summary> /// Gets and sets the property Description. /// <para> /// The stage's description. /// </para> /// </summary> public string Description { get { return this._description; } set { this._description = value; } } // Check to see if Description property is set internal bool IsSetDescription() { return this._description != null; } /// <summary> /// Gets and sets the property LastUpdatedDate. /// <para> /// The date and time that information about the stage was last updated, in <a target="_blank" /// href="http://www.iso.org/iso/home/standards/iso8601.htm">ISO 8601 format</a>. /// </para> /// </summary> public DateTime LastUpdatedDate { get { return this._lastUpdatedDate.GetValueOrDefault(); } set { this._lastUpdatedDate = value; } } // Check to see if LastUpdatedDate property is set internal bool IsSetLastUpdatedDate() { return this._lastUpdatedDate.HasValue; } /// <summary> /// Gets and sets the property MethodSettings. /// <para> /// A map that defines the method settings for a <a>Stage</a> resource. Keys are defined /// as <code>{resource_path}/{http_method}</code> for an individual method override, or /// <code>\*/\*</code> for the settings applied to all methods in the stage. /// </para> /// </summary> public Dictionary<string, MethodSetting> MethodSettings { get { return this._methodSettings; } set { this._methodSettings = value; } } // Check to see if MethodSettings property is set internal bool IsSetMethodSettings() { return this._methodSettings != null && this._methodSettings.Count > 0; } /// <summary> /// Gets and sets the property StageName. /// <para> /// The name of the stage is the first path segment in the Uniform Resource Identifier /// (URI) of a call to Amazon API Gateway. /// </para> /// </summary> public string StageName { get { return this._stageName; } set { this._stageName = value; } } // Check to see if StageName property is set internal bool IsSetStageName() { return this._stageName != null; } /// <summary> /// Gets and sets the property Variables. /// <para> /// A map that defines the stage variables for a <a>Stage</a> resource. Variable names /// can have alphabetic characters, and the values must match [A-Za-z0-9-._~:/?#&amp;=,]+ /// </para> /// </summary> public Dictionary<string, string> Variables { get { return this._variables; } set { this._variables = value; } } // Check to see if Variables property is set internal bool IsSetVariables() { return this._variables != null && this._variables.Count > 0; } } }
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 Luis.MasteringExtJs.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; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; using System.Security.Principal; namespace System.Security.AccessControl { public sealed class RegistryAccessRule : AccessRule { // Constructor for creating access rules for registry objects public RegistryAccessRule(IdentityReference identity, RegistryRights registryRights, AccessControlType type) : this(identity, (int)registryRights, false, InheritanceFlags.None, PropagationFlags.None, type) { } public RegistryAccessRule(string identity, RegistryRights registryRights, AccessControlType type) : this(new NTAccount(identity), (int)registryRights, false, InheritanceFlags.None, PropagationFlags.None, type) { } public RegistryAccessRule(IdentityReference identity, RegistryRights registryRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) : this(identity, (int)registryRights, false, inheritanceFlags, propagationFlags, type) { } public RegistryAccessRule(string identity, RegistryRights registryRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) : this(new NTAccount(identity), (int)registryRights, false, inheritanceFlags, propagationFlags, type) { } // // Internal constructor to be called by public constructors // and the access rule factory methods of {File|Folder}Security // internal RegistryAccessRule( IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) : base( identity, accessMask, isInherited, inheritanceFlags, propagationFlags, type) { } public RegistryRights RegistryRights { get { return (RegistryRights)AccessMask; } } } public sealed class RegistryAuditRule : AuditRule { public RegistryAuditRule(IdentityReference identity, RegistryRights registryRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) : this(identity, (int)registryRights, false, inheritanceFlags, propagationFlags, flags) { } public RegistryAuditRule(string identity, RegistryRights registryRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) : this(new NTAccount(identity), (int)registryRights, false, inheritanceFlags, propagationFlags, flags) { } internal RegistryAuditRule(IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) : base(identity, accessMask, isInherited, inheritanceFlags, propagationFlags, flags) { } public RegistryRights RegistryRights { get { return (RegistryRights)AccessMask; } } } public sealed partial class RegistrySecurity : NativeObjectSecurity { public RegistrySecurity() : base(true, ResourceType.RegistryKey) { } internal RegistrySecurity(SafeRegistryHandle hKey, string name, AccessControlSections includeSections) : base(true, ResourceType.RegistryKey, hKey, includeSections, _HandleErrorCode, null) { } private static Exception _HandleErrorCode(int errorCode, string name, SafeHandle handle, object context) { return _HandleErrorCodeCore(errorCode, name, handle, context); } public override AccessRule AccessRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) { return new RegistryAccessRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, type); } public override AuditRule AuditRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) { return new RegistryAuditRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, flags); } internal AccessControlSections GetAccessControlSectionsFromChanges() { AccessControlSections persistRules = AccessControlSections.None; if (AccessRulesModified) { persistRules = AccessControlSections.Access; } if (AuditRulesModified) { persistRules |= AccessControlSections.Audit; } if (OwnerModified) { persistRules |= AccessControlSections.Owner; } if (GroupModified) { persistRules |= AccessControlSections.Group; } return persistRules; } internal void Persist(SafeRegistryHandle hKey, string keyName) { WriteLock(); try { AccessControlSections persistRules = GetAccessControlSectionsFromChanges(); if (persistRules == AccessControlSections.None) { return; // Don't need to persist anything. } Persist(hKey, persistRules); OwnerModified = GroupModified = AuditRulesModified = AccessRulesModified = false; } finally { WriteUnlock(); } } public void AddAccessRule(RegistryAccessRule rule) { base.AddAccessRule(rule); } public void SetAccessRule(RegistryAccessRule rule) { base.SetAccessRule(rule); } public void ResetAccessRule(RegistryAccessRule rule) { base.ResetAccessRule(rule); } public bool RemoveAccessRule(RegistryAccessRule rule) { return base.RemoveAccessRule(rule); } public void RemoveAccessRuleAll(RegistryAccessRule rule) { base.RemoveAccessRuleAll(rule); } public void RemoveAccessRuleSpecific(RegistryAccessRule rule) { base.RemoveAccessRuleSpecific(rule); } public void AddAuditRule(RegistryAuditRule rule) { base.AddAuditRule(rule); } public void SetAuditRule(RegistryAuditRule rule) { base.SetAuditRule(rule); } public bool RemoveAuditRule(RegistryAuditRule rule) { return base.RemoveAuditRule(rule); } public void RemoveAuditRuleAll(RegistryAuditRule rule) { base.RemoveAuditRuleAll(rule); } public void RemoveAuditRuleSpecific(RegistryAuditRule rule) { base.RemoveAuditRuleSpecific(rule); } public override Type AccessRightType { get { return typeof(RegistryRights); } } public override Type AccessRuleType { get { return typeof(RegistryAccessRule); } } public override Type AuditRuleType { get { return typeof(RegistryAuditRule); } } } }
using System; using System.Collections.Generic; namespace Lucene.Net.Index { using NUnit.Framework; using BytesRef = Lucene.Net.Util.BytesRef; using Directory = Lucene.Net.Store.Directory; using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator; /* * 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 Document = Documents.Document; using IOContext = Lucene.Net.Store.IOContext; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using TestUtil = Lucene.Net.Util.TestUtil; [TestFixture] public class TestSegmentReader : LuceneTestCase { private Directory Dir; private Document TestDoc; private SegmentReader Reader; //TODO: Setup the reader w/ multiple documents [SetUp] public override void SetUp() { base.SetUp(); Dir = NewDirectory(); TestDoc = new Document(); DocHelper.SetupDoc(TestDoc); SegmentCommitInfo info = DocHelper.WriteDoc(Random(), Dir, TestDoc); Reader = new SegmentReader(info, DirectoryReader.DEFAULT_TERMS_INDEX_DIVISOR, IOContext.READ); } [TearDown] public override void TearDown() { Reader.Dispose(); Dir.Dispose(); base.TearDown(); } [Test] public virtual void Test() { Assert.IsTrue(Dir != null); Assert.IsTrue(Reader != null); Assert.IsTrue(DocHelper.NameValues.Count > 0); Assert.IsTrue(DocHelper.NumFields(TestDoc) == DocHelper.All.Count); } [Test] public virtual void TestDocument() { Assert.IsTrue(Reader.NumDocs == 1); Assert.IsTrue(Reader.MaxDoc >= 1); Document result = Reader.Document(0); Assert.IsTrue(result != null); //There are 2 unstored fields on the document that are not preserved across writing Assert.IsTrue(DocHelper.NumFields(result) == DocHelper.NumFields(TestDoc) - DocHelper.Unstored.Count); IList<IIndexableField> fields = result.Fields; foreach (IIndexableField field in fields) { Assert.IsTrue(field != null); Assert.IsTrue(DocHelper.NameValues.ContainsKey(field.Name)); } } [Test] public virtual void TestGetFieldNameVariations() { ICollection<string> allFieldNames = new HashSet<string>(); ICollection<string> indexedFieldNames = new HashSet<string>(); ICollection<string> notIndexedFieldNames = new HashSet<string>(); ICollection<string> tvFieldNames = new HashSet<string>(); ICollection<string> noTVFieldNames = new HashSet<string>(); foreach (FieldInfo fieldInfo in Reader.FieldInfos) { string name = fieldInfo.Name; allFieldNames.Add(name); if (fieldInfo.IsIndexed) { indexedFieldNames.Add(name); } else { notIndexedFieldNames.Add(name); } if (fieldInfo.HasVectors) { tvFieldNames.Add(name); } else if (fieldInfo.IsIndexed) { noTVFieldNames.Add(name); } } Assert.IsTrue(allFieldNames.Count == DocHelper.All.Count); foreach (string s in allFieldNames) { Assert.IsTrue(DocHelper.NameValues.ContainsKey(s) == true || s.Equals("")); } Assert.IsTrue(indexedFieldNames.Count == DocHelper.Indexed.Count); foreach (string s in indexedFieldNames) { Assert.IsTrue(DocHelper.Indexed.ContainsKey(s) == true || s.Equals("")); } Assert.IsTrue(notIndexedFieldNames.Count == DocHelper.Unindexed.Count); //Get all indexed fields that are storing term vectors Assert.IsTrue(tvFieldNames.Count == DocHelper.Termvector.Count); Assert.IsTrue(noTVFieldNames.Count == DocHelper.Notermvector.Count); } [Test] public virtual void TestTerms() { Fields fields = MultiFields.GetFields(Reader); foreach (string field in fields) { Terms terms = fields.GetTerms(field); Assert.IsNotNull(terms); TermsEnum termsEnum = terms.GetIterator(null); while (termsEnum.Next() != null) { BytesRef term = termsEnum.Term; Assert.IsTrue(term != null); string fieldValue = (string)DocHelper.NameValues[field]; Assert.IsTrue(fieldValue.IndexOf(term.Utf8ToString()) != -1); } } DocsEnum termDocs = TestUtil.Docs(Random(), Reader, DocHelper.TEXT_FIELD_1_KEY, new BytesRef("field"), MultiFields.GetLiveDocs(Reader), null, 0); Assert.IsTrue(termDocs.NextDoc() != DocIdSetIterator.NO_MORE_DOCS); termDocs = TestUtil.Docs(Random(), Reader, DocHelper.NO_NORMS_KEY, new BytesRef(DocHelper.NO_NORMS_TEXT), MultiFields.GetLiveDocs(Reader), null, 0); Assert.IsTrue(termDocs.NextDoc() != DocIdSetIterator.NO_MORE_DOCS); DocsAndPositionsEnum positions = MultiFields.GetTermPositionsEnum(Reader, MultiFields.GetLiveDocs(Reader), DocHelper.TEXT_FIELD_1_KEY, new BytesRef("field")); // NOTE: prior rev of this test was failing to first // call next here: Assert.IsTrue(positions.NextDoc() != DocIdSetIterator.NO_MORE_DOCS); Assert.IsTrue(positions.DocID == 0); Assert.IsTrue(positions.NextPosition() >= 0); } [Test] public virtual void TestNorms() { //TODO: Not sure how these work/should be tested /* try { byte [] norms = reader.norms(DocHelper.TEXT_FIELD_1_KEY); System.out.println("Norms: " + norms); Assert.IsTrue(norms != null); } catch (IOException e) { e.printStackTrace(); Assert.IsTrue(false); } */ CheckNorms(Reader); } public static void CheckNorms(AtomicReader reader) { // test omit norms for (int i = 0; i < DocHelper.Fields.Length; i++) { IIndexableField f = DocHelper.Fields[i]; if (f.IndexableFieldType.IsIndexed) { Assert.AreEqual(reader.GetNormValues(f.Name) != null, !f.IndexableFieldType.OmitNorms); Assert.AreEqual(reader.GetNormValues(f.Name) != null, !DocHelper.NoNorms.ContainsKey(f.Name)); if (reader.GetNormValues(f.Name) == null) { // test for norms of null NumericDocValues norms = MultiDocValues.GetNormValues(reader, f.Name); Assert.IsNull(norms); } } } } [Test] public virtual void TestTermVectors() { Terms result = Reader.GetTermVectors(0).GetTerms(DocHelper.TEXT_FIELD_2_KEY); Assert.IsNotNull(result); Assert.AreEqual(3, result.Count); TermsEnum termsEnum = result.GetIterator(null); while (termsEnum.Next() != null) { string term = termsEnum.Term.Utf8ToString(); int freq = (int)termsEnum.TotalTermFreq; Assert.IsTrue(DocHelper.FIELD_2_TEXT.IndexOf(term) != -1); Assert.IsTrue(freq > 0); } Fields results = Reader.GetTermVectors(0); Assert.IsTrue(results != null); Assert.AreEqual(3, results.Count, "We do not have 3 term freq vectors"); } [Test] public virtual void TestOutOfBoundsAccess() { int numDocs = Reader.MaxDoc; try { Reader.Document(-1); Assert.Fail(); } #pragma warning disable 168 catch (System.IndexOutOfRangeException expected) #pragma warning restore 168 { } try { Reader.GetTermVectors(-1); Assert.Fail(); } #pragma warning disable 168 catch (System.IndexOutOfRangeException expected) #pragma warning restore 168 { } try { Reader.Document(numDocs); Assert.Fail(); } #pragma warning disable 168 catch (System.IndexOutOfRangeException expected) #pragma warning restore 168 { } try { Reader.GetTermVectors(numDocs); Assert.Fail(); } #pragma warning disable 168 catch (System.IndexOutOfRangeException expected) #pragma warning restore 168 { } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using BTDB.EventStoreLayer; using Disruptor; namespace SimpleTester { public class EventStorageSpeedTestAwaitable { const int RepetitionCount = 10000; const int ParallelTasks = 1000; public class MyAwaitable : INotifyCompletion { volatile Action _continuation; public MyAwaitable GetAwaiter() { return this; } public bool IsCompleted { get { return false; } } public void GetResult() { } public void OnCompleted(Action continuation) { _continuation = continuation; } public void RunContinuation() { while (_continuation == null) { Thread.Yield(); } Task.Run(_continuation); _continuation = null; } } public class Event { public ulong Id { get; set; } public DateTime Time { get; set; } public string Payload { get; set; } } readonly Stopwatch _sw = new Stopwatch(); IWriteEventStore _writeStore; RingBuffer<ValueEvent> _ring; ISequenceBarrier _sequenceBarrier; Sequence _sequence; public MyAwaitable PublishEvent(object obj) { var seq = _ring.Next(); var valueEvent = _ring[seq]; valueEvent.Event = obj; _ring.Publish(seq); return valueEvent.Awaitable; } public class ValueEvent { public ValueEvent() { Awaitable = new MyAwaitable(); } public object Event; public readonly MyAwaitable Awaitable; } public void EventConsumer() { var lw = new ReadOnlyListRingWrapper(_ring); var nextSequence = _sequence.Value + 1L; while (true) { try { var availableSequence = _sequenceBarrier.WaitFor(nextSequence); var count = (int)(availableSequence - nextSequence + 1); if (count == 0) { continue; } lw.SetStartAndCount(nextSequence, count); nextSequence = availableSequence + 1; _writeStore.Store(null, lw); lw.RunContinuations(); _sequence.LazySet(nextSequence - 1L); } catch (AlertException) { break; } } } class ReadOnlyListRingWrapper : IReadOnlyList<object> { readonly RingBuffer<ValueEvent> _ring; long _start; public ReadOnlyListRingWrapper(RingBuffer<ValueEvent> ring) { _ring = ring; } public void SetStartAndCount(long start, int count) { _start = start; Count = count; } public void RunContinuations() { for (var i = 0; i < Count; i++) { var valueEvent = _ring[_start + i]; valueEvent.Awaitable.RunContinuation(); valueEvent.Event = null; } } public IEnumerator<object> GetEnumerator() { for (int i = 0; i < Count; i++) { yield return this[i]; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public int Count { get; private set; } public object this[int index] { get { return _ring[_start + index].Event; } } } public void Run() { _ring = new RingBuffer<ValueEvent>(() => new ValueEvent(), new MultiThreadedClaimStrategy(2048), new YieldingWaitStrategy()); _sequenceBarrier = _ring.NewBarrier(); _sequence = new Sequence(Sequencer.InitialCursorValue); _ring.SetGatingSequences(_sequence); var manager = new EventStoreManager(); //manager.CompressionStrategy = new NoCompressionStrategy(); using (var stream = new FileStream("0.event", FileMode.Create, FileAccess.ReadWrite, FileShare.None, 1)) { var file = new StreamEventFileStorage(stream); _writeStore = manager.AppendToStore(file); var consumerTask = Task.Factory.StartNew(EventConsumer, TaskCreationOptions.LongRunning | TaskCreationOptions.HideScheduler); _sw.Start(); var tasks = new Task[ParallelTasks]; Parallel.For(0, tasks.Length, i => { tasks[i] = PublishSampleEvents(RepetitionCount); }); Task.WaitAll(tasks); _sequenceBarrier.Alert(); consumerTask.Wait(); _sw.Stop(); Console.WriteLine("Write {0}ms events per second:{1:f0} total len:{2}", _sw.ElapsedMilliseconds, tasks.Length * RepetitionCount / _sw.Elapsed.TotalSeconds, stream.Length); _sw.Restart(); var allObserverCounter = new AllObserverCounter(); manager.OpenReadOnlyStore(file).ReadFromStartToEnd(allObserverCounter); _sw.Stop(); Console.WriteLine("Read {0}ms events per second:{1:f0} events:{2}", _sw.ElapsedMilliseconds, allObserverCounter.Count / _sw.Elapsed.TotalSeconds, allObserverCounter.Count); } } public class AllObserverCounter : IEventStoreObserver { ulong _count; public bool ObservedMetadata(object metadata, uint eventCount) { return true; } public bool ShouldStopReadingNextEvents() { return false; } public void ObservedEvents(object[] events) { if (events != null) _count += (ulong)events.Length; } public ulong Count { get { return _count; } } } async Task PublishSampleEvents(int count) { for (var i = 0; i < count; i++) { var e = new Event { Id = (ulong)i, Time = DateTime.UtcNow, Payload = "Payload" }; await PublishEvent(e); } } } }
/* MIT License Copyright (c) 2017 Saied Zarrinmehr Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Linq; using SpatialAnalysis.Interoperability; using System.Windows; using SpatialAnalysis.Geometry; namespace SpatialAnalysis.CellularEnvironment { /// <summary> /// This base class represents a 2D grid that covers the floor /// </summary> public class CellularFloorBaseGeometry { /// <summary> /// The elevation of the floor used for simulation /// </summary> public double Elevation { get; set; } /// <summary> /// The bottom left corner of the simulation area /// </summary> public UV Origin { get; set; } /// <summary> /// The upper right corner of the simulation area /// </summary> public UV TopRight { get; set; } /// <summary> /// The right border line of the simulation area /// </summary> protected UVLine right { get; set; } /// <summary> /// The left border line of the simulation area /// </summary> protected UVLine left { get; set; } /// <summary> /// The top border line of the simulation area /// </summary> protected UVLine top { get; set; } /// <summary> /// The bottom border line of the simulation area /// </summary> protected UVLine bottom { get; set; } /// <summary> /// A two dimensional array that included all of the cells in the floor /// </summary> public Cell[,] Cells { get; set; } /// <summary> /// The edges of all of the visual barriers /// </summary> public UVLine[] VisualBarrierEdges { get; set; } /// <summary> /// The edges of all of the physical barriers /// </summary> public UVLine[] PhysicalBarrierEdges { get; set; } /// <summary> /// The edges of all of the visual barriers /// </summary> public UVLine[] FieldBarrierEdges { get; set; } /// <summary> /// The size (i.e. width and height) of each cell /// </summary> public double CellSize { get; set; } /// <summary> /// Number of cells in the hight direction of the cellular floor /// </summary> public int GridHeight { get; set; } /// <summary> /// Number of cells in the width direction of the cellular floor /// </summary> public int GridWidth { get; set; } /// <summary> /// This dictionary can be used to retrieve the cell index in the floor /// </summary> public Dictionary<Cell, Index> CellToIndexGuide { get; set; } /// <summary> /// Number of the cells that are inside the walkable field /// </summary> public int NumberOfCellsInField { get; set; } /// <summary> /// The lower left corner of the walkable field territory inside the cellular floor /// </summary> public UV Territory_Min { get; set; } /// <summary> /// The upper right corner of the walkable field territory inside the cellular floor /// </summary> public UV Territory_Max { get; set; } /// <summary> /// Field polygons /// </summary> public BarrierPolygon[] FieldBarriers { get; set; } /// <summary> /// Visual obstacle polygons /// </summary> public BarrierPolygon[] VisualBarriers { get; set; } /// <summary> /// Physical obstacle polygons /// </summary> public BarrierPolygon[] PhysicalBarriers { get; set; } /// <summary> /// The length of the cell diagonal /// </summary> public double cellDiagonalDistance { get; set; } /// <summary> /// Using this dictionary you can find the barrier index of an visual barrier's edge as well as the start point of that edge in that barrier from its global edge index. /// </summary> public Dictionary<int, EdgeGlobalAddress> VisualBarrierEdgeAddress { get; set; } /// <summary> /// Using this dictionary you can find the barrier index of an physical barrier's edge as well as the start point of that edge in that barrier from its global edge index. /// </summary> public Dictionary<int, EdgeGlobalAddress> PhysicalBarrierEdgeAddress { get; set; } public readonly int NumberOfVisualBarriers; public readonly int NumberOfPhysicalBarriers; public readonly int NumberOfFieldBarriers; /// <summary> /// Using this dictionary you can find the barrier index of an field edge as well as the start point of that edge in that barrier from its global edge index. /// </summary> public Dictionary<int, EdgeGlobalAddress> FieldBarrierEdgeAddress { get; set; } /// <summary> /// An empty constructor to create an instance of CellularFloorBaseGeometry. This is limited to internal use only. /// </summary> internal CellularFloorBaseGeometry() { } /// <summary> /// a public constructor to create an instance of CellularFloorBaseGeometry /// </summary> /// <param name="desiredCellSize">Desired size for cells</param> /// <param name="barrierEnvironment">The environment parsed from BIM</param> /// <param name="pointOnWalkableArea">A point of the cellular floor where the walking territory should include</param> public CellularFloorBaseGeometry(double desiredCellSize, BIM_To_OSM_Base barrierEnvironment, UV pointOnWalkableArea) { this.CellSize = desiredCellSize; //upgrade UV to EdgeEndPoint that has ID this.VisualBarriers = barrierEnvironment.VisualBarriers; this.PhysicalBarriers = barrierEnvironment.PhysicalBarriers; this.FieldBarriers = barrierEnvironment.FieldBarriers; this.loadCellularSize(barrierEnvironment.FloorMinBound, barrierEnvironment.FloorMaxBound); this.Elevation = barrierEnvironment.PlanElevation; #region Creating visual, physical, and field barrier lines #region creating the edges of the visual barriers and loading their addresses this.VisualBarrierEdgeAddress = new Dictionary<int, EdgeGlobalAddress>(); int numberOfVisualBarrier = 0; foreach (BarrierPolygon item in this.VisualBarriers) { numberOfVisualBarrier += item.BoundaryPoints.Length; } this.VisualBarrierEdges = new UVLine[numberOfVisualBarrier]; numberOfVisualBarrier = 0; for (int barrierIndex = 0; barrierIndex < this.VisualBarriers.Length; barrierIndex++) { for (int i = 0; i < this.VisualBarriers[barrierIndex].Length; i++) { UVLine barrierEdge = new UVLine(this.VisualBarriers[barrierIndex].PointAt(i), this.VisualBarriers[barrierIndex].PointAt(this.VisualBarriers[barrierIndex].NextIndex(i))); this.VisualBarrierEdges[numberOfVisualBarrier] = barrierEdge; this.VisualBarrierEdgeAddress.Add(numberOfVisualBarrier, new EdgeGlobalAddress(barrierIndex, i)); barrierEdge = null; numberOfVisualBarrier++; } } this.NumberOfVisualBarriers = numberOfVisualBarrier; #endregion #region creating the edges of the physical barriers and loading their addresses this.PhysicalBarrierEdgeAddress = new Dictionary<int, EdgeGlobalAddress>(); int numberOfPhysicalBarrier = 0; foreach (BarrierPolygon item in this.PhysicalBarriers) { numberOfPhysicalBarrier += item.BoundaryPoints.Length; } this.PhysicalBarrierEdges = new UVLine[numberOfPhysicalBarrier]; numberOfPhysicalBarrier = 0; for (int barrierIndex = 0; barrierIndex < this.PhysicalBarriers.Length; barrierIndex++) { for (int i = 0; i < this.PhysicalBarriers[barrierIndex].Length; i++) { UVLine barrierEdge = new UVLine(this.PhysicalBarriers[barrierIndex].PointAt(i), this.PhysicalBarriers[barrierIndex].PointAt(this.PhysicalBarriers[barrierIndex].NextIndex(i))); this.PhysicalBarrierEdges[numberOfPhysicalBarrier] = barrierEdge; this.PhysicalBarrierEdgeAddress.Add(numberOfPhysicalBarrier, new EdgeGlobalAddress(barrierIndex, i)); barrierEdge = null; numberOfPhysicalBarrier++; } } this.NumberOfPhysicalBarriers = numberOfPhysicalBarrier; #endregion #region creating the edges of the fields and loading their addresses this.FieldBarrierEdgeAddress = new Dictionary<int, EdgeGlobalAddress>(); int numberOfFieldBarriers = 0; foreach (BarrierPolygon item in this.FieldBarriers) { numberOfFieldBarriers += item.BoundaryPoints.Length; } this.FieldBarrierEdges = new UVLine[numberOfFieldBarriers]; numberOfFieldBarriers = 0; for (int barrierIndex = 0; barrierIndex < this.FieldBarriers.Length; barrierIndex++) { for (int i = 0; i < this.FieldBarriers[barrierIndex].Length; i++) { UVLine barrierEdge = new UVLine(this.FieldBarriers[barrierIndex].PointAt(i), this.FieldBarriers[barrierIndex].PointAt(this.FieldBarriers[barrierIndex].NextIndex(i))); this.FieldBarrierEdges[numberOfFieldBarriers] = barrierEdge; this.FieldBarrierEdgeAddress.Add(numberOfFieldBarriers, new EdgeGlobalAddress(barrierIndex, i)); barrierEdge = null; numberOfFieldBarriers++; } } this.NumberOfFieldBarriers = numberOfFieldBarriers; #endregion #endregion #region creating the cells this.Cells = new Cell[this.GridWidth, this.GridHeight]; //this._cells = new Cell[this.GridWidth* this.GridHeight]; this.CellToIndexGuide = new Dictionary<Cell, Index>(); int id = 0; for (int i = 0; i < this.GridWidth; i++) { for (int j = 0; j < this.GridHeight; j++) { this.Cells[i, j] = new Cell(this.Origin + new UV(i * this.CellSize, j * this.CellSize), id, i, j); this.CellToIndexGuide.Add(this.Cells[i, j], new Index(i, j)); //this._cells[id] = this.Cells[i, j]; id++; } } this.cellDiagonalDistance = Math.Sqrt(this.CellSize * this.CellSize + this.CellSize * this.CellSize); #endregion #region loading the lines into the cells #region visual barriers for (int i = 0; i < this.VisualBarrierEdges.Length; i++) { Index[] intersectingCellIndices = this.FindLineIndices(this.VisualBarrierEdges[i]); foreach (Index index in intersectingCellIndices) { this.FindCell(index).VisualBarrierEdgeIndices.Add(i); } } #endregion #region physical barriers for (int i = 0; i < this.PhysicalBarrierEdges.Length; i++) { Index[] intersectingCellIndices = this.FindLineIndices(this.PhysicalBarrierEdges[i]); foreach (Index index in intersectingCellIndices) { this.FindCell(index).PhysicalBarrierEdgeIndices.Add(i); } } #endregion #region loading field Edges for (int i = 0; i < this.FieldBarrierEdges.Length; i++) { Index[] intersectingCellIndices = this.FindLineIndices(this.FieldBarrierEdges[i]); foreach (Index index in intersectingCellIndices) { this.FindCell(index).FieldBarrierEdgeIndices.Add(i); } } #endregion #endregion #region loading the overlapping states in cells this.LoadFieldOverlappingStates(pointOnWalkableArea); this.LoadVisualOverlappingStates(pointOnWalkableArea); this.LoadPhysicalOverlappingStates(pointOnWalkableArea); #endregion #region setting min and max of the selected territory this.Territory_Max = new UV(double.NegativeInfinity, double.NegativeInfinity); this.Territory_Min = new UV(double.PositiveInfinity, double.PositiveInfinity); UV d = new UV(this.CellSize, this.CellSize); foreach (Cell cell in this.Cells) { if (cell.FieldOverlapState != OverlapState.Outside) { if (this.Territory_Min.U > cell.U) this.Territory_Min.U = cell.U; if (this.Territory_Min.V > cell.V) this.Territory_Min.V = cell.V; var p = cell + d; if (this.Territory_Max.U < p.U) this.Territory_Max.U = p.U; if (this.Territory_Max.V < p.V) this.Territory_Max.V = p.V; } } d = null; #endregion #region loading edge end points to cells foreach (BarrierPolygon polygon in this.VisualBarriers) { foreach (UV point in polygon.BoundaryPoints) { Cell cell = this.FindCell(point); if(cell != null) { if (cell.VisualBarrierEndPoints == null) { cell.VisualBarrierEndPoints = new List<UV>(); } cell.VisualBarrierEndPoints.Add(point); } } } foreach (BarrierPolygon polygon in this.PhysicalBarriers) { foreach (UV point in polygon.BoundaryPoints) { Cell cell = this.FindCell(point); if (cell != null) { if (cell.PhysicalBarrierEndPoints == null) { cell.PhysicalBarrierEndPoints = new List<UV>(); } cell.PhysicalBarrierEndPoints.Add(point); } } } foreach (BarrierPolygon polygon in this.FieldBarriers) { foreach (UV point in polygon.BoundaryPoints) { Cell cell = this.FindCell(point); if (cell != null) { if (cell.FieldBarrierEndPoints == null) { cell.FieldBarrierEndPoints = new List<UV>(); } cell.FieldBarrierEndPoints.Add(point); } } } #endregion } /// <summary> /// Loads the cell size /// </summary> /// <param name="min"></param> /// <param name="max"></param> private void loadCellularSize(UV min, UV max) { double xMin = min.U; double xMax = max.U; double yMin = min.V; double yMax = max.V; foreach (BarrierPolygon barrier in this.PhysicalBarriers) { foreach (UV point in barrier.BoundaryPoints) { xMin = (point.U < xMin) ? point.U : xMin; xMax = (point.U > xMax) ? point.U : xMax; yMin = (point.V < yMin) ? point.V : yMin; yMax = (point.V > yMax) ? point.V : yMax; } } xMin -= this.CellSize / 2; yMin -= this.CellSize / 2; xMax += this.CellSize / 2; yMax += this.CellSize / 2; double w = xMax - xMin; double h = yMax - yMin; this.GridWidth = (int)(w / this.CellSize) + 1; this.GridHeight = (int)(h / this.CellSize) + 1; xMax = this.CellSize * this.GridWidth +xMin; yMax = this.CellSize * this.GridHeight +yMin; this.Origin = new UV(xMin, yMin); this.TopRight = new UV(xMax, yMax); this.top = new UVLine(new UV(xMin, yMax), new UV(xMax, yMax)); this.bottom = new UVLine(new UV(xMin, yMin), new UV(xMax, yMin)); this.left = new UVLine(new UV(xMin, yMin), new UV(xMin, yMax)); this.right = new UVLine(new UV(xMax, yMin), new UV(xMax, yMax)); } #region finding cells and indices interchangeably /// <summary> /// Find a cell based on its ID /// </summary> /// <param name="id">Cell ID</param> /// <returns>Found Cell</returns> public Cell FindCell(int id) { int i = (int)(id / this.GridHeight); int j = id - i * this.GridHeight; return this.Cells[i, j]; } /// <summary> /// Finds a cell index based on a cell ID /// </summary> /// <param name="id">Cell ID</param> /// <returns>Cell Index</returns> public Index FindIndex(int id) { int i = (int)(id / this.GridHeight); int j = id - i * this.GridHeight; return new Index(i, j); } /// <summary> /// Finds a cell that contains a given point /// </summary> /// <param name="p">A point</param> /// <returns>The containing cell if found</returns> public Cell FindCell(UV p) { if (p.U<this.Origin.U || p.V<this.Origin.V || p.U>this.TopRight.U || p.V>this.TopRight.V) { return null; } double i = (p.U - this.Origin.U) / this.CellSize; int I = (int)i; double j = (p.V - this.Origin.V) / this.CellSize; int J = (int)j; if (I>=0 && i<this.GridWidth && J>=0 && j<this.GridHeight) { return this.Cells[I, J]; } return null; } /// <summary> /// Find a cell based a given index /// </summary> /// <param name="index">A given index</param> /// <returns>The corresponding cell if found</returns> public Cell FindCell(Index index) { if (index.I >= this.GridWidth || index.I < 0) { return null; } if (index.J >= this.GridHeight || index.J < 0) { return null; } return this.Cells[index.I, index.J]; } /// <summary> /// Finds the index of the cell that contains a given point /// </summary> /// <param name="p">A given point</param> /// <returns>The index of the containing cell if found</returns> public Index FindIndex(UV p) { double i = (p.U - this.Origin.U) / this.CellSize; int I = (int)i; double j = (p.V - this.Origin.V) / this.CellSize; int J = (int)j; if (J == this.GridHeight) { J -= 1; } if (I == this.GridWidth) { I -= 1; } return new Index(I, J); } /// <summary> /// Returns the index of a given cell /// </summary> /// <param name="cell">A given cell</param> /// <returns>The index of the cell</returns> public Index FindIndex(Cell cell) { /* Index index; this.CellToIndexGuide.TryGetValue(cell, out index); */ //double i = (double)(.5 + (cell.Origin.U - this.Origin.U) / this.WidthOfCells); //int I = (int)i; //double j = (double)(.5 + (cell.Origin.V - this.Origin.V) / this.HeightOfCells); //int J = (int)j; //Index index = new Index(I, J); return cell.CellToIndex.Copy(); } /// <summary> /// Finds a cell that is translated from a given index /// </summary> /// <param name="baseIndex">The original cell location</param> /// <param name="translation">Translation Index</param> /// <returns>A translated cell if found</returns> public Cell RelativeIndex(Index baseIndex, Index translation) { int i = baseIndex.I + translation.I; int j = baseIndex.J + translation.J; if (i > -1 && i < this.GridWidth && j > -1 && j < this.GridHeight) { return this.Cells[i, j]; } return null; } /// <summary> /// Finds a cell translated from a given cell /// </summary> /// <param name="cell">Original cell</param> /// <param name="translation">Translation Index</param> /// <returns>A translated cell if it exists</returns> public Cell RelativeIndex(Cell cell, Index translation) { Index baseIndex = this.FindIndex(cell); int i = baseIndex.I + translation.I; int j = baseIndex.J + translation.J; if (i > -1 && i < this.GridWidth && j > -1 && j < this.GridHeight) { return this.Cells[i, j]; } return null; } /// <summary> /// Reports if a cell with the given index exists /// </summary> /// <param name="index">Index to find the cell for</param> /// <returns>True when exists, false when does not exist</returns> public bool ContainsCell(Index index) { if (index.I>=0 && index.I<this.GridWidth && index.J>=0 && index.J<this.GridHeight) { return true; } return false; } /// <summary> /// Reports if a cell with given index exists /// </summary> /// <param name="i">I index of the cell</param> /// <param name="j">J index of a cell</param> /// <returns>True when exists, false when does not exist</returns> public bool ContainsCell(int i, int j) { if (i >= 0 && i < this.GridWidth && j >= 0 && j < this.GridHeight) { return true; } return false; } /// <summary> /// Reports if a cell includes a point /// </summary> /// <param name="cell">The cell that is subject to inclusion test</param> /// <param name="point">The point</param> /// <returns>True when contains, false when does not contain</returns> public bool CellIncludesPoint(Cell cell, UV point) { double u = point.U - cell.U; double v = point.V - cell.V; return u >= 0 && u < this.CellSize && v >= 0 && v < this.CellSize; } /// <summary> /// Reports if a cell with the given index includes a point /// </summary> /// <param name="index">The index of t he cell that is subject to inclusion test</param> /// <param name="point">The point</param> /// <returns>True when contains, false when does not contain</returns> public bool CellIncludesPoint(Index index, UV point) { double u = point.U - this.Cells[index.I,index.J].U; double v = point.V - this.Cells[index.I, index.J].V; return u >= 0 && u < this.CellSize && v >= 0 && v < this.CellSize; } #endregion #region Ray tracing /// <summary> /// Find the intersection result of a ray /// </summary> /// <param name="origin">Origin of the ray</param> /// <param name="direction">Direction of the ray</param> /// <param name="barrierType">Type of intersecting barriers</param> /// <param name="tolerance">Tolerance which by default is set to the absolute tolerance of the main document</param> /// <returns>An instance of RayIntersectionResult</returns> public RayIntersectionResult RayIntersection(UV origin, UV direction, BarrierType barrierType, double tolerance = OSMDocument.AbsoluteTolerance) { Index originIndex = this.FindIndex(origin); if (!this.ContainsCell(originIndex)) { return null; } UV hitPoint = null; UV _hitPoint = null; UVLine hitEdge = null; int edgeIndex=-1; double min = double.PositiveInfinity; Ray ray = new Ray(origin, direction, this.Origin, this.CellSize, tolerance); Index nextIndex = originIndex.Copy(); while (min == double.PositiveInfinity) { nextIndex = ray.NextIndex(this.FindIndex, tolerance); if (this.ContainsCell(nextIndex)) { switch (barrierType) { case BarrierType.Visual: if (this.Cells[nextIndex.I, nextIndex.J].VisualOverlapState == OverlapState.Overlap) { foreach (int item in this.Cells[nextIndex.I, nextIndex.J].VisualBarrierEdgeIndices) { double? distance = ray.DistanceTo(this.VisualBarrierEdges[item], ref hitPoint, tolerance); if (distance != null) { if (min>distance.Value && distance > tolerance ) { _hitPoint = hitPoint; hitEdge = this.VisualBarrierEdges[item]; edgeIndex = item; min = distance.Value; } } } } break; case BarrierType.Field: if (this.Cells[nextIndex.I, nextIndex.J].FieldOverlapState == OverlapState.Overlap) { foreach (int item in this.Cells[nextIndex.I, nextIndex.J].FieldBarrierEdgeIndices) { double? distance = ray.DistanceTo(this.FieldBarrierEdges[item], ref hitPoint, tolerance); if (distance != null) { if (min > distance.Value && distance > tolerance) { _hitPoint = hitPoint; hitEdge = this.FieldBarrierEdges[item]; edgeIndex = item; min = distance.Value; } } } } break; case BarrierType.Physical: if (this.Cells[nextIndex.I, nextIndex.J].PhysicalOverlapState == OverlapState.Overlap) { foreach (int item in this.Cells[nextIndex.I, nextIndex.J].PhysicalBarrierEdgeIndices) { double? distance = ray.DistanceTo(this.PhysicalBarrierEdges[item], ref hitPoint, tolerance); if (distance != null) { if (min > distance.Value && distance > tolerance) { _hitPoint = hitPoint; hitEdge = this.PhysicalBarrierEdges[item]; edgeIndex = item; min = distance.Value; } } } } break; default: break; } } else { break; } } RayIntersectionResult result=null; if (min != double.PositiveInfinity) { switch (barrierType) { case BarrierType.Visual: result = new RayIntersectionResult(_hitPoint,edgeIndex, this.VisualBarrierEdgeAddress[edgeIndex], min, barrierType); break; case BarrierType.Physical: result = new RayIntersectionResult(_hitPoint,edgeIndex, this.PhysicalBarrierEdgeAddress[edgeIndex], min, barrierType); break; case BarrierType.Field: result = new RayIntersectionResult(_hitPoint, edgeIndex, this.FieldBarrierEdgeAddress[edgeIndex], min, barrierType); break; default: break; } } return result; } /// <summary> /// Find the intersection results of a ray with a number of bounces /// </summary> /// <param name="origin">Origin of the ray</param> /// <param name="direction">Direction of the ray</param> /// <param name="bounces">Number of bounces</param> /// <param name="barrierType">Barrier type</param> /// <param name="tolerance">Tolerance which by default is set to the absolute tolerance of the main document</param> /// <returns>a list of RayIntersectionResults</returns> public List<RayIntersectionResult> RayTrace(UV origin, UV direction, int bounces, BarrierType barrierType, double tolerance = OSMDocument.AbsoluteTolerance) { List<RayIntersectionResult> results = new List<RayIntersectionResult>(); int bounceNum = 0; var _origin= origin; var _direction = direction; while (bounceNum < bounces) { var intersectionResult = this.RayIntersection(_origin, _direction, barrierType, tolerance); if (intersectionResult != null) { bounceNum++; results.Add(intersectionResult); UVLine edge = null; switch (barrierType) { case BarrierType.Visual: edge = this.VisualBarrierEdges[intersectionResult.EdgeIndexInCellularFloor]; break; case BarrierType.Physical: edge = this.PhysicalBarrierEdges[intersectionResult.EdgeIndexInCellularFloor]; break; case BarrierType.Field: edge = this.FieldBarrierEdges[intersectionResult.EdgeIndexInCellularFloor]; break; default: break; } _direction = _direction.GetReflection(edge); _origin = intersectionResult.IntersectingPoint; } else { break; } } return results; } /// <summary> /// Checks to see if two points are visible from each other /// </summary> public bool Visible(UV origin, UV target, double tolerance = 0.000001f) { return Ray.Visible(origin, target, BarrierType.Physical, this, tolerance); } /// <summary> /// Checks the visibility between the origins of two cells /// </summary> public bool CellVisibility(Cell cell1, Cell cell2, double tolerance = 0.000001) { return Ray.Visible(cell1, cell2, BarrierType.Physical, this, tolerance); } #endregion #region Finding indices of cells that a given curve hits /// <summary> /// Findes the indices of the cells that a line intersects with /// </summary> /// <param name="start">Start point of the line</param> /// <param name="end">End point of the line</param> /// <param name="tolerance">Tolerance which by default is set to the absolute tolerance of the main document</param> /// <returns>An array of indices</returns> public Index[] FindLineIndices(UV start, UV end, double tolerance = OSMDocument.AbsoluteTolerance) { List<Index> _indices = new List<Index>(); UV direction = end - start; double length = direction.GetLength(); direction /= length; Ray ray = new Ray(start, direction, this.Origin, this.CellSize, tolerance); while (ray.Length + tolerance < length) { var _index = ray.NextIndex(this.FindIndex, tolerance); _indices.Add(_index); } ray = null; Index[] _IndexArray = _indices.ToArray(); _indices.Clear(); _indices = null; return _IndexArray; } /// <summary> /// Findes the indices of the cells that a line intersects with /// </summary> /// <param name="edge">The line instance</param> /// <param name="tolerance">Tolerance which by default is set to the absolute tolerance of the main document</param> /// <returns>An array of indices</returns> public Index[] FindLineIndices(UVLine edge, double tolerance = OSMDocument.AbsoluteTolerance) { List<Index> _indices = new List<Index>(); UV direction = edge.End - edge.Start; double length = direction.GetLength(); direction /= length; Ray ray = new Ray(edge.Start, direction, this.Origin, this.CellSize, tolerance); while (ray.Length + tolerance < length) { var _index = ray.NextIndex(this.FindIndex, tolerance); _indices.Add(_index); } ray = null; Index[] _IndexArray = _indices.ToArray(); _indices.Clear(); _indices = null; return _IndexArray; } /// <summary> /// Finds the overlapping part of a line clipped by the cellular floor /// </summary> /// <param name="ray"></param> /// <param name="tolerance"></param> /// <returns></returns> private UVLine LineClip(UVLine ray, double tolerance = OSMDocument.AbsoluteTolerance) { List<double> values = new List<double>(); double? u = ray.Intersection(top); if (u != null) { values.Add(u.Value); } u = ray.Intersection(bottom); if (u != null) { values.Add(u.Value); } u = ray.Intersection(left); if (u != null) { values.Add(u.Value); } u = ray.Intersection(right); if (u != null) { values.Add(u.Value); } if (values.Count == 1) { if (new Interval(this.Origin.U, this.TopRight.U).Includes(ray.Start.U) && new Interval(this.Origin.V, this.TopRight.V).Includes(ray.Start.V)) { return new UVLine(ray.Start, ray.FindPoint(values[0] - tolerance)); } return new UVLine(ray.FindPoint(values[0] + tolerance), ray.End); } if (values.Count == 2) { return new UVLine(ray.FindPoint(Math.Min(values[0], values[1]) + tolerance), ray.FindPoint(Math.Max(values[0], values[1]) - tolerance)); } if (values.Count == 0 && ray.Start.U > this.Origin.U && ray.Start.U < this.TopRight.U) { return ray; } return null; } /// <summary> /// Finds indices of the cells which intersect with a line that extends outside the floor /// </summary> /// <param name="ray">A line that represents the ray</param> /// <param name="tolerance">Numeric tolerance which by default is set to the absolute tolerance of the main document</param> /// <returns>An array of indices</returns> public Index[] FindRayIndices(UVLine ray, double tolerance = OSMDocument.AbsoluteTolerance) { UVLine rayOverlapWithTerritory = this.LineClip(ray, tolerance); if (rayOverlapWithTerritory != null) { return FindLineIndices(rayOverlapWithTerritory); } return new Index[0]; } #endregion #region Determining the overlapping state of cells private void LoadFieldOverlappingStates(UV p) { for (int i = 0; i < this.GridWidth; i++) { for (int j = 0; j < this.GridHeight; j++) { if (this.Cells[i, j].FieldBarrierEdgeIndices.Count != 0) { this.Cells[i, j].FieldOverlapState = OverlapState.Overlap; } else { this.Cells[i, j].FieldOverlapState = OverlapState.Outside; } } } HashSet<Index> overlaps = new HashSet<Index>(); Index index = this.FindIndex(p); HashSet<Index> edge = new HashSet<Index>(); HashSet<Index> temp_edge = new HashSet<Index>(); HashSet<Index> area = new HashSet<Index>(); area.Add(index); edge.Add(index); while (edge.Count != 0) { foreach (var item in edge) { foreach (var neighbor in Index.Neighbors) { var next = item + neighbor; if (this.ContainsCell(next)) { if (!area.Contains(next)) { if (this.Cells[next.I, next.J].FieldOverlapState != OverlapState.Overlap) { temp_edge.Add(next); } else { overlaps.Add(next); } } } } } edge.Clear(); edge.UnionWith(temp_edge); area.UnionWith(temp_edge); temp_edge.Clear(); } foreach (Cell item in this.Cells) { item.FieldOverlapState = OverlapState.Outside; } foreach (var item in area) { this.Cells[item.I, item.J].FieldOverlapState = OverlapState.Inside; } this.NumberOfCellsInField = area.Count; foreach (var item in overlaps) { this.Cells[item.I, item.J].FieldOverlapState = OverlapState.Overlap; } edge.Clear(); area.Clear(); temp_edge.Clear(); overlaps.Clear(); area = null; edge = null; temp_edge = null; overlaps = null; } private void LoadVisualOverlappingStates(UV p) { for (int i = 0; i < this.GridWidth; i++) { for (int j = 0; j < this.GridHeight; j++) { if (this.Cells[i, j].VisualBarrierEdgeIndices.Count != 0) { this.Cells[i, j].VisualOverlapState = OverlapState.Overlap; } else { this.Cells[i, j].VisualOverlapState = OverlapState.Inside; } } } Index index = this.FindIndex(p); HashSet<Index> edge = new HashSet<Index>(); HashSet<Index> temp_edge = new HashSet<Index>(); HashSet<Index> area = new HashSet<Index>(); area.Add(index); edge.Add(index); while (edge.Count != 0) { foreach (var item in edge) { foreach (var neighbor in Index.Neighbors) { var next = item + neighbor; if (this.ContainsCell(next)) { if (!area.Contains(next)) { if (this.Cells[next.I,next.J].VisualOverlapState != OverlapState.Overlap) { temp_edge.Add(next); } } } } } edge.Clear(); edge.UnionWith(temp_edge); area.UnionWith(temp_edge); temp_edge.Clear(); } foreach (var item in area) { this.Cells[item.I, item.J].VisualOverlapState = OverlapState.Outside; } area = null; edge = null; temp_edge = null; } private void LoadPhysicalOverlappingStates(UV p) { for (int i = 0; i < this.GridWidth; i++) { for (int j = 0; j < this.GridHeight; j++) { if (this.Cells[i, j].PhysicalBarrierEdgeIndices.Count != 0) { this.Cells[i, j].PhysicalOverlapState = OverlapState.Overlap; } else { this.Cells[i, j].PhysicalOverlapState = OverlapState.Inside; } } } Index index = this.FindIndex(p); HashSet<Index> edge = new HashSet<Index>(); HashSet<Index> temp_edge = new HashSet<Index>(); HashSet<Index> area = new HashSet<Index>(); area.Add(index); edge.Add(index); while (edge.Count != 0) { foreach (var item in edge) { foreach (var neighbor in Index.Neighbors) { var next = item + neighbor; if (this.ContainsCell(next)) { if (!area.Contains(next)) { if (this.Cells[next.I,next.J].PhysicalOverlapState != OverlapState.Overlap) { temp_edge.Add(next); } } } } } edge.Clear(); edge.UnionWith(temp_edge); area.UnionWith(temp_edge); temp_edge.Clear(); } foreach (var item in area) { this.Cells[item.I, item.J].PhysicalOverlapState = OverlapState.Outside; } area = null; edge = null; temp_edge = null; } #endregion /// <summary> /// Converts a given cell to a hash set of lines /// </summary> /// <param name="cell"></param> /// <returns></returns> public HashSet<UVLine> CellToLines(Cell cell) { Index index = this.FindIndex(cell); double u, v; u = (index.I == this.GridWidth - 1) ? this.TopRight.U : this.Cells[index.I + 1, index.J].U; v = (index.J == this.GridHeight - 1) ? this.TopRight.V : this.Cells[index.I, index.J + 1].V; HashSet<UVLine> lines = new HashSet<UVLine>(); UV pt = new UV(cell.U, v); UV pb = new UV(u, cell.V); UV p = new UV(u, v); lines.Add(new UVLine(cell, pt)); lines.Add(new UVLine(cell, pb)); lines.Add(new UVLine(pb, p)); lines.Add(new UVLine(pt, p)); return lines; } #region Find cells inside a barrier /// <summary> /// For any polygon finds the cells that locate inside it or intersect with it /// </summary> /// <param name="barrier">A polygon</param> /// <param name="tolerance">Tolerance factor by default set to the absolute tolerance of the main document</param> /// <returns></returns> public HashSet<Index> GetIndicesInsideBarrier(BarrierPolygon barrier, double tolerance = OSMDocument.AbsoluteTolerance ) { Dictionary<Index, List<UVLine>> indexToLines = new Dictionary<Index, List<UVLine>>(new IndexComparer()); for (int i = 0; i < barrier.Length; i++) { UVLine edge = new UVLine(barrier.PointAt(i), barrier.PointAt(barrier.NextIndex(i))); var indices = this.FindLineIndices(edge, tolerance); foreach (Index item in indices) { if (indexToLines.ContainsKey(item)) { indexToLines[item].Add(edge); } else { List<UVLine> lines = new List<UVLine>() { edge }; indexToLines.Add(item, lines); } } } int iMin = this.GridWidth, iMax = -1, jMin = this.GridHeight, jMax = -1; foreach (var item in indexToLines.Keys) { if (iMin > item.I) iMin = item.I; if (iMax < item.I) iMax = item.I; if (jMin > item.J) jMin = item.J; if (jMax < item.J) jMax = item.J; } HashSet<Index> inside = new HashSet<Index>(); for (int i = iMin; i <= iMax; i++) { List<Index> column = new List<Index>(); List<int> numbers = new List<int>(); int n = 0; for (int j = jMin; j < jMax; j++) { UVLine line = new UVLine(this.Cells[i, j], this.Cells[i, j + 1]); Index index = new Index(i, j); if (indexToLines.ContainsKey(index)) { foreach (var item in indexToLines[index]) { if (line.Intersects(item, tolerance)) { n++; } } } column.Add(index); numbers.Add(n); } for (int k = 0; k < column.Count; k++) { if (numbers[k] % 2 == 1 ) { inside.Add(column[k]); } } } inside.UnionWith(indexToLines.Keys); return inside; } /// <summary> /// For any polygon finds the cells that only intersect with it /// </summary> /// <param name="barrier">A polygon</param> /// <param name="tolerance">Tolerance factor by default set to the absolute tolerance of the main document</param> /// <returns></returns> public HashSet<Index> GetIndicesOnBarrier(BarrierPolygon barrier, double tolerance = OSMDocument.AbsoluteTolerance) { HashSet<Index> indices = new HashSet<Index>(); for (int i = 0; i < barrier.Length; i++) { var edgeIndices = this.FindLineIndices(barrier.PointAt(i), barrier.PointAt(barrier.NextIndex(i)), tolerance); indices.UnionWith(edgeIndices); } return indices; } #endregion } }
// ======================================================================================================= // // ,uEZGZX LG Eu iJ vi // BB7. .: uM 8F 0BN Bq S: // @X LO rJLYi : i iYLL XJ Xu7@ Mu 7LjL; rBOii 7LJ7 .vYUi // ,@ LG 7Br...SB vB B B1...7BL 0S i@, OU :@7. ,u@ @u.. :@: ;B LB. :: // v@ LO B Z0 i@ @ BU @Y qq .@L Oj @ 5@ Oi @. MB U@ // .@ JZ :@ :@ rB B @ 5U Eq @0 Xj ,B .B Br ,B:rv777i :0ZU // @M LO @ Mk :@ .@ BL @J EZ GZML @ XM B; @ Y@ // ZBFi::vu 1B ;B7..:qO BS..iGB BJ..:vB2 BM rBj :@7,.:5B qM.. i@r..i5. ir. UB // iuU1vi , ;LLv, iYvi , ;LLr . ., . rvY7: rLi 7LLr, ,uvv: // // // Copyright 2014-2015 daxnet // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ======================================================================================================= namespace CloudNotes.DesktopClient.Extensions.Blog.MetaWeblogSharp { using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using CloudNotes.DesktopClient.Extensions.Blog.MetaWeblogSharp.XmlRPC; public class Client { public string AppKey = "0123456789ABCDEF"; public BlogConnectionInfo BlogConnectionInfo; public Client(BlogConnectionInfo connectionInfo) { this.BlogConnectionInfo = connectionInfo; } public async Task<List<PostInfo>> GetRecentPostsAsync(int numposts) { Service service = new Service(this.BlogConnectionInfo.MetaWeblogURL); MethodCall methodCall = new MethodCall("metaWeblog.getRecentPosts"); methodCall.Parameters.Add(this.BlogConnectionInfo.BlogID); methodCall.Parameters.Add(this.BlogConnectionInfo.Username); methodCall.Parameters.Add(this.BlogConnectionInfo.Password); methodCall.Parameters.Add(numposts); service.Cookies = this.BlogConnectionInfo.Cookies; MethodResponse methodResponse = await service.ExecuteAsync(methodCall); Value value = methodResponse.Parameters[0]; XmlRPC.Array array = (XmlRPC.Array)value; List<PostInfo> list = new List<PostInfo>(); foreach (Value current in array) { Struct @struct = (Struct)current; list.Add(new PostInfo { Title = @struct.Get<StringValue>("title", StringValue.NullString).String, DateCreated = new DateTime?(@struct.Get<DateTimeValue>("dateCreated").Data), Link = @struct.Get<StringValue>("link", StringValue.NullString).String, PostID = @struct.Get<StringValue>("postid", StringValue.NullString).String, UserID = @struct.Get<StringValue>("userid", StringValue.NullString).String, CommentCount = @struct.Get<IntegerValue>("commentCount", 0).Integer, PostStatus = @struct.Get<StringValue>("post_status", StringValue.NullString).String, PermaLink = @struct.Get<StringValue>("permaLink", StringValue.NullString).String, Description = @struct.Get<StringValue>("description", StringValue.NullString).String }); } return list; } public async Task<MediaObjectInfo> NewMediaObjectAsync(string name, string type, byte[] bits) { Service service = new Service(this.BlogConnectionInfo.MetaWeblogURL); Struct @struct = new Struct(); @struct["name"] = new StringValue(name); @struct["type"] = new StringValue(type); @struct["bits"] = new Base64Data(bits); MethodCall methodCall = new MethodCall("metaWeblog.newMediaObject"); methodCall.Parameters.Add(this.BlogConnectionInfo.BlogID); methodCall.Parameters.Add(this.BlogConnectionInfo.Username); methodCall.Parameters.Add(this.BlogConnectionInfo.Password); methodCall.Parameters.Add(@struct); service.Cookies = this.BlogConnectionInfo.Cookies; MethodResponse methodResponse = await service.ExecuteAsync(methodCall); Value value = methodResponse.Parameters[0]; Struct struct2 = (Struct)value; return new MediaObjectInfo { URL = struct2.Get<StringValue>("url", StringValue.NullString).String }; } public async Task<PostInfo> GetPostAsync(string postid) { Service service = new Service(this.BlogConnectionInfo.MetaWeblogURL); MethodCall methodCall = new MethodCall("metaWeblog.getPost"); methodCall.Parameters.Add(postid); methodCall.Parameters.Add(this.BlogConnectionInfo.Username); methodCall.Parameters.Add(this.BlogConnectionInfo.Password); service.Cookies = this.BlogConnectionInfo.Cookies; MethodResponse methodResponse = await service.ExecuteAsync(methodCall); Value value = methodResponse.Parameters[0]; Struct @struct = (Struct)value; PostInfo postinfo = new PostInfo(); postinfo.PostID = @struct.Get<StringValue>("postid").String; postinfo.Description = @struct.Get<StringValue>("description").String; postinfo.Link = @struct.Get<StringValue>("link", StringValue.NullString).String; postinfo.DateCreated = new DateTime?(@struct.Get<DateTimeValue>("dateCreated").Data); postinfo.PermaLink = @struct.Get<StringValue>("permaLink", StringValue.NullString).String; postinfo.PostStatus = @struct.Get<StringValue>("post_status", StringValue.NullString).String; postinfo.Title = @struct.Get<StringValue>("title").String; postinfo.UserID = @struct.Get<StringValue>("userid", StringValue.NullString).String; XmlRPC.Array source = @struct.Get<global::CloudNotes.DesktopClient.Extensions.Blog.MetaWeblogSharp.XmlRPC.Array>("categories"); source.ToList<Value>().ForEach(delegate(Value i) { if (i is StringValue) { string @string = (i as StringValue).String; if (@string != "" && !postinfo.Categories.Contains(@string)) { postinfo.Categories.Add(@string); } } }); return postinfo; } public async Task<string> NewPostAsync(PostInfo pi, IList<string> categories, bool publish) { return await this.NewPostAsync(pi.Title, pi.Description, categories, publish, pi.DateCreated); } public async Task<string> NewPostAsync(string title, string description, IList<string> categories, bool publish, DateTime? date_created) { XmlRPC.Array array; if (categories == null) { array = new XmlRPC.Array(0); } else { array = new XmlRPC.Array(categories.Count); List<Value> ss = new List<Value>(); ( from c in categories select new StringValue(c)).ToList<StringValue>().ForEach(delegate(StringValue i) { ss.Add(i); }); array.AddRange(ss); } Service service = new Service(this.BlogConnectionInfo.MetaWeblogURL); Struct @struct = new Struct(); @struct["title"] = new StringValue(title); @struct["description"] = new StringValue(description); @struct["categories"] = array; if (date_created.HasValue) { @struct["dateCreated"] = new DateTimeValue(date_created.Value); @struct["date_created_gmt"] = new DateTimeValue(date_created.Value.ToUniversalTime()); } MethodCall methodCall = new MethodCall("metaWeblog.newPost"); methodCall.Parameters.Add(this.BlogConnectionInfo.BlogID); methodCall.Parameters.Add(this.BlogConnectionInfo.Username); methodCall.Parameters.Add(this.BlogConnectionInfo.Password); methodCall.Parameters.Add(@struct); methodCall.Parameters.Add(publish); service.Cookies = this.BlogConnectionInfo.Cookies; MethodResponse methodResponse = await service.ExecuteAsync(methodCall); Value value = methodResponse.Parameters[0]; return ((StringValue)value).String; } public async Task<bool> DeletePostAsync(string postid) { Service service = new Service(this.BlogConnectionInfo.MetaWeblogURL); MethodCall methodCall = new MethodCall("blogger.deletePost"); methodCall.Parameters.Add(this.AppKey); methodCall.Parameters.Add(postid); methodCall.Parameters.Add(this.BlogConnectionInfo.Username); methodCall.Parameters.Add(this.BlogConnectionInfo.Password); methodCall.Parameters.Add(true); service.Cookies = this.BlogConnectionInfo.Cookies; MethodResponse methodResponse = await service.ExecuteAsync(methodCall); Value value = methodResponse.Parameters[0]; BooleanValue booleanValue = (BooleanValue)value; return booleanValue.Boolean; } public async Task<List<BlogInfo>> GetUsersBlogsAsync() { Service service = new Service(this.BlogConnectionInfo.MetaWeblogURL); MethodCall methodCall = new MethodCall("blogger.getUsersBlogs"); methodCall.Parameters.Add(this.AppKey); methodCall.Parameters.Add(this.BlogConnectionInfo.Username); methodCall.Parameters.Add(this.BlogConnectionInfo.Password); service.Cookies = this.BlogConnectionInfo.Cookies; MethodResponse methodResponse = await service.ExecuteAsync(methodCall); XmlRPC.Array array = (XmlRPC.Array)methodResponse.Parameters[0]; List<BlogInfo> list = new List<BlogInfo>(array.Count); for (int i = 0; i < array.Count; i++) { Struct @struct = (Struct)array[i]; list.Add(new BlogInfo { BlogID = @struct.Get<StringValue>("blogid", StringValue.NullString).String, URL = @struct.Get<StringValue>("url", StringValue.NullString).String, BlogName = @struct.Get<StringValue>("blogName", StringValue.NullString).String, IsAdmin = @struct.Get<BooleanValue>("isAdmin", false).Boolean, SiteName = @struct.Get<StringValue>("siteName", StringValue.NullString).String, Capabilities = @struct.Get<StringValue>("capabilities", StringValue.NullString).String, XmlRPCEndPoint = @struct.Get<StringValue>("xmlrpc", StringValue.NullString).String }); } return list; } public async Task<bool> EditPostAsync(string postid, string title, string description, IList<string> categories, bool publish) { XmlRPC.Array array = new XmlRPC.Array((categories == null) ? 0 : categories.Count); if (categories != null) { List<string> list = categories.Distinct<string>().ToList<string>(); list.Sort(); List<Value> ss = new List<Value>(); ( from c in list select new StringValue(c)).ToList<StringValue>().ForEach(delegate(StringValue i) { ss.Add(i); }); array.AddRange(ss); } Service service = new Service(this.BlogConnectionInfo.MetaWeblogURL); Struct @struct = new Struct(); @struct["title"] = new StringValue(title); @struct["description"] = new StringValue(description); @struct["categories"] = array; MethodCall methodCall = new MethodCall("metaWeblog.editPost"); methodCall.Parameters.Add(postid); methodCall.Parameters.Add(this.BlogConnectionInfo.Username); methodCall.Parameters.Add(this.BlogConnectionInfo.Password); methodCall.Parameters.Add(@struct); methodCall.Parameters.Add(publish); service.Cookies = this.BlogConnectionInfo.Cookies; MethodResponse methodResponse = await service.ExecuteAsync(methodCall); Value value = methodResponse.Parameters[0]; BooleanValue booleanValue = (BooleanValue)value; return booleanValue.Boolean; } public async Task<List<CategoryInfo>> GetCategoriesAsync() { Service service = new Service(this.BlogConnectionInfo.MetaWeblogURL); MethodCall methodCall = new MethodCall("metaWeblog.getCategories"); methodCall.Parameters.Add(this.BlogConnectionInfo.BlogID); methodCall.Parameters.Add(this.BlogConnectionInfo.Username); methodCall.Parameters.Add(this.BlogConnectionInfo.Password); service.Cookies = this.BlogConnectionInfo.Cookies; MethodResponse methodResponse = await service.ExecuteAsync(methodCall); Value value = methodResponse.Parameters[0]; global::CloudNotes.DesktopClient.Extensions.Blog.MetaWeblogSharp.XmlRPC.Array array = (global::CloudNotes.DesktopClient.Extensions.Blog.MetaWeblogSharp.XmlRPC.Array)value; List<CategoryInfo> list = new List<CategoryInfo>(); foreach (Value current in array) { Struct @struct = (Struct)current; list.Add(new CategoryInfo { Title = @struct.Get<StringValue>("title", StringValue.NullString).String, Description = @struct.Get<StringValue>("description", StringValue.NullString).String, HTMLURL = @struct.Get<StringValue>("htmlUrl", StringValue.NullString).String, RSSURL = @struct.Get<StringValue>("rssUrl", StringValue.NullString).String, CategoryID = @struct.Get<StringValue>("categoryid", StringValue.NullString).String }); } return list; } public async Task<UserInfo> GetUserInfoAsync() { Service service = new Service(this.BlogConnectionInfo.MetaWeblogURL); MethodCall methodCall = new MethodCall("blogger.getUserInfo"); methodCall.Parameters.Add(this.AppKey); methodCall.Parameters.Add(this.BlogConnectionInfo.Username); methodCall.Parameters.Add(this.BlogConnectionInfo.Password); service.Cookies = this.BlogConnectionInfo.Cookies; MethodResponse methodResponse = await service.ExecuteAsync(methodCall); Value value = methodResponse.Parameters[0]; Struct @struct = (Struct)value; return new UserInfo { UserID = @struct.Get<StringValue>("userid", StringValue.NullString).String, Nickname = @struct.Get<StringValue>("nickname", StringValue.NullString).String, FirstName = @struct.Get<StringValue>("firstname", StringValue.NullString).String, LastName = @struct.Get<StringValue>("lastname", StringValue.NullString).String, URL = @struct.Get<StringValue>("url", StringValue.NullString).String }; } } }
using System; using System.Linq; using System.Collections.Generic; using Blueprint41; using Blueprint41.Core; using Blueprint41.Query; using Blueprint41.DatastoreTemplates; using q = Domain.Data.Query; namespace Domain.Data.Manipulation { public interface IProductPhotoOriginalData : ISchemaBaseOriginalData { string ThumbNailPhoto { get; } string ThumbNailPhotoFileName { get; } string LargePhoto { get; } string LargePhotoFileName { get; } } public partial class ProductPhoto : OGM<ProductPhoto, ProductPhoto.ProductPhotoData, System.String>, ISchemaBase, INeo4jBase, IProductPhotoOriginalData { #region Initialize static ProductPhoto() { Register.Types(); } protected override void RegisterGeneratedStoredQueries() { #region LoadByKeys RegisterQuery(nameof(LoadByKeys), (query, alias) => query. Where(alias.Uid.In(Parameter.New<System.String>(Param0)))); #endregion AdditionalGeneratedStoredQueries(); } partial void AdditionalGeneratedStoredQueries(); public static Dictionary<System.String, ProductPhoto> LoadByKeys(IEnumerable<System.String> uids) { return FromQuery(nameof(LoadByKeys), new Parameter(Param0, uids.ToArray(), typeof(System.String))).ToDictionary(item=> item.Uid, item => item); } protected static void RegisterQuery(string name, Func<IMatchQuery, q.ProductPhotoAlias, IWhereQuery> query) { q.ProductPhotoAlias alias; IMatchQuery matchQuery = Blueprint41.Transaction.CompiledQuery.Match(q.Node.ProductPhoto.Alias(out alias)); IWhereQuery partial = query.Invoke(matchQuery, alias); ICompiled compiled = partial.Return(alias).Compile(); RegisterQuery(name, compiled); } public override string ToString() { return $"ProductPhoto => ThumbNailPhoto : {this.ThumbNailPhoto?.ToString() ?? "null"}, ThumbNailPhotoFileName : {this.ThumbNailPhotoFileName?.ToString() ?? "null"}, LargePhoto : {this.LargePhoto?.ToString() ?? "null"}, LargePhotoFileName : {this.LargePhotoFileName?.ToString() ?? "null"}, ModifiedDate : {this.ModifiedDate}, Uid : {this.Uid}"; } public override int GetHashCode() { return base.GetHashCode(); } protected override void LazySet() { base.LazySet(); if (PersistenceState == PersistenceState.NewAndChanged || PersistenceState == PersistenceState.LoadedAndChanged) { if ((object)InnerData == (object)OriginalData) OriginalData = new ProductPhotoData(InnerData); } } #endregion #region Validations protected override void ValidateSave() { bool isUpdate = (PersistenceState != PersistenceState.New && PersistenceState != PersistenceState.NewAndChanged); #pragma warning disable CS0472 if (InnerData.ModifiedDate == null) throw new PersistenceException(string.Format("Cannot save ProductPhoto with key '{0}' because the ModifiedDate cannot be null.", this.Uid?.ToString() ?? "<null>")); #pragma warning restore CS0472 } protected override void ValidateDelete() { } #endregion #region Inner Data public class ProductPhotoData : Data<System.String> { public ProductPhotoData() { } public ProductPhotoData(ProductPhotoData data) { ThumbNailPhoto = data.ThumbNailPhoto; ThumbNailPhotoFileName = data.ThumbNailPhotoFileName; LargePhoto = data.LargePhoto; LargePhotoFileName = data.LargePhotoFileName; ModifiedDate = data.ModifiedDate; Uid = data.Uid; } #region Initialize Collections protected override void InitializeCollections() { NodeType = "ProductPhoto"; } public string NodeType { get; private set; } sealed public override System.String GetKey() { return Entity.Parent.PersistenceProvider.ConvertFromStoredType<System.String>(Uid); } sealed protected override void SetKey(System.String key) { Uid = (string)Entity.Parent.PersistenceProvider.ConvertToStoredType<System.String>(key); base.SetKey(Uid); } #endregion #region Map Data sealed public override IDictionary<string, object> MapTo() { IDictionary<string, object> dictionary = new Dictionary<string, object>(); dictionary.Add("ThumbNailPhoto", ThumbNailPhoto); dictionary.Add("ThumbNailPhotoFileName", ThumbNailPhotoFileName); dictionary.Add("LargePhoto", LargePhoto); dictionary.Add("LargePhotoFileName", LargePhotoFileName); dictionary.Add("ModifiedDate", Conversion<System.DateTime, long>.Convert(ModifiedDate)); dictionary.Add("Uid", Uid); return dictionary; } sealed public override void MapFrom(IReadOnlyDictionary<string, object> properties) { object value; if (properties.TryGetValue("ThumbNailPhoto", out value)) ThumbNailPhoto = (string)value; if (properties.TryGetValue("ThumbNailPhotoFileName", out value)) ThumbNailPhotoFileName = (string)value; if (properties.TryGetValue("LargePhoto", out value)) LargePhoto = (string)value; if (properties.TryGetValue("LargePhotoFileName", out value)) LargePhotoFileName = (string)value; if (properties.TryGetValue("ModifiedDate", out value)) ModifiedDate = Conversion<long, System.DateTime>.Convert((long)value); if (properties.TryGetValue("Uid", out value)) Uid = (string)value; } #endregion #region Members for interface IProductPhoto public string ThumbNailPhoto { get; set; } public string ThumbNailPhotoFileName { get; set; } public string LargePhoto { get; set; } public string LargePhotoFileName { get; set; } #endregion #region Members for interface ISchemaBase public System.DateTime ModifiedDate { get; set; } #endregion #region Members for interface INeo4jBase public string Uid { get; set; } #endregion } #endregion #region Outer Data #region Members for interface IProductPhoto public string ThumbNailPhoto { get { LazyGet(); return InnerData.ThumbNailPhoto; } set { if (LazySet(Members.ThumbNailPhoto, InnerData.ThumbNailPhoto, value)) InnerData.ThumbNailPhoto = value; } } public string ThumbNailPhotoFileName { get { LazyGet(); return InnerData.ThumbNailPhotoFileName; } set { if (LazySet(Members.ThumbNailPhotoFileName, InnerData.ThumbNailPhotoFileName, value)) InnerData.ThumbNailPhotoFileName = value; } } public string LargePhoto { get { LazyGet(); return InnerData.LargePhoto; } set { if (LazySet(Members.LargePhoto, InnerData.LargePhoto, value)) InnerData.LargePhoto = value; } } public string LargePhotoFileName { get { LazyGet(); return InnerData.LargePhotoFileName; } set { if (LazySet(Members.LargePhotoFileName, InnerData.LargePhotoFileName, value)) InnerData.LargePhotoFileName = value; } } #endregion #region Members for interface ISchemaBase public System.DateTime ModifiedDate { get { LazyGet(); return InnerData.ModifiedDate; } set { if (LazySet(Members.ModifiedDate, InnerData.ModifiedDate, value)) InnerData.ModifiedDate = value; } } #endregion #region Members for interface INeo4jBase public string Uid { get { return InnerData.Uid; } set { KeySet(() => InnerData.Uid = value); } } #endregion #region Virtual Node Type public string NodeType { get { return InnerData.NodeType; } } #endregion #endregion #region Reflection private static ProductPhotoMembers members = null; public static ProductPhotoMembers Members { get { if (members == null) { lock (typeof(ProductPhoto)) { if (members == null) members = new ProductPhotoMembers(); } } return members; } } public class ProductPhotoMembers { internal ProductPhotoMembers() { } #region Members for interface IProductPhoto public Property ThumbNailPhoto { get; } = Datastore.AdventureWorks.Model.Entities["ProductPhoto"].Properties["ThumbNailPhoto"]; public Property ThumbNailPhotoFileName { get; } = Datastore.AdventureWorks.Model.Entities["ProductPhoto"].Properties["ThumbNailPhotoFileName"]; public Property LargePhoto { get; } = Datastore.AdventureWorks.Model.Entities["ProductPhoto"].Properties["LargePhoto"]; public Property LargePhotoFileName { get; } = Datastore.AdventureWorks.Model.Entities["ProductPhoto"].Properties["LargePhotoFileName"]; #endregion #region Members for interface ISchemaBase public Property ModifiedDate { get; } = Datastore.AdventureWorks.Model.Entities["SchemaBase"].Properties["ModifiedDate"]; #endregion #region Members for interface INeo4jBase public Property Uid { get; } = Datastore.AdventureWorks.Model.Entities["Neo4jBase"].Properties["Uid"]; #endregion } private static ProductPhotoFullTextMembers fullTextMembers = null; public static ProductPhotoFullTextMembers FullTextMembers { get { if (fullTextMembers == null) { lock (typeof(ProductPhoto)) { if (fullTextMembers == null) fullTextMembers = new ProductPhotoFullTextMembers(); } } return fullTextMembers; } } public class ProductPhotoFullTextMembers { internal ProductPhotoFullTextMembers() { } } sealed public override Entity GetEntity() { if (entity == null) { lock (typeof(ProductPhoto)) { if (entity == null) entity = Datastore.AdventureWorks.Model.Entities["ProductPhoto"]; } } return entity; } private static ProductPhotoEvents events = null; public static ProductPhotoEvents Events { get { if (events == null) { lock (typeof(ProductPhoto)) { if (events == null) events = new ProductPhotoEvents(); } } return events; } } public class ProductPhotoEvents { #region OnNew private bool onNewIsRegistered = false; private EventHandler<ProductPhoto, EntityEventArgs> onNew; public event EventHandler<ProductPhoto, EntityEventArgs> OnNew { add { lock (this) { if (!onNewIsRegistered) { Entity.Events.OnNew -= onNewProxy; Entity.Events.OnNew += onNewProxy; onNewIsRegistered = true; } onNew += value; } } remove { lock (this) { onNew -= value; if (onNew == null && onNewIsRegistered) { Entity.Events.OnNew -= onNewProxy; onNewIsRegistered = false; } } } } private void onNewProxy(object sender, EntityEventArgs args) { EventHandler<ProductPhoto, EntityEventArgs> handler = onNew; if ((object)handler != null) handler.Invoke((ProductPhoto)sender, args); } #endregion #region OnDelete private bool onDeleteIsRegistered = false; private EventHandler<ProductPhoto, EntityEventArgs> onDelete; public event EventHandler<ProductPhoto, EntityEventArgs> OnDelete { add { lock (this) { if (!onDeleteIsRegistered) { Entity.Events.OnDelete -= onDeleteProxy; Entity.Events.OnDelete += onDeleteProxy; onDeleteIsRegistered = true; } onDelete += value; } } remove { lock (this) { onDelete -= value; if (onDelete == null && onDeleteIsRegistered) { Entity.Events.OnDelete -= onDeleteProxy; onDeleteIsRegistered = false; } } } } private void onDeleteProxy(object sender, EntityEventArgs args) { EventHandler<ProductPhoto, EntityEventArgs> handler = onDelete; if ((object)handler != null) handler.Invoke((ProductPhoto)sender, args); } #endregion #region OnSave private bool onSaveIsRegistered = false; private EventHandler<ProductPhoto, EntityEventArgs> onSave; public event EventHandler<ProductPhoto, EntityEventArgs> OnSave { add { lock (this) { if (!onSaveIsRegistered) { Entity.Events.OnSave -= onSaveProxy; Entity.Events.OnSave += onSaveProxy; onSaveIsRegistered = true; } onSave += value; } } remove { lock (this) { onSave -= value; if (onSave == null && onSaveIsRegistered) { Entity.Events.OnSave -= onSaveProxy; onSaveIsRegistered = false; } } } } private void onSaveProxy(object sender, EntityEventArgs args) { EventHandler<ProductPhoto, EntityEventArgs> handler = onSave; if ((object)handler != null) handler.Invoke((ProductPhoto)sender, args); } #endregion #region OnPropertyChange public static class OnPropertyChange { #region OnThumbNailPhoto private static bool onThumbNailPhotoIsRegistered = false; private static EventHandler<ProductPhoto, PropertyEventArgs> onThumbNailPhoto; public static event EventHandler<ProductPhoto, PropertyEventArgs> OnThumbNailPhoto { add { lock (typeof(OnPropertyChange)) { if (!onThumbNailPhotoIsRegistered) { Members.ThumbNailPhoto.Events.OnChange -= onThumbNailPhotoProxy; Members.ThumbNailPhoto.Events.OnChange += onThumbNailPhotoProxy; onThumbNailPhotoIsRegistered = true; } onThumbNailPhoto += value; } } remove { lock (typeof(OnPropertyChange)) { onThumbNailPhoto -= value; if (onThumbNailPhoto == null && onThumbNailPhotoIsRegistered) { Members.ThumbNailPhoto.Events.OnChange -= onThumbNailPhotoProxy; onThumbNailPhotoIsRegistered = false; } } } } private static void onThumbNailPhotoProxy(object sender, PropertyEventArgs args) { EventHandler<ProductPhoto, PropertyEventArgs> handler = onThumbNailPhoto; if ((object)handler != null) handler.Invoke((ProductPhoto)sender, args); } #endregion #region OnThumbNailPhotoFileName private static bool onThumbNailPhotoFileNameIsRegistered = false; private static EventHandler<ProductPhoto, PropertyEventArgs> onThumbNailPhotoFileName; public static event EventHandler<ProductPhoto, PropertyEventArgs> OnThumbNailPhotoFileName { add { lock (typeof(OnPropertyChange)) { if (!onThumbNailPhotoFileNameIsRegistered) { Members.ThumbNailPhotoFileName.Events.OnChange -= onThumbNailPhotoFileNameProxy; Members.ThumbNailPhotoFileName.Events.OnChange += onThumbNailPhotoFileNameProxy; onThumbNailPhotoFileNameIsRegistered = true; } onThumbNailPhotoFileName += value; } } remove { lock (typeof(OnPropertyChange)) { onThumbNailPhotoFileName -= value; if (onThumbNailPhotoFileName == null && onThumbNailPhotoFileNameIsRegistered) { Members.ThumbNailPhotoFileName.Events.OnChange -= onThumbNailPhotoFileNameProxy; onThumbNailPhotoFileNameIsRegistered = false; } } } } private static void onThumbNailPhotoFileNameProxy(object sender, PropertyEventArgs args) { EventHandler<ProductPhoto, PropertyEventArgs> handler = onThumbNailPhotoFileName; if ((object)handler != null) handler.Invoke((ProductPhoto)sender, args); } #endregion #region OnLargePhoto private static bool onLargePhotoIsRegistered = false; private static EventHandler<ProductPhoto, PropertyEventArgs> onLargePhoto; public static event EventHandler<ProductPhoto, PropertyEventArgs> OnLargePhoto { add { lock (typeof(OnPropertyChange)) { if (!onLargePhotoIsRegistered) { Members.LargePhoto.Events.OnChange -= onLargePhotoProxy; Members.LargePhoto.Events.OnChange += onLargePhotoProxy; onLargePhotoIsRegistered = true; } onLargePhoto += value; } } remove { lock (typeof(OnPropertyChange)) { onLargePhoto -= value; if (onLargePhoto == null && onLargePhotoIsRegistered) { Members.LargePhoto.Events.OnChange -= onLargePhotoProxy; onLargePhotoIsRegistered = false; } } } } private static void onLargePhotoProxy(object sender, PropertyEventArgs args) { EventHandler<ProductPhoto, PropertyEventArgs> handler = onLargePhoto; if ((object)handler != null) handler.Invoke((ProductPhoto)sender, args); } #endregion #region OnLargePhotoFileName private static bool onLargePhotoFileNameIsRegistered = false; private static EventHandler<ProductPhoto, PropertyEventArgs> onLargePhotoFileName; public static event EventHandler<ProductPhoto, PropertyEventArgs> OnLargePhotoFileName { add { lock (typeof(OnPropertyChange)) { if (!onLargePhotoFileNameIsRegistered) { Members.LargePhotoFileName.Events.OnChange -= onLargePhotoFileNameProxy; Members.LargePhotoFileName.Events.OnChange += onLargePhotoFileNameProxy; onLargePhotoFileNameIsRegistered = true; } onLargePhotoFileName += value; } } remove { lock (typeof(OnPropertyChange)) { onLargePhotoFileName -= value; if (onLargePhotoFileName == null && onLargePhotoFileNameIsRegistered) { Members.LargePhotoFileName.Events.OnChange -= onLargePhotoFileNameProxy; onLargePhotoFileNameIsRegistered = false; } } } } private static void onLargePhotoFileNameProxy(object sender, PropertyEventArgs args) { EventHandler<ProductPhoto, PropertyEventArgs> handler = onLargePhotoFileName; if ((object)handler != null) handler.Invoke((ProductPhoto)sender, args); } #endregion #region OnModifiedDate private static bool onModifiedDateIsRegistered = false; private static EventHandler<ProductPhoto, PropertyEventArgs> onModifiedDate; public static event EventHandler<ProductPhoto, PropertyEventArgs> OnModifiedDate { add { lock (typeof(OnPropertyChange)) { if (!onModifiedDateIsRegistered) { Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy; Members.ModifiedDate.Events.OnChange += onModifiedDateProxy; onModifiedDateIsRegistered = true; } onModifiedDate += value; } } remove { lock (typeof(OnPropertyChange)) { onModifiedDate -= value; if (onModifiedDate == null && onModifiedDateIsRegistered) { Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy; onModifiedDateIsRegistered = false; } } } } private static void onModifiedDateProxy(object sender, PropertyEventArgs args) { EventHandler<ProductPhoto, PropertyEventArgs> handler = onModifiedDate; if ((object)handler != null) handler.Invoke((ProductPhoto)sender, args); } #endregion #region OnUid private static bool onUidIsRegistered = false; private static EventHandler<ProductPhoto, PropertyEventArgs> onUid; public static event EventHandler<ProductPhoto, PropertyEventArgs> OnUid { add { lock (typeof(OnPropertyChange)) { if (!onUidIsRegistered) { Members.Uid.Events.OnChange -= onUidProxy; Members.Uid.Events.OnChange += onUidProxy; onUidIsRegistered = true; } onUid += value; } } remove { lock (typeof(OnPropertyChange)) { onUid -= value; if (onUid == null && onUidIsRegistered) { Members.Uid.Events.OnChange -= onUidProxy; onUidIsRegistered = false; } } } } private static void onUidProxy(object sender, PropertyEventArgs args) { EventHandler<ProductPhoto, PropertyEventArgs> handler = onUid; if ((object)handler != null) handler.Invoke((ProductPhoto)sender, args); } #endregion } #endregion } #endregion #region IProductPhotoOriginalData public IProductPhotoOriginalData OriginalVersion { get { return this; } } #region Members for interface IProductPhoto string IProductPhotoOriginalData.ThumbNailPhoto { get { return OriginalData.ThumbNailPhoto; } } string IProductPhotoOriginalData.ThumbNailPhotoFileName { get { return OriginalData.ThumbNailPhotoFileName; } } string IProductPhotoOriginalData.LargePhoto { get { return OriginalData.LargePhoto; } } string IProductPhotoOriginalData.LargePhotoFileName { get { return OriginalData.LargePhotoFileName; } } #endregion #region Members for interface ISchemaBase ISchemaBaseOriginalData ISchemaBase.OriginalVersion { get { return this; } } System.DateTime ISchemaBaseOriginalData.ModifiedDate { get { return OriginalData.ModifiedDate; } } #endregion #region Members for interface INeo4jBase INeo4jBaseOriginalData INeo4jBase.OriginalVersion { get { return this; } } string INeo4jBaseOriginalData.Uid { get { return OriginalData.Uid; } } #endregion #endregion } }
using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Threading.Tasks; using FluentAssertions; using JsonApiDotNetCore.Serialization.Objects; using Microsoft.EntityFrameworkCore; using TestBuildingBlocks; using Xunit; namespace JsonApiDotNetCoreTests.IntegrationTests.IdObfuscation { public sealed class IdObfuscationTests : IClassFixture<IntegrationTestContext<TestableStartup<ObfuscationDbContext>, ObfuscationDbContext>> { private readonly IntegrationTestContext<TestableStartup<ObfuscationDbContext>, ObfuscationDbContext> _testContext; private readonly ObfuscationFakers _fakers = new(); public IdObfuscationTests(IntegrationTestContext<TestableStartup<ObfuscationDbContext>, ObfuscationDbContext> testContext) { _testContext = testContext; testContext.UseController<BankAccountsController>(); testContext.UseController<DebitCardsController>(); } [Fact] public async Task Can_filter_equality_in_primary_resources() { // Arrange List<BankAccount> accounts = _fakers.BankAccount.Generate(2); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<BankAccount>(); dbContext.BankAccounts.AddRange(accounts); await dbContext.SaveChangesAsync(); }); string route = $"/bankAccounts?filter=equals(id,'{accounts[1].StringId}')"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Id.Should().Be(accounts[1].StringId); } [Fact] public async Task Can_filter_any_in_primary_resources() { // Arrange List<BankAccount> accounts = _fakers.BankAccount.Generate(2); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<BankAccount>(); dbContext.BankAccounts.AddRange(accounts); await dbContext.SaveChangesAsync(); }); var codec = new HexadecimalCodec(); string route = $"/bankAccounts?filter=any(id,'{accounts[1].StringId}','{codec.Encode(Unknown.TypedId.Int32)}')"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Id.Should().Be(accounts[1].StringId); } [Fact] public async Task Cannot_get_primary_resource_for_invalid_ID() { // Arrange const string route = "/bankAccounts/not-a-hex-value"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.BadRequest); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.BadRequest); error.Title.Should().Be("Invalid ID value."); error.Detail.Should().Be("The value 'not-a-hex-value' is not a valid hexadecimal value."); } [Fact] public async Task Can_get_primary_resource_by_ID() { // Arrange DebitCard card = _fakers.DebitCard.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.DebitCards.Add(card); await dbContext.SaveChangesAsync(); }); string route = $"/debitCards/{card.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Data.SingleValue.Id.Should().Be(card.StringId); } [Fact] public async Task Can_get_secondary_resources() { // Arrange BankAccount account = _fakers.BankAccount.Generate(); account.Cards = _fakers.DebitCard.Generate(2); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.BankAccounts.Add(account); await dbContext.SaveChangesAsync(); }); string route = $"/bankAccounts/{account.StringId}/cards"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(2); responseDocument.Data.ManyValue[0].Id.Should().Be(account.Cards[0].StringId); responseDocument.Data.ManyValue[1].Id.Should().Be(account.Cards[1].StringId); } [Fact] public async Task Can_include_resource_with_sparse_fieldset() { // Arrange BankAccount account = _fakers.BankAccount.Generate(); account.Cards = _fakers.DebitCard.Generate(1); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.BankAccounts.Add(account); await dbContext.SaveChangesAsync(); }); string route = $"/bankAccounts/{account.StringId}?include=cards&fields[debitCards]=ownerName"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Data.SingleValue.Id.Should().Be(account.StringId); responseDocument.Included.Should().HaveCount(1); responseDocument.Included[0].Id.Should().Be(account.Cards[0].StringId); responseDocument.Included[0].Attributes.Should().HaveCount(1); responseDocument.Included[0].Relationships.Should().BeNull(); } [Fact] public async Task Can_get_relationship() { // Arrange BankAccount account = _fakers.BankAccount.Generate(); account.Cards = _fakers.DebitCard.Generate(1); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.BankAccounts.Add(account); await dbContext.SaveChangesAsync(); }); string route = $"/bankAccounts/{account.StringId}/relationships/cards"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Id.Should().Be(account.Cards[0].StringId); } [Fact] public async Task Can_create_resource_with_relationship() { // Arrange BankAccount existingAccount = _fakers.BankAccount.Generate(); DebitCard newCard = _fakers.DebitCard.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.BankAccounts.Add(existingAccount); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "debitCards", attributes = new { ownerName = newCard.OwnerName, pinCode = newCard.PinCode }, relationships = new { account = new { data = new { type = "bankAccounts", id = existingAccount.StringId } } } } }; const string route = "/debitCards"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Created); responseDocument.Data.SingleValue.Attributes["ownerName"].Should().Be(newCard.OwnerName); responseDocument.Data.SingleValue.Attributes["pinCode"].Should().Be(newCard.PinCode); var codec = new HexadecimalCodec(); int newCardId = codec.Decode(responseDocument.Data.SingleValue.Id); await _testContext.RunOnDatabaseAsync(async dbContext => { DebitCard cardInDatabase = await dbContext.DebitCards.Include(card => card.Account).FirstWithIdAsync(newCardId); cardInDatabase.OwnerName.Should().Be(newCard.OwnerName); cardInDatabase.PinCode.Should().Be(newCard.PinCode); cardInDatabase.Account.Should().NotBeNull(); cardInDatabase.Account.Id.Should().Be(existingAccount.Id); cardInDatabase.Account.StringId.Should().Be(existingAccount.StringId); }); } [Fact] public async Task Can_update_resource_with_relationship() { // Arrange BankAccount existingAccount = _fakers.BankAccount.Generate(); existingAccount.Cards = _fakers.DebitCard.Generate(1); DebitCard existingCard = _fakers.DebitCard.Generate(); string newIban = _fakers.BankAccount.Generate().Iban; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.AddInRange(existingAccount, existingCard); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "bankAccounts", id = existingAccount.StringId, attributes = new { iban = newIban }, relationships = new { cards = new { data = new[] { new { type = "debitCards", id = existingCard.StringId } } } } } }; string route = $"/bankAccounts/{existingAccount.StringId}"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { BankAccount accountInDatabase = await dbContext.BankAccounts.Include(account => account.Cards).FirstWithIdAsync(existingAccount.Id); accountInDatabase.Iban.Should().Be(newIban); accountInDatabase.Cards.Should().HaveCount(1); accountInDatabase.Cards[0].Id.Should().Be(existingCard.Id); accountInDatabase.Cards[0].StringId.Should().Be(existingCard.StringId); }); } [Fact] public async Task Can_add_to_ToMany_relationship() { // Arrange BankAccount existingAccount = _fakers.BankAccount.Generate(); existingAccount.Cards = _fakers.DebitCard.Generate(1); DebitCard existingDebitCard = _fakers.DebitCard.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.AddInRange(existingAccount, existingDebitCard); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new[] { new { type = "debitCards", id = existingDebitCard.StringId } } }; string route = $"/bankAccounts/{existingAccount.StringId}/relationships/cards"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { BankAccount accountInDatabase = await dbContext.BankAccounts.Include(account => account.Cards).FirstWithIdAsync(existingAccount.Id); accountInDatabase.Cards.Should().HaveCount(2); }); } [Fact] public async Task Can_remove_from_ToMany_relationship() { // Arrange BankAccount existingAccount = _fakers.BankAccount.Generate(); existingAccount.Cards = _fakers.DebitCard.Generate(2); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.BankAccounts.Add(existingAccount); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new[] { new { type = "debitCards", id = existingAccount.Cards[0].StringId } } }; string route = $"/bankAccounts/{existingAccount.StringId}/relationships/cards"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { BankAccount accountInDatabase = await dbContext.BankAccounts.Include(account => account.Cards).FirstWithIdAsync(existingAccount.Id); accountInDatabase.Cards.Should().HaveCount(1); }); } [Fact] public async Task Can_delete_resource() { // Arrange BankAccount existingAccount = _fakers.BankAccount.Generate(); existingAccount.Cards = _fakers.DebitCard.Generate(1); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.BankAccounts.Add(existingAccount); await dbContext.SaveChangesAsync(); }); string route = $"/bankAccounts/{existingAccount.StringId}"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { BankAccount accountInDatabase = await dbContext.BankAccounts.Include(account => account.Cards).FirstWithIdOrDefaultAsync(existingAccount.Id); accountInDatabase.Should().BeNull(); }); } [Fact] public async Task Cannot_delete_unknown_resource() { // Arrange var codec = new HexadecimalCodec(); string stringId = codec.Encode(Unknown.TypedId.Int32); string route = $"/bankAccounts/{stringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteDeleteAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("The requested resource does not exist."); error.Detail.Should().Be($"Resource of type 'bankAccounts' with ID '{stringId}' does not exist."); } } }
using System.Diagnostics; using System.Text; using System.Text.Json.Serialization; namespace Meziantou.Framework; [JsonConverter(typeof(FullPathJsonConverter))] public readonly struct FullPath : IEquatable<FullPath>, IComparable<FullPath> { internal readonly string? _value; private FullPath(string path) { // The checks are already performed in the static methods // No need to check if the path is null or absolute here Debug.Assert(path != null); #if NETCOREAPP3_1_OR_GREATER Debug.Assert(Path.IsPathFullyQualified(path)); #elif NETSTANDARD2_0 || NET472 #else #error Platform not supported #endif Debug.Assert(Path.GetFullPath(path) == path); _value = path; } public static FullPath Empty => default; [MemberNotNullWhen(returnValue: false, nameof(_value))] public bool IsEmpty => _value is null; public string Value => _value ?? ""; public static implicit operator string(FullPath fullPath) => fullPath.ToString(); public static bool operator ==(FullPath path1, FullPath path2) => path1.Equals(path2); public static bool operator !=(FullPath path1, FullPath path2) => !(path1 == path2); public static bool operator <(FullPath path1, FullPath path2) => path1.CompareTo(path2) < 0; public static bool operator >(FullPath path1, FullPath path2) => path1.CompareTo(path2) > 0; public static bool operator <=(FullPath path1, FullPath path2) => path1.CompareTo(path2) <= 0; public static bool operator >=(FullPath path1, FullPath path2) => path1.CompareTo(path2) >= 0; public static FullPath operator /(FullPath rootPath, string relativePath) => Combine(rootPath, relativePath); public FullPath Parent { get { var result = Path.GetDirectoryName(_value); if (result is null) return Empty; return new FullPath(result); } } public string? Name => Path.GetFileName(_value); public string? NameWithoutExtension => Path.GetFileNameWithoutExtension(_value); public string? Extension => Path.GetExtension(_value); public int CompareTo(FullPath other) => FullPathComparer.Default.Compare(this, other); public int CompareTo(FullPath other, bool ignoreCase) => FullPathComparer.GetComparer(ignoreCase).Compare(this, other); public override bool Equals(object? obj) => obj is FullPath path && Equals(path); public bool Equals(FullPath other) => FullPathComparer.Default.Equals(this, other); public bool Equals(FullPath other, bool ignoreCase) => FullPathComparer.GetComparer(ignoreCase).Equals(this, other); public override int GetHashCode() => FullPathComparer.Default.GetHashCode(this); public int GetHashCode(bool ignoreCase) => FullPathComparer.GetComparer(ignoreCase).GetHashCode(this); public override string ToString() => Value; public string MakePathRelativeTo(FullPath rootPath) { if (IsEmpty) throw new InvalidOperationException("The path is empty"); if (rootPath.IsEmpty) return _value; if (rootPath == this) return "."; return PathDifference(rootPath._value + Path.DirectorySeparatorChar, _value, compareCase: FullPathComparer.Default.IsCaseSensitive); } private static string PathDifference(string path1, string path2, bool compareCase) { var directorySeparator = Path.DirectorySeparatorChar; int i; var si = -1; for (i = 0; (i < path1.Length) && (i < path2.Length); ++i) { if ((path1[i] != path2[i]) && (compareCase || (char.ToUpperInvariant(path1[i]) != char.ToUpperInvariant(path2[i])))) break; if (path1[i] == directorySeparator) { si = i; } } if (i == 0) return path2; if ((i == path1.Length) && (i == path2.Length)) return string.Empty; var relPath = new StringBuilder(); // Walk down several dirs for (; i < path1.Length; ++i) { if (path1[i] == directorySeparator) { relPath.Append(".."); relPath.Append(directorySeparator); } } // Same path except that path1 ended with a file name and path2 didn't if (relPath.Length == 0 && path2.Length - 1 == si) return "." + directorySeparator; // Truncate the file name #if NETSTANDARD2_0 || NET472 return relPath.Append(path2.AsSpan(si + 1).ToString()).ToString(); #elif NETCOREAPP3_1_OR_GREATER return relPath.Append(path2.AsSpan(si + 1)).ToString(); #else #error Platform not supported #endif } public bool IsChildOf(FullPath rootPath) { if (IsEmpty) throw new InvalidOperationException("Path is empty"); if (rootPath.IsEmpty) throw new ArgumentException("Root path is empty", nameof(rootPath)); if (_value.Length <= rootPath._value.Length) return false; if (!_value.StartsWith(rootPath._value, StringComparison.Ordinal)) return false; // rootpath: /a/b // current: /a/b/c => true // current: /a/b/ => false // current: /a/bc => false if (_value[rootPath._value.Length] == Path.DirectorySeparatorChar && _value.Length > rootPath._value.Length + 1) return true; return false; } public void CreateParentDirectory() { if (IsEmpty) return; var parent = Path.GetDirectoryName(Value); if (parent != null) { Directory.CreateDirectory(parent); } } public static FullPath GetTempPath() => FromPath(Path.GetTempPath()); public static FullPath GetTempFileName() => FromPath(Path.GetTempFileName()); public static FullPath GetFolderPath(Environment.SpecialFolder folder) => FromPath(Environment.GetFolderPath(folder)); public static FullPath CurrentDirectory() => FromPath(Environment.CurrentDirectory); public static FullPath FromPath(string path) { if (PathInternal.IsExtended(path)) { path = path[4..]; } var fullPath = Path.GetFullPath(path); var fullPathWithoutTrailingDirectorySeparator = TrimEndingDirectorySeparator(fullPath); if (string.IsNullOrEmpty(fullPathWithoutTrailingDirectorySeparator)) return Empty; return new FullPath(fullPathWithoutTrailingDirectorySeparator); } private static string TrimEndingDirectorySeparator(string path) { #if NETCOREAPP3_1_OR_GREATER return Path.TrimEndingDirectorySeparator(path); #elif NETSTANDARD2_0 || NET472 if (!path.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal) && !path.EndsWith(Path.AltDirectorySeparatorChar.ToString(), StringComparison.Ordinal)) return path; if (path.StartsWith("\\", StringComparison.Ordinal)) throw new ArgumentException("UNC paths are not supported", nameof(path)); return path[0..^1]; #else #error Platform not supported #endif } public static FullPath Combine(string rootPath, string relativePath) => FromPath(Path.Combine(rootPath, relativePath)); public static FullPath Combine(string rootPath, string path1, string path2) => FromPath(Path.Combine(rootPath, path1, path2)); public static FullPath Combine(string rootPath, string path1, string path2, string path3) => FromPath(Path.Combine(rootPath, path1, path2, path3)); public static FullPath Combine(params string[] paths) => FromPath(Path.Combine(paths)); public static FullPath Combine(FullPath rootPath, string relativePath) { if (rootPath.IsEmpty) return FromPath(relativePath); return FromPath(Path.Combine(rootPath._value, relativePath)); } public static FullPath Combine(FullPath rootPath, string path1, string path2) { if (rootPath.IsEmpty) return FromPath(Path.Combine(path1, path2)); return FromPath(Path.Combine(rootPath._value, path1, path2)); } public static FullPath Combine(FullPath rootPath, params string[] paths) { if (rootPath.IsEmpty) return FromPath(Path.Combine(paths)); return FromPath(Path.Combine(rootPath._value, Path.Combine(paths))); } public static FullPath Combine(FullPath rootPath, string path1, string path2, string path3) { if (rootPath.IsEmpty) return FromPath(Path.Combine(path1, path2, path3)); return FromPath(Path.Combine(rootPath._value, path1, path2, path3)); } public static FullPath FromFileSystemInfo(FileSystemInfo? fsi) { if (fsi == null) return Empty; return FromPath(fsi.FullName); } public bool IsSymbolicLink() { if (IsEmpty) return false; return Symlink.IsSymbolicLink(_value); } public bool TryGetSymbolicLinkTarget([NotNullWhen(true)] out FullPath? result) { if (!IsEmpty && Symlink.TryGetSymLinkTarget(_value, out var path)) { result = FromPath(path); return true; } result = null; return false; } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Remoting.Contexts; using System.Threading; using System.Threading.Tasks; using SteamKit2; using SteamTrade.Exceptions; using SteamTrade.TradeWebAPI; namespace SteamTrade { /// <summary> /// Class which represents a trade. /// Note that the logic that Steam uses can be seen from their web-client source-code: http://steamcommunity-a.akamaihd.net/public/javascript/economy_trade.js /// </summary> public partial class LiveTrade { #region Static Public data public static Schema CurrentSchema = null; public enum TradeStatusType { OnGoing = 0, CompletedSuccessfully = 1, Empty = 2, TradeCancelled = 3, SessionExpired = 4, TradeFailed = 5, PendingConfirmation = 6 } public string GetTradeStatusErrorString(TradeStatusType tradeStatusType) { switch(tradeStatusType) { case TradeStatusType.OnGoing: return "is still going on"; case TradeStatusType.CompletedSuccessfully: return "completed successfully"; case TradeStatusType.Empty: return "completed empty - no items were exchanged"; case TradeStatusType.TradeCancelled: return "was cancelled " + (tradeCancelledByBot ? "by bot" : "by other user"); case TradeStatusType.SessionExpired: return String.Format("expired because {0} timed out", (otherUserTimingOut ? "other user" : "bot")); case TradeStatusType.TradeFailed: return "failed unexpectedly"; case TradeStatusType.PendingConfirmation: return "completed - pending confirmation"; default: return "STATUS IS UNKNOWN - THIS SHOULD NEVER HAPPEN!"; } } #endregion private const int WEB_REQUEST_MAX_RETRIES = 3; private const int WEB_REQUEST_TIME_BETWEEN_RETRIES_MS = 600; // list to store all trade events already processed private readonly List<TradeEvent> eventList; // current bot's sid private readonly SteamID mySteamId; private readonly Dictionary<int, TradeUserAssets> myOfferedItemsLocalCopy; private readonly TradeSession session; private readonly Task<Inventory> myInventoryTask; private readonly Task<Inventory> otherInventoryTask; private List<TradeUserAssets> myOfferedItems; private List<TradeUserAssets> otherOfferedItems; private bool otherUserTimingOut; private bool tradeCancelledByBot; private int numUnknownStatusUpdates; internal LiveTrade(SteamID me, SteamID other, SteamWeb steamWeb, Task<Inventory> myInventoryTask, Task<Inventory> otherInventoryTask) { TradeStarted = false; OtherIsReady = false; MeIsReady = false; mySteamId = me; OtherSID = other; session = new TradeSession(other, steamWeb); this.eventList = new List<TradeEvent>(); myOfferedItemsLocalCopy = new Dictionary<int, TradeUserAssets>(); otherOfferedItems = new List<TradeUserAssets>(); myOfferedItems = new List<TradeUserAssets>(); this.otherInventoryTask = otherInventoryTask; this.myInventoryTask = myInventoryTask; } #region Public Properties /// <summary>Gets the other user's steam ID.</summary> public SteamID OtherSID { get; private set; } /// <summary> /// Gets the bot's Steam ID. /// </summary> public SteamID MySteamId { get { return mySteamId; } } /// <summary> /// Gets the inventory of the other user. /// </summary> public Inventory OtherInventory { get { if(otherInventoryTask == null) return null; otherInventoryTask.Wait(); return otherInventoryTask.Result; } } /// <summary> /// Gets the private inventory of the other user. /// </summary> public ForeignInventory OtherPrivateInventory { get; private set; } /// <summary> /// Gets the inventory of the bot. /// </summary> public Inventory MyInventory { get { if(myInventoryTask == null) return null; myInventoryTask.Wait(); return myInventoryTask.Result; } } /// <summary> /// Gets the items the user has offered, by itemid. /// </summary> /// <value> /// The other offered items. /// </value> public IEnumerable<TradeUserAssets> OtherOfferedItems { get { return otherOfferedItems; } } /// <summary> /// Gets the items the bot has offered, by itemid. /// </summary> /// <value> /// The bot offered items. /// </value> public IEnumerable<TradeUserAssets> MyOfferedItems { get { return myOfferedItems; } } /// <summary> /// Gets a value indicating if the other user is ready to trade. /// </summary> public bool OtherIsReady { get; private set; } /// <summary> /// Gets a value indicating if the bot is ready to trade. /// </summary> public bool MeIsReady { get; private set; } /// <summary> /// Gets a value indicating if a trade has started. /// </summary> public bool TradeStarted { get; private set; } /// <summary> /// Gets a value indicating if the remote trading partner cancelled the trade. /// </summary> public bool OtherUserCancelled { get; private set; } /// <summary> /// Gets a value indicating whether the trade completed normally. This /// is independent of other flags. /// </summary> public bool HasTradeCompletedOk { get; private set; } /// <summary> /// Gets a value indicating whether the trade completed awaiting email confirmation. This /// is independent of other flags. /// </summary> public bool IsTradeAwaitingConfirmation { get; private set; } /// <summary> /// Gets a value indicating whether the trade has finished (regardless of the cause, eg. success, cancellation, error, etc) /// </summary> public bool HasTradeEnded { get { return OtherUserCancelled || HasTradeCompletedOk || IsTradeAwaitingConfirmation || tradeCancelledByBot; } } /// <summary> /// Gets a value indicating if the remote trading partner accepted the trade. /// </summary> public bool OtherUserAccepted { get; private set; } #endregion #region Public Events public delegate void CloseHandler(); public delegate void CompleteHandler(); public delegate void WaitingForEmailHandler(); public delegate void ErrorHandler(string errorMessage, string errorstatus); public delegate void StatusErrorHandler(TradeStatusType statusType); public delegate void TimeoutHandler(); public delegate void SuccessfulInit(); public delegate void UserAddItemHandler(Schema.Item schemaItem, Inventory.Item inventoryItem); public delegate void UserRemoveItemHandler(Schema.Item schemaItem, Inventory.Item inventoryItem); public delegate void MessageHandler(string msg); public delegate void UserSetReadyStateHandler(bool ready); public delegate void UserAcceptHandler(); /// <summary> /// When the trade closes, this is called. It doesn't matter /// whether or not it was a timeout or an error, this is called /// to close the trade. /// </summary> public event CloseHandler OnClose; /// <summary> /// Called when the trade completes successfully. /// </summary> public event CompleteHandler OnSuccess; /// <summary> /// Called when the trade ends awaiting email confirmation /// </summary> public event WaitingForEmailHandler OnAwaitingConfirmation; /// <summary> /// This is for handling errors that may occur, like inventories /// not loading. /// </summary> public event ErrorHandler OnError; /// <summary> /// Specifically for trade_status errors. /// </summary> public event StatusErrorHandler OnStatusError; /// <summary> /// This occurs after Inventories have been loaded. /// </summary> public event SuccessfulInit OnAfterInit; /// <summary> /// This occurs when the other user adds an item to the trade. /// </summary> public event UserAddItemHandler OnUserAddItem; /// <summary> /// This occurs when the other user removes an item from the /// trade. /// </summary> public event UserAddItemHandler OnUserRemoveItem; /// <summary> /// This occurs when the user sends a message to the bot over /// trade. /// </summary> public event MessageHandler OnMessage; /// <summary> /// This occurs when the user sets their ready state to either /// true or false. /// </summary> public event UserSetReadyStateHandler OnUserSetReady; /// <summary> /// This occurs when the user accepts the trade. /// </summary> public event UserAcceptHandler OnUserAccept; #endregion /// <summary> /// Cancel the trade. This calls the OnClose handler, as well. /// </summary> public bool CancelTrade() { tradeCancelledByBot = true; return RetryWebRequest(session.CancelTradeWebCmd); } /// <summary> /// Adds a specified TF2 item by its itemid. /// If the item is not a TF2 item, use the AddItem(ulong itemid, int appid, long contextid) overload /// </summary> /// <returns><c>false</c> if the tf2 item was not found in the inventory.</returns> public bool AddItem(ulong itemid) { if(MyInventory.GetItem(itemid) == null) { return false; } else { return AddItem(new TradeUserAssets(440, 2, itemid)); } } public bool AddItem(ulong itemid, int appid, long contextid) { return AddItem(new TradeUserAssets(appid, contextid, itemid)); } public bool AddItem(TradeUserAssets item) { var slot = NextTradeSlot(); bool success = RetryWebRequest(() => session.AddItemWebCmd(item.assetid, slot, item.appid, item.contextid)); if(success) myOfferedItemsLocalCopy[slot] = item; return success; } /// <summary> /// Adds a single item by its Defindex. /// </summary> /// <returns> /// <c>true</c> if an item was found with the corresponding /// defindex, <c>false</c> otherwise. /// </returns> public bool AddItemByDefindex(int defindex) { List<Inventory.Item> items = MyInventory.GetItemsByDefindex(defindex); foreach(Inventory.Item item in items) { if(item != null && myOfferedItemsLocalCopy.Values.All(o => o.assetid != item.Id) && !item.IsNotTradeable) { return AddItem(item.Id); } } return false; } /// <summary> /// Adds an entire set of items by Defindex to each successive /// slot in the trade. /// </summary> /// <param name="defindex">The defindex. (ex. 5022 = crates)</param> /// <param name="numToAdd">The upper limit on amount of items to add. <c>0</c> to add all items.</param> /// <returns>Number of items added.</returns> public uint AddAllItemsByDefindex(int defindex, uint numToAdd = 0) { List<Inventory.Item> items = MyInventory.GetItemsByDefindex(defindex); uint added = 0; foreach(Inventory.Item item in items) { if(item != null && myOfferedItemsLocalCopy.Values.All(o => o.assetid != item.Id) && !item.IsNotTradeable) { bool success = AddItem(item.Id); if(success) added++; if(numToAdd > 0 && added >= numToAdd) return added; } } return added; } public bool RemoveItem(TradeUserAssets item) { return RemoveItem(item.assetid, item.appid, item.contextid); } /// <summary> /// Removes an item by its itemid. /// </summary> /// <returns><c>false</c> the item was not found in the trade.</returns> public bool RemoveItem(ulong itemid, int appid = 440, long contextid = 2) { int? slot = GetItemSlot(itemid); if(!slot.HasValue) return false; bool success = RetryWebRequest(() => session.RemoveItemWebCmd(itemid, slot.Value, appid, contextid)); if(success) myOfferedItemsLocalCopy.Remove(slot.Value); return success; } /// <summary> /// Removes an item with the given Defindex from the trade. /// </summary> /// <returns> /// Returns <c>true</c> if it found a corresponding item; <c>false</c> otherwise. /// </returns> public bool RemoveItemByDefindex(int defindex) { foreach(TradeUserAssets asset in myOfferedItemsLocalCopy.Values) { Inventory.Item item = MyInventory.GetItem(asset.assetid); if(item != null && item.Defindex == defindex) { return RemoveItem(item.Id); } } return false; } /// <summary> /// Removes an entire set of items by Defindex. /// </summary> /// <param name="defindex">The defindex. (ex. 5022 = crates)</param> /// <param name="numToRemove">The upper limit on amount of items to remove. <c>0</c> to remove all items.</param> /// <returns>Number of items removed.</returns> public uint RemoveAllItemsByDefindex(int defindex, uint numToRemove = 0) { List<Inventory.Item> items = MyInventory.GetItemsByDefindex(defindex); uint removed = 0; foreach(Inventory.Item item in items) { if(item != null && myOfferedItemsLocalCopy.Values.Any(o => o.assetid == item.Id)) { bool success = RemoveItem(item.Id); if(success) removed++; if(numToRemove > 0 && removed >= numToRemove) return removed; } } return removed; } /// <summary> /// Removes all offered items from the trade. /// </summary> /// <returns>Number of items removed.</returns> public uint RemoveAllItems() { uint numRemoved = 0; foreach(TradeUserAssets asset in myOfferedItemsLocalCopy.Values.ToList()) { Inventory.Item item = MyInventory.GetItem(asset.assetid); if(item != null) { bool wasRemoved = RemoveItem(item.Id); if(wasRemoved) numRemoved++; } } return numRemoved; } /// <summary> /// Sends a message to the user over the trade chat. /// </summary> public bool SendMessage(string msg) { return RetryWebRequest(() => session.SendMessageWebCmd(msg)); } /// <summary> /// Sets the bot to a ready status. /// </summary> public bool SetReady(bool ready) { //If the bot calls SetReady(false) and the call fails, we still want meIsReady to be //set to false. Otherwise, if the call to SetReady() was a result of a callback //from Trade.Poll() inside of the OnTradeAccept() handler, the OnTradeAccept() //handler might think the bot is ready, when really it's not! if(!ready) MeIsReady = false; ValidateLocalTradeItems(); return RetryWebRequest(() => session.SetReadyWebCmd(ready)); } /// <summary> /// Accepts the trade from the user. Returns whether the acceptance went through or not /// </summary> public bool AcceptTrade() { if(!MeIsReady) return false; ValidateLocalTradeItems(); return RetryWebRequest(session.AcceptTradeWebCmd); } /// <summary> /// Calls the given function multiple times, until we get a non-null/non-false/non-zero result, or we've made at least /// WEB_REQUEST_MAX_RETRIES attempts (with WEB_REQUEST_TIME_BETWEEN_RETRIES_MS between attempts) /// </summary> /// <returns>The result of the function if it succeeded, or default(T) (null/false/0) otherwise</returns> private T RetryWebRequest<T>(Func<T> webEvent) { for(int i = 0; i < WEB_REQUEST_MAX_RETRIES; i++) { //Don't make any more requests if the trade has ended! if (HasTradeEnded) return default(T); try { T result = webEvent(); // if the web request returned some error. if(!EqualityComparer<T>.Default.Equals(result, default(T))) return result; } catch(Exception ex) { // TODO: log to SteamBot.Log but... see issue #394 // realistically we should not throw anymore Console.WriteLine(ex); } if(i != WEB_REQUEST_MAX_RETRIES) { //This will cause the bot to stop responding while we wait between web requests. ...Is this really what we want? Thread.Sleep(WEB_REQUEST_TIME_BETWEEN_RETRIES_MS); } } return default(T); } /// <summary> /// This updates the trade. This is called at an interval of a /// default of 800ms, not including the execution time of the /// method itself. /// </summary> /// <returns><c>true</c> if the other trade partner performed an action; otherwise <c>false</c>.</returns> public bool Poll() { if(!TradeStarted) { TradeStarted = true; // since there is no feedback to let us know that the trade // is fully initialized we assume that it is when we start polling. if(OnAfterInit != null) OnAfterInit(); } TradeStatus status = RetryWebRequest(session.GetStatus); if(status == null) return false; TradeStatusType tradeStatusType = (TradeStatusType) status.trade_status; switch (tradeStatusType) { // Nothing happened. i.e. trade hasn't closed yet. case TradeStatusType.OnGoing: return HandleTradeOngoing(status); // Successful trade case TradeStatusType.CompletedSuccessfully: HasTradeCompletedOk = true; return false; // Email/mobile confirmation case TradeStatusType.PendingConfirmation: IsTradeAwaitingConfirmation = true; return false; //On a status of 2, the Steam web code attempts the request two more times case TradeStatusType.Empty: numUnknownStatusUpdates++; if(numUnknownStatusUpdates < 3) { return false; } break; } FireOnStatusErrorEvent(tradeStatusType); OtherUserCancelled = true; return false; } private bool HandleTradeOngoing(TradeStatus status) { bool otherUserDidSomething = false; if (status.newversion) { HandleTradeVersionChange(status); otherUserDidSomething = true; } else if(status.version > session.Version) { // oh crap! we missed a version update abort so we don't get // scammed. if we could get what steam thinks what's in the // trade then this wouldn't be an issue. but we can only get // that when we see newversion == true throw new TradeException("The trade version does not match. Aborting."); } // Update Local Variables if(status.them != null) { OtherIsReady = status.them.ready == 1; MeIsReady = status.me.ready == 1; OtherUserAccepted = status.them.confirmed == 1; //Similar to the logic Steam uses to determine whether or not to show the "waiting" spinner in the trade window otherUserTimingOut = (status.them.connection_pending || status.them.sec_since_touch >= 5); } var events = status.GetAllEvents(); foreach(var tradeEvent in events.OrderBy(o => o.timestamp)) { if(eventList.Contains(tradeEvent)) continue; //add event to processed list, as we are taking care of this event now eventList.Add(tradeEvent); bool isBot = tradeEvent.steamid == MySteamId.ConvertToUInt64().ToString(); // dont process if this is something the bot did if(isBot) continue; otherUserDidSomething = true; switch((TradeEventType) tradeEvent.action) { case TradeEventType.ItemAdded: TradeUserAssets newAsset = new TradeUserAssets(tradeEvent.appid, tradeEvent.contextid, tradeEvent.assetid); if(!otherOfferedItems.Contains(newAsset)) { otherOfferedItems.Add(newAsset); FireOnUserAddItem(newAsset); } break; case TradeEventType.ItemRemoved: TradeUserAssets oldAsset = new TradeUserAssets(tradeEvent.appid, tradeEvent.contextid, tradeEvent.assetid); if(otherOfferedItems.Contains(oldAsset)) { otherOfferedItems.Remove(oldAsset); FireOnUserRemoveItem(oldAsset); } break; case TradeEventType.UserSetReady: OnUserSetReady(true); break; case TradeEventType.UserSetUnReady: OnUserSetReady(false); break; case TradeEventType.UserAccept: OnUserAccept(); break; case TradeEventType.UserChat: OnMessage(tradeEvent.text); break; default: throw new TradeException("Unknown event type: " + tradeEvent.action); } } if(status.logpos != 0) { session.LogPos = status.logpos; } return otherUserDidSomething; } private void HandleTradeVersionChange(TradeStatus status) { //Figure out which items have been added/removed IEnumerable<TradeUserAssets> otherOfferedItemsUpdated = status.them.GetAssets(); IEnumerable<TradeUserAssets> addedItems = otherOfferedItemsUpdated.Except(otherOfferedItems).ToList(); IEnumerable<TradeUserAssets> removedItems = otherOfferedItems.Except(otherOfferedItemsUpdated).ToList(); //Copy over the new items and update the version number otherOfferedItems = status.them.GetAssets().ToList(); myOfferedItems = status.me.GetAssets().ToList(); session.Version = status.version; //Fire the OnUserRemoveItem events foreach (TradeUserAssets asset in removedItems) { FireOnUserRemoveItem(asset); } //Fire the OnUserAddItem events foreach (TradeUserAssets asset in addedItems) { FireOnUserAddItem(asset); } } /// <summary> /// Gets an item from a TradeEvent, and passes it into the UserHandler's implemented OnUserAddItem([...]) routine. /// Passes in null items if something went wrong. /// </summary> private void FireOnUserAddItem(TradeUserAssets asset) { if(MeIsReady) { SetReady(false); } if(OtherInventory != null && !OtherInventory.IsPrivate) { Inventory.Item item = OtherInventory.GetItem(asset.assetid); if(item != null) { Schema.Item schemaItem = CurrentSchema.GetItem(item.Defindex); if(schemaItem == null) { Console.WriteLine("User added an unknown item to the trade."); } OnUserAddItem(schemaItem, item); } else { item = new Inventory.Item { Id = asset.assetid, AppId = asset.appid, ContextId = asset.contextid }; //Console.WriteLine("User added a non TF2 item to the trade."); OnUserAddItem(null, item); } } else { var schemaItem = GetItemFromPrivateBp(asset); if(schemaItem == null) { Console.WriteLine("User added an unknown item to the trade."); } OnUserAddItem(schemaItem, null); // todo: figure out what to send in with Inventory item..... } } private Schema.Item GetItemFromPrivateBp(TradeUserAssets asset) { if (OtherPrivateInventory == null) { dynamic foreignInventory = session.GetForeignInventory(OtherSID, asset.contextid, asset.appid); if (foreignInventory == null || foreignInventory.success == null || !foreignInventory.success.Value) { return null; } OtherPrivateInventory = new ForeignInventory(foreignInventory); } int defindex = OtherPrivateInventory.GetDefIndex(asset.assetid); Schema.Item schemaItem = CurrentSchema.GetItem(defindex); return schemaItem; } /// <summary> /// Gets an item from a TradeEvent, and passes it into the UserHandler's implemented OnUserRemoveItem([...]) routine. /// Passes in null items if something went wrong. /// </summary> /// <returns></returns> private void FireOnUserRemoveItem(TradeUserAssets asset) { if(MeIsReady) { SetReady(false); } if(OtherInventory != null) { Inventory.Item item = OtherInventory.GetItem(asset.assetid); if(item != null) { Schema.Item schemaItem = CurrentSchema.GetItem(item.Defindex); if(schemaItem == null) { // TODO: Add log (counldn't find item in CurrentSchema) } OnUserRemoveItem(schemaItem, item); } else { // TODO: Log this (Couldn't find item in user's inventory can't find item in CurrentSchema item = new Inventory.Item { Id = asset.assetid, AppId = asset.appid, ContextId = asset.contextid }; OnUserRemoveItem(null, item); } } else { var schemaItem = GetItemFromPrivateBp(asset); if(schemaItem == null) { // TODO: Add log (counldn't find item in CurrentSchema) } OnUserRemoveItem(schemaItem, null); } } internal void FireOnSuccessEvent() { var onSuccessEvent = OnSuccess; if(onSuccessEvent != null) onSuccessEvent(); } internal void FireOnAwaitingConfirmation() { var onAwaitingConfirmation = OnAwaitingConfirmation; if (onAwaitingConfirmation != null) onAwaitingConfirmation(); } internal void FireOnCloseEvent() { var onCloseEvent = OnClose; if(onCloseEvent != null) onCloseEvent(); } internal void FireOnErrorEvent(string message) { var onErrorEvent = OnError; if(onErrorEvent != null) onErrorEvent(message, message); } internal void FireOnStatusErrorEvent(TradeStatusType statusType) { var onStatusErrorEvent = OnStatusError; if (onStatusErrorEvent != null) onStatusErrorEvent(statusType); } private int NextTradeSlot() { int slot = 0; while(myOfferedItemsLocalCopy.ContainsKey(slot)) { slot++; } return slot; } private int? GetItemSlot(ulong itemid) { foreach(int slot in myOfferedItemsLocalCopy.Keys) { if(myOfferedItemsLocalCopy[slot].assetid == itemid) { return slot; } } return null; } private void ValidateLocalTradeItems() { if (!myOfferedItemsLocalCopy.Values.OrderBy(o => o).SequenceEqual(MyOfferedItems.OrderBy(o => o))) { throw new TradeException("Error validating local copy of offered items in the trade"); } } } }
using System; using System.IO; using System.Text; using System.Reflection; using System.Globalization; using System.Collections.Generic; using System.Runtime.InteropServices; using Xunit; #pragma warning disable 0067 // Unused events #pragma warning disable 0649 // Uninitialized fields namespace System.Reflection.Tests { public static class TypeTests_PrefixingOnlyAllowedOnGetMember { [Fact] public static void TestGetEvent() { MemberInfo member; Type t = typeof(TestClass).Project(); member = t.GetEvent("My*", BindingFlags.Public | BindingFlags.Instance); Assert.Null(member); } [Fact] public static void TestGetField() { MemberInfo member; Type t = typeof(TestClass).Project(); member = t.GetField("My*", BindingFlags.Public | BindingFlags.Instance); Assert.Null(member); } [Fact] public static void TestGetMethod() { MemberInfo member; Type t = typeof(TestClass).Project(); member = t.GetMethod("My*", BindingFlags.Public | BindingFlags.Instance); Assert.Null(member); } [Fact] public static void TestGetNestedType() { MemberInfo member; Type t = typeof(TestClass).Project(); member = t.GetNestedType("My*", BindingFlags.Public | BindingFlags.Instance); Assert.Null(member); } [Fact] public static void TestGetProperty() { MemberInfo member; Type t = typeof(TestClass).Project(); member = t.GetProperty("My*", BindingFlags.Public | BindingFlags.Instance); Assert.Null(member); } [Fact] public static void TestGetMemberAll() { Type t = typeof(TestClass).Project(); MemberInfo[] members = t.GetMember("My*", BindingFlags.Public | BindingFlags.Instance); Assert.Equal(5, members.Length); } //[Fact] public static void TestGetMemberEvent() { Type t = typeof(TestClass).Project(); MemberInfo[] members = t.GetMember("My*", MemberTypes.Event, BindingFlags.Public | BindingFlags.Instance); Assert.Equal(members.Length, 1); Assert.Equal("MyEvent", members[0].Name); } //[Fact] public static void TestGetMemberField() { Type t = typeof(TestClass).Project(); MemberInfo[] members = t.GetMember("My*", MemberTypes.Field, BindingFlags.Public | BindingFlags.Instance); Assert.Equal(members.Length, 1); Assert.Equal("MyField", members[0].Name); } //[Fact] public static void TestGetMemberMethod() { Type t = typeof(TestClass).Project(); MemberInfo[] members = t.GetMember("My*", MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance); Assert.Equal(members.Length, 1); Assert.Equal("MyMethod", members[0].Name); } //[Fact] public static void TestGetMemberNestedType() { Type t = typeof(TestClass).Project(); MemberInfo[] members = t.GetMember("My*", MemberTypes.NestedType, BindingFlags.Public | BindingFlags.Instance); Assert.Equal(members.Length, 1); Assert.Equal("MyNestedType", members[0].Name); } //[Fact] public static void TestGetMemberProperty() { Type t = typeof(TestClass).Project(); MemberInfo[] members = t.GetMember("My*", MemberTypes.Property, BindingFlags.Public | BindingFlags.Instance); Assert.Equal(members.Length, 1); Assert.Equal("MyProperty", members[0].Name); } private class TestClass { public event Action MyEvent { add { } remove { } } public int MyField; public void MyMethod() { } public class MyNestedType { } public int MyProperty { get; } } } public static class TypeTests_HiddenEvents { [Fact] public static void GetEventHidesEventsBySimpleNameCompare() { Type t = typeof(Derived).Project(); EventInfo[] es = t.GetEvents(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy); Assert.Equal(4, es.Length); int count = 0; foreach (EventInfo e in es) { if (e.DeclaringType.Equals(typeof(Base).Project())) count++; } Assert.Equal(0, count); } private class Base { public event Action MyEvent { add { } remove { } } public static event Action MyStaticEvent { add { } remove { } } public event Action MyEventInstanceStatic { add { } remove { } } public static event Action MyEventStaticInstance { add { } remove { } } } private class Derived : Base { public new event Action<int> MyEvent { add { } remove { } } public new static event Action<double> MyStaticEvent { add { } remove { } } public new static event Action<float> MyEventInstanceStatic { add { } remove { } } public new event Action<long> MyEventStaticInstance { add { } remove { } } } } public static class TypeTests_HiddenFields { [Fact] public static void GetFieldDoesNotHideHiddenFields() { Type t = typeof(Derived).Project(); FieldInfo[] fs = t.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy); Assert.Equal(4, fs.Length); int count = 0; foreach (FieldInfo f in fs) { if (f.DeclaringType.Equals(typeof(Base).Project())) count++; } Assert.Equal(2, count); } private class Base { public int MyField; public static int MyStaticField; } private class Derived : Base { public new int MyField; public new static int MyStaticField; } } public static class TypeTests_HiddenMethods { [Fact] public static void GetMethodDoesNotHideHiddenMethods() { Type t = typeof(Derived).Project(); MethodInfo[] ms = t.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy); int count = 0; foreach (MethodInfo m in ms) { if (m.DeclaringType.Equals(typeof(Base).Project())) count++; } Assert.Equal(2, count); } private class Base { public int MyMethod() { throw null; } public static int MyStaticMethod() { throw null; } } private class Derived : Base { public new int MyMethod() { throw null; } public new static int MyStaticMethod() { throw null; } } } public static class TypeTests_HiddenProperties { [Fact] public static void GetPropertyHidesPropertiesByNameAndSigAndCallingConventionCompare() { Type t = typeof(Derived).Project(); PropertyInfo[] ps = t.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy); List<string> names = new List<string>(); foreach (PropertyInfo p in ps) { if (p.DeclaringType.Equals(typeof(Base).Project())) { names.Add(p.Name); } } names.Sort(); string[] expected = { "Item", nameof(Base.MyInstanceThenStaticProp), nameof(Base.MyStaticThenInstanceProp), nameof(Base.MyStringThenDoubleProp) }; Assert.Equal<string>(expected, names.ToArray()); } private abstract class Base { public int MyProp { get; } // will get hidden public static int MyStaticProp { get; } // will get hidden public int MyInstanceThenStaticProp { get; } // won't get hidden (calling convention mismatch) public static int MyStaticThenInstanceProp { get; } // won't get hidden (calling convention mismatch) public string MyStringThenDoubleProp { get; } // won't get hidden (signature mismatch on return type) public abstract int this[int x] { get; } // won't get hidden (signature mismatch on parameter type) } private abstract class Derived : Base { public new int MyProp { get; } public new static int MyStaticProp { get; } public new static int MyInstanceThenStaticProp { get; } public new int MyStaticThenInstanceProp { get; } public new double MyStringThenDoubleProp { get; } public abstract int this[double x] { get; } } } public static class TypeTests_HiddenTestingOrder { [Fact] public static void HideDetectionHappensBeforeBindingFlagChecks() { // Hiding members suppress results even if the hiding member itself is filtered out by the binding flags. Type derived = typeof(Derived).Project(); EventInfo[] events = derived.GetEvents(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); Assert.Equal(0, events.Length); PropertyInfo[] properties = derived.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); Assert.Equal(0, properties.Length); } [Fact] public static void HideDetectionHappensAfterPrivateInBaseClassChecks() { // Hiding members won't suppress results if the hiding member is filtered out due to being a private member in a base class. Type derived2 = typeof(Derived2).Project(); EventInfo[] events = derived2.GetEvents(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); Assert.Equal(1, events.Length); Assert.Equal(typeof(Base).Project(), events[0].DeclaringType); Assert.Equal(nameof(Base.MyEvent), events[0].Name); PropertyInfo[] properties = derived2.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); Assert.Equal(1, properties.Length); Assert.Equal(typeof(Base).Project(), properties[0].DeclaringType); Assert.Equal(nameof(Base.MyProp), properties[0].Name); } [Fact] public static void HideDetectionHappensBeforeStaticInNonFlattenedHierarchyChecks() { // Hiding members suppress results even if the hiding member is filtered out due to being a static member in a base class (and BindingFlags.FlattenHierarchy not being specified.) // (that check is actually just another bindingflags check.) Type staticDerived2 = typeof(StaticDerived2).Project(); EventInfo[] events = staticDerived2.GetEvents(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); Assert.Equal(0, events.Length); } private abstract class Base { public event Action MyEvent { add { } remove { } } public int MyProp { get; } } private abstract class Derived : Base { private new event Action MyEvent { add { } remove { } } private new int MyProp { get; } } private abstract class Derived2 : Derived { } private class StaticBase { public event Action MyEvent { add { } remove { } } } private class StaticDerived : StaticBase { public new static event Action MyEvent { add { } remove { } } } private class StaticDerived2 : StaticDerived { } } public static class TypeTests_AmbiguityResolution_NoParameterBinding { [Fact] public static void EventsThrowAlways() { BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase; Type t = typeof(Derived).Project(); Assert.Throws<AmbiguousMatchException>(() => t.GetEvent("myevent", bf)); } [Fact] public static void NestedTypesThrowAlways() { BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase; Type t = typeof(Derived).Project(); Assert.Throws<AmbiguousMatchException>(() => t.GetNestedType("myinner", bf)); } [Fact] public static void PropertiesThrowAlways() { BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase; Type t = typeof(Derived).Project(); Assert.Throws<AmbiguousMatchException>(() => t.GetProperty("myprop", bf)); } [Fact] public static void FieldsThrowIfDeclaringTypeIsSame() { BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase; Type t = typeof(Derived).Project(); // Fields return the most derived match. FieldInfo f = t.GetField("myfield", bf); Assert.Equal(f.Name, "MyField"); // Unless two of them are both the most derived match... Assert.Throws<AmbiguousMatchException>(() => t.GetField("myfield2", bf)); } [Fact] public static void MethodsThrowIfDeclaringTypeIsSameAndSigIsDifferent() { BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase; Type t = typeof(Derived).Project(); // Methods return the most derived match, provided all their signatures are the same. MethodInfo m1 = t.GetMethod("mymethod1", bf); Assert.Equal(m1.Name, "MyMethod1"); MethodInfo m2 = t.GetMethod("mymethod2", bf); Assert.Equal(m2.Name, "MyMethod2"); // Unless two of them are both the most derived match... Assert.Throws<AmbiguousMatchException>(() => t.GetMethod("mymethod3", bf)); // or they have different sigs. Assert.Throws<AmbiguousMatchException>(() => t.GetMethod("mymethod4", bf)); } private class Base { public event Action myevent; public int myprop { get; } public int myfield; public void mymethod1(int x) { } public static void mymethod2(int x, int y) { } public void mymethod4(int x) { } } private class Derived : Base { public event Action MyEvent; public class myinner { } public class MyInner { } public int MyProp { get; } public int MyField; public int MyField2; public int myfield2; public void MyMethod1(int x) { } public void MyMethod2(int x, int y) { } public static void mymethod3(int x, int y, double z) { } public void MyMethod3(int x, int y, double z) { } public void mymethod4(string x) { } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using UMA; public class UMACrowdRandomSet : ScriptableObject { public CrowdRaceData data; [System.Serializable] public class CrowdRaceData { public string raceID; public CrowdSlotElement[] slotElements; } [System.Serializable] public class CrowdSlotElement { public CrowdSlotData[] possibleSlots; public string requirement; public string condition; } [System.Serializable] public class CrowdSlotData { public string slotID; public bool useSharedOverlayList; public int overlayListSource; public CrowdOverlayElement[] overlayElements; } [System.Serializable] public class CrowdOverlayElement { public CrowdOverlayData[] possibleOverlays; } public enum OverlayType { Unknown, Random, Texture, Color, Skin, Hair, } public enum ChannelUse { None, Color, InverseColor } [System.Serializable] public class CrowdOverlayData { public string overlayID; public Color maxRGB; public Color minRGB; public bool useSkinColor; public bool useHairColor; public float hairColorMultiplier; public ChannelUse colorChannelUse; public int colorChannel; public OverlayType overlayType; public void UpdateVersion() { if (overlayType == UMACrowdRandomSet.OverlayType.Unknown) { if (useSkinColor) { overlayType = UMACrowdRandomSet.OverlayType.Skin; } else if (useHairColor) { overlayType = UMACrowdRandomSet.OverlayType.Hair; } else { if (minRGB == maxRGB) { if (minRGB == Color.white) { overlayType = UMACrowdRandomSet.OverlayType.Texture; } else { overlayType = UMACrowdRandomSet.OverlayType.Color; } } else { overlayType = UMACrowdRandomSet.OverlayType.Random; } } } } } public static void Apply(UMA.UMAData umaData, CrowdRaceData race, Color skinColor, Color HairColor, Color Shine, HashSet<string> Keywords, SlotLibraryBase slotLibrary, OverlayLibraryBase overlayLibrary) { var slotParts = new HashSet<string>(); umaData.umaRecipe.slotDataList = new SlotData[race.slotElements.Length]; for (int i = 0; i < race.slotElements.Length; i++) { var currentElement = race.slotElements[i]; if (!string.IsNullOrEmpty(currentElement.requirement) && !slotParts.Contains(currentElement.requirement)) continue; if (!string.IsNullOrEmpty(currentElement.condition)) { if (currentElement.condition.StartsWith("!")) { if (Keywords.Contains(currentElement.condition.Substring(1))) continue; } else { if (!Keywords.Contains(currentElement.condition)) continue; } } if (currentElement.possibleSlots.Length == 0) continue; int randomResult = Random.Range(0, currentElement.possibleSlots.Length); var slot = currentElement.possibleSlots[randomResult]; if (string.IsNullOrEmpty(slot.slotID)) continue; slotParts.Add(slot.slotID); SlotData slotData; if (slot.useSharedOverlayList && slot.overlayListSource >= 0 && slot.overlayListSource < i) { slotData = slotLibrary.InstantiateSlot(slot.slotID, umaData.umaRecipe.slotDataList[slot.overlayListSource].GetOverlayList()); } else { if (slot.useSharedOverlayList) { Debug.LogError("UMA Crowd: Invalid overlayListSource for " + slot.slotID); } slotData = slotLibrary.InstantiateSlot(slot.slotID); } umaData.umaRecipe.slotDataList[i] = slotData; for (int overlayIdx = 0; overlayIdx < slot.overlayElements.Length; overlayIdx++) { var currentOverlayElement = slot.overlayElements[overlayIdx]; randomResult = Random.Range(0, currentOverlayElement.possibleOverlays.Length); var overlay = currentOverlayElement.possibleOverlays[randomResult]; if (string.IsNullOrEmpty(overlay.overlayID)) continue; overlay.UpdateVersion(); slotParts.Add(overlay.overlayID); Color overlayColor = Color.black; var overlayData = overlayLibrary.InstantiateOverlay(overlay.overlayID, overlayColor); switch (overlay.overlayType) { case UMACrowdRandomSet.OverlayType.Color: overlayColor = overlay.minRGB; overlayData.colorData.color = overlayColor; break; case UMACrowdRandomSet.OverlayType.Texture: overlayColor = Color.white; overlayData.colorData.color = overlayColor; break; case UMACrowdRandomSet.OverlayType.Hair: overlayColor = HairColor * overlay.hairColorMultiplier; overlayColor.a = 1.0f; overlayData.colorData.color = overlayColor; break; case UMACrowdRandomSet.OverlayType.Skin: overlayColor = skinColor;// + new Color(Random.Range(overlay.minRGB.r, overlay.maxRGB.r), Random.Range(overlay.minRGB.g, overlay.maxRGB.g), Random.Range(overlay.minRGB.b, overlay.maxRGB.b), 1); overlayData.colorData.color = overlayColor; if (overlayData.colorData.channelAdditiveMask.Length > 2) { overlayData.colorData.channelAdditiveMask[2] = Shine; } else { break; } break; case UMACrowdRandomSet.OverlayType.Random: { float randomShine = Random.Range(0.05f, 0.25f); float randomMetal = Random.Range(0.1f, 0.3f); overlayColor = new Color(Random.Range(overlay.minRGB.r, overlay.maxRGB.r), Random.Range(overlay.minRGB.g, overlay.maxRGB.g), Random.Range(overlay.minRGB.b, overlay.maxRGB.b), Random.Range(overlay.minRGB.a, overlay.maxRGB.a)); overlayData.colorData.color = overlayColor; if (overlayData.colorData.channelAdditiveMask.Length > 2) { overlayData.colorData.channelAdditiveMask[2] = new Color(randomMetal, randomMetal, randomMetal, randomShine); } } break; default: Debug.LogError("Unknown RandomSet overlayType: "+((int)overlay.overlayType)); overlayColor = overlay.minRGB; overlayData.colorData.color = overlayColor; break; } slotData.AddOverlay(overlayData); if (overlay.colorChannelUse != ChannelUse.None) { overlayColor.a *= overlay.minRGB.a; if (overlay.colorChannelUse == ChannelUse.InverseColor) { Vector3 color = new Vector3(overlayColor.r, overlayColor.g, overlayColor.b); var len = color.magnitude; if (len < 1f) len = 1f; color = new Vector3(1.001f, 1.001f, 1.001f) - color; color = color.normalized* len; overlayColor = new Color(color.x, color.y, color.z, overlayColor.a); } overlayData.SetColor(overlay.colorChannel, overlayColor); } } } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type SingleValueLegacyExtendedPropertyRequest. /// </summary> public partial class SingleValueLegacyExtendedPropertyRequest : BaseRequest, ISingleValueLegacyExtendedPropertyRequest { /// <summary> /// Constructs a new SingleValueLegacyExtendedPropertyRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public SingleValueLegacyExtendedPropertyRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified SingleValueLegacyExtendedProperty using POST. /// </summary> /// <param name="singleValueLegacyExtendedPropertyToCreate">The SingleValueLegacyExtendedProperty to create.</param> /// <returns>The created SingleValueLegacyExtendedProperty.</returns> public System.Threading.Tasks.Task<SingleValueLegacyExtendedProperty> CreateAsync(SingleValueLegacyExtendedProperty singleValueLegacyExtendedPropertyToCreate) { return this.CreateAsync(singleValueLegacyExtendedPropertyToCreate, CancellationToken.None); } /// <summary> /// Creates the specified SingleValueLegacyExtendedProperty using POST. /// </summary> /// <param name="singleValueLegacyExtendedPropertyToCreate">The SingleValueLegacyExtendedProperty to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created SingleValueLegacyExtendedProperty.</returns> public async System.Threading.Tasks.Task<SingleValueLegacyExtendedProperty> CreateAsync(SingleValueLegacyExtendedProperty singleValueLegacyExtendedPropertyToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<SingleValueLegacyExtendedProperty>(singleValueLegacyExtendedPropertyToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified SingleValueLegacyExtendedProperty. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified SingleValueLegacyExtendedProperty. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<SingleValueLegacyExtendedProperty>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified SingleValueLegacyExtendedProperty. /// </summary> /// <returns>The SingleValueLegacyExtendedProperty.</returns> public System.Threading.Tasks.Task<SingleValueLegacyExtendedProperty> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified SingleValueLegacyExtendedProperty. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The SingleValueLegacyExtendedProperty.</returns> public async System.Threading.Tasks.Task<SingleValueLegacyExtendedProperty> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<SingleValueLegacyExtendedProperty>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified SingleValueLegacyExtendedProperty using PATCH. /// </summary> /// <param name="singleValueLegacyExtendedPropertyToUpdate">The SingleValueLegacyExtendedProperty to update.</param> /// <returns>The updated SingleValueLegacyExtendedProperty.</returns> public System.Threading.Tasks.Task<SingleValueLegacyExtendedProperty> UpdateAsync(SingleValueLegacyExtendedProperty singleValueLegacyExtendedPropertyToUpdate) { return this.UpdateAsync(singleValueLegacyExtendedPropertyToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified SingleValueLegacyExtendedProperty using PATCH. /// </summary> /// <param name="singleValueLegacyExtendedPropertyToUpdate">The SingleValueLegacyExtendedProperty to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated SingleValueLegacyExtendedProperty.</returns> public async System.Threading.Tasks.Task<SingleValueLegacyExtendedProperty> UpdateAsync(SingleValueLegacyExtendedProperty singleValueLegacyExtendedPropertyToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<SingleValueLegacyExtendedProperty>(singleValueLegacyExtendedPropertyToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public ISingleValueLegacyExtendedPropertyRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public ISingleValueLegacyExtendedPropertyRequest Expand(Expression<Func<SingleValueLegacyExtendedProperty, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public ISingleValueLegacyExtendedPropertyRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public ISingleValueLegacyExtendedPropertyRequest Select(Expression<Func<SingleValueLegacyExtendedProperty, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="singleValueLegacyExtendedPropertyToInitialize">The <see cref="SingleValueLegacyExtendedProperty"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(SingleValueLegacyExtendedProperty singleValueLegacyExtendedPropertyToInitialize) { } } }
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Diagnostics; using Autodesk.Revit; using Autodesk.Revit.UI; using Autodesk.Revit.ApplicationServices; namespace Revit.SDK.Samples.EventsMonitor.CS { /// <summary> /// A class inherits IExternalApplication interface and provide an entry of the sample. /// This class controls other function class and plays the bridge role in this sample. /// It create a custom menu "Track Revit Events" of which the corresponding /// external command is the command in this project. /// </summary> [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)] [Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)] [Autodesk.Revit.Attributes.Journaling(Autodesk.Revit.Attributes.JournalingMode.NoCommandData)] public class ExternalApplication : IExternalApplication { #region Class Member Variables /// <summary> /// A controlled application used to register the events. Because all trigger points /// in this sample come from UI, all events in application level must be registered /// to ControlledApplication. If the trigger point is from API, user can register it /// to Application or Document according to what level it is in. But then, /// the syntax is the same in these three cases. /// </summary> private static UIControlledApplication m_ctrlApp; /// <summary> /// A common object used to write the log file and generate the data table /// for event information. /// </summary> private static LogManager m_logManager; /// <summary> /// The window is used to show events' information. /// </summary> private static EventsInfoWindows m_infWindows; /// <summary> /// The window is used to choose what event to be subscribed. /// </summary> private static EventsSettingForm m_settingDialog; /// <summary> /// This list is used to store what user selected. /// It can be got from the selectionDialog. /// </summary> private static List<String> m_appEventsSelection; /// <summary> /// This object is used to manager the events in application level. /// It can be updated according to what user select. /// </summary> private static EventManager m_appEventMgr; // These #if directives within file are used to compile project in different purpose: // . Build project with Release mode for regression test, // . Build project with Debug mode for manual run #if !(Debug || DEBUG) /// <summary> /// This object is used to make the sample can be autotest. /// It can dump the event list to file or commandData.Data /// and also can retrieval the list from file and commandData.Data. /// If you just pay attention to how to use events, /// please skip over this class and related sentence. /// </summary> private static JournalProcessor m_journalProcessor; #endif #endregion #region Class Static Property /// <summary> /// Property to get and set private member variable of InfoWindows /// </summary> public static EventsInfoWindows InfoWindows { get { if (null == m_infWindows) { m_infWindows = new EventsInfoWindows(EventLogManager); } return m_infWindows; } set { m_infWindows = value; } } /// <summary> /// Property to get private member variable of SeletionDialog /// </summary> public static EventsSettingForm SettingDialog { get { if (null == m_settingDialog) { m_settingDialog = new EventsSettingForm(); } return m_settingDialog; } } /// <summary> /// Property to get and set private member variable of log data /// </summary> public static LogManager EventLogManager { get { if (null == m_logManager) { m_logManager = new LogManager(); } return m_logManager; } } /// <summary> /// Property to get and set private member variable of application events selection. /// </summary> public static List<String> ApplicationEvents { get { if (null == m_appEventsSelection) { m_appEventsSelection = new List<string>(); } return m_appEventsSelection; } set { m_appEventsSelection = value; } } /// <summary> /// Property to get private member variable of application events manager. /// </summary> public static EventManager AppEventMgr { get { if (null == m_appEventMgr) { m_appEventMgr = new EventManager(m_ctrlApp); } return m_appEventMgr; } } #if !(Debug || DEBUG) /// <summary> /// Property to get private member variable of journal processor. /// </summary> public static JournalProcessor JnlProcessor { get { if (null == m_journalProcessor) { m_journalProcessor = new JournalProcessor(); } return m_journalProcessor; } } #endif #endregion #region IExternalApplication Members /// <summary> /// Implement this method to implement the external application which should be called when /// Revit starts before a file or default template is actually loaded. /// </summary> /// <param name="application">An object that is passed to the external application /// which contains the controlled application.</param> /// <returns>Return the status of the external application. /// A result of Succeeded means that the external application successfully started. /// Cancelled can be used to signify that the user cancelled the external operation at /// some point. /// If false is returned then Revit should inform the user that the external application /// failed to load and the release the internal reference.</returns> public Autodesk.Revit.UI.Result OnStartup(UIControlledApplication application) { // initialize member variables. m_ctrlApp = application; m_logManager = new LogManager(); m_infWindows = new EventsInfoWindows(m_logManager); m_settingDialog = new EventsSettingForm(); m_appEventsSelection = new List<string>(); m_appEventMgr = new EventManager(m_ctrlApp); #if !(Debug || DEBUG) m_journalProcessor = new JournalProcessor(); #endif try { #if !(Debug || DEBUG) // playing journal. if (m_journalProcessor.IsReplay) { m_appEventsSelection = m_journalProcessor.EventsList; } // running the sample form UI. else { #endif m_settingDialog.ShowDialog(); if (DialogResult.OK == m_settingDialog.DialogResult) { //get what user select. m_appEventsSelection = m_settingDialog.AppSelectionList; } #if !(Debug || DEBUG) // dump what user select to a file in order to autotesting. m_journalProcessor.DumpEventsListToFile(m_appEventsSelection); } #endif // update the events according to the selection. m_appEventMgr.Update(m_appEventsSelection); // track the selected events by showing the information in the information windows. m_infWindows.Show(); // add menu item in Revit menu bar to provide an approach to // retrieve events setting form. User can change his choices // by calling the setting form again. AddCustomPanel(application); } catch (Exception) { return Autodesk.Revit.UI.Result.Failed; } return Autodesk.Revit.UI.Result.Succeeded; } /// <summary> /// Implement this method to implement the external application which should be called when /// Revit is about to exit,Any documents must have been closed before this method is called. /// </summary> /// <param name="application">An object that is passed to the external application /// which contains the controlled application.</param> /// <returns>Return the status of the external application. /// A result of Succeeded means that the external application successfully shutdown. /// Cancelled can be used to signify that the user cancelled the external operation at /// some point. /// If false is returned then the Revit user should be warned of the failure of the external /// application to shut down correctly.</returns> public Autodesk.Revit.UI.Result OnShutdown(UIControlledApplication application) { // dispose some resource. Dispose(); return Autodesk.Revit.UI.Result.Succeeded; } #endregion #region Class Methods /// <summary> /// Dispose some resource. /// </summary> public static void Dispose() { if (m_infWindows != null) { m_infWindows.Close(); m_infWindows = null; } if (m_settingDialog != null) { m_settingDialog.Close(); m_settingDialog = null; } m_appEventMgr = null; m_logManager.CloseLogFile(); m_logManager = null; } /// <summary> /// Add custom menu. /// </summary> static private void AddCustomPanel(UIControlledApplication application) { // create a panel named "Events Monitor"; string panelName = "Events Monitor"; // create a button on the panel. RibbonPanel ribbonPanelPushButtons = application.CreateRibbonPanel(panelName); PushButtonData pushButtonData = new PushButtonData("EventsSetting", "Set Events", System.Reflection.Assembly.GetExecutingAssembly().Location, "Revit.SDK.Samples.EventsMonitor.CS.Command"); PushButton pushButtonCreateWall = ribbonPanelPushButtons.AddItem(pushButtonData)as PushButton; pushButtonCreateWall.ToolTip = "Setting Events"; } #endregion } }
namespace AgileObjects.ReadableExpressions.Translations.Reflection { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; using Extensions; using static System.Reflection.GenericParameterAttributes; /// <summary> /// Factory class for creating <see cref="IGenericParameter"/> instances. /// </summary> public static class GenericParameterFactory { /// <summary> /// Creates an <see cref="IGenericParameter"/> for the given <paramref name="genericParameter"/>. /// </summary> /// <param name="genericParameter">The Type representing the generic argument.</param> /// <returns>An <see cref="IGenericParameter"/> for the given <paramref name="genericParameter"/> Type.</returns> public static IGenericParameter For(Type genericParameter) => For(ClrTypeWrapper.For(genericParameter)); /// <summary> /// Creates an <see cref="IGenericParameter"/> for the given <paramref name="genericParameter"/>. /// </summary> /// <param name="genericParameter">The <see cref="IType"/> representing the generic argument.</param> /// <returns>An <see cref="IGenericParameter"/> for the given <paramref name="genericParameter"/> Type.</returns> public static IGenericParameter For(IType genericParameter) { if (!genericParameter.IsGenericParameter || (genericParameter.Constraints == None && !genericParameter.ConstraintTypes.Any())) { return new UnconstrainedGenericParameter(genericParameter); } return new ConstrainedGenericParameter(genericParameter); } #region Implementation Classes private abstract class GenericParameterBase : IType { private readonly IType _type; protected GenericParameterBase(IType type) { _type = type; } #region IType Members public IType BaseType => _type.BaseType; public ReadOnlyCollection<IType> AllInterfaces => _type.AllInterfaces; public Assembly Assembly => _type.Assembly; public string Namespace => _type.Namespace; public string Name => _type.Name; public string FullName => _type.FullName; public bool IsInterface => _type.IsInterface; public bool IsClass => _type.IsClass; public bool IsEnum => _type.IsEnum; public bool IsPrimitive => _type.IsPrimitive; public bool IsAnonymous => _type.IsAnonymous; public bool IsAbstract => _type.IsAbstract; public bool IsSealed => _type.IsSealed; public bool IsEnumerable => _type.IsEnumerable; public bool IsDictionary => _type.IsDictionary; public bool IsGeneric => _type.IsGeneric; public bool IsGenericDefinition => _type.IsGenericDefinition; public IType GenericDefinition => _type.GenericDefinition; public int GenericParameterCount => _type.GenericParameterCount; public ReadOnlyCollection<IType> GenericTypeArguments => _type.GenericTypeArguments; public bool IsGenericParameter => _type.IsGenericParameter; public abstract GenericParameterAttributes Constraints { get; } public abstract ReadOnlyCollection<IType> ConstraintTypes { get; } public bool IsNested => _type.IsNested; public IType DeclaringType => _type.DeclaringType; public bool IsArray => _type.IsArray; public IType ElementType => _type.ElementType; public bool IsObjectType => _type.IsObjectType; public bool IsNullable => _type.IsNullable; public IType NonNullableUnderlyingType => _type.NonNullableUnderlyingType; public bool IsByRef => _type.IsByRef; public IEnumerable<IMember> AllMembers => _type.AllMembers; public IEnumerable<IMember> GetMembers(Action<MemberSelector> selectionConfigurator) => _type.GetMembers(selectionConfigurator); public IEnumerable<TMember> GetMembers<TMember>(Action<MemberSelector> selectionConfigurator) where TMember : IMember { return _type.GetMembers(selectionConfigurator).OfType<TMember>(); } public bool Equals(IType otherType) => _type.Equals(otherType); public Type AsType() => _type.AsType(); #endregion public override bool Equals(object obj) { if (ReferenceEquals(this, obj)) { return true; } switch (obj) { case IType type: return Equals(type); case Type bclType: return Equals(ClrTypeWrapper.For(bclType)); default: return false; } } public override int GetHashCode() { unchecked { return _type.GetHashCode() * 397; } } } private class UnconstrainedGenericParameter : GenericParameterBase, IGenericParameter { public UnconstrainedGenericParameter(IType type) : base(type) { } public bool HasConstraints => false; public bool HasClassConstraint => false; public bool HasStructConstraint => false; public bool HasNewableConstraint => false; public override GenericParameterAttributes Constraints => None; public override ReadOnlyCollection<IType> ConstraintTypes => Enumerable<IType>.EmptyReadOnlyCollection; } private class ConstrainedGenericParameter : GenericParameterBase, IGenericParameter { public ConstrainedGenericParameter(IType type) : base(type) { var constraints = Constraints = type.Constraints; var constraintTypes = new List<IType>(type.ConstraintTypes); HasStructConstraint = (constraints | NotNullableValueTypeConstraint) == constraints; if (HasStructConstraint) { constraintTypes.Remove(ClrTypeWrapper.ValueType); } else { HasClassConstraint = (constraints | ReferenceTypeConstraint) == constraints; HasNewableConstraint = (constraints | DefaultConstructorConstraint) == constraints; } ConstraintTypes = constraintTypes.ToReadOnlyCollection(); } public bool HasConstraints => true; public bool HasClassConstraint { get; } public bool HasStructConstraint { get; } public bool HasNewableConstraint { get; } public override GenericParameterAttributes Constraints { get; } public override ReadOnlyCollection<IType> ConstraintTypes { get; } } #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.Collections.Generic; using System.Diagnostics; using System.Threading; namespace System.Data.SqlClient.SNI { /// <summary> /// SNI MARS connection. Multiple MARS streams will be overlaid on this connection. /// </summary> internal class SNIMarsConnection { private readonly Guid _connectionId = Guid.NewGuid(); private readonly Dictionary<int, SNIMarsHandle> _sessions = new Dictionary<int, SNIMarsHandle>(); private readonly byte[] _headerBytes = new byte[SNISMUXHeader.HEADER_LENGTH]; private SNIHandle _lowerHandle; private ushort _nextSessionId = 0; private int _currentHeaderByteCount = 0; private int _dataBytesLeft = 0; private SNISMUXHeader _currentHeader; private SNIPacket _currentPacket; /// <summary> /// Connection ID /// </summary> public Guid ConnectionId { get { return _connectionId; } } /// <summary> /// Constructor /// </summary> /// <param name="lowerHandle">Lower handle</param> public SNIMarsConnection(SNIHandle lowerHandle) { _lowerHandle = lowerHandle; _lowerHandle.SetAsyncCallbacks(HandleReceiveComplete, HandleSendComplete); } public SNIMarsHandle CreateSession(object callbackObject, bool async) { lock (this) { ushort sessionId = _nextSessionId++; SNIMarsHandle handle = new SNIMarsHandle(this, sessionId, callbackObject, async); _sessions.Add(sessionId, handle); return handle; } } /// <summary> /// Start receiving /// </summary> /// <returns></returns> public uint StartReceive() { SNIPacket packet = null; if (ReceiveAsync(ref packet) == TdsEnums.SNI_SUCCESS_IO_PENDING) { return TdsEnums.SNI_SUCCESS_IO_PENDING; } return SNICommon.ReportSNIError(SNIProviders.SMUX_PROV, 0, SNICommon.ConnNotUsableError, string.Empty); } /// <summary> /// Send a packet synchronously /// </summary> /// <param name="packet">SNI packet</param> /// <returns>SNI error code</returns> public uint Send(SNIPacket packet) { lock (this) { return _lowerHandle.Send(packet); } } /// <summary> /// Send a packet asynchronously /// </summary> /// <param name="packet">SNI packet</param> /// <param name="callback">Completion callback</param> /// <returns>SNI error code</returns> public uint SendAsync(SNIPacket packet, SNIAsyncCallback callback) { lock (this) { return _lowerHandle.SendAsync(packet, callback); } } /// <summary> /// Receive a packet asynchronously /// </summary> /// <param name="packet">SNI packet</param> /// <returns>SNI error code</returns> public uint ReceiveAsync(ref SNIPacket packet) { lock (this) { return _lowerHandle.ReceiveAsync(ref packet); } } /// <summary> /// Check SNI handle connection /// </summary> /// <param name="handle"></param> /// <returns>SNI error status</returns> public uint CheckConnection() { lock (this) { return _lowerHandle.CheckConnection(); } } /// <summary> /// Process a receive error /// </summary> public void HandleReceiveError(SNIPacket packet) { Debug.Assert(Monitor.IsEntered(this), "HandleReceiveError was called without being locked."); foreach (SNIMarsHandle handle in _sessions.Values) { handle.HandleReceiveError(packet); } } /// <summary> /// Process a send completion /// </summary> /// <param name="packet">SNI packet</param> /// <param name="sniErrorCode">SNI error code</param> public void HandleSendComplete(SNIPacket packet, uint sniErrorCode) { packet.InvokeCompletionCallback(sniErrorCode); } /// <summary> /// Process a receive completion /// </summary> /// <param name="packet">SNI packet</param> /// <param name="sniErrorCode">SNI error code</param> public void HandleReceiveComplete(SNIPacket packet, uint sniErrorCode) { SNISMUXHeader currentHeader = null; SNIPacket currentPacket = null; SNIMarsHandle currentSession = null; if (sniErrorCode != TdsEnums.SNI_SUCCESS) { lock (this) { HandleReceiveError(packet); return; } } while (true) { lock (this) { if (_currentHeaderByteCount != SNISMUXHeader.HEADER_LENGTH) { currentHeader = null; currentPacket = null; currentSession = null; while (_currentHeaderByteCount != SNISMUXHeader.HEADER_LENGTH) { int bytesTaken = packet.TakeData(_headerBytes, _currentHeaderByteCount, SNISMUXHeader.HEADER_LENGTH - _currentHeaderByteCount); _currentHeaderByteCount += bytesTaken; if (bytesTaken == 0) { sniErrorCode = ReceiveAsync(ref packet); if (sniErrorCode == TdsEnums.SNI_SUCCESS_IO_PENDING) { return; } HandleReceiveError(packet); return; } } _currentHeader = new SNISMUXHeader() { SMID = _headerBytes[0], flags = _headerBytes[1], sessionId = BitConverter.ToUInt16(_headerBytes, 2), length = BitConverter.ToUInt32(_headerBytes, 4) - SNISMUXHeader.HEADER_LENGTH, sequenceNumber = BitConverter.ToUInt32(_headerBytes, 8), highwater = BitConverter.ToUInt32(_headerBytes, 12) }; _dataBytesLeft = (int)_currentHeader.length; _currentPacket = new SNIPacket(null); _currentPacket.Allocate((int)_currentHeader.length); } currentHeader = _currentHeader; currentPacket = _currentPacket; if (_currentHeader.flags == (byte)SNISMUXFlags.SMUX_DATA) { if (_dataBytesLeft > 0) { int length = packet.TakeData(_currentPacket, _dataBytesLeft); _dataBytesLeft -= length; if (_dataBytesLeft > 0) { sniErrorCode = ReceiveAsync(ref packet); if (sniErrorCode == TdsEnums.SNI_SUCCESS_IO_PENDING) { return; } HandleReceiveError(packet); return; } } } _currentHeaderByteCount = 0; if (!_sessions.ContainsKey(_currentHeader.sessionId)) { SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.SMUX_PROV, 0, SNICommon.InvalidParameterError, string.Empty); HandleReceiveError(packet); _lowerHandle.Dispose(); _lowerHandle = null; return; } if (_currentHeader.flags == (byte)SNISMUXFlags.SMUX_FIN) { _sessions.Remove(_currentHeader.sessionId); } else { currentSession = _sessions[_currentHeader.sessionId]; } } if (currentHeader.flags == (byte)SNISMUXFlags.SMUX_DATA) { currentSession.HandleReceiveComplete(currentPacket, currentHeader); } if (_currentHeader.flags == (byte)SNISMUXFlags.SMUX_ACK) { try { currentSession.HandleAck(currentHeader.highwater); } catch (Exception e) { SNICommon.ReportSNIError(SNIProviders.SMUX_PROV, SNICommon.InternalExceptionError, e); } } lock (this) { if (packet.DataLeft == 0) { sniErrorCode = ReceiveAsync(ref packet); if (sniErrorCode == TdsEnums.SNI_SUCCESS_IO_PENDING) { return; } HandleReceiveError(packet); return; } } } } /// <summary> /// Enable SSL /// </summary> public uint EnableSsl(uint options) { return _lowerHandle.EnableSsl(options); } /// <summary> /// Disable SSL /// </summary> public void DisableSsl() { _lowerHandle.DisableSsl(); } #if DEBUG /// <summary> /// Test handle for killing underlying connection /// </summary> public void KillConnection() { _lowerHandle.KillConnection(); } #endif } }
using Braintree.Exceptions; using NUnit.Framework; using System.Xml; namespace Braintree.Tests { [TestFixture] public class PaymentMethodNonceTest { private BraintreeGateway gateway; private BraintreeService service; [SetUp] public void Setup() { gateway = new BraintreeGateway { Environment = Environment.DEVELOPMENT, MerchantId = "integration_merchant_id", PublicKey = "integration_public_key", PrivateKey = "integration_private_key" }; service = new BraintreeService(gateway.Configuration); } [Test] public void ParsesNodeCorrectlyWithDetailsMissing() { string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<payment-method-nonce>" + " <type>CreditCard</type>" + " <nonce>fake-valid-nonce</nonce>" + " <description>ending in 22</description>" + " <consumed type=\"boolean\">false</consumed>" + " <three-d-secure-info nil=\"true\"/>" + "</payment-method-nonce>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); XmlNode newNode = doc.DocumentElement; var node = new NodeWrapper(newNode); var result = new ResultImpl<PaymentMethodNonce>(node, gateway); Assert.IsNotNull(result.Target); Assert.AreEqual("fake-valid-nonce", result.Target.Nonce); Assert.AreEqual("CreditCard", result.Target.Type); Assert.IsNull(result.Target.ThreeDSecureInfo); Assert.IsNull(result.Target.Details); } [Test] public void ParsesNodeCorrectlyWithPayPalDetails() { string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<payment-method-nonce>" + " <type>PayPalAccount</type>" + " <nonce>fake-paypal-account-nonce</nonce>" + " <description></description>" + " <consumed type=\"boolean\">false</consumed>" + " <details>" + " <payer-info>" + " <email>jane.doe@paypal.com</email>" + " <first-name>first</first-name>" + " <last-name>last</last-name>" + " <payer-id>pay-123</payer-id>" + " <country-code>US</country-code>" + " </payer-info>" + " </details>" + "</payment-method-nonce>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); XmlNode newNode = doc.DocumentElement; var node = new NodeWrapper(newNode); var result = new ResultImpl<PaymentMethodNonce>(node, gateway); Assert.IsNotNull(result.Target); Assert.AreEqual("fake-paypal-account-nonce", result.Target.Nonce); Assert.AreEqual("PayPalAccount", result.Target.Type); Assert.IsNotNull(result.Target.Details); Assert.IsNotNull(result.Target.Details.PayerInfo); Assert.AreEqual("jane.doe@paypal.com", result.Target.Details.PayerInfo.Email); Assert.AreEqual("first", result.Target.Details.PayerInfo.FirstName); Assert.AreEqual("last", result.Target.Details.PayerInfo.LastName); Assert.AreEqual("pay-123", result.Target.Details.PayerInfo.PayerId); Assert.AreEqual("US", result.Target.Details.PayerInfo.CountryCode); } [Test] public void ParsesNodeCorrectlyWithGooglePayDetails() { string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<payment-method-nonce>" + " <type>AndroidPayCard</type>" + " <nonce>fake-android-pay-nonce</nonce>" + " <description></description>" + " <consumed type=\"boolean\">false</consumed>" + " <details>" + " <is-network-tokenized>true</is-network-tokenized>" + " </details>" + "</payment-method-nonce>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); XmlNode newNode = doc.DocumentElement; var node = new NodeWrapper(newNode); var result = new ResultImpl<PaymentMethodNonce>(node, gateway); Assert.IsNotNull(result.Target); Assert.AreEqual("fake-android-pay-nonce", result.Target.Nonce); Assert.AreEqual("AndroidPayCard", result.Target.Type); Assert.IsNotNull(result.Target.Details); Assert.IsTrue(result.Target.Details.IsNetworkTokenized); } [Test] public void ParsesNodeCorrectlyWithVenmoDetails() { string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<payment-method-nonce>" + " <type>VenmoAccount</type>" + " <nonce>fake-venmo-account-nonce</nonce>" + " <description></description>" + " <consumed type=\"boolean\">false</consumed>" + " <details>" + " <last-two>99</last-two>" + " <username>venmojoe</username>" + " <venmo-user-id>Venmo-Joe-1</venmo-user-id>" + " </details>" + "</payment-method-nonce>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); XmlNode newNode = doc.DocumentElement; var node = new NodeWrapper(newNode); var result = new ResultImpl<PaymentMethodNonce>(node, gateway); Assert.IsNotNull(result.Target); Assert.AreEqual("fake-venmo-account-nonce", result.Target.Nonce); Assert.AreEqual("VenmoAccount", result.Target.Type); Assert.IsNotNull(result.Target.Details); Assert.AreEqual("99", result.Target.Details.LastTwo); Assert.AreEqual("venmojoe", result.Target.Details.Username); Assert.AreEqual("Venmo-Joe-1", result.Target.Details.VenmoUserId); } [Test] public void ParsesNodeCorrectlyWithCreditCardDetails() { string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<payment-method-nonce>" + " <type>CreditCard</type>" + " <nonce>fake-visa-nonce</nonce>" + " <description></description>" + " <consumed type=\"boolean\">false</consumed>" + " <details>" + " <last-two>99</last-two>" + " <last-four>9999</last-four>" + " <expiration-month>12</expiration-month>" + " <expiration-year>2001</expiration-year>" + " </details>" + "</payment-method-nonce>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); XmlNode newNode = doc.DocumentElement; var node = new NodeWrapper(newNode); var result = new ResultImpl<PaymentMethodNonce>(node, gateway); Assert.IsNotNull(result.Target); Assert.AreEqual("fake-visa-nonce", result.Target.Nonce); Assert.AreEqual("CreditCard", result.Target.Type); Assert.IsNotNull(result.Target.Details); Assert.AreEqual("99", result.Target.Details.LastTwo); Assert.AreEqual("9999", result.Target.Details.LastFour); Assert.AreEqual("12", result.Target.Details.ExpirationMonth); Assert.AreEqual("2001", result.Target.Details.ExpirationYear); } [Test] public void ParsesNodeCorrectlyWithBinData() { string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<payment-method-nonce>" + " <type>CreditCard</type>" + " <nonce>fake-valid-nonce</nonce>" + " <description>ending in 22</description>" + " <consumed type=\"boolean\">false</consumed>" + " <three-d-secure-info nil=\"true\"/>" + " <details nil=\"true\"/>" + " <bin-data>" + " <healthcare>Yes</healthcare>" + " <debit>No</debit>" + " <durbin-regulated>Unknown</durbin-regulated>" + " <commercial>Unknown</commercial>" + " <payroll>Unknown</payroll>" + " <prepaid>NO</prepaid>" + " <issuing-bank>Unknown</issuing-bank>" + " <country-of-issuance>Something</country-of-issuance>" + " <product-id>123</product-id>" + " </bin-data>" + "</payment-method-nonce>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); XmlNode newNode = doc.DocumentElement; var node = new NodeWrapper(newNode); var result = new ResultImpl<PaymentMethodNonce>(node, gateway); Assert.IsNotNull(result.Target); Assert.AreEqual("fake-valid-nonce", result.Target.Nonce); Assert.AreEqual("CreditCard", result.Target.Type); Assert.IsNull(result.Target.ThreeDSecureInfo); Assert.IsNull(result.Target.Details); Assert.IsNotNull(result.Target.BinData); Assert.AreEqual(Braintree.CreditCardCommercial.UNKNOWN, result.Target.BinData.Commercial); Assert.AreEqual(Braintree.CreditCardDebit.NO, result.Target.BinData.Debit); Assert.AreEqual(Braintree.CreditCardDurbinRegulated.UNKNOWN, result.Target.BinData.DurbinRegulated); Assert.AreEqual(Braintree.CreditCardHealthcare.YES, result.Target.BinData.Healthcare); Assert.AreEqual(Braintree.CreditCardPayroll.UNKNOWN, result.Target.BinData.Payroll); Assert.AreEqual(Braintree.CreditCardPrepaid.NO, result.Target.BinData.Prepaid); Assert.AreEqual("Something", result.Target.BinData.CountryOfIssuance); Assert.AreEqual("123", result.Target.BinData.ProductId); Assert.AreEqual("Unknown", result.Target.BinData.IssuingBank); } [Test] public void ParsesNodeCorrectlyWithNilValues() { string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<payment-method-nonce>" + " <type>CreditCard</type>" + " <nonce>fake-valid-nonce</nonce>" + " <description>ending in 22</description>" + " <consumed type=\"boolean\">false</consumed>" + " <three-d-secure-info nil=\"true\"/>" + " <details nil=\"true\"/>" + "</payment-method-nonce>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); XmlNode newNode = doc.DocumentElement; var node = new NodeWrapper(newNode); var result = new ResultImpl<PaymentMethodNonce>(node, gateway); Assert.IsNotNull(result.Target); Assert.AreEqual("fake-valid-nonce", result.Target.Nonce); Assert.AreEqual("CreditCard", result.Target.Type); Assert.IsNull(result.Target.ThreeDSecureInfo); Assert.IsNull(result.Target.Details); } [Test] public void ParseThreeDSecureInfo() { string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<payment-method-nonce>" + " <type>CreditCard</type>" + " <nonce>fake-valid-nonce</nonce>" + " <description>ending in 22</description>" + " <consumed type=\"boolean\">false</consumed>" + " <three-d-secure-info>" + " <enrolled>Y</enrolled>" + " <status>authenticate_successful</status>" + " <liability-shifted>true</liability-shifted>" + " <liability-shift-possible>true</liability-shift-possible>" + " <cavv>cavv-value</cavv>" + " <xid>xid-value</xid>" + " <ds-transaction-id>ds-trx-id-value</ds-transaction-id>" + " <eci-flag>06</eci-flag>" + " <three-d-secure-version>2.0.1</three-d-secure-version>" + " </three-d-secure-info>" + " <details nil=\"true\"/>" + "</payment-method-nonce>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); XmlNode newNode = doc.DocumentElement; var node = new NodeWrapper(newNode); var result = new ResultImpl<PaymentMethodNonce>(node, gateway); var threeDSecureInfo = result.Target.ThreeDSecureInfo; Assert.IsNotNull(result.Target.ThreeDSecureInfo); Assert.AreEqual("Y", threeDSecureInfo.Enrolled); Assert.AreEqual("authenticate_successful", threeDSecureInfo.Status); Assert.IsTrue(threeDSecureInfo.LiabilityShifted); Assert.IsTrue(threeDSecureInfo.LiabilityShiftPossible); Assert.AreEqual("cavv-value", threeDSecureInfo.Cavv); Assert.AreEqual("xid-value", threeDSecureInfo.Xid); Assert.AreEqual("ds-trx-id-value", threeDSecureInfo.DsTransactionId); Assert.AreEqual("06", threeDSecureInfo.EciFlag); Assert.AreEqual("2.0.1", threeDSecureInfo.ThreeDSecureVersion); } [Test] public void ParseAuthenticationInsights() { string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<payment-method-nonce>" + " <authentication-insight>" + " <regulation-environment>bar</regulation-environment>" + " <sca-indicator>foo</sca-indicator>" + " </authentication-insight>" + "</payment-method-nonce>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); XmlNode newNode = doc.DocumentElement; var node = new NodeWrapper(newNode); var result = new ResultImpl<PaymentMethodNonce>(node, gateway); Assert.IsNotNull(result.Target); Assert.AreEqual("foo", result.Target.AuthenticationInsight.ScaIndicator); Assert.AreEqual("bar", result.Target.AuthenticationInsight.RegulationEnvironment); } } }
//------------------------------------------------------------------------------ // <copyright file="HttpListenerRequest.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Net { using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Net.Sockets; using System.Net.WebSockets; using System.Runtime.InteropServices; using System.Security.Authentication.ExtendedProtection; using System.Security.Permissions; using System.Globalization; using System.Text; using System.Threading; using System.Threading.Tasks; using System.ComponentModel; using System.Diagnostics; using System.Security; using System.Security.Principal; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; internal enum ListenerClientCertState { NotInitialized, InProgress, Completed } unsafe internal class ListenerClientCertAsyncResult : LazyAsyncResult { private NativeOverlapped* m_pOverlapped; private byte[] m_BackingBuffer; private UnsafeNclNativeMethods.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* m_MemoryBlob; private uint m_Size; internal NativeOverlapped* NativeOverlapped { get { return m_pOverlapped; } } internal UnsafeNclNativeMethods.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* RequestBlob { get { return m_MemoryBlob; } } private static readonly IOCompletionCallback s_IOCallback = new IOCompletionCallback(WaitCallback); internal ListenerClientCertAsyncResult(object asyncObject, object userState, AsyncCallback callback, uint size) : base(asyncObject, userState, callback) { // we will use this overlapped structure to issue async IO to ul // the event handle will be put in by the BeginHttpApi2.ERROR_SUCCESS() method Reset(size); } internal void Reset(uint size) { if (size == m_Size) { return; } if (m_Size != 0) { Overlapped.Free(m_pOverlapped); } m_Size = size; if (size == 0) { m_pOverlapped = null; m_MemoryBlob = null; m_BackingBuffer = null; return; } m_BackingBuffer = new byte[checked((int) size)]; Overlapped overlapped = new Overlapped(); overlapped.AsyncResult = this; m_pOverlapped = overlapped.Pack(s_IOCallback, m_BackingBuffer); m_MemoryBlob = (UnsafeNclNativeMethods.HttpApi.HTTP_SSL_CLIENT_CERT_INFO*) Marshal.UnsafeAddrOfPinnedArrayElement(m_BackingBuffer, 0); } internal unsafe void IOCompleted(uint errorCode, uint numBytes) { IOCompleted(this, errorCode, numBytes); } private static unsafe void IOCompleted(ListenerClientCertAsyncResult asyncResult, uint errorCode, uint numBytes) { HttpListenerRequest httpListenerRequest = (HttpListenerRequest) asyncResult.AsyncObject; object result = null; try { if (errorCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_MORE_DATA) { //There is a bug that has existed in http.sys since w2k3. Bytesreceived will only //return the size of the inital cert structure. To get the full size, //we need to add the certificate encoding size as well. UnsafeNclNativeMethods.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* pClientCertInfo = asyncResult.RequestBlob; asyncResult.Reset(numBytes + pClientCertInfo->CertEncodedSize); uint bytesReceived = 0; errorCode = UnsafeNclNativeMethods.HttpApi.HttpReceiveClientCertificate( httpListenerRequest.HttpListenerContext.RequestQueueHandle, httpListenerRequest.m_ConnectionId, (uint)UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS.NONE, asyncResult.m_MemoryBlob, asyncResult.m_Size, &bytesReceived, asyncResult.m_pOverlapped); if(errorCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_IO_PENDING || (errorCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS && !HttpListener.SkipIOCPCallbackOnSuccess)) { return; } } if (errorCode!=UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS) { asyncResult.ErrorCode = (int)errorCode; result = new HttpListenerException((int)errorCode); } else { UnsafeNclNativeMethods.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* pClientCertInfo = asyncResult.m_MemoryBlob; if (pClientCertInfo!=null) { GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(httpListenerRequest) + "::ProcessClientCertificate() pClientCertInfo:" + ValidationHelper.ToString((IntPtr)pClientCertInfo) + " pClientCertInfo->CertFlags:" + ValidationHelper.ToString(pClientCertInfo->CertFlags) + " pClientCertInfo->CertEncodedSize:" + ValidationHelper.ToString(pClientCertInfo->CertEncodedSize) + " pClientCertInfo->pCertEncoded:" + ValidationHelper.ToString((IntPtr)pClientCertInfo->pCertEncoded) + " pClientCertInfo->Token:" + ValidationHelper.ToString((IntPtr)pClientCertInfo->Token) + " pClientCertInfo->CertDeniedByMapper:" + ValidationHelper.ToString(pClientCertInfo->CertDeniedByMapper)); if (pClientCertInfo->pCertEncoded!=null) { try { byte[] certEncoded = new byte[pClientCertInfo->CertEncodedSize]; Marshal.Copy((IntPtr)pClientCertInfo->pCertEncoded, certEncoded, 0, certEncoded.Length); result = httpListenerRequest.ClientCertificate = new X509Certificate2(certEncoded); } catch (CryptographicException exception) { GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(httpListenerRequest) + "::ProcessClientCertificate() caught CryptographicException in X509Certificate2..ctor():" + ValidationHelper.ToString(exception)); result = exception; } catch (SecurityException exception) { GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(httpListenerRequest) + "::ProcessClientCertificate() caught SecurityException in X509Certificate2..ctor():" + ValidationHelper.ToString(exception)); result = exception; } } httpListenerRequest.SetClientCertificateError((int)pClientCertInfo->CertFlags); } } // complete the async IO and invoke the callback GlobalLog.Print("ListenerClientCertAsyncResult#" + ValidationHelper.HashString(asyncResult) + "::WaitCallback() calling Complete()"); } catch (Exception exception) { if (NclUtilities.IsFatal(exception)) throw; result = exception; } finally { if(errorCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_IO_PENDING){ httpListenerRequest.ClientCertState = ListenerClientCertState.Completed; } } asyncResult.InvokeCallback(result); } private static unsafe void WaitCallback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped) { // take the ListenerClientCertAsyncResult object from the state Overlapped callbackOverlapped = Overlapped.Unpack(nativeOverlapped); ListenerClientCertAsyncResult asyncResult = (ListenerClientCertAsyncResult) callbackOverlapped.AsyncResult; GlobalLog.Print("ListenerClientCertAsyncResult#" + ValidationHelper.HashString(asyncResult) + "::WaitCallback() errorCode:[" + errorCode.ToString() + "] numBytes:[" + numBytes.ToString() + "] nativeOverlapped:[" + ((long)nativeOverlapped).ToString() + "]"); IOCompleted(asyncResult, errorCode, numBytes); } // Will be called from the base class upon InvokeCallback() protected override void Cleanup() { if (m_pOverlapped != null) { m_MemoryBlob = null; Overlapped.Free(m_pOverlapped); m_pOverlapped = null; } GC.SuppressFinalize(this); base.Cleanup(); } ~ListenerClientCertAsyncResult() { if (m_pOverlapped != null && !NclUtilities.HasShutdownStarted) { Overlapped.Free(m_pOverlapped); m_pOverlapped = null; // Must do this in case application calls GC.ReRegisterForFinalize(). } } } public sealed unsafe class HttpListenerRequest/* BaseHttpRequest, */ { private Uri m_RequestUri; private ulong m_RequestId; internal ulong m_ConnectionId; private SslStatus m_SslStatus; private string m_RawUrl; private string m_CookedUrlHost; private string m_CookedUrlPath; private string m_CookedUrlQuery; private long m_ContentLength; private Stream m_RequestStream; private string m_HttpMethod; private TriState m_KeepAlive; private Version m_Version; private WebHeaderCollection m_WebHeaders; private IPEndPoint m_LocalEndPoint; private IPEndPoint m_RemoteEndPoint; private BoundaryType m_BoundaryType; private ListenerClientCertState m_ClientCertState; private X509Certificate2 m_ClientCertificate; private int m_ClientCertificateError; private RequestContextBase m_MemoryBlob; private CookieCollection m_Cookies; private HttpListenerContext m_HttpContext; private bool m_IsDisposed = false; internal const uint CertBoblSize = 1500; private string m_ServiceName; private object m_Lock = new object(); private List<TokenBinding> m_TokenBindings = null; private int m_TokenBindingVerifyMessageStatus = 0; private enum SslStatus : byte { Insecure, NoClientCert, ClientCert } internal HttpListenerRequest(HttpListenerContext httpContext, RequestContextBase memoryBlob) { if (Logging.On) Logging.PrintInfo(Logging.HttpListener, this, ".ctor", "httpContext#" + ValidationHelper.HashString(httpContext) + " memoryBlob# " + ValidationHelper.HashString((IntPtr) memoryBlob.RequestBlob)); if(Logging.On)Logging.Associate(Logging.HttpListener, this, httpContext); m_HttpContext = httpContext; m_MemoryBlob = memoryBlob; m_BoundaryType = BoundaryType.None; // Set up some of these now to avoid refcounting on memory blob later. m_RequestId = memoryBlob.RequestBlob->RequestId; m_ConnectionId = memoryBlob.RequestBlob->ConnectionId; m_SslStatus = memoryBlob.RequestBlob->pSslInfo == null ? SslStatus.Insecure : memoryBlob.RequestBlob->pSslInfo->SslClientCertNegotiated == 0 ? SslStatus.NoClientCert : SslStatus.ClientCert; if (memoryBlob.RequestBlob->pRawUrl != null && memoryBlob.RequestBlob->RawUrlLength > 0) { m_RawUrl = Marshal.PtrToStringAnsi((IntPtr) memoryBlob.RequestBlob->pRawUrl, memoryBlob.RequestBlob->RawUrlLength); } UnsafeNclNativeMethods.HttpApi.HTTP_COOKED_URL cookedUrl = memoryBlob.RequestBlob->CookedUrl; if (cookedUrl.pHost != null && cookedUrl.HostLength > 0) { m_CookedUrlHost = Marshal.PtrToStringUni((IntPtr)cookedUrl.pHost, cookedUrl.HostLength / 2); } if (cookedUrl.pAbsPath != null && cookedUrl.AbsPathLength > 0) { m_CookedUrlPath = Marshal.PtrToStringUni((IntPtr)cookedUrl.pAbsPath, cookedUrl.AbsPathLength / 2); } if (cookedUrl.pQueryString != null && cookedUrl.QueryStringLength > 0) { m_CookedUrlQuery = Marshal.PtrToStringUni((IntPtr)cookedUrl.pQueryString, cookedUrl.QueryStringLength / 2); } m_Version = new Version(memoryBlob.RequestBlob->Version.MajorVersion, memoryBlob.RequestBlob->Version.MinorVersion); m_ClientCertState = ListenerClientCertState.NotInitialized; m_KeepAlive = TriState.Unspecified; GlobalLog.Print("HttpListenerContext#" + ValidationHelper.HashString(this) + "::.ctor() RequestId:" + RequestId + " ConnectionId:" + m_ConnectionId + " RawConnectionId:" + memoryBlob.RequestBlob->RawConnectionId + " UrlContext:" + memoryBlob.RequestBlob->UrlContext + " RawUrl:" + m_RawUrl + " Version:" + m_Version.ToString() + " Secure:" + m_SslStatus.ToString()); if(Logging.On)Logging.PrintInfo(Logging.HttpListener, this, ".ctor", "httpContext#"+ ValidationHelper.HashString(httpContext)+ " RequestUri:" + ValidationHelper.ToString(RequestUri) + " Content-Length:" + ValidationHelper.ToString(ContentLength64) + " HTTP Method:" + ValidationHelper.ToString(HttpMethod)); // Log headers if(Logging.On) { StringBuilder sb = new StringBuilder("HttpListenerRequest Headers:\n"); for (int i=0; i<Headers.Count; i++) { sb.Append("\t"); sb.Append(Headers.GetKey(i)); sb.Append(" : "); sb.Append(Headers.Get(i)); sb.Append("\n"); } Logging.PrintInfo(Logging.HttpListener, this, ".ctor", sb.ToString()); } } internal HttpListenerContext HttpListenerContext { get { return m_HttpContext; } } internal byte[] RequestBuffer { get { CheckDisposed(); return m_MemoryBlob.RequestBuffer; } } internal IntPtr OriginalBlobAddress { get { CheckDisposed(); return m_MemoryBlob.OriginalBlobAddress; } } // Use this to save the blob from dispose if this object was never used (never given to a user) and is about to be // disposed. internal void DetachBlob(RequestContextBase memoryBlob) { if (memoryBlob != null && (object) memoryBlob == (object) m_MemoryBlob) { m_MemoryBlob = null; } } // Finalizes ownership of the memory blob. DetachBlob can't be called after this. internal void ReleasePins() { m_MemoryBlob.ReleasePins(); } public Guid RequestTraceIdentifier { get { Guid guid = new Guid(); *(1+ (ulong *) &guid) = RequestId; return guid; } } internal ulong RequestId { get { return m_RequestId; } } public /* override */ string[] AcceptTypes { get { return Helpers.ParseMultivalueHeader(GetKnownHeader(HttpRequestHeader.Accept)); } } public /* override */ Encoding ContentEncoding { get { if (UserAgent!=null && CultureInfo.InvariantCulture.CompareInfo.IsPrefix(UserAgent, "UP")) { string postDataCharset = Headers["x-up-devcap-post-charset"]; if (postDataCharset!=null && postDataCharset.Length>0) { try { return Encoding.GetEncoding(postDataCharset); } catch (ArgumentException) { } } } if (HasEntityBody) { if (ContentType!=null) { string charSet = Helpers.GetAttributeFromHeader(ContentType, "charset"); if (charSet!=null) { try { return Encoding.GetEncoding(charSet); } catch (ArgumentException) { } } } } return Encoding.Default; } } public /* override */ long ContentLength64 { get { if (m_BoundaryType==BoundaryType.None) { if (HttpWebRequest.ChunkedHeader.Equals(GetKnownHeader(HttpRequestHeader.TransferEncoding), StringComparison.OrdinalIgnoreCase)) { m_BoundaryType = BoundaryType.Chunked; m_ContentLength = -1; } else { m_ContentLength = 0; m_BoundaryType = BoundaryType.ContentLength; string length = GetKnownHeader(HttpRequestHeader.ContentLength); if (length!=null) { bool success = long.TryParse(length, NumberStyles.None, CultureInfo.InvariantCulture.NumberFormat, out m_ContentLength); if (!success) { m_ContentLength = 0; m_BoundaryType = BoundaryType.Invalid; } } } } GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ContentLength_get() returning m_ContentLength:" + m_ContentLength + " m_BoundaryType:" + m_BoundaryType); return m_ContentLength; } } public /* override */ string ContentType { get { return GetKnownHeader(HttpRequestHeader.ContentType); } } public /* override */ NameValueCollection Headers { get { if (m_WebHeaders==null) { m_WebHeaders = UnsafeNclNativeMethods.HttpApi.GetHeaders(RequestBuffer, OriginalBlobAddress); } GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::Headers_get() returning#" + ValidationHelper.HashString(m_WebHeaders)); return m_WebHeaders; } } public /* override */ string HttpMethod { get { if (m_HttpMethod==null) { m_HttpMethod = UnsafeNclNativeMethods.HttpApi.GetVerb(RequestBuffer, OriginalBlobAddress); } GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::HttpMethod_get() returning m_HttpMethod:" + ValidationHelper.ToString(m_HttpMethod)); return m_HttpMethod; } } public /* override */ Stream InputStream { get { if(Logging.On)Logging.Enter(Logging.HttpListener, this, "InputStream_get", ""); if (m_RequestStream==null) { m_RequestStream = HasEntityBody ? new HttpRequestStream(HttpListenerContext) : Stream.Null; } if(Logging.On)Logging.Exit(Logging.HttpListener, this, "InputStream_get", ""); return m_RequestStream; } } // Requires ControlPrincipal permission if the request was authenticated with Negotiate, NTLM, or Digest. public /* override */ bool IsAuthenticated { get { IPrincipal user = HttpListenerContext.User; return user != null && user.Identity != null && user.Identity.IsAuthenticated; } } public /* override */ bool IsLocal { get { return LocalEndPoint.Address.Equals(RemoteEndPoint.Address); } } public /* override */ bool IsSecureConnection { get { return m_SslStatus != SslStatus.Insecure; } } public bool IsWebSocketRequest { get { if (!WebSocketProtocolComponent.IsSupported) { return false; } bool foundConnectionUpgradeHeader = false; if (string.IsNullOrEmpty(this.Headers[HttpKnownHeaderNames.Connection]) || string.IsNullOrEmpty(this.Headers[HttpKnownHeaderNames.Upgrade])) { return false; } foreach (string connection in this.Headers.GetValues(HttpKnownHeaderNames.Connection)) { if (string.Compare(connection, HttpKnownHeaderNames.Upgrade, StringComparison.OrdinalIgnoreCase) == 0) { foundConnectionUpgradeHeader = true; break; } } if (!foundConnectionUpgradeHeader) { return false; } foreach (string upgrade in this.Headers.GetValues(HttpKnownHeaderNames.Upgrade)) { if (string.Compare(upgrade, WebSocketHelpers.WebSocketUpgradeToken, StringComparison.OrdinalIgnoreCase) == 0) { return true; } } return false; } } public /* override */ NameValueCollection QueryString { get { NameValueCollection queryString = new NameValueCollection(); Helpers.FillFromString(queryString, Url.Query, true, ContentEncoding); return queryString; } } public /* override */ string RawUrl { get { return m_RawUrl; } } public string ServiceName { get { return m_ServiceName; } internal set { m_ServiceName = value; } } public /* override */ Uri Url { get { return RequestUri; } } public /* override */ Uri UrlReferrer { get { string referrer = GetKnownHeader(HttpRequestHeader.Referer); if (referrer==null) { return null; } Uri urlReferrer; bool success = Uri.TryCreate(referrer, UriKind.RelativeOrAbsolute, out urlReferrer); return success ? urlReferrer : null; } } public /* override */ string UserAgent { get { return GetKnownHeader(HttpRequestHeader.UserAgent); } } public /* override */ string UserHostAddress { get { return LocalEndPoint.ToString(); } } public /* override */ string UserHostName { get { return GetKnownHeader(HttpRequestHeader.Host); } } public /* override */ string[] UserLanguages { get { return Helpers.ParseMultivalueHeader(GetKnownHeader(HttpRequestHeader.AcceptLanguage)); } } public int ClientCertificateError { get { if (m_ClientCertState == ListenerClientCertState.NotInitialized) throw new InvalidOperationException(SR.GetString(SR.net_listener_mustcall, "GetClientCertificate()/BeginGetClientCertificate()")); else if (m_ClientCertState == ListenerClientCertState.InProgress) throw new InvalidOperationException(SR.GetString(SR.net_listener_mustcompletecall, "GetClientCertificate()/BeginGetClientCertificate()")); GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ClientCertificateError_get() returning ClientCertificateError:" + ValidationHelper.ToString(m_ClientCertificateError)); return m_ClientCertificateError; } } internal X509Certificate2 ClientCertificate { set { m_ClientCertificate = value; } } internal ListenerClientCertState ClientCertState { set { m_ClientCertState = value; } } internal void SetClientCertificateError(int clientCertificateError) { m_ClientCertificateError = clientCertificateError; } public X509Certificate2 GetClientCertificate() { if(Logging.On)Logging.Enter(Logging.HttpListener, this, "GetClientCertificate", ""); try { ProcessClientCertificate(); GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::GetClientCertificate() returning m_ClientCertificate:" + ValidationHelper.ToString(m_ClientCertificate)); } finally { if(Logging.On)Logging.Exit(Logging.HttpListener, this, "GetClientCertificate", ValidationHelper.ToString(m_ClientCertificate)); } return m_ClientCertificate; } public IAsyncResult BeginGetClientCertificate(AsyncCallback requestCallback, object state) { if(Logging.On)Logging.PrintInfo(Logging.HttpListener, this, "BeginGetClientCertificate", ""); return AsyncProcessClientCertificate(requestCallback, state); } public X509Certificate2 EndGetClientCertificate(IAsyncResult asyncResult) { if(Logging.On)Logging.Enter(Logging.HttpListener, this, "EndGetClientCertificate", ""); X509Certificate2 clientCertificate = null; try { if (asyncResult==null) { throw new ArgumentNullException("asyncResult"); } ListenerClientCertAsyncResult clientCertAsyncResult = asyncResult as ListenerClientCertAsyncResult; if (clientCertAsyncResult==null || clientCertAsyncResult.AsyncObject!=this) { throw new ArgumentException(SR.GetString(SR.net_io_invalidasyncresult), "asyncResult"); } if (clientCertAsyncResult.EndCalled) { throw new InvalidOperationException(SR.GetString(SR.net_io_invalidendcall, "EndGetClientCertificate")); } clientCertAsyncResult.EndCalled = true; clientCertificate = clientCertAsyncResult.InternalWaitForCompletion() as X509Certificate2; GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::EndGetClientCertificate() returning m_ClientCertificate:" + ValidationHelper.ToString(m_ClientCertificate)); } finally { if(Logging.On)Logging.Exit(Logging.HttpListener, this, "EndGetClientCertificate", ValidationHelper.HashString(clientCertificate)); } return clientCertificate; } //************* Task-based async public methods ************************* [HostProtection(ExternalThreading = true)] public Task<X509Certificate2> GetClientCertificateAsync() { return Task<X509Certificate2>.Factory.FromAsync(BeginGetClientCertificate, EndGetClientCertificate, null); } public TransportContext TransportContext { get { return new HttpListenerRequestContext(this); } } private CookieCollection ParseCookies(Uri uri, string setCookieHeader) { GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ParseCookies() uri:" + uri + " setCookieHeader:" + setCookieHeader); CookieCollection cookies = new CookieCollection(); CookieParser parser = new CookieParser(setCookieHeader); for (;;) { Cookie cookie = parser.GetServer(); GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ParseCookies() CookieParser returned cookie:" + ValidationHelper.ToString(cookie)); if (cookie==null) { // EOF, done. break; } if (cookie.Name.Length==0) { continue; } cookies.InternalAdd(cookie, true); } return cookies; } public CookieCollection Cookies { get { if (m_Cookies==null) { string cookieString = GetKnownHeader(HttpRequestHeader.Cookie); if (cookieString!=null && cookieString.Length>0) { m_Cookies = ParseCookies(RequestUri, cookieString); } if (m_Cookies==null) { m_Cookies = new CookieCollection(); } if (HttpListenerContext.PromoteCookiesToRfc2965) { for (int index=0; index<m_Cookies.Count; index++) { if (m_Cookies[index].Variant==CookieVariant.Rfc2109) { m_Cookies[index].Variant = CookieVariant.Rfc2965; } } } } return m_Cookies; } } public Version ProtocolVersion { get { return m_Version; } } public /* override */ bool HasEntityBody { get { // accessing the ContentLength property delay creates m_BoundaryType return (ContentLength64 > 0 && m_BoundaryType == BoundaryType.ContentLength) || m_BoundaryType == BoundaryType.Chunked || m_BoundaryType == BoundaryType.Multipart; } } public /* override */ bool KeepAlive { get { if (m_KeepAlive == TriState.Unspecified) { string header = Headers[HttpKnownHeaderNames.ProxyConnection]; if (string.IsNullOrEmpty(header)) { header = GetKnownHeader(HttpRequestHeader.Connection); } if (string.IsNullOrEmpty(header)) { if (ProtocolVersion >= HttpVersion.Version11) { m_KeepAlive = TriState.True; } else { header = GetKnownHeader(HttpRequestHeader.KeepAlive); m_KeepAlive = string.IsNullOrEmpty(header) ? TriState.False : TriState.True; } } else { header = header.ToLower(CultureInfo.InvariantCulture); m_KeepAlive = header.IndexOf("close") < 0 || header.IndexOf("keep-alive") >= 0 ? TriState.True : TriState.False; } } GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::KeepAlive_get() returning:" + m_KeepAlive); return m_KeepAlive == TriState.True; } } public /* override */ IPEndPoint RemoteEndPoint { get { if (m_RemoteEndPoint==null) { m_RemoteEndPoint = UnsafeNclNativeMethods.HttpApi.GetRemoteEndPoint(RequestBuffer, OriginalBlobAddress); } GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::RemoteEndPoint_get() returning:" + m_RemoteEndPoint); return m_RemoteEndPoint; } } public /* override */ IPEndPoint LocalEndPoint { get { if (m_LocalEndPoint==null) { m_LocalEndPoint = UnsafeNclNativeMethods.HttpApi.GetLocalEndPoint(RequestBuffer, OriginalBlobAddress); } GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::LocalEndPoint_get() returning:" + m_LocalEndPoint); return m_LocalEndPoint; } } //should only be called from httplistenercontext internal void Close() { if(Logging.On)Logging.Enter(Logging.HttpListener, this, "Close", ""); RequestContextBase memoryBlob = m_MemoryBlob; if (memoryBlob != null) { memoryBlob.Close(); m_MemoryBlob = null; } m_IsDisposed = true; if(Logging.On)Logging.Exit(Logging.HttpListener, this, "Close", ""); } private ListenerClientCertAsyncResult AsyncProcessClientCertificate(AsyncCallback requestCallback, object state) { if (m_ClientCertState == ListenerClientCertState.InProgress) throw new InvalidOperationException(SR.GetString(SR.net_listener_callinprogress, "GetClientCertificate()/BeginGetClientCertificate()")); m_ClientCertState = ListenerClientCertState.InProgress; HttpListenerContext.EnsureBoundHandle(); ListenerClientCertAsyncResult asyncResult = null; //-------------------------------------------------------------------- //When you configure the HTTP.SYS with a flag value 2 //which means require client certificates, when the client makes the //initial SSL connection, server (HTTP.SYS) demands the client certificate // //Some apps may not want to demand the client cert at the beginning //perhaps server the default.htm. In this case the HTTP.SYS is configured //with a flag value other than 2, whcih means that the client certificate is //optional.So intially when SSL is established HTTP.SYS won't ask for client //certificate. This works fine for the default.htm in the case above //However, if the app wants to demand a client certficate at a later time //perhaps showing "YOUR ORDERS" page, then the server wans to demand //Client certs. this will inturn makes HTTP.SYS to do the //SEC_I_RENOGOTIATE through which the client cert demand is made // //THE if (m_SslStatus != SslStatus.Insecure) { // at this point we know that DefaultFlags has the 2 bit set (Negotiate Client certificate) // the cert, though might or might not be there. try to retrieve it // this number is the same that IIS decided to use uint size = CertBoblSize; asyncResult = new ListenerClientCertAsyncResult(this, state, requestCallback, size); try { while (true) { GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ProcessClientCertificate() calling UnsafeNclNativeMethods.HttpApi.HttpReceiveClientCertificate size:" + size); uint bytesReceived = 0; uint statusCode = UnsafeNclNativeMethods.HttpApi.HttpReceiveClientCertificate( HttpListenerContext.RequestQueueHandle, m_ConnectionId, (uint)UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS.NONE, asyncResult.RequestBlob, size, &bytesReceived, asyncResult.NativeOverlapped); GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ProcessClientCertificate() call to UnsafeNclNativeMethods.HttpApi.HttpReceiveClientCertificate returned:" + statusCode + " bytesReceived:" + bytesReceived); if (statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_MORE_DATA) { UnsafeNclNativeMethods.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* pClientCertInfo = asyncResult.RequestBlob; size = bytesReceived + pClientCertInfo->CertEncodedSize; asyncResult.Reset(size); continue; } if (statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS && statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_IO_PENDING) { // someother bad error, possible(?) return values are: // ERROR_INVALID_HANDLE, ERROR_INSUFFICIENT_BUFFER, ERROR_OPERATION_ABORTED // Also ERROR_BAD_DATA if we got it twice or it reported smaller size buffer required. throw new HttpListenerException((int)statusCode); } if (statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS && HttpListener.SkipIOCPCallbackOnSuccess) { asyncResult.IOCompleted(statusCode, bytesReceived); } break; } } catch { if (asyncResult!=null) { asyncResult.InternalCleanup(); } throw; } } else { asyncResult = new ListenerClientCertAsyncResult(this, state, requestCallback, 0); asyncResult.InvokeCallback(); } return asyncResult; } private void ProcessClientCertificate() { if (m_ClientCertState == ListenerClientCertState.InProgress) throw new InvalidOperationException(SR.GetString(SR.net_listener_callinprogress, "GetClientCertificate()/BeginGetClientCertificate()")); m_ClientCertState = ListenerClientCertState.InProgress; GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ProcessClientCertificate()"); //-------------------------------------------------------------------- //When you configure the HTTP.SYS with a flag value 2 //which means require client certificates, when the client makes the //initial SSL connection, server (HTTP.SYS) demands the client certificate // //Some apps may not want to demand the client cert at the beginning //perhaps server the default.htm. In this case the HTTP.SYS is configured //with a flag value other than 2, whcih means that the client certificate is //optional.So intially when SSL is established HTTP.SYS won't ask for client //certificate. This works fine for the default.htm in the case above //However, if the app wants to demand a client certficate at a later time //perhaps showing "YOUR ORDERS" page, then the server wans to demand //Client certs. this will inturn makes HTTP.SYS to do the //SEC_I_RENOGOTIATE through which the client cert demand is made // //THE if (m_SslStatus != SslStatus.Insecure) { // at this point we know that DefaultFlags has the 2 bit set (Negotiate Client certificate) // the cert, though might or might not be there. try to retrieve it // this number is the same that IIS decided to use uint size = CertBoblSize; while (true) { byte[] clientCertInfoBlob = new byte[checked((int) size)]; fixed (byte* pClientCertInfoBlob = clientCertInfoBlob) { UnsafeNclNativeMethods.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* pClientCertInfo = (UnsafeNclNativeMethods.HttpApi.HTTP_SSL_CLIENT_CERT_INFO*) pClientCertInfoBlob; GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ProcessClientCertificate() calling UnsafeNclNativeMethods.HttpApi.HttpReceiveClientCertificate size:" + size); uint bytesReceived = 0; uint statusCode = UnsafeNclNativeMethods.HttpApi.HttpReceiveClientCertificate( HttpListenerContext.RequestQueueHandle, m_ConnectionId, (uint)UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS.NONE, pClientCertInfo, size, &bytesReceived, null); GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ProcessClientCertificate() call to UnsafeNclNativeMethods.HttpApi.HttpReceiveClientCertificate returned:" + statusCode + " bytesReceived:" + bytesReceived); if (statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_MORE_DATA) { size = bytesReceived + pClientCertInfo->CertEncodedSize; continue; } else if (statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS) { if (pClientCertInfo!=null) { GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ProcessClientCertificate() pClientCertInfo:" + ValidationHelper.ToString((IntPtr)pClientCertInfo) + " pClientCertInfo->CertFlags:" + ValidationHelper.ToString(pClientCertInfo->CertFlags) + " pClientCertInfo->CertEncodedSize:" + ValidationHelper.ToString(pClientCertInfo->CertEncodedSize) + " pClientCertInfo->pCertEncoded:" + ValidationHelper.ToString((IntPtr)pClientCertInfo->pCertEncoded) + " pClientCertInfo->Token:" + ValidationHelper.ToString((IntPtr)pClientCertInfo->Token) + " pClientCertInfo->CertDeniedByMapper:" + ValidationHelper.ToString(pClientCertInfo->CertDeniedByMapper)); if (pClientCertInfo->pCertEncoded!=null) { try { byte[] certEncoded = new byte[pClientCertInfo->CertEncodedSize]; Marshal.Copy((IntPtr)pClientCertInfo->pCertEncoded, certEncoded, 0, certEncoded.Length); m_ClientCertificate = new X509Certificate2(certEncoded); } catch (CryptographicException exception) { GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ProcessClientCertificate() caught CryptographicException in X509Certificate2..ctor():" + ValidationHelper.ToString(exception)); } catch (SecurityException exception) { GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::ProcessClientCertificate() caught SecurityException in X509Certificate2..ctor():" + ValidationHelper.ToString(exception)); } } m_ClientCertificateError = (int)pClientCertInfo->CertFlags; } } else { GlobalLog.Assert(statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_NOT_FOUND, "HttpListenerRequest#{0}::ProcessClientCertificate()|Call to UnsafeNclNativeMethods.HttpApi.HttpReceiveClientCertificate() failed with statusCode {1}.", ValidationHelper.HashString(this), statusCode); } } break; } } m_ClientCertState = ListenerClientCertState.Completed; } private string RequestScheme { get { return IsSecureConnection ? "https" : "http"; } } private Uri RequestUri { get { if (m_RequestUri == null) { m_RequestUri = HttpListenerRequestUriBuilder.GetRequestUri( m_RawUrl, RequestScheme, m_CookedUrlHost, m_CookedUrlPath, m_CookedUrlQuery); } GlobalLog.Print("HttpListenerRequest#" + ValidationHelper.HashString(this) + "::RequestUri_get() returning m_RequestUri:" + ValidationHelper.ToString(m_RequestUri)); return m_RequestUri; } } /* private DateTime IfModifiedSince { get { string headerValue = GetKnownHeader(HttpRequestHeader.IfModifiedSince); if (headerValue==null) { return DateTime.Now; } return DateTime.Parse(headerValue, CultureInfo.InvariantCulture); } } */ private string GetKnownHeader(HttpRequestHeader header) { return UnsafeNclNativeMethods.HttpApi.GetKnownHeader(RequestBuffer, OriginalBlobAddress, (int) header); } internal ChannelBinding GetChannelBinding() { return HttpListenerContext.Listener.GetChannelBindingFromTls(m_ConnectionId); } internal IEnumerable<TokenBinding> GetTlsTokenBindings() { // Try to get the token binding if not created. if (Volatile.Read(ref m_TokenBindings) == null) { lock (m_Lock) { if (Volatile.Read(ref m_TokenBindings) == null) { // If token binding is supported on the machine get it else create empty list. if (UnsafeNclNativeMethods.TokenBindingOSHelper.SupportsTokenBinding) { ProcessTlsTokenBindings(); } else { m_TokenBindings = new List<TokenBinding>(); } } } } // If the cached status is not success throw exception, else return the token binding if (0 != m_TokenBindingVerifyMessageStatus) { throw new HttpListenerException(m_TokenBindingVerifyMessageStatus); } else { return m_TokenBindings.AsReadOnly(); } } /// <summary> /// Process the token binding information in the request and populate m_TokenBindings /// This method should be called once only as token binding information is cached in m_TokenBindings for further use. /// </summary> private void ProcessTlsTokenBindings() { Debug.Assert(m_TokenBindings == null); if (m_TokenBindings != null) { return; } m_TokenBindings = new List<TokenBinding>(); UnsafeNclNativeMethods.HttpApi.HTTP_REQUEST_TOKEN_BINDING_INFO* pTokenBindingInfo = GetTlsTokenBindingRequestInfo(); if (pTokenBindingInfo == null) { // The current request isn't over TLS or the client or server doesn't support the token binding // protocol. This isn't an error; just return "nothing here". return; } UnsafeNclNativeMethods.HttpApi.HeapAllocHandle handle = null; m_TokenBindingVerifyMessageStatus = -1; m_TokenBindingVerifyMessageStatus = UnsafeNclNativeMethods.HttpApi.TokenBindingVerifyMessage( pTokenBindingInfo->TokenBinding, pTokenBindingInfo->TokenBindingSize, pTokenBindingInfo->KeyType, pTokenBindingInfo->TlsUnique, pTokenBindingInfo->TlsUniqueSize, out handle); if (m_TokenBindingVerifyMessageStatus != 0) { throw new HttpListenerException(m_TokenBindingVerifyMessageStatus); } Debug.Assert(handle != null); Debug.Assert(!handle.IsInvalid); using (handle) { UnsafeNclNativeMethods.HttpApi.TOKENBINDING_RESULT_LIST* pResultList = (UnsafeNclNativeMethods.HttpApi.TOKENBINDING_RESULT_LIST*)handle.DangerousGetHandle(); for (int i = 0; i < pResultList->resultCount; i++) { UnsafeNclNativeMethods.HttpApi.TOKENBINDING_RESULT_DATA* pThisResultData = &pResultList->resultData[i]; if (pThisResultData != null) { // Per http://tools.ietf.org/html/draft-ietf-tokbind-protocol-00, Sec. 4, // We'll strip off the token binding type and return the remainder as an opaque blob. Debug.Assert((long)(&pThisResultData->identifierData->hashAlgorithm) == (long)(pThisResultData->identifierData) + 1); byte[] retVal = new byte[pThisResultData->identifierSize - 1]; Marshal.Copy((IntPtr)(&pThisResultData->identifierData->hashAlgorithm), retVal, 0, retVal.Length); if (pThisResultData->identifierData->bindingType == UnsafeNclNativeMethods.HttpApi.TOKENBINDING_TYPE.TOKENBINDING_TYPE_PROVIDED) { m_TokenBindings.Add(new TokenBinding(TokenBindingType.Provided, retVal)); } else if (pThisResultData->identifierData->bindingType == UnsafeNclNativeMethods.HttpApi.TOKENBINDING_TYPE.TOKENBINDING_TYPE_REFERRED) { m_TokenBindings.Add(new TokenBinding(TokenBindingType.Referred, retVal)); } } } } } private UnsafeNclNativeMethods.HttpApi.HTTP_REQUEST_TOKEN_BINDING_INFO* GetTlsTokenBindingRequestInfo() { fixed (byte* pMemoryBlob = RequestBuffer) { UnsafeNclNativeMethods.HttpApi.HTTP_REQUEST_V2* request = (UnsafeNclNativeMethods.HttpApi.HTTP_REQUEST_V2*)pMemoryBlob; for (int i = 0; i < request->RequestInfoCount; i++) { UnsafeNclNativeMethods.HttpApi.HTTP_REQUEST_INFO* pThisInfo = &request->pRequestInfo[i]; if (pThisInfo != null && pThisInfo->InfoType == UnsafeNclNativeMethods.HttpApi.HTTP_REQUEST_INFO_TYPE.HttpRequestInfoTypeSslTokenBinding) { return (UnsafeNclNativeMethods.HttpApi.HTTP_REQUEST_TOKEN_BINDING_INFO*)pThisInfo->pInfo; } } } return null; } internal void CheckDisposed() { if (m_IsDisposed) { throw new ObjectDisposedException(this.GetType().FullName); } } // < static class Helpers { // // Get attribute off header value // internal static String GetAttributeFromHeader(String headerValue, String attrName) { if (headerValue == null) return null; int l = headerValue.Length; int k = attrName.Length; // find properly separated attribute name int i = 1; // start searching from 1 while (i < l) { i = CultureInfo.InvariantCulture.CompareInfo.IndexOf(headerValue, attrName, i, CompareOptions.IgnoreCase); if (i < 0) break; if (i+k >= l) break; char chPrev = headerValue[i-1]; char chNext = headerValue[i+k]; if ((chPrev == ';' || chPrev == ',' || Char.IsWhiteSpace(chPrev)) && (chNext == '=' || Char.IsWhiteSpace(chNext))) break; i += k; } if (i < 0 || i >= l) return null; // skip to '=' and the following whitespaces i += k; while (i < l && Char.IsWhiteSpace(headerValue[i])) i++; if (i >= l || headerValue[i] != '=') return null; i++; while (i < l && Char.IsWhiteSpace(headerValue[i])) i++; if (i >= l) return null; // parse the value String attrValue = null; int j; if (i < l && headerValue[i] == '"') { if (i == l-1) return null; j = headerValue.IndexOf('"', i+1); if (j < 0 || j == i+1) return null; attrValue = headerValue.Substring(i+1, j-i-1).Trim(); } else { for (j = i; j < l; j++) { if (headerValue[j] == ' ' || headerValue[j] == ',') break; } if (j == i) return null; attrValue = headerValue.Substring(i, j-i).Trim(); } return attrValue; } internal static String[] ParseMultivalueHeader(String s) { if (s == null) return null; int l = s.Length; // collect comma-separated values into list ArrayList values = new ArrayList(); int i = 0; while (i < l) { // find next , int ci = s.IndexOf(',', i); if (ci < 0) ci = l; // append corresponding server value values.Add(s.Substring(i, ci-i)); // move to next i = ci+1; // skip leading space if (i < l && s[i] == ' ') i++; } // return list as array of strings int n = values.Count; String[] strings; // if n is 0 that means s was empty string if (n == 0) { strings = new String[1]; strings[0] = String.Empty; } else { strings = new String[n]; values.CopyTo(0, strings, 0, n); } return strings; } private static string UrlDecodeStringFromStringInternal(string s, Encoding e) { int count = s.Length; UrlDecoder helper = new UrlDecoder(count, e); // go through the string's chars collapsing %XX and %uXXXX and // appending each char as char, with exception of %XX constructs // that are appended as bytes for (int pos = 0; pos < count; pos++) { char ch = s[pos]; if (ch == '+') { ch = ' '; } else if (ch == '%' && pos < count-2) { if (s[pos+1] == 'u' && pos < count-5) { int h1 = HexToInt(s[pos+2]); int h2 = HexToInt(s[pos+3]); int h3 = HexToInt(s[pos+4]); int h4 = HexToInt(s[pos+5]); if (h1 >= 0 && h2 >= 0 && h3 >= 0 && h4 >= 0) { // valid 4 hex chars ch = (char)((h1 << 12) | (h2 << 8) | (h3 << 4) | h4); pos += 5; // only add as char helper.AddChar(ch); continue; } } else { int h1 = HexToInt(s[pos+1]); int h2 = HexToInt(s[pos+2]); if (h1 >= 0 && h2 >= 0) { // valid 2 hex chars byte b = (byte)((h1 << 4) | h2); pos += 2; // don't add as char helper.AddByte(b); continue; } } } if ((ch & 0xFF80) == 0) helper.AddByte((byte)ch); // 7 bit have to go as bytes because of Unicode else helper.AddChar(ch); } return helper.GetString(); } private static int HexToInt(char h) { return( h >= '0' && h <= '9' ) ? h - '0' : ( h >= 'a' && h <= 'f' ) ? h - 'a' + 10 : ( h >= 'A' && h <= 'F' ) ? h - 'A' + 10 : -1; } private class UrlDecoder { private int _bufferSize; // Accumulate characters in a special array private int _numChars; private char[] _charBuffer; // Accumulate bytes for decoding into characters in a special array private int _numBytes; private byte[] _byteBuffer; // Encoding to convert chars to bytes private Encoding _encoding; private void FlushBytes() { if (_numBytes > 0) { _numChars += _encoding.GetChars(_byteBuffer, 0, _numBytes, _charBuffer, _numChars); _numBytes = 0; } } internal UrlDecoder(int bufferSize, Encoding encoding) { _bufferSize = bufferSize; _encoding = encoding; _charBuffer = new char[bufferSize]; // byte buffer created on demand } internal void AddChar(char ch) { if (_numBytes > 0) FlushBytes(); _charBuffer[_numChars++] = ch; } internal void AddByte(byte b) { // if there are no pending bytes treat 7 bit bytes as characters // this optimization is temp disable as it doesn't work for some encodings /* if (_numBytes == 0 && ((b & 0x80) == 0)) { AddChar((char)b); } else */ { if (_byteBuffer == null) _byteBuffer = new byte[_bufferSize]; _byteBuffer[_numBytes++] = b; } } internal String GetString() { if (_numBytes > 0) FlushBytes(); if (_numChars > 0) return new String(_charBuffer, 0, _numChars); else return String.Empty; } } internal static void FillFromString(NameValueCollection nvc, String s, bool urlencoded, Encoding encoding) { int l = (s != null) ? s.Length : 0; int i = (s.Length>0 && s[0]=='?') ? 1 : 0; while (i < l) { // find next & while noting first = on the way (and if there are more) int si = i; int ti = -1; while (i < l) { char ch = s[i]; if (ch == '=') { if (ti < 0) ti = i; } else if (ch == '&') { break; } i++; } // extract the name / value pair String name = null; String value = null; if (ti >= 0) { name = s.Substring(si, ti-si); value = s.Substring(ti+1, i-ti-1); } else { value = s.Substring(si, i-si); } // add name / value pair to the collection if (urlencoded) nvc.Add( name == null ? null : UrlDecodeStringFromStringInternal(name, encoding), UrlDecodeStringFromStringInternal(value, encoding)); else nvc.Add(name, value); // trailing '&' if (i == l-1 && s[i] == '&') nvc.Add(null, ""); i++; } } } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Dispatcher { using System; using System.Collections; using System.Collections.Generic; using System.Runtime; #if NO internal interface IQueryBufferPool { // Clear all pools void Reset(); // Trim pools void Trim(); } #endif // // Generic struct representing ranges within buffers // internal struct QueryRange { internal int end; // INCLUSIVE - the end of the range internal int start; // INCLUSIVE - the start of the range #if NO internal QueryRange(int offset, QueryRange range) { this.start = range.start + offset; this.end = range.end + offset; } #endif internal QueryRange(int start, int end) { this.start = start; this.end = end; } internal int Count { get { return this.end - this.start + 1; } } #if NO internal int this[int offset] { get { return this.start + offset; } } internal bool IsNotEmpty { get { return (this.end >= this.start); } } internal void Clear() { this.end = this.start - 1; } internal void Grow(int offset) { this.end += offset; } #endif internal bool IsInRange(int point) { return (this.start <= point && point <= this.end); } #if NO internal void Set(int start, int end) { this.start = start; this.end = end; } #endif internal void Shift(int offset) { this.start += offset; this.end += offset; } } /// <summary> /// Our own buffer management /// There are a few reasons why we don't reuse something in System.Collections.Generic /// 1. We want Clear() to NOT reallocate the internal array. We want it to simply set the Count = 0 /// This allows us to reuse buffers with impunity. /// 2. We want to be able to replace the internal buffer in a collection with a different one. Again, /// this is to help with pooling /// 3. We want to be able to control how fast buffers grow. /// 4. Does absolutely no bounds or null checking. As fast as we can make it. All checking should be done /// by whoever wraps this. Checking is unnecessary for many internal uses where we need optimal perf. /// 5. Does more precise trimming /// 6. AND this is a struct /// /// </summary> internal struct QueryBuffer<T> { internal T[] buffer; // buffer of T. Frequently larger than count internal int count; // Actual # of items internal static T[] EmptyBuffer = new T[0]; /// <summary> /// Construct a new buffer /// </summary> /// <param name="capacity"></param> internal QueryBuffer(int capacity) { if (0 == capacity) { this.buffer = QueryBuffer<T>.EmptyBuffer; } else { this.buffer = new T[capacity]; } this.count = 0; } #if NO internal QueryBuffer(QueryBuffer<T> buffer) { this.buffer = (T[]) buffer.buffer.Clone(); this.count = buffer.count; } internal QueryBuffer(T[] buffer) { Fx.Assert(null != buffer, ""); this.buffer = buffer; this.count = 0; } /// <summary> /// Get and set the internal buffer /// If you set the buffer, the count will automatically be set to 0 /// </summary> internal T[] Buffer { get { return this.buffer; } set { Fx.Assert(null != value, ""); this.buffer = value; this.count = 0; } } #endif /// <summary> /// # of items /// </summary> internal int Count { get { return this.count; } #if NO set { Fx.Assert(value >= 0 && value <= this.buffer.Length, ""); this.count = value; } #endif } #if NO /// <summary> /// How much can it hold /// </summary> internal int Capacity { get { return this.buffer.Length; } set { Fx.Assert(value >= this.count, ""); if (value > this.buffer.Length) { Array.Resize<T>(ref this.buffer, value); } } } #endif internal T this[int index] { get { return this.buffer[index]; } set { this.buffer[index] = value; } } #if NO internal void Add() { if (this.count == this.buffer.Length) { Array.Resize<T>(ref this.buffer, this.count > 0 ? this.count * 2 : 16); } this.count++; } #endif /// <summary> /// Add an element to the buffer /// </summary> internal void Add(T t) { if (this.count == this.buffer.Length) { Array.Resize<T>(ref this.buffer, this.count > 0 ? this.count * 2 : 16); } this.buffer[this.count++] = t; } #if NO /// <summary> /// Useful when this is a buffer of structs /// </summary> internal void AddReference(ref T t) { if (this.count == this.buffer.Length) { Array.Resize<T>(ref this.buffer, this.count > 0 ? this.count * 2 : 16); } this.buffer[this.count++] = t; } #endif /// <summary> /// Add all the elements in the given buffer to this one /// We can do this very efficiently using an Array Copy /// </summary> internal void Add(ref QueryBuffer<T> addBuffer) { if (1 == addBuffer.count) { this.Add(addBuffer.buffer[0]); return; } int newCount = this.count + addBuffer.count; if (newCount >= this.buffer.Length) { this.Grow(newCount); } // Copy all the new elements in Array.Copy(addBuffer.buffer, 0, this.buffer, this.count, addBuffer.count); this.count = newCount; } #if NO internal void Add(T[] addBuffer, int startAt, int addCount) { int newCount = this.count + addCount; if (newCount >= this.buffer.Length) { this.Grow(newCount); } // Copy all the new elements in Array.Copy(addBuffer, startAt, this.buffer, this.count, addCount); this.count = newCount; } /// <summary> /// Add without attempting to grow the buffer. Faster, but must be used with care. /// Caller must ensure that the buffer is large enough. /// </summary> internal void AddOnly(T t) { this.buffer[this.count++] = t; } #endif /// <summary> /// Set the count to zero but do NOT get rid of the actual buffer /// </summary> internal void Clear() { this.count = 0; } #if NO // // Copy from one location in the buffer to another // internal void Copy(int from, int to) { this.buffer[to] = this.buffer[from]; } internal void Copy(int from, int to, int count) { Array.Copy(this.buffer, from, this.buffer, to, count); } #endif internal void CopyFrom(ref QueryBuffer<T> addBuffer) { int addCount = addBuffer.count; switch (addCount) { default: if (addCount > this.buffer.Length) { this.buffer = new T[addCount]; } // Copy all the new elements in Array.Copy(addBuffer.buffer, 0, this.buffer, 0, addCount); this.count = addCount; break; case 0: this.count = 0; break; case 1: if (this.buffer.Length == 0) { this.buffer = new T[1]; } this.buffer[0] = addBuffer.buffer[0]; this.count = 1; break; } } internal void CopyTo(T[] dest) { Array.Copy(this.buffer, dest, this.count); } #if NO /// <summary> /// Ensure that the internal buffer has adequate capacity /// </summary> internal void EnsureCapacity(int capacity) { if (capacity > this.buffer.Length) { this.Grow(capacity); } } internal void Erase() { Array.Clear(this.buffer, 0, this.count); this.count = 0; } #endif void Grow(int capacity) { int newCapacity = this.buffer.Length * 2; Array.Resize<T>(ref this.buffer, capacity > newCapacity ? capacity : newCapacity); } internal int IndexOf(T t) { for (int i = 0; i < this.count; ++i) { if (t.Equals(this.buffer[i])) { return i; } } return -1; } internal int IndexOf(T t, int startAt) { for (int i = startAt; i < this.count; ++i) { if (t.Equals(this.buffer[i])) { return i; } } return -1; } #if NO internal void InsertAt(T t, int at) { this.ReserveAt(at, 1); this.buffer[at] = t; } #endif internal bool IsValidIndex(int index) { return (index >= 0 && index < this.count); } #if NO internal T Pop() { Fx.Assert(this.count > 0, ""); return this.buffer[--this.count]; } internal void Push(T t) { this.Add(t); } #endif /// <summary> /// Reserve enough space for count elements /// </summary> internal void Reserve(int reserveCount) { int newCount = this.count + reserveCount; if (newCount >= this.buffer.Length) { this.Grow(newCount); } this.count = newCount; } internal void ReserveAt(int index, int reserveCount) { if (index == this.count) { this.Reserve(reserveCount); return; } int newCount; if (index > this.count) { // We want to reserve starting at a location past what is current committed. // No shifting needed newCount = index + reserveCount + 1; if (newCount >= this.buffer.Length) { this.Grow(newCount); } } else { // reserving space within an already allocated portion of the buffer // we'll ensure that the buffer can fit 'newCount' items, then shift by reserveCount starting at index newCount = this.count + reserveCount; if (newCount >= this.buffer.Length) { this.Grow(newCount); } // Move to make room Array.Copy(this.buffer, index, this.buffer, index + reserveCount, this.count - index); } this.count = newCount; } internal void Remove(T t) { int index = this.IndexOf(t); if (index >= 0) { this.RemoveAt(index); } } internal void RemoveAt(int index) { if (index < this.count - 1) { Array.Copy(this.buffer, index + 1, this.buffer, index, this.count - index - 1); } this.count--; } internal void Sort(IComparer<T> comparer) { Array.Sort<T>(this.buffer, 0, this.count, comparer); } #if NO /// <summary> /// Reduce the buffer capacity so that it is no greater than twice the element count /// </summary> internal void Trim() { int maxSize = this.count * 2; if (maxSize < this.buffer.Length / 2) { if (0 == maxSize) { this.buffer = QueryBuffer<T>.EmptyBuffer; } else { T[] newBuffer = new T[maxSize]; Array.Copy(this.buffer, newBuffer, maxSize); } } } #endif /// <summary> /// Reduce the buffer capacity so that its size is exactly == to the element count /// </summary> internal void TrimToCount() { if (this.count < this.buffer.Length) { if (0 == this.count) { this.buffer = QueryBuffer<T>.EmptyBuffer; } else { T[] newBuffer = new T[this.count]; Array.Copy(this.buffer, newBuffer, this.count); } } } } internal struct SortedBuffer<T, C> where C : IComparer<T> { int size; T[] buffer; static DefaultComparer Comparer; internal SortedBuffer(C comparerInstance) { this.size = 0; this.buffer = null; if (Comparer == null) { Comparer = new DefaultComparer(comparerInstance); } else { Fx.Assert(object.ReferenceEquals(DefaultComparer.Comparer, comparerInstance), "The SortedBuffer type has already been initialized with a different comparer instance."); } } internal T this[int index] { get { return GetAt(index); } } internal int Capacity { #if NO get { return this.buffer == null ? 0 : this.buffer.Length; } #endif set { if (this.buffer != null) { if (value != this.buffer.Length) { Fx.Assert(value >= this.size, "New capacity must be >= size"); if (value > 0) { Array.Resize(ref this.buffer, value); } else { this.buffer = null; } } } else { this.buffer = new T[value]; } } } internal int Count { get { return this.size; } } internal int Add(T item) { int i = Search(item); if (i < 0) { i = ~i; InsertAt(i, item); } return i; } #if NO internal void CopyTo(T[] array) { CopyTo(array, 0, this.size); } internal void CopyTo(T[] array, int start, int length) { Fx.Assert(array != null, ""); Fx.Assert(start >= 0, ""); Fx.Assert(length >= 0, ""); Fx.Assert(start + length < this.size, ""); Array.Copy(this.buffer, 0, array, start, length); } #endif internal void Clear() { this.size = 0; } #if NO internal bool Contains(T item) { return IndexOf(item) >= 0; } #endif internal void Exchange(T old, T replace) { if (Comparer.Compare(old, replace) == 0) { int i = IndexOf(old); if (i >= 0) { this.buffer[i] = replace; } else { Insert(replace); } } else { // PERF, [....], can this be made more efficient? Does it need to be? Remove(old); Insert(replace); } } internal T GetAt(int index) { Fx.Assert(index < this.size, "Index is greater than size"); return this.buffer[index]; } internal int IndexOf(T item) { return Search(item); } internal int IndexOfKey<K>(K key, IItemComparer<K, T> itemComp) { return Search(key, itemComp); } internal int Insert(T item) { int i = Search(item); if (i >= 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperCritical(new ArgumentException(SR.GetString(SR.QueryItemAlreadyExists))); } // If an item is not found, Search returns the bitwise negation of // the index an item should inserted at; InsertAt(~i, item); return ~i; } void InsertAt(int index, T item) { Fx.Assert(index >= 0 && index <= this.size, ""); if (this.buffer == null) { this.buffer = new T[1]; } else if (this.buffer.Length == this.size) { // PERF, [....], how should we choose a new size? T[] tmp = new T[this.size + 1]; if (index == 0) { Array.Copy(this.buffer, 0, tmp, 1, this.size); } else if (index == this.size) { Array.Copy(this.buffer, 0, tmp, 0, this.size); } else { Array.Copy(this.buffer, 0, tmp, 0, index); Array.Copy(this.buffer, index, tmp, index + 1, this.size - index); } this.buffer = tmp; } else { Array.Copy(this.buffer, index, this.buffer, index + 1, this.size - index); } this.buffer[index] = item; ++this.size; } internal bool Remove(T item) { int i = IndexOf(item); if (i >= 0) { RemoveAt(i); return true; } return false; } internal void RemoveAt(int index) { Fx.Assert(index >= 0 && index < this.size, ""); if (index < this.size - 1) { Array.Copy(this.buffer, index + 1, this.buffer, index, this.size - index - 1); } this.buffer[--this.size] = default(T); } int Search(T item) { if (size == 0) return ~0; return Search(item, Comparer); } int Search<K>(K key, IItemComparer<K, T> comparer) { if (this.size <= 8) { return LinearSearch<K>(key, comparer, 0, this.size); } else { return BinarySearch(key, comparer); } } int BinarySearch<K>(K key, IItemComparer<K, T> comparer) { // [low, high) int low = 0; int high = this.size; int mid, result; // Binary search is implemented here so we could look for a type that is different from the // buffer type. Also, the search switches to linear for 8 or fewer elements. while (high - low > 8) { mid = (high + low) / 2; result = comparer.Compare(key, this.buffer[mid]); if (result < 0) { high = mid; } else if (result > 0) { low = mid + 1; } else { return mid; } } return LinearSearch<K>(key, comparer, low, high); } // [start, bound) int LinearSearch<K>(K key, IItemComparer<K, T> comparer, int start, int bound) { int result; for (int i = start; i < bound; ++i) { result = comparer.Compare(key, this.buffer[i]); if (result == 0) { return i; } if (result < 0) { // Return the bitwise negation of the insertion index return ~i; } } // Return the bitwise negation of the insertion index return ~bound; } #if NO internal T[] ToArray() { T[] tmp = new T[this.size]; Array.Copy(this.buffer, 0, tmp, 0, this.size); return tmp; } #endif internal void Trim() { this.Capacity = this.size; } internal class DefaultComparer : IItemComparer<T, T> { public static IComparer<T> Comparer; public DefaultComparer(C comparer) { Comparer = comparer; } public int Compare(T item1, T item2) { return Comparer.Compare(item1, item2); } } } internal interface IItemComparer<K, V> { int Compare(K key, V value); } }
//------------------------------------------------------------------------------ // <copyright file="ScrollBar.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Windows.Forms { using System.Runtime.Serialization.Formatters; using System.Runtime.InteropServices; using System.Runtime.Remoting; using System.Diagnostics; using System; using System.Security.Permissions; using System.Windows.Forms; using System.ComponentModel; using System.Drawing; using Microsoft.Win32; using System.Globalization; /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar"]/*' /> /// <devdoc> /// <para> /// Implements the basic functionality of a scroll bar control. /// </para> /// </devdoc> [ ComVisible(true), ClassInterface(ClassInterfaceType.AutoDispatch), DefaultProperty("Value"), DefaultEvent("Scroll"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1012:AbstractTypesShouldNotHaveConstructors") // Shipped in Everett ] public abstract class ScrollBar : Control { private static readonly object EVENT_SCROLL = new object(); private static readonly object EVENT_VALUECHANGED = new object(); private int minimum = 0; private int maximum = 100; private int smallChange = 1; private int largeChange = 10; private int value = 0; private ScrollOrientation scrollOrientation; private int wheelDelta = 0; /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.ScrollBar"]/*' /> /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Windows.Forms.ScrollBar'/> /// class. /// /// </para> /// </devdoc> public ScrollBar() : base() { SetStyle(ControlStyles.UserPaint, false); SetStyle(ControlStyles.StandardClick, false); SetStyle(ControlStyles.UseTextForAccessibility, false); TabStop = false; if ((this.CreateParams.Style & NativeMethods.SBS_VERT) != 0) { scrollOrientation = ScrollOrientation.VerticalScroll; } else { scrollOrientation = ScrollOrientation.HorizontalScroll; } } /// <devdoc> /// <para>Hide AutoSize: it doesn't make sense for this control</para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public override bool AutoSize { get { return base.AutoSize; } set { base.AutoSize = value; } } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.AutoSizeChanged"]/*' /> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler AutoSizeChanged { add { base.AutoSizeChanged += value; } remove { base.AutoSizeChanged -= value; } } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.BackColor"]/*' /> /// <internalonly/> /// <devdoc> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public override Color BackColor { get { return base.BackColor; } set { base.BackColor = value; } } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.BackColorChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler BackColorChanged { add { base.BackColorChanged += value; } remove { base.BackColorChanged -= value; } } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.BackgroundImage"]/*' /> /// <internalonly/> /// <devdoc> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public override Image BackgroundImage { get { return base.BackgroundImage; } set { base.BackgroundImage = value; } } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.BackgroundImageChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler BackgroundImageChanged { add { base.BackgroundImageChanged += value; } remove { base.BackgroundImageChanged -= value; } } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.BackgroundImageLayout"]/*' /> /// <internalonly/> /// <devdoc> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public override ImageLayout BackgroundImageLayout { get { return base.BackgroundImageLayout; } set { base.BackgroundImageLayout = value; } } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.BackgroundImageLayoutChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler BackgroundImageLayoutChanged { add { base.BackgroundImageLayoutChanged += value; } remove { base.BackgroundImageLayoutChanged -= value; } } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.CreateParams"]/*' /> /// <devdoc> /// Retrieves the parameters needed to create the handle. Inheriting classes /// can override this to provide extra functionality. They should not, /// however, forget to call base.getCreateParams() first to get the struct /// filled up with the basic info. /// </devdoc> /// <internalonly/> protected override CreateParams CreateParams { [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] get { CreateParams cp = base.CreateParams; cp.ClassName = "SCROLLBAR"; cp.Style &= (~NativeMethods.WS_BORDER); return cp; } } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.DefaultImeMode"]/*' /> protected override ImeMode DefaultImeMode { get { return ImeMode.Disable; } } protected override Padding DefaultMargin { get { return Padding.Empty; } } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.ForeColor"]/*' /> /// <internalonly/> /// <devdoc> /// <para> /// Gets or sets the foreground color of the scroll bar control. /// </para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public override Color ForeColor { get { return base.ForeColor; } set { base.ForeColor = value; } } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.ForeColorChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler ForeColorChanged { add { base.ForeColorChanged += value; } remove { base.ForeColorChanged -= value; } } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.Font"]/*' /> /// <internalonly/><hideinheritance/> /// <devdoc> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public override Font Font { get { return base.Font; } set { base.Font = value; } } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.FontChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler FontChanged { add { base.FontChanged += value; } remove { base.FontChanged -= value; } } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.ImeMode"]/*' /> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public ImeMode ImeMode { get { return base.ImeMode; } set { base.ImeMode = value; } } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.ImeModeChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new event EventHandler ImeModeChanged { add { base.ImeModeChanged += value; } remove { base.ImeModeChanged -= value; } } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.LargeChange"]/*' /> /// <devdoc> /// <para> /// Gets or sets a value to be added or subtracted to the <see cref='System.Windows.Forms.ScrollBar.Value'/> /// property when the scroll box is moved a large distance. /// </para> /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(10), SRDescription(SR.ScrollBarLargeChangeDescr), RefreshProperties(RefreshProperties.Repaint) ] public int LargeChange { get { // We preserve the actual large change value that has been set, but when we come to // get the value of this property, make sure it's within the maximum allowable value. // This way we ensure that we don't depend on the order of property sets when // code is generated at design-time. // return Math.Min(largeChange, maximum - minimum + 1); } set { if (largeChange != value) { if (value < 0) { throw new ArgumentOutOfRangeException("LargeChange", SR.GetString(SR.InvalidLowBoundArgumentEx, "LargeChange", (value).ToString(CultureInfo.CurrentCulture), (0).ToString(CultureInfo.CurrentCulture))); } largeChange = value; UpdateScrollInfo(); } } } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.Maximum"]/*' /> /// <devdoc> /// <para> /// Gets or sets the upper limit of values of the scrollable range. /// </para> /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(100), SRDescription(SR.ScrollBarMaximumDescr), RefreshProperties(RefreshProperties.Repaint) ] public int Maximum { get { return maximum; } set { if (maximum != value) { if (minimum > value) minimum = value; // bring this.value in line. if (value < this.value) Value = value; maximum = value; UpdateScrollInfo(); } } } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.Minimum"]/*' /> /// <devdoc> /// <para> /// Gets or sets the lower limit of values of the scrollable range. /// </para> /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(0), SRDescription(SR.ScrollBarMinimumDescr), RefreshProperties(RefreshProperties.Repaint) ] public int Minimum { get { return minimum; } set { if (minimum != value) { if (maximum < value) maximum = value; // bring this.value in line. if (value > this.value) this.value = value; minimum = value; UpdateScrollInfo(); } } } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.SmallChange"]/*' /> /// <devdoc> /// <para> /// Gets or sets the value to be added or subtracted to the /// <see cref='System.Windows.Forms.ScrollBar.Value'/> /// property when the scroll box is /// moved a small distance. /// </para> /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(1), SRDescription(SR.ScrollBarSmallChangeDescr) ] public int SmallChange { get { // We can't have SmallChange > LargeChange, but we shouldn't manipulate // the set values for these properties, so we just return the smaller // value here. // return Math.Min(smallChange, LargeChange); } set { if (smallChange != value) { if (value < 0) { throw new ArgumentOutOfRangeException("SmallChange", SR.GetString(SR.InvalidLowBoundArgumentEx, "SmallChange", (value).ToString(CultureInfo.CurrentCulture), (0).ToString(CultureInfo.CurrentCulture))); } smallChange = value; UpdateScrollInfo(); } } } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.TabStop"]/*' /> /// <internalonly/> /// <devdoc> /// </devdoc> [DefaultValue(false)] new public bool TabStop { get { return base.TabStop; } set { base.TabStop = value; } } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.Text"]/*' /> /// <internalonly/> /// <devdoc> /// </devdoc> [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never), Bindable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public override string Text { get { return base.Text; } set { base.Text = value; } } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.TextChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler TextChanged { add { base.TextChanged += value; } remove { base.TextChanged -= value; } } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.Value"]/*' /> /// <devdoc> /// <para> /// Gets or sets a numeric value that represents the current /// position of the scroll box /// on /// the scroll bar control. /// </para> /// </devdoc> [ SRCategory(SR.CatBehavior), DefaultValue(0), Bindable(true), SRDescription(SR.ScrollBarValueDescr) ] public int Value { get { return value; } set { if (this.value != value) { if (value < minimum || value > maximum) { throw new ArgumentOutOfRangeException("Value", SR.GetString(SR.InvalidBoundArgument, "Value", (value).ToString(CultureInfo.CurrentCulture), "'minimum'", "'maximum'")); } this.value = value; UpdateScrollInfo(); OnValueChanged(EventArgs.Empty); } } } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.Click"]/*' /> /// <internalonly/><hideinheritance/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new event EventHandler Click { add { base.Click += value; } remove { base.Click -= value; } } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.OnPaint"]/*' /> /// <devdoc> /// ScrollBar Onpaint. /// </devdoc> /// <internalonly/><hideinheritance/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new event PaintEventHandler Paint { add { base.Paint += value; } remove { base.Paint -= value; } } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.DoubleClick"]/*' /> /// <internalonly/><hideinheritance/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new event EventHandler DoubleClick { add { base.DoubleClick += value; } remove { base.DoubleClick -= value; } } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.MouseClick"]/*' /> /// <internalonly/><hideinheritance/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new event MouseEventHandler MouseClick { add { base.MouseClick += value; } remove { base.MouseClick -= value; } } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.MouseDoubleClick"]/*' /> /// <internalonly/><hideinheritance/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new event MouseEventHandler MouseDoubleClick { add { base.MouseDoubleClick += value; } remove { base.MouseDoubleClick -= value; } } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.MouseDown"]/*' /> /// <internalonly/><hideinheritance/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new event MouseEventHandler MouseDown { add { base.MouseDown += value; } remove { base.MouseDown -= value; } } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.MouseUp"]/*' /> /// <internalonly/><hideinheritance/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new event MouseEventHandler MouseUp { add { base.MouseUp += value; } remove { base.MouseUp -= value; } } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.MouseMove"]/*' /> /// <internalonly/><hideinheritance/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new event MouseEventHandler MouseMove { add { base.MouseMove += value; } remove { base.MouseMove -= value; } } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.Scroll"]/*' /> /// <devdoc> /// <para> /// Occurs when the scroll box has /// been /// moved by either a mouse or keyboard action. /// </para> /// </devdoc> [SRCategory(SR.CatAction), SRDescription(SR.ScrollBarOnScrollDescr)] public event ScrollEventHandler Scroll { add { Events.AddHandler(EVENT_SCROLL, value); } remove { Events.RemoveHandler(EVENT_SCROLL, value); } } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.ValueChanged"]/*' /> /// <devdoc> /// <para> /// Occurs when the <see cref='System.Windows.Forms.ScrollBar.Value'/> property has changed, either by a /// <see cref='System.Windows.Forms.ScrollBar.OnScroll'/> event or programatically. /// </para> /// </devdoc> [SRCategory(SR.CatAction), SRDescription(SR.valueChangedEventDescr)] public event EventHandler ValueChanged { add { Events.AddHandler(EVENT_VALUECHANGED, value); } remove { Events.RemoveHandler(EVENT_VALUECHANGED, value); } } /// <devdoc> /// This is a helper method that is called by ScaleControl to retrieve the bounds /// that the control should be scaled by. You may override this method if you /// wish to reuse ScaleControl's scaling logic but you need to supply your own /// bounds. The default implementation returns scaled bounds that take into /// account the BoundsSpecified, whether the control is top level, and whether /// the control is fixed width or auto size, and any adornments the control may have. /// </devdoc> protected override Rectangle GetScaledBounds(Rectangle bounds, SizeF factor, BoundsSpecified specified) { // Adjust Specified for vertical or horizontal scaling if (scrollOrientation == ScrollOrientation.VerticalScroll) { specified &= ~BoundsSpecified.Width; } else { specified &= ~BoundsSpecified.Height; } return base.GetScaledBounds(bounds, factor, specified); } internal override IntPtr InitializeDCForWmCtlColor (IntPtr dc, int msg) { return IntPtr.Zero; } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.OnEnabledChanged"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected override void OnEnabledChanged(EventArgs e) { if (Enabled) { UpdateScrollInfo(); } base.OnEnabledChanged(e); } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.OnHandleCreated"]/*' /> /// <devdoc> /// Creates the handle. overridden to help set up scrollbar information. /// </devdoc> /// <internalonly/> protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); UpdateScrollInfo(); } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.OnScroll"]/*' /> /// <devdoc> /// <para> /// Raises the <see cref='System.Windows.Forms.ScrollBar.ValueChanged'/> event. /// </para> /// </devdoc> protected virtual void OnScroll(ScrollEventArgs se) { ScrollEventHandler handler = (ScrollEventHandler)Events[EVENT_SCROLL]; if (handler != null) handler(this,se); } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.OnMouseWheel"]/*' /> /// <devdoc> /// Converts mouse wheel movements into scrolling, when scrollbar has the focus. /// Typically one wheel step will cause one small scroll increment, in either /// direction. A single wheel message could represent either one wheel step, multiple /// wheel steps (fast wheeling), or even a fraction of a step (smooth-wheeled mice). /// So we accumulate the total wheel delta, and consume it in whole numbers of steps. /// </devdoc> protected override void OnMouseWheel(MouseEventArgs e) { wheelDelta += e.Delta; bool scrolled = false; while (Math.Abs(wheelDelta) >= NativeMethods.WHEEL_DELTA) { if (wheelDelta > 0) { wheelDelta -= NativeMethods.WHEEL_DELTA; DoScroll(ScrollEventType.SmallDecrement); scrolled = true; } else { wheelDelta += NativeMethods.WHEEL_DELTA; DoScroll(ScrollEventType.SmallIncrement); scrolled = true; } } if (scrolled) { DoScroll(ScrollEventType.EndScroll); } if (e is HandledMouseEventArgs) { ((HandledMouseEventArgs) e).Handled = true; } // The base implementation should be called before the implementation above, // but changing the order in Whidbey would be too much of a breaking change // for this particular class. base.OnMouseWheel(e); } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.OnValueChanged"]/*' /> /// <devdoc> /// <para> /// Raises the <see cref='System.Windows.Forms.ScrollBar.ValueChanged'/> event. /// </para> /// </devdoc> protected virtual void OnValueChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[EVENT_VALUECHANGED]; if (handler != null) handler(this,e); } // Reflects the position of the scrollbar private int ReflectPosition(int position) { if (this is HScrollBar) { return minimum + (maximum - LargeChange + 1) - position; } return position; } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.ToString"]/*' /> /// <internalonly/> /// <devdoc> /// </devdoc> public override string ToString() { string s = base.ToString(); return s + ", Minimum: " + Minimum.ToString(CultureInfo.CurrentCulture) + ", Maximum: " + Maximum.ToString(CultureInfo.CurrentCulture) + ", Value: " + Value.ToString(CultureInfo.CurrentCulture); } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.UpdateScrollInfo"]/*' /> /// <devdoc> /// Internal helper method /// </devdoc> /// <internalonly/> protected void UpdateScrollInfo() { if (IsHandleCreated && Enabled) { NativeMethods.SCROLLINFO si = new NativeMethods.SCROLLINFO(); si.cbSize = Marshal.SizeOf(typeof(NativeMethods.SCROLLINFO)); si.fMask = NativeMethods.SIF_ALL; si.nMin = minimum; si.nMax = maximum; si.nPage = LargeChange; if (RightToLeft == RightToLeft.Yes) { // Reflect the scrollbar position horizontally on an Rtl system si.nPos = ReflectPosition(value); } else { si.nPos = value; } si.nTrackPos = 0; UnsafeNativeMethods.SetScrollInfo(new HandleRef(this, Handle), NativeMethods.SB_CTL, si, true); } } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.WmReflectScroll"]/*' /> /// <devdoc> /// </devdoc> /// <internalonly/> private void WmReflectScroll(ref Message m) { ScrollEventType type = (ScrollEventType)NativeMethods.Util.LOWORD(m.WParam); DoScroll(type); } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.DoScroll"]/*' /> /// <devdoc> /// </devdoc> /// <internalonly/> private void DoScroll(ScrollEventType type) { // For Rtl systems we need to swap increment and decrement // if (RightToLeft == RightToLeft.Yes) { switch (type) { case ScrollEventType.First: type = ScrollEventType.Last; break; case ScrollEventType.Last: type = ScrollEventType.First; break; case ScrollEventType.SmallDecrement: type = ScrollEventType.SmallIncrement; break; case ScrollEventType.SmallIncrement: type = ScrollEventType.SmallDecrement; break; case ScrollEventType.LargeDecrement: type = ScrollEventType.LargeIncrement; break; case ScrollEventType.LargeIncrement: type = ScrollEventType.LargeDecrement; break; } } int newValue = value; int oldValue = value; // The ScrollEventArgs constants are defined in terms of the windows // messages.. this eliminates confusion between the VSCROLL and // HSCROLL constants, which are identical. // switch (type) { case ScrollEventType.First: newValue = minimum; break; case ScrollEventType.Last: newValue = maximum - LargeChange + 1; // si.nMax - si.nPage + 1; break; case ScrollEventType.SmallDecrement: newValue = Math.Max(value - SmallChange, minimum); break; case ScrollEventType.SmallIncrement: newValue = Math.Min(value + SmallChange, maximum - LargeChange + 1); // max - lChange + 1); break; case ScrollEventType.LargeDecrement: newValue = Math.Max(value - LargeChange, minimum); break; case ScrollEventType.LargeIncrement: newValue = Math.Min(value + LargeChange, maximum - LargeChange + 1); // si.nPos + si.nPage,si.nMax - si.nPage + 1); break; case ScrollEventType.ThumbPosition: case ScrollEventType.ThumbTrack: NativeMethods.SCROLLINFO si = new NativeMethods.SCROLLINFO(); si.fMask = NativeMethods.SIF_TRACKPOS; SafeNativeMethods.GetScrollInfo(new HandleRef(this, Handle), NativeMethods.SB_CTL, si); if (RightToLeft == RightToLeft.Yes) { newValue = ReflectPosition(si.nTrackPos); } else { newValue = si.nTrackPos; } break; } ScrollEventArgs se = new ScrollEventArgs(type, oldValue, newValue, this.scrollOrientation); OnScroll(se); Value = se.NewValue; } /// <include file='doc\ScrollBar.uex' path='docs/doc[@for="ScrollBar.WndProc"]/*' /> /// <devdoc> /// </devdoc> /// <internalonly/> [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] protected override void WndProc(ref Message m) { switch (m.Msg) { case NativeMethods.WM_REFLECT + NativeMethods.WM_HSCROLL: case NativeMethods.WM_REFLECT + NativeMethods.WM_VSCROLL: WmReflectScroll(ref m); break; case NativeMethods.WM_ERASEBKGND: break; case NativeMethods.WM_SIZE: //VS7#13707 : [....], 4/26/1999 - Fixes the scrollbar focus rect if (UnsafeNativeMethods.GetFocus() == this.Handle) { DefWndProc(ref m); SendMessage(NativeMethods.WM_KILLFOCUS, 0, 0); SendMessage(NativeMethods.WM_SETFOCUS, 0, 0); } break; default: base.WndProc(ref m); break; } } } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. extern alias MbUnit2; using System; using System.Collections.Generic; using System.Text; using Gallio.Common.Collections; using Gallio.MbUnit2Adapter.Properties; using Gallio.Common.Diagnostics; using Gallio.Model.Commands; using Gallio.Model.Contexts; using Gallio.Model.Helpers; using Gallio.Model.Tree; using Gallio.Runtime.ProgressMonitoring; using Gallio.Model; using Gallio.Common.Markup; using MbUnit2::MbUnit.Core; using MbUnit2::MbUnit.Core.Remoting; using MbUnit2::MbUnit.Core.Filters; using MbUnit2::MbUnit.Core.Reports.Serialization; namespace Gallio.MbUnit2Adapter.Model { /// <summary> /// Controls the execution of MbUnit v2 tests. /// </summary> internal class MbUnit2TestController : TestController { private readonly FixtureExplorer fixtureExplorer; /// <summary> /// Creates a runner. /// </summary> /// <param name="fixtureExplorer">The fixture explorer.</param> public MbUnit2TestController(FixtureExplorer fixtureExplorer) { this.fixtureExplorer = fixtureExplorer; } /// <inheritdoc /> protected override TestResult RunImpl(ITestCommand rootTestCommand, TestStep parentTestStep, TestExecutionOptions options, IProgressMonitor progressMonitor) { ThrowIfDisposed(); using (progressMonitor.BeginTask(Resources.MbUnit2TestController_RunningMbUnitTests, 1)) { if (progressMonitor.IsCanceled) return new TestResult(TestOutcome.Canceled); if (options.SkipTestExecution) { return SkipAll(rootTestCommand, parentTestStep); } else { IList<ITestCommand> testCommands = rootTestCommand.GetAllCommands(); using (InstrumentedFixtureRunner fixtureRunner = new InstrumentedFixtureRunner(fixtureExplorer, testCommands, progressMonitor, parentTestStep)) { return fixtureRunner.Run(); } } } } private void ThrowIfDisposed() { if (fixtureExplorer == null) throw new ObjectDisposedException(Resources.MbUnit2TestController_ControlledWasDisposedException); } private class InstrumentedFixtureRunner : DependencyFixtureRunner, IDisposable, IFixtureFilter, IRunPipeFilter, IRunPipeListener { private readonly FixtureExplorer fixtureExplorer; private readonly IList<ITestCommand> testCommands; private readonly IProgressMonitor progressMonitor; private readonly TestStep topTestStep; private HashSet<Type> includedFixtureTypes; private TestOutcome assemblyTestOutcome; private TestResult assemblyTestResult; private ITestCommand assemblyTestCommand; private Dictionary<Fixture, ITestCommand> fixtureTestCommands; private Dictionary<RunPipe, ITestCommand> runPipeTestCommands; private Dictionary<ITestCommand, ITestContext> activeTestContexts; private double workUnit; public InstrumentedFixtureRunner(FixtureExplorer fixtureExplorer, IList<ITestCommand> testCommands, IProgressMonitor progressMonitor, TestStep topTestStep) { this.fixtureExplorer = fixtureExplorer; this.progressMonitor = progressMonitor; this.testCommands = testCommands; this.topTestStep = topTestStep; Initialize(); } public void Dispose() { progressMonitor.Canceled -= HandleCanceled; } private void Initialize() { progressMonitor.Canceled += HandleCanceled; progressMonitor.SetStatus(Resources.MbUnit2TestController_InitializingMbUnitTestRunner); int totalWork = 1; if (fixtureExplorer.HasAssemblySetUp) totalWork += 1; if (fixtureExplorer.HasAssemblyTearDown) totalWork += 1; // Build a reverse mapping from types and run-pipes to tests. includedFixtureTypes = new HashSet<Type>(); fixtureTestCommands = new Dictionary<Fixture, ITestCommand>(); runPipeTestCommands = new Dictionary<RunPipe, ITestCommand>(); activeTestContexts = new Dictionary<ITestCommand, ITestContext>(); bool isExplicit = false; foreach (ITestCommand testCommand in testCommands) { if (testCommand.IsExplicit) isExplicit = true; MbUnit2Test test = (MbUnit2Test)testCommand.Test; Fixture fixture = test.Fixture; RunPipe runPipe = test.RunPipe; if (fixture == null) { assemblyTestCommand = testCommand; } else if (runPipe == null) { includedFixtureTypes.Add(fixture.Type); fixtureTestCommands[fixture] = testCommand; if (fixture.HasSetUp) totalWork += 1; if (fixture.HasTearDown) totalWork += 1; } else { runPipeTestCommands[runPipe] = testCommand; totalWork += 1; } } // Set options IsExplicit = isExplicit; FixtureFilter = this; RunPipeFilter = this; workUnit = 1.0 / totalWork; progressMonitor.Worked(workUnit); } public TestResult Run() { assemblyTestOutcome = TestOutcome.Passed; if (assemblyTestCommand != null) { ReportListener reportListener = new ReportListener(); Run(fixtureExplorer, reportListener); // TODO: Do we need to do anyhing with the result in the report listener? } return assemblyTestResult ?? new TestResult(TestOutcome.Error); } #region Overrides to track assembly and fixture lifecycle protected override bool RunAssemblySetUp() { CheckCanceled(); progressMonitor.SetStatus(assemblyTestCommand.Test.Name); HandleAssemblyStart(); ITestContext assemblyTestContext = activeTestContexts[assemblyTestCommand]; if (Explorer.HasAssemblySetUp) assemblyTestContext.LifecyclePhase = LifecyclePhases.SetUp; bool success = base.RunAssemblySetUp(); // Note: MbUnit won't call RunAssemblyTearDown itself if the assembly setup fails // so we need to make sure we finish things up ourselves. if (!success) { assemblyTestContext.LogWriter.Failures.Write("The test assembly setup failed.\n"); HandleAssemblyFinish(TestOutcome.Failed); } else { assemblyTestContext.LifecyclePhase = LifecyclePhases.Execute; } progressMonitor.Worked(workUnit); return success; } protected override bool RunAssemblyTearDown() { progressMonitor.SetStatus(assemblyTestCommand.Test.Name); ITestContext assemblyTestContext = activeTestContexts[assemblyTestCommand]; if (Explorer.HasAssemblyTearDown) assemblyTestContext.LifecyclePhase = LifecyclePhases.TearDown; bool success = base.RunAssemblyTearDown(); if (success) { HandleAssemblyFinish(TestOutcome.Passed); } else { assemblyTestContext.LogWriter.Failures.Write("The test assembly teardown failed.\n"); HandleAssemblyFinish(TestOutcome.Failed); } progressMonitor.Worked(workUnit); return success; } protected override ReportRunResult RunFixture(Fixture fixture) { CheckCanceled(); try { HandleFixtureStart(fixture); foreach (RunPipeStarter starter in fixture.Starters) starter.Listeners.Add(this); ReportRunResult reportRunResult = base.RunFixture(fixture); HandleFixtureFinish(fixture, reportRunResult); return reportRunResult; } finally { foreach (RunPipeStarter starter in fixture.Starters) { if (starter.Listeners.Contains(this)) starter.Listeners.Remove(this); } } } protected override void SkipStarters(Fixture fixture, Exception ex) { CheckCanceled(); HandleFixtureStart(fixture); base.SkipStarters(fixture, ex); HandleFixtureFinish(fixture, ReportRunResult.Skip); } protected override object RunFixtureSetUp(Fixture fixture, object fixtureInstance) { CheckCanceled(); ITestCommand fixtureTestCommand; ITestContext fixtureTestContext = null; if (fixtureTestCommands.TryGetValue(fixture, out fixtureTestCommand)) { progressMonitor.SetStatus(fixtureTestCommand.Test.Name); fixtureTestContext = activeTestContexts[fixtureTestCommand]; fixtureTestContext.LifecyclePhase = LifecyclePhases.SetUp; } object result = base.RunFixtureSetUp(fixture, fixtureInstance); if (fixtureTestContext != null) fixtureTestContext.LifecyclePhase = LifecyclePhases.Execute; progressMonitor.Worked(workUnit); return result; } protected override void RunFixtureTearDown(Fixture fixture, object fixtureInstance) { CheckCanceled(); ITestCommand fixtureTestCommand; if (fixtureTestCommands.TryGetValue(fixture, out fixtureTestCommand)) { progressMonitor.SetStatus(fixtureTestCommand.Test.Name); ITestContext fixtureTestContext = activeTestContexts[fixtureTestCommand]; fixtureTestContext.LifecyclePhase = LifecyclePhases.TearDown; } base.RunFixtureTearDown(fixture, fixtureInstance); progressMonitor.Worked(workUnit); } #endregion #region IFixtureFilter bool IFixtureFilter.Filter(Type type) { return includedFixtureTypes.Contains(type); } #endregion #region IRunPipeFilter bool IRunPipeFilter.Filter(RunPipe runPipe) { return runPipeTestCommands.ContainsKey(runPipe); } #endregion #region IRunPipeListener void IRunPipeListener.Start(RunPipe pipe) { CheckCanceled(); HandleTestStart(pipe); } void IRunPipeListener.Success(RunPipe pipe, ReportRun result) { HandleTestFinish(pipe, result); } void IRunPipeListener.Failure(RunPipe pipe, ReportRun result) { HandleTestFinish(pipe, result); } void IRunPipeListener.Ignore(RunPipe pipe, ReportRun result) { HandleTestFinish(pipe, result); } void IRunPipeListener.Skip(RunPipe pipe, ReportRun result) { HandleTestFinish(pipe, result); } #endregion private void HandleAssemblyStart() { ITestContext assemblyTestContext = assemblyTestCommand.StartPrimaryChildStep(topTestStep); activeTestContexts.Add(assemblyTestCommand, assemblyTestContext); } private void HandleAssemblyFinish(TestOutcome outcome) { ITestContext assemblyTestContext = activeTestContexts[assemblyTestCommand]; activeTestContexts.Remove(assemblyTestCommand); // only update status if more severe if (outcome.Status > assemblyTestOutcome.Status) assemblyTestOutcome = outcome; assemblyTestResult = assemblyTestContext.FinishStep(assemblyTestOutcome, null); } private void HandleFixtureStart(Fixture fixture) { ITestCommand fixtureTestCommand; if (!fixtureTestCommands.TryGetValue(fixture, out fixtureTestCommand)) return; ITestContext assemblyTestContext; if (!activeTestContexts.TryGetValue(assemblyTestCommand, out assemblyTestContext)) return; ITestContext fixtureTestContext = fixtureTestCommand.StartPrimaryChildStep(assemblyTestContext.TestStep); activeTestContexts.Add(fixtureTestCommand, fixtureTestContext); } private void HandleFixtureFinish(Fixture fixture, ReportRunResult reportRunResult) { ITestCommand fixtureTestCommand; if (!fixtureTestCommands.TryGetValue(fixture, out fixtureTestCommand)) return; ITestContext fixtureTestContext = activeTestContexts[fixtureTestCommand]; activeTestContexts.Remove(fixtureTestCommand); FinishStepWithReportRunResult(fixtureTestContext, reportRunResult); } private void HandleTestStart(RunPipe runPipe) { ITestCommand runPipeTestCommand; if (!runPipeTestCommands.TryGetValue(runPipe, out runPipeTestCommand)) return; ITestCommand fixtureTestCommand; if (!fixtureTestCommands.TryGetValue(runPipe.Fixture, out fixtureTestCommand)) return; ITestContext fixtureTestContext; if (!activeTestContexts.TryGetValue(fixtureTestCommand, out fixtureTestContext)) return; progressMonitor.SetStatus(runPipeTestCommand.Test.Name); ITestContext runPipeTestContext = runPipeTestCommand.StartPrimaryChildStep(fixtureTestContext.TestStep); activeTestContexts.Add(runPipeTestCommand, runPipeTestContext); runPipeTestContext.LifecyclePhase = LifecyclePhases.Execute; } private void HandleTestFinish(RunPipe runPipe, ReportRun reportRun) { ITestCommand runPipeTestCommand; if (runPipeTestCommands.TryGetValue(runPipe, out runPipeTestCommand)) { ITestContext testContext = activeTestContexts[runPipeTestCommand]; activeTestContexts.Remove(runPipeTestCommand); // Output all execution log contents. // Note: ReportRun.Asserts is not actually populated by MbUnit so we ignore it. if (reportRun.ConsoleOut.Length != 0) { testContext.LogWriter.ConsoleOutput.Write(reportRun.ConsoleOut); } if (reportRun.ConsoleError.Length != 0) { testContext.LogWriter.ConsoleError.Write(reportRun.ConsoleError); } foreach (ReportWarning warning in reportRun.Warnings) { testContext.LogWriter.Warnings.WriteLine(warning.Text); } if (reportRun.Exception != null) { testContext.LogWriter.Failures.WriteException(GetExceptionDataFromReportException(reportRun.Exception), "Exception"); } // Finish up... testContext.AddAssertCount(reportRun.AssertCount); FinishStepWithReportRunResult(testContext, reportRun.Result); } progressMonitor.Worked(workUnit); } private void HandleCanceled(object sender, EventArgs e) { Abort(); } /// <summary> /// Checks for requested cancelation. /// </summary> /// <remarks> /// <para> /// MbUnit's handling of Abort() isn't very robust. It is susceptible to /// race conditions in various placed. For example, the fixture runner resets /// its AbortPending flag when Run is invoked. It is possible that this /// will prevent the abort from succeeding if it happens too early. /// </para> /// </remarks> private void CheckCanceled() { if (progressMonitor.IsCanceled) Abort(); } private void FinishStepWithReportRunResult(ITestContext testContext, ReportRunResult reportRunResult) { TestOutcome outcome = GetOutcomeFromReportRunResult(reportRunResult); testContext.FinishStep(outcome, null); // only update assembly status if more severe if (outcome.Status > assemblyTestOutcome.Status) assemblyTestOutcome = outcome; } private static TestOutcome GetOutcomeFromReportRunResult(ReportRunResult reportRunResult) { switch (reportRunResult) { case ReportRunResult.NotRun: case ReportRunResult.Skip: return TestOutcome.Skipped; case ReportRunResult.Ignore: return TestOutcome.Ignored; case ReportRunResult.Success: return TestOutcome.Passed; case ReportRunResult.Failure: return TestOutcome.Failed; default: throw new ArgumentException("Unsupported report run result.", "reportRunResult"); } } private static ExceptionData GetExceptionDataFromReportException(ReportException ex) { PropertySet properties = null; foreach (object obj in ex.Properties) { ReportProperty property = obj as ReportProperty; if (property != null && property.Value != null) { if (properties == null) properties = new PropertySet(); properties[property.Name] = property.Value; } } return new ExceptionData(ex.Type ?? "", ex.Message ?? "", ex.StackTrace ?? "", properties ?? ExceptionData.NoProperties, ex.Exception != null ? GetExceptionDataFromReportException(ex.Exception) : null); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime; using System.Reflection; using System.Runtime.CompilerServices; using System.Diagnostics; using Internal.Reflection.Core.NonPortable; using Internal.Runtime.Augments; namespace System { [System.Runtime.CompilerServices.DependencyReductionRoot] public static class InvokeUtils { // // Various reflection scenarios (Array.SetValue(), reflection Invoke, delegate DynamicInvoke and FieldInfo.Set()) perform // automatic conveniences such as automatically widening primitive types to fit the destination type. // // This method attempts to collect as much of that logic as possible in place. (This may not be completely possible // as the desktop CLR is not particularly consistent across all these scenarios either.) // // The transforms supported are: // // Value-preserving widenings of primitive integrals and floats. // Enums can be converted to the same or wider underlying primitive. // Primitives can be converted to an enum with the same or wider underlying primitive. // // null converted to default(T) (this is important when T is a valuetype.) // // There is also another transform of T -> Nullable<T>. This method acknowleges that rule but does not actually transform the T. // Rather, the transformation happens naturally when the caller unboxes the value to its final destination. // // This method is targeted by the Delegate ILTransformer. // // public static Object CheckArgument(Object srcObject, RuntimeTypeHandle dstType, BinderBundle binderBundle) { EETypePtr dstEEType = dstType.ToEETypePtr(); return CheckArgument(srcObject, dstEEType, CheckArgumentSemantics.DynamicInvoke, binderBundle, getExactTypeForCustomBinder: null); } // This option tweaks the coercion rules to match classic inconsistencies. internal enum CheckArgumentSemantics { ArraySet, // Throws InvalidCastException DynamicInvoke, // Throws ArgumentException SetFieldDirect, // Throws ArgumentException - other than that, like DynamicInvoke except that enums and integers cannot be intermingled, and null cannot substitute for default(valuetype). } internal static Object CheckArgument(Object srcObject, EETypePtr dstEEType, CheckArgumentSemantics semantics, BinderBundle binderBundle, Func<Type> getExactTypeForCustomBinder = null) { if (srcObject == null) { // null -> default(T) if (dstEEType.IsValueType && !dstEEType.IsNullable) { if (semantics == CheckArgumentSemantics.SetFieldDirect) throw CreateChangeTypeException(CommonRuntimeTypes.Object.TypeHandle.ToEETypePtr(), dstEEType, semantics); return Runtime.RuntimeImports.RhNewObject(dstEEType); } else { return null; } } else { EETypePtr srcEEType = srcObject.EETypePtr; if (RuntimeImports.AreTypesAssignable(srcEEType, dstEEType)) return srcObject; if (dstEEType.IsInterface) { ICastable castable = srcObject as ICastable; Exception castError; if (castable != null && castable.IsInstanceOfInterface(new RuntimeTypeHandle(dstEEType), out castError)) return srcObject; } object dstObject; Exception exception = ConvertOrWidenPrimitivesEnumsAndPointersIfPossible(srcObject, srcEEType, dstEEType, semantics, out dstObject); if (exception == null) return dstObject; if (binderBundle == null) throw exception; // Our normal coercion rules could not convert the passed in argument but we were supplied a custom binder. See if it can do it. Type exactDstType; if (getExactTypeForCustomBinder == null) { // We were called by someone other than DynamicInvokeParamHelperCore(). Those callers pass the correct dstEEType. exactDstType = Type.GetTypeFromHandle(new RuntimeTypeHandle(dstEEType)); } else { // We were called by DynamicInvokeParamHelperCore(). He passes a dstEEType that enums folded to int and possibly other adjustments. A custom binder // is app code however and needs the exact type. exactDstType = getExactTypeForCustomBinder(); } srcObject = binderBundle.ChangeType(srcObject, exactDstType); // For compat with desktop, the result of the binder call gets processed through the default rules again. dstObject = CheckArgument(srcObject, dstEEType, semantics, binderBundle: null, getExactTypeForCustomBinder: null); return dstObject; } } // Special coersion rules for primitives, enums and pointer. private static Exception ConvertOrWidenPrimitivesEnumsAndPointersIfPossible(object srcObject, EETypePtr srcEEType, EETypePtr dstEEType, CheckArgumentSemantics semantics, out object dstObject) { if (semantics == CheckArgumentSemantics.SetFieldDirect && (srcEEType.IsEnum || dstEEType.IsEnum)) { dstObject = null; return CreateChangeTypeException(srcEEType, dstEEType, semantics); } if (!((srcEEType.IsEnum || srcEEType.IsPrimitive) && (dstEEType.IsEnum || dstEEType.IsPrimitive || dstEEType.IsPointer))) { dstObject = null; return CreateChangeTypeException(srcEEType, dstEEType, semantics); } if (dstEEType.IsPointer) { dstObject = null; return new NotImplementedException(); //TODO: https://github.com/dotnet/corert/issues/2113 } RuntimeImports.RhCorElementType dstCorElementType = dstEEType.CorElementType; if (!srcEEType.CorElementTypeInfo.CanWidenTo(dstCorElementType)) { dstObject = null; return CreateChangeTypeArgumentException(srcEEType, dstEEType); } switch (dstCorElementType) { case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN: dstObject = Convert.ToBoolean(srcObject); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR: dstObject = Convert.ToChar(srcObject); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1: dstObject = Convert.ToSByte(srcObject); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2: dstObject = Convert.ToInt16(srcObject); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4: dstObject = Convert.ToInt32(srcObject); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8: dstObject = Convert.ToInt64(srcObject); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1: dstObject = Convert.ToByte(srcObject); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2: dstObject = Convert.ToUInt16(srcObject); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4: dstObject = Convert.ToUInt32(srcObject); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8: dstObject = Convert.ToUInt64(srcObject); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_R4: if (srcEEType.CorElementType == RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR) { dstObject = (float)(char)srcObject; } else { dstObject = Convert.ToSingle(srcObject); } break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_R8: if (srcEEType.CorElementType == RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR) { dstObject = (double)(char)srcObject; } else { dstObject = Convert.ToDouble(srcObject); } break; default: Debug.Assert(false, "Unexpected CorElementType: " + dstCorElementType + ": Not a valid widening target."); dstObject = null; return CreateChangeTypeException(srcEEType, dstEEType, semantics); } if (dstEEType.IsEnum) { Type dstType = ReflectionCoreNonPortable.GetRuntimeTypeForEEType(dstEEType); dstObject = Enum.ToObject(dstType, dstObject); } Debug.Assert(dstObject.EETypePtr == dstEEType); return null; } private static Exception CreateChangeTypeException(EETypePtr srcEEType, EETypePtr dstEEType, CheckArgumentSemantics semantics) { switch (semantics) { case CheckArgumentSemantics.DynamicInvoke: case CheckArgumentSemantics.SetFieldDirect: return CreateChangeTypeArgumentException(srcEEType, dstEEType); case CheckArgumentSemantics.ArraySet: return CreateChangeTypeInvalidCastException(srcEEType, dstEEType); default: Debug.Assert(false, "Unexpected CheckArgumentSemantics value: " + semantics); throw new InvalidOperationException(); } } private static ArgumentException CreateChangeTypeArgumentException(EETypePtr srcEEType, EETypePtr dstEEType) { return new ArgumentException(SR.Format(SR.Arg_ObjObjEx, Type.GetTypeFromHandle(new RuntimeTypeHandle(srcEEType)), Type.GetTypeFromHandle(new RuntimeTypeHandle(dstEEType)))); } private static InvalidCastException CreateChangeTypeInvalidCastException(EETypePtr srcEEType, EETypePtr dstEEType) { return new InvalidCastException(SR.InvalidCast_StoreArrayElement); } // ----------------------------------------------- // Infrastructure and logic for Dynamic Invocation // ----------------------------------------------- public enum DynamicInvokeParamType { In = 0, Ref = 1 } public enum DynamicInvokeParamLookupType { ValuetypeObjectReturned = 0, IndexIntoObjectArrayReturned = 1, } public struct ArgSetupState { public bool fComplete; public object[] nullableCopyBackObjects; } // These thread static fields are used instead of passing parameters normally through to the helper functions // that actually implement dynamic invocation. This allows the large number of dynamically generated // functions to be just that little bit smaller, which, when spread across the many invocation helper thunks // generated adds up quite a bit. [ThreadStatic] private static object[] s_parameters; [ThreadStatic] private static object[] s_nullableCopyBackObjects; [ThreadStatic] private static int s_curIndex; [ThreadStatic] private static object s_targetMethodOrDelegate; [ThreadStatic] private static BinderBundle s_binderBundle; [ThreadStatic] private static object[] s_customBinderProvidedParameters; private static object GetDefaultValue(RuntimeTypeHandle thType, int argIndex) { object targetMethodOrDelegate = s_targetMethodOrDelegate; if (targetMethodOrDelegate == null) { throw new ArgumentException(SR.Arg_DefaultValueMissingException); } object defaultValue; bool hasDefaultValue; Delegate delegateInstance = targetMethodOrDelegate as Delegate; if (delegateInstance != null) { hasDefaultValue = delegateInstance.TryGetDefaultParameterValue(thType, argIndex, out defaultValue); } else { hasDefaultValue = RuntimeAugments.Callbacks.TryGetDefaultParameterValue(targetMethodOrDelegate, thType, argIndex, out defaultValue); } if (!hasDefaultValue) { throw new ArgumentException(SR.Arg_DefaultValueMissingException); } // Note that we might return null even for value types which cannot have null value here. // This case is handled in the CheckArgument method which is called after this one on the returned parameter value. return defaultValue; } // This is only called if we have to invoke a custom binder to coerce a parameter type. It leverages s_targetMethodOrDelegate to retrieve // the unaltered parameter type to pass to the binder. private static Type GetExactTypeForCustomBinder() { Debug.Assert(s_binderBundle != null && s_targetMethodOrDelegate is MethodBase); MethodBase method = (MethodBase)s_targetMethodOrDelegate; // DynamicInvokeParamHelperCore() increments s_curIndex before calling us - that's why we have to subtract 1. return method.GetParametersNoCopy()[s_curIndex - 1].ParameterType; } private static readonly Func<Type> s_getExactTypeForCustomBinder = GetExactTypeForCustomBinder; [DebuggerGuidedStepThroughAttribute] internal static object CallDynamicInvokeMethod( object thisPtr, IntPtr methodToCall, object thisPtrDynamicInvokeMethod, IntPtr dynamicInvokeHelperMethod, IntPtr dynamicInvokeHelperGenericDictionary, object targetMethodOrDelegate, object[] parameters, BinderBundle binderBundle, bool invokeMethodHelperIsThisCall = true, bool methodToCallIsThisCall = true) { // This assert is needed because we've double-purposed "targetMethodOrDelegate" (which is actually a MethodBase anytime a custom binder is used) // as a way of obtaining the true parameter type which we need to pass to Binder.ChangeType(). (The type normally passed to DynamicInvokeParamHelperCore // isn't always the exact type (byref stripped off, enums converted to int, etc.) Debug.Assert(!(binderBundle != null && !(targetMethodOrDelegate is MethodBase)), "The only callers that can pass a custom binder are those servicing MethodBase.Invoke() apis."); bool fDontWrapInTargetInvocationException = false; bool parametersNeedCopyBack = false; ArgSetupState argSetupState = default(ArgSetupState); // Capture state of thread static invoke helper statics object[] parametersOld = s_parameters; object[] nullableCopyBackObjectsOld = s_nullableCopyBackObjects; int curIndexOld = s_curIndex; object targetMethodOrDelegateOld = s_targetMethodOrDelegate; BinderBundle binderBundleOld = s_binderBundle; s_binderBundle = binderBundle; object[] customBinderProvidedParametersOld = s_customBinderProvidedParameters; s_customBinderProvidedParameters = null; try { // If the passed in array is not an actual object[] instance, we need to copy it over to an actual object[] // instance so that the rest of the code can safely create managed object references to individual elements. if (parameters != null && EETypePtr.EETypePtrOf<object[]>() != parameters.EETypePtr) { s_parameters = new object[parameters.Length]; Array.Copy(parameters, s_parameters, parameters.Length); parametersNeedCopyBack = true; } else { s_parameters = parameters; } s_nullableCopyBackObjects = null; s_curIndex = 0; s_targetMethodOrDelegate = targetMethodOrDelegate; try { object result = null; if (invokeMethodHelperIsThisCall) { Debug.Assert(methodToCallIsThisCall == true); result = CalliIntrinsics.Call(dynamicInvokeHelperMethod, thisPtrDynamicInvokeMethod, thisPtr, methodToCall, ref argSetupState); System.Diagnostics.DebugAnnotations.PreviousCallContainsDebuggerStepInCode(); } else { if (dynamicInvokeHelperGenericDictionary != IntPtr.Zero) { result = CalliIntrinsics.Call(dynamicInvokeHelperMethod, dynamicInvokeHelperGenericDictionary, thisPtr, methodToCall, ref argSetupState, methodToCallIsThisCall); DebugAnnotations.PreviousCallContainsDebuggerStepInCode(); } else { result = CalliIntrinsics.Call(dynamicInvokeHelperMethod, thisPtr, methodToCall, ref argSetupState, methodToCallIsThisCall); DebugAnnotations.PreviousCallContainsDebuggerStepInCode(); } } return result; } finally { if (parametersNeedCopyBack) { Array.Copy(s_parameters, parameters, parameters.Length); } if (!argSetupState.fComplete) { fDontWrapInTargetInvocationException = true; } else { // Nullable objects can't take advantage of the ability to update the boxed value on the heap directly, so perform // an update of the parameters array now. if (argSetupState.nullableCopyBackObjects != null) { for (int i = 0; i < argSetupState.nullableCopyBackObjects.Length; i++) { if (argSetupState.nullableCopyBackObjects[i] != null) { parameters[i] = DynamicInvokeBoxIntoNonNullable(argSetupState.nullableCopyBackObjects[i]); } } } } } } catch (Exception e) { if (fDontWrapInTargetInvocationException) { throw; } else { throw new System.Reflection.TargetInvocationException(e); } } finally { // Restore state of thread static helper statics s_parameters = parametersOld; s_nullableCopyBackObjects = nullableCopyBackObjectsOld; s_curIndex = curIndexOld; s_targetMethodOrDelegate = targetMethodOrDelegateOld; s_binderBundle = binderBundleOld; s_customBinderProvidedParameters = customBinderProvidedParametersOld; } } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] internal static void DynamicInvokeArgSetupComplete(ref ArgSetupState argSetupState) { int parametersLength = s_parameters != null ? s_parameters.Length : 0; if (s_curIndex != parametersLength) { throw new System.Reflection.TargetParameterCountException(); } argSetupState.fComplete = true; argSetupState.nullableCopyBackObjects = s_nullableCopyBackObjects; s_nullableCopyBackObjects = null; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] public static unsafe void DynamicInvokeArgSetupPtrComplete(IntPtr argSetupStatePtr) { // argSetupStatePtr is a pointer to a *pinned* ArgSetupState object DynamicInvokeArgSetupComplete(ref Unsafe.As<byte, ArgSetupState>(ref *(byte*)argSetupStatePtr)); } [System.Runtime.InteropServices.McgIntrinsicsAttribute] private static class CalliIntrinsics { [DebuggerStepThrough] internal static object Call( IntPtr dynamicInvokeHelperMethod, object thisPtrForDynamicInvokeHelperMethod, object thisPtr, IntPtr methodToCall, ref ArgSetupState argSetupState) { // This method is implemented elsewhere in the toolchain throw new PlatformNotSupportedException(); } [DebuggerStepThrough] internal static object Call( IntPtr dynamicInvokeHelperMethod, object thisPtr, IntPtr methodToCall, ref ArgSetupState argSetupState, bool isTargetThisCall) { // This method is implemented elsewhere in the toolchain throw new PlatformNotSupportedException(); } [DebuggerStepThrough] internal static object Call( IntPtr dynamicInvokeHelperMethod, IntPtr dynamicInvokeHelperGenericDictionary, object thisPtr, IntPtr methodToCall, ref ArgSetupState argSetupState, bool isTargetThisCall) { // This method is implemented elsewhere in the toolchain throw new PlatformNotSupportedException(); } } // Template function that is used to call dynamically internal static object DynamicInvokeThisCallTemplate(object thisPtr, IntPtr methodToCall, ref ArgSetupState argSetupState) { // This function will look like // // !For each parameter to the method // !if (parameter is In Parameter) // localX is TypeOfParameterX& // ldtoken TypeOfParameterX // call DynamicInvokeParamHelperIn(RuntimeTypeHandle) // stloc localX // !else // localX is TypeOfParameter // ldtoken TypeOfParameterX // call DynamicInvokeParamHelperRef(RuntimeTypeHandle) // stloc localX // ldarg.2 // call DynamicInvokeArgSetupComplete(ref ArgSetupState) // ldarg.0 // Load this pointer // !For each parameter // !if (parameter is In Parameter) // ldloc localX // ldobj TypeOfParameterX // !else // ldloc localX // ldarg.1 // calli ReturnType thiscall(TypeOfParameter1, ...) // !if ((ReturnType != void) && !(ReturnType is a byref) // ldnull // !else // box ReturnType // ret return null; } internal static object DynamicInvokeCallTemplate(object thisPtr, IntPtr methodToCall, ref ArgSetupState argSetupState, bool targetIsThisCall) { // This function will look like // // !For each parameter to the method // !if (parameter is In Parameter) // localX is TypeOfParameterX& // ldtoken TypeOfParameterX // call DynamicInvokeParamHelperIn(RuntimeTypeHandle) // stloc localX // !else // localX is TypeOfParameter // ldtoken TypeOfParameterX // call DynamicInvokeParamHelperRef(RuntimeTypeHandle) // stloc localX // ldarg.2 // call DynamicInvokeArgSetupComplete(ref ArgSetupState) // !if (targetIsThisCall) // ldarg.0 // Load this pointer // !For each parameter // !if (parameter is In Parameter) // ldloc localX // ldobj TypeOfParameterX // !else // ldloc localX // ldarg.1 // calli ReturnType thiscall(TypeOfParameter1, ...) // !if ((ReturnType != void) && !(ReturnType is a byref) // ldnull // !else // box ReturnType // ret // !else // !For each parameter // !if (parameter is In Parameter) // ldloc localX // ldobj TypeOfParameterX // !else // ldloc localX // ldarg.1 // calli ReturnType (TypeOfParameter1, ...) // !if ((ReturnType != void) && !(ReturnType is a byref) // ldnull // !else // box ReturnType // ret return null; } [DebuggerStepThrough] [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static void DynamicInvokeUnboxIntoActualNullable(object actualBoxedNullable, object boxedFillObject, EETypePtr nullableType) { // get a byref to the data within the actual boxed nullable, and then call RhUnBox with the boxedFillObject as the boxed object, and nullableType as the unbox type, and unbox into the actualBoxedNullable RuntimeImports.RhUnbox(boxedFillObject, ref actualBoxedNullable.GetRawData(), nullableType); } [DebuggerStepThrough] [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static object DynamicInvokeBoxIntoNonNullable(object actualBoxedNullable) { // grab the pointer to data, box using the EEType of the actualBoxedNullable, and then return the boxed object return RuntimeImports.RhBox(actualBoxedNullable.EETypePtr, ref actualBoxedNullable.GetRawData()); } [DebuggerStepThrough] [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] internal static ref IntPtr DynamicInvokeParamHelperIn(RuntimeTypeHandle rth) { // // Call DynamicInvokeParamHelperCore as an in parameter, and return a managed byref to the interesting bit. // // This function exactly matches DynamicInvokeParamHelperRef except for the value of the enum passed to DynamicInvokeParamHelperCore // int index; DynamicInvokeParamLookupType paramLookupType; object obj = DynamicInvokeParamHelperCore(rth, out paramLookupType, out index, DynamicInvokeParamType.In); if (paramLookupType == DynamicInvokeParamLookupType.ValuetypeObjectReturned) { return ref Unsafe.As<byte, IntPtr>(ref obj.GetRawData()); } else { return ref Unsafe.As<object, IntPtr>(ref Unsafe.As<object[]>(obj)[index]); } } [DebuggerStepThrough] [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] internal static ref IntPtr DynamicInvokeParamHelperRef(RuntimeTypeHandle rth) { // // Call DynamicInvokeParamHelperCore as a ref parameter, and return a managed byref to the interesting bit. As this can't actually be defined in C# there is an IL transform that fills this in. // // This function exactly matches DynamicInvokeParamHelperIn except for the value of the enum passed to DynamicInvokeParamHelperCore // int index; DynamicInvokeParamLookupType paramLookupType; object obj = DynamicInvokeParamHelperCore(rth, out paramLookupType, out index, DynamicInvokeParamType.Ref); if (paramLookupType == DynamicInvokeParamLookupType.ValuetypeObjectReturned) { return ref Unsafe.As<byte, IntPtr>(ref obj.GetRawData()); } else { return ref Unsafe.As<object, IntPtr>(ref Unsafe.As<object[]>(obj)[index]); } } internal static object DynamicInvokeBoxedValuetypeReturn(out DynamicInvokeParamLookupType paramLookupType, object boxedValuetype, int index, RuntimeTypeHandle type, DynamicInvokeParamType paramType) { object finalObjectToReturn = boxedValuetype; EETypePtr eeType = type.ToEETypePtr(); bool nullable = eeType.IsNullable; if (finalObjectToReturn == null || nullable || paramType == DynamicInvokeParamType.Ref) { finalObjectToReturn = RuntimeImports.RhNewObject(eeType); if (boxedValuetype != null) { DynamicInvokeUnboxIntoActualNullable(finalObjectToReturn, boxedValuetype, eeType); } } if (nullable) { if (paramType == DynamicInvokeParamType.Ref) { if (s_nullableCopyBackObjects == null) { s_nullableCopyBackObjects = new object[s_parameters.Length]; } s_nullableCopyBackObjects[index] = finalObjectToReturn; s_parameters[index] = null; } } else { System.Diagnostics.Debug.Assert(finalObjectToReturn != null); if (paramType == DynamicInvokeParamType.Ref) s_parameters[index] = finalObjectToReturn; } paramLookupType = DynamicInvokeParamLookupType.ValuetypeObjectReturned; return finalObjectToReturn; } public static object DynamicInvokeParamHelperCore(RuntimeTypeHandle type, out DynamicInvokeParamLookupType paramLookupType, out int index, DynamicInvokeParamType paramType) { index = s_curIndex++; int parametersLength = s_parameters != null ? s_parameters.Length : 0; if (index >= parametersLength) throw new System.Reflection.TargetParameterCountException(); object incomingParam = s_parameters[index]; // Handle default parameters if ((incomingParam == System.Reflection.Missing.Value) && paramType == DynamicInvokeParamType.In) { incomingParam = GetDefaultValue(type, index); // The default value is captured into the parameters array s_parameters[index] = incomingParam; } RuntimeTypeHandle widenAndCompareType = type; bool nullable = type.ToEETypePtr().IsNullable; if (nullable) { widenAndCompareType = new RuntimeTypeHandle(type.ToEETypePtr().NullableType); } if (widenAndCompareType.ToEETypePtr().IsPrimitive || type.ToEETypePtr().IsEnum) { // Nullable requires exact matching if (incomingParam != null) { if (nullable || paramType == DynamicInvokeParamType.Ref) { if (widenAndCompareType.ToEETypePtr() != incomingParam.EETypePtr) { if (s_binderBundle == null) throw CreateChangeTypeArgumentException(incomingParam.EETypePtr, type.ToEETypePtr()); Type exactDstType = GetExactTypeForCustomBinder(); incomingParam = s_binderBundle.ChangeType(incomingParam, exactDstType); if (incomingParam != null && widenAndCompareType.ToEETypePtr() != incomingParam.EETypePtr) throw CreateChangeTypeArgumentException(incomingParam.EETypePtr, type.ToEETypePtr()); } } else { if (widenAndCompareType.ToEETypePtr().CorElementType != incomingParam.EETypePtr.CorElementType) { System.Diagnostics.Debug.Assert(paramType == DynamicInvokeParamType.In); incomingParam = InvokeUtils.CheckArgument(incomingParam, widenAndCompareType.ToEETypePtr(), InvokeUtils.CheckArgumentSemantics.DynamicInvoke, s_binderBundle, s_getExactTypeForCustomBinder); } } } return DynamicInvokeBoxedValuetypeReturn(out paramLookupType, incomingParam, index, type, paramType); } else if (type.ToEETypePtr().IsValueType) { incomingParam = InvokeUtils.CheckArgument(incomingParam, type.ToEETypePtr(), InvokeUtils.CheckArgumentSemantics.DynamicInvoke, s_binderBundle, s_getExactTypeForCustomBinder); if (s_binderBundle == null) { System.Diagnostics.Debug.Assert(s_parameters[index] == null || Object.ReferenceEquals(incomingParam, s_parameters[index])); } return DynamicInvokeBoxedValuetypeReturn(out paramLookupType, incomingParam, index, type, paramType); } else { incomingParam = InvokeUtils.CheckArgument(incomingParam, widenAndCompareType.ToEETypePtr(), InvokeUtils.CheckArgumentSemantics.DynamicInvoke, s_binderBundle, s_getExactTypeForCustomBinder); paramLookupType = DynamicInvokeParamLookupType.IndexIntoObjectArrayReturned; if (s_binderBundle == null) { System.Diagnostics.Debug.Assert(Object.ReferenceEquals(incomingParam, s_parameters[index])); return s_parameters; } else { if (object.ReferenceEquals(incomingParam, s_parameters[index])) { return s_parameters; } else { // If we got here, the original argument object was superceded by invoking the custom binder. if (paramType == DynamicInvokeParamType.Ref) { s_parameters[index] = incomingParam; return s_parameters; } else { // Since this not a by-ref parameter, we don't want to bash the original user-owned argument array but the rules of DynamicInvokeParamHelperCore() require // that we return non-value types as the "index"th element in an array. Thus, create an on-demand throwaway array just for this purpose. if (s_customBinderProvidedParameters == null) { s_customBinderProvidedParameters = new object[s_parameters.Length]; } s_customBinderProvidedParameters[index] = incomingParam; return s_customBinderProvidedParameters; } } } } } } }
// Created by Paul Gonzalez Becerra using System; using Saserdote.DataSystems; using Saserdote.GamingServices; using Saserdote.Input; namespace Saserdote.UI { public class GUIContainer:GUIComponent { #region --- Field Variables --- // Variables public GUIComponent focusedComp; protected FList<GUIComponent> components; #endregion // Field Variables #region --- Constructors --- protected GUIContainer():base() { components= new FList<GUIComponent>(); focusedComp= null; pSprite= null; } #endregion // Constructors #region --- Properties --- // Gets the soze of the components of the container public int containerSize { get { return components.size; } } // Gets and sets the items of the list of components public GUIComponent this[int index] { get { return components[index]; } set { components[index]= value; if(onComponentsChanged!= null) onComponentsChanged(this); } } #endregion // Properties #region --- Events --- // Event for when the list of components have changed public event GEvent onComponentsChanged; #endregion // Events #region --- Methods --- // Clears the components on the list public void clear() { components.clear(); focusedComp= null; if(onComponentsChanged!= null) onComponentsChanged(this); } // Adds the given component into the list of components public bool add(GUIComponent comp) { // Variables bool bFirst= (containerSize== 0); if(components.add(comp)) { components.items[containerSize-1].parent= this; components.items[containerSize-1].setGUI(ref gui); if(bFirst) focusedComp= components.items[0]; if(onComponentsChanged!= null) onComponentsChanged(this); return true; } return false; } // Adds the given array of components into the list of components public bool addRange(params GUIComponent[] comps) { // Variables int startIndex= containerSize; bool bFirst= (startIndex== 0); if(components.addRange(comps)) { for(int i= startIndex; i< containerSize; i++) { components.items[i].parent= this; components.items[i].setGUI(ref gui); } if(bFirst) focusedComp= components.items[0]; if(onComponentsChanged!= null) onComponentsChanged(this); return true; } return false; } // Finds if the given component is contained within the container public bool contains(GUIComponent comp, int startIndex) { return components.contains(comp, startIndex); } public bool contains(GUIComponent comp) { return contains(comp, 0); } // Gets the index of the given component public int getIndex(GUIComponent comp, int startIndex) { return components.getIndex(comp, startIndex); } public int getIndex(GUIComponent comp) { return getIndex(comp, 0); } // Removes the gui component from the list of components public bool remove(GUIComponent comp, int startIndex) { if(components.remove(comp, startIndex)) { if(focusedComp== comp || containerSize== 0) focusedComp= null; if(onComponentsChanged!= null) onComponentsChanged(this); return true; } return false; } public bool remove(GUIComponent comp) { return remove(comp, 0); } // Inserts the given components into the given index public void insert(GUIComponent comp, int index) { // Variables bool bFirst= (containerSize== 0); components.insert(comp, index); if(bFirst) focusedComp= components.items[0]; if(onComponentsChanged!= null) onComponentsChanged(this); } // Removes the components of the given index public bool removeAt(int index) { if(index< 0 || index>= containerSize) return false; if(focusedComp== components.items[index]) focusedComp= null; if(components.removeAt(index)) { if(containerSize== 0) focusedComp= null; if(onComponentsChanged!= null) onComponentsChanged(this); return true; } return false; } #endregion // Methods #region --- Inherited Methods --- // Renders the gui component public override void render(ref GameTime time, ref Game game) { for(int i= 0; i< containerSize; i++) components.items[i].render(ref time, ref game); base.render(ref time, ref game); } // Updates the gui component public override void update(ref GameTime time, ref Game game) { for(int i= 0; i< containerSize; i++) components.items[i].update(ref time, ref game); base.update(ref time, ref game); } // Handles the component's input public override void handleInput(ref InputArgs args) { for(int i= 0; i< containerSize; i++) components.items[i].handleInput(ref args); base.handleInput(ref args); } // Sets the gui to the given gui internal override void setGUI(ref GUI pmGUI) { base.setGUI(ref pmGUI); for(int i= 0; i< containerSize; i++) components.items[i].setGUI(ref pmGUI); } // Resizes the sprite of the component internal override void resize() { base.resize(); for(int i= 0; i< containerSize; i++) components.items[i].resize(); } #endregion // Inherited Methods } } // End of File
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Globalization; using System.Net; using System.Reflection; using System.Xml; using log4net; using OpenMetaverse; //using OpenSim.Framework.Console; namespace OpenSim.Framework { public class ConfigurationMember { #region Delegates public delegate bool ConfigurationOptionResult(string configuration_key, object configuration_result); public delegate void ConfigurationOptionsLoad(); #endregion private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private int cE = 0; private string configurationDescription = String.Empty; private string configurationFilename = String.Empty; private XmlNode configurationFromXMLNode = null; private List<ConfigurationOption> configurationOptions = new List<ConfigurationOption>(); private IGenericConfig configurationPlugin = null; /// <summary> /// This is the default configuration DLL loaded /// </summary> private string configurationPluginFilename = "OpenSim.Framework.Configuration.XML.dll"; private ConfigurationOptionsLoad loadFunction; private ConfigurationOptionResult resultFunction; private bool useConsoleToPromptOnError = true; public ConfigurationMember(string configuration_filename, string configuration_description, ConfigurationOptionsLoad load_function, ConfigurationOptionResult result_function, bool use_console_to_prompt_on_error) { configurationFilename = configuration_filename; configurationDescription = configuration_description; loadFunction = load_function; resultFunction = result_function; useConsoleToPromptOnError = use_console_to_prompt_on_error; } public ConfigurationMember(XmlNode configuration_xml, string configuration_description, ConfigurationOptionsLoad load_function, ConfigurationOptionResult result_function, bool use_console_to_prompt_on_error) { configurationFilename = String.Empty; configurationFromXMLNode = configuration_xml; configurationDescription = configuration_description; loadFunction = load_function; resultFunction = result_function; useConsoleToPromptOnError = use_console_to_prompt_on_error; } public void setConfigurationFilename(string filename) { configurationFilename = filename; } public void setConfigurationDescription(string desc) { configurationDescription = desc; } public void setConfigurationResultFunction(ConfigurationOptionResult result) { resultFunction = result; } public void forceConfigurationPluginLibrary(string dll_filename) { configurationPluginFilename = dll_filename; } private void checkAndAddConfigOption(ConfigurationOption option) { if ((option.configurationKey != String.Empty && option.configurationQuestion != String.Empty) || (option.configurationKey != String.Empty && option.configurationUseDefaultNoPrompt)) { if (!configurationOptions.Contains(option)) { configurationOptions.Add(option); } } else { m_log.Info( "Required fields for adding a configuration option is invalid. Will not add this option (" + option.configurationKey + ")"); } } public void addConfigurationOption(string configuration_key, ConfigurationOption.ConfigurationTypes configuration_type, string configuration_question, string configuration_default, bool use_default_no_prompt) { ConfigurationOption configOption = new ConfigurationOption(); configOption.configurationKey = configuration_key; configOption.configurationQuestion = configuration_question; configOption.configurationDefault = configuration_default; configOption.configurationType = configuration_type; configOption.configurationUseDefaultNoPrompt = use_default_no_prompt; configOption.shouldIBeAsked = null; //Assumes true, I can ask whenever checkAndAddConfigOption(configOption); } public void addConfigurationOption(string configuration_key, ConfigurationOption.ConfigurationTypes configuration_type, string configuration_question, string configuration_default, bool use_default_no_prompt, ConfigurationOption.ConfigurationOptionShouldBeAsked shouldIBeAskedDelegate) { ConfigurationOption configOption = new ConfigurationOption(); configOption.configurationKey = configuration_key; configOption.configurationQuestion = configuration_question; configOption.configurationDefault = configuration_default; configOption.configurationType = configuration_type; configOption.configurationUseDefaultNoPrompt = use_default_no_prompt; configOption.shouldIBeAsked = shouldIBeAskedDelegate; checkAndAddConfigOption(configOption); } // TEMP - REMOVE public void performConfigurationRetrieve() { if (cE > 1) m_log.Error("READING CONFIGURATION COUT: " + cE.ToString()); configurationPlugin = LoadConfigDll(configurationPluginFilename); configurationOptions.Clear(); if (loadFunction == null) { m_log.Error("Load Function for '" + configurationDescription + "' is null. Refusing to run configuration."); return; } if (resultFunction == null) { m_log.Error("Result Function for '" + configurationDescription + "' is null. Refusing to run configuration."); return; } //m_log.Debug("[CONFIG]: Calling Configuration Load Function..."); loadFunction(); if (configurationOptions.Count <= 0) { m_log.Error("[CONFIG]: No configuration options were specified for '" + configurationOptions + "'. Refusing to continue configuration."); return; } bool useFile = true; if (configurationPlugin == null) { m_log.Error("[CONFIG]: Configuration Plugin NOT LOADED!"); return; } if (configurationFilename.Trim() != String.Empty) { configurationPlugin.SetFileName(configurationFilename); try { configurationPlugin.LoadData(); useFile = true; } catch (XmlException e) { m_log.WarnFormat("[CONFIG] Not using {0}: {1}", configurationFilename, e.Message.ToString()); //m_log.Error("Error loading " + configurationFilename + ": " + e.ToString()); useFile = false; } } else { if (configurationFromXMLNode != null) { m_log.Info("Loading from XML Node, will not save to the file"); configurationPlugin.LoadDataFromString(configurationFromXMLNode.OuterXml); } m_log.Info("XML Configuration Filename is not valid; will not save to the file."); useFile = false; } foreach (ConfigurationOption configOption in configurationOptions) { bool convertSuccess = false; object return_result = null; string errorMessage = String.Empty; bool ignoreNextFromConfig = false; while (convertSuccess == false) { string console_result = String.Empty; string attribute = null; if (useFile || configurationFromXMLNode != null) { if (!ignoreNextFromConfig) { attribute = configurationPlugin.GetAttribute(configOption.configurationKey); } else { ignoreNextFromConfig = false; } } if (attribute == null) { if (configOption.configurationUseDefaultNoPrompt || useConsoleToPromptOnError == false) { console_result = configOption.configurationDefault; } else { if ((configOption.shouldIBeAsked != null && configOption.shouldIBeAsked(configOption.configurationKey)) || configOption.shouldIBeAsked == null) { if (configurationDescription.Trim() != String.Empty) { console_result = MainConsole.Instance.CmdPrompt( configurationDescription + ": " + configOption.configurationQuestion, configOption.configurationDefault); } else { console_result = MainConsole.Instance.CmdPrompt(configOption.configurationQuestion, configOption.configurationDefault); } } else { //Dont Ask! Just use default console_result = configOption.configurationDefault; } } } else { console_result = attribute; } // if the first character is a "$", assume it's the name // of an environment variable and substitute with the value of that variable if (console_result.StartsWith("$")) console_result = Environment.GetEnvironmentVariable(console_result.Substring(1)); switch (configOption.configurationType) { case ConfigurationOption.ConfigurationTypes.TYPE_STRING: return_result = console_result; convertSuccess = true; break; case ConfigurationOption.ConfigurationTypes.TYPE_STRING_NOT_EMPTY: if (console_result.Length > 0) { return_result = console_result; convertSuccess = true; } errorMessage = "a string that is not empty"; break; case ConfigurationOption.ConfigurationTypes.TYPE_BOOLEAN: bool boolResult; if (Boolean.TryParse(console_result, out boolResult)) { convertSuccess = true; return_result = boolResult; } errorMessage = "'true' or 'false' (Boolean)"; break; case ConfigurationOption.ConfigurationTypes.TYPE_BYTE: byte byteResult; if (Byte.TryParse(console_result, out byteResult)) { convertSuccess = true; return_result = byteResult; } errorMessage = "a byte (Byte)"; break; case ConfigurationOption.ConfigurationTypes.TYPE_CHARACTER: char charResult; if (Char.TryParse(console_result, out charResult)) { convertSuccess = true; return_result = charResult; } errorMessage = "a character (Char)"; break; case ConfigurationOption.ConfigurationTypes.TYPE_INT16: short shortResult; if (Int16.TryParse(console_result, out shortResult)) { convertSuccess = true; return_result = shortResult; } errorMessage = "a signed 32 bit integer (short)"; break; case ConfigurationOption.ConfigurationTypes.TYPE_INT32: int intResult; if (Int32.TryParse(console_result, out intResult)) { convertSuccess = true; return_result = intResult; } errorMessage = "a signed 32 bit integer (int)"; break; case ConfigurationOption.ConfigurationTypes.TYPE_INT64: long longResult; if (Int64.TryParse(console_result, out longResult)) { convertSuccess = true; return_result = longResult; } errorMessage = "a signed 32 bit integer (long)"; break; case ConfigurationOption.ConfigurationTypes.TYPE_IP_ADDRESS: IPAddress ipAddressResult; if (IPAddress.TryParse(console_result, out ipAddressResult)) { convertSuccess = true; return_result = ipAddressResult; } errorMessage = "an IP Address (IPAddress)"; break; case ConfigurationOption.ConfigurationTypes.TYPE_UUID: UUID uuidResult; if (UUID.TryParse(console_result, out uuidResult)) { convertSuccess = true; return_result = uuidResult; } errorMessage = "a UUID (UUID)"; break; case ConfigurationOption.ConfigurationTypes.TYPE_UUID_NULL_FREE: UUID uuidResult2; if (UUID.TryParse(console_result, out uuidResult2)) { convertSuccess = true; if (uuidResult2 == UUID.Zero) uuidResult2 = UUID.Random(); return_result = uuidResult2; } errorMessage = "a non-null UUID (UUID)"; break; case ConfigurationOption.ConfigurationTypes.TYPE_Vector3: Vector3 vectorResult; if (Vector3.TryParse(console_result, out vectorResult)) { convertSuccess = true; return_result = vectorResult; } errorMessage = "a vector (Vector3)"; break; case ConfigurationOption.ConfigurationTypes.TYPE_UINT16: ushort ushortResult; if (UInt16.TryParse(console_result, out ushortResult)) { convertSuccess = true; return_result = ushortResult; } errorMessage = "an unsigned 16 bit integer (ushort)"; break; case ConfigurationOption.ConfigurationTypes.TYPE_UINT32: uint uintResult; if (UInt32.TryParse(console_result, out uintResult)) { convertSuccess = true; return_result = uintResult; } errorMessage = "an unsigned 32 bit integer (uint)"; break; case ConfigurationOption.ConfigurationTypes.TYPE_UINT64: ulong ulongResult; if (UInt64.TryParse(console_result, out ulongResult)) { convertSuccess = true; return_result = ulongResult; } errorMessage = "an unsigned 64 bit integer (ulong)"; break; case ConfigurationOption.ConfigurationTypes.TYPE_FLOAT: float floatResult; if ( float.TryParse(console_result, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, Culture.NumberFormatInfo, out floatResult)) { convertSuccess = true; return_result = floatResult; } errorMessage = "a single-precision floating point number (float)"; break; case ConfigurationOption.ConfigurationTypes.TYPE_DOUBLE: double doubleResult; if ( Double.TryParse(console_result, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, Culture.NumberFormatInfo, out doubleResult)) { convertSuccess = true; return_result = doubleResult; } errorMessage = "an double-precision floating point number (double)"; break; } if (convertSuccess) { if (useFile) { configurationPlugin.SetAttribute(configOption.configurationKey, console_result); } if (!resultFunction(configOption.configurationKey, return_result)) { m_log.Info( "The handler for the last configuration option denied that input, please try again."); convertSuccess = false; ignoreNextFromConfig = true; } } else { if (configOption.configurationUseDefaultNoPrompt) { m_log.Error(string.Format( "[CONFIG]: [{3}]:[{1}] is not valid default for parameter [{0}].\nThe configuration result must be parsable to {2}.\n", configOption.configurationKey, console_result, errorMessage, configurationFilename)); convertSuccess = true; } else { m_log.Warn(string.Format( "[CONFIG]: [{3}]:[{1}] is not a valid value [{0}].\nThe configuration result must be parsable to {2}.\n", configOption.configurationKey, console_result, errorMessage, configurationFilename)); ignoreNextFromConfig = true; } } } } if (useFile) { configurationPlugin.Commit(); configurationPlugin.Close(); } } private static IGenericConfig LoadConfigDll(string dllName) { Assembly pluginAssembly = Assembly.LoadFrom(dllName); IGenericConfig plug = null; foreach (Type pluginType in pluginAssembly.GetTypes()) { if (pluginType.IsPublic) { if (!pluginType.IsAbstract) { Type typeInterface = pluginType.GetInterface("IGenericConfig", true); if (typeInterface != null) { plug = (IGenericConfig) Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString())); } } } } pluginAssembly = null; return plug; } public void forceSetConfigurationOption(string configuration_key, string configuration_value) { configurationPlugin.LoadData(); configurationPlugin.SetAttribute(configuration_key, configuration_value); configurationPlugin.Commit(); configurationPlugin.Close(); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using TestCodeMetrics.Areas.HelpPage.ModelDescriptions; using TestCodeMetrics.Areas.HelpPage.Models; namespace TestCodeMetrics.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } if (complexTypeDescription != null) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://github.com/jskeet/dotnet-protobufs/ // Original C++/Java/Python code: // http://code.google.com/p/protobuf/ // // 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 Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections.Generic; using ExtensionByNameMap = System.Collections.Generic.Dictionary<object, System.Collections.Generic.Dictionary<string, Google.ProtocolBuffers.IGeneratedExtensionLite>>; using ExtensionByIdMap = System.Collections.Generic.Dictionary<Google.ProtocolBuffers.ExtensionRegistry.ExtensionIntPair, Google.ProtocolBuffers.IGeneratedExtensionLite>; namespace Google.ProtocolBuffers { /// <summary> /// A table of known extensions, searchable by name or field number. When /// parsing a protocol message that might have extensions, you must provide /// an <see cref="ExtensionRegistry"/> in which you have registered any extensions /// that you want to be able to parse. Otherwise, those extensions will just /// be treated like unknown fields. /// </summary> /// <example> /// For example, if you had the <c>.proto</c> file: /// <code> /// option java_class = "MyProto"; /// /// message Foo { /// extensions 1000 to max; /// } /// /// extend Foo { /// optional int32 bar; /// } /// </code> /// /// Then you might write code like: /// /// <code> /// extensionRegistry registry = extensionRegistry.CreateInstance(); /// registry.Add(MyProto.Bar); /// MyProto.Foo message = MyProto.Foo.ParseFrom(input, registry); /// </code> /// </example> /// /// <remarks> /// <para>You might wonder why this is necessary. Two alternatives might come to /// mind. First, you might imagine a system where generated extensions are /// automatically registered when their containing classes are loaded. This /// is a popular technique, but is bad design; among other things, it creates a /// situation where behavior can change depending on what classes happen to be /// loaded. It also introduces a security vulnerability, because an /// unprivileged class could cause its code to be called unexpectedly from a /// privileged class by registering itself as an extension of the right type. /// </para> /// <para>Another option you might consider is lazy parsing: do not parse an /// extension until it is first requested, at which point the caller must /// provide a type to use. This introduces a different set of problems. First, /// it would require a mutex lock any time an extension was accessed, which /// would be slow. Second, corrupt data would not be detected until first /// access, at which point it would be much harder to deal with it. Third, it /// could violate the expectation that message objects are immutable, since the /// type provided could be any arbitrary message class. An unprivileged user /// could take advantage of this to inject a mutable object into a message /// belonging to privileged code and create mischief.</para> /// </remarks> public sealed partial class ExtensionRegistry { private static readonly ExtensionRegistry empty = new ExtensionRegistry( new ExtensionByNameMap(), new ExtensionByIdMap(), true); private readonly ExtensionByNameMap extensionsByName; private readonly ExtensionByIdMap extensionsByNumber; private readonly bool readOnly; private ExtensionRegistry(ExtensionByNameMap byName, ExtensionByIdMap byNumber, bool readOnly) { this.extensionsByName = byName; this.extensionsByNumber = byNumber; this.readOnly = readOnly; } /// <summary> /// Construct a new, empty instance. /// </summary> public static ExtensionRegistry CreateInstance() { return new ExtensionRegistry(new ExtensionByNameMap(), new ExtensionByIdMap(), false); } public ExtensionRegistry AsReadOnly() { return new ExtensionRegistry(extensionsByName, extensionsByNumber, true); } /// <summary> /// Get the unmodifiable singleton empty instance. /// </summary> public static ExtensionRegistry Empty { get { return empty; } } /// <summary> /// Finds an extension by containing type and field number. /// A null reference is returned if the extension can't be found. /// </summary> public IGeneratedExtensionLite this[IMessageLite containingType, int fieldNumber] { get { IGeneratedExtensionLite ret; extensionsByNumber.TryGetValue(new ExtensionIntPair(containingType, fieldNumber), out ret); return ret; } } public IGeneratedExtensionLite FindByName(IMessageLite defaultInstanceOfType, string fieldName) { return FindExtensionByName(defaultInstanceOfType, fieldName); } private IGeneratedExtensionLite FindExtensionByName(object forwhat, string fieldName) { IGeneratedExtensionLite extension = null; Dictionary<string, IGeneratedExtensionLite> map; if (extensionsByName.TryGetValue(forwhat, out map) && map.TryGetValue(fieldName, out extension)) { return extension; } return null; } /// <summary> /// Add an extension from a generated file to the registry. /// </summary> public void Add(IGeneratedExtensionLite extension) { if (readOnly) { throw new InvalidOperationException("Cannot add entries to a read-only extension registry"); } extensionsByNumber.Add(new ExtensionIntPair(extension.ContainingType, extension.Number), extension); Dictionary<string, IGeneratedExtensionLite> map; if (!extensionsByName.TryGetValue(extension.ContainingType, out map)) { extensionsByName.Add(extension.ContainingType, map = new Dictionary<string, IGeneratedExtensionLite>()); } map[extension.Descriptor.Name] = extension; map[extension.Descriptor.FullName] = extension; } /// <summary> /// Nested type just used to represent a pair of MessageDescriptor and int, as /// the key into the "by number" map. /// </summary> internal struct ExtensionIntPair : IEquatable<ExtensionIntPair> { private readonly object msgType; private readonly int number; internal ExtensionIntPair(object msgType, int number) { this.msgType = msgType; this.number = number; } public override int GetHashCode() { return msgType.GetHashCode()*((1 << 16) - 1) + number; } public override bool Equals(object obj) { if (!(obj is ExtensionIntPair)) { return false; } return Equals((ExtensionIntPair) obj); } public bool Equals(ExtensionIntPair other) { return msgType.Equals(other.msgType) && number == other.number; } } } }
namespace Firebase.Database.Streaming { using System; using System.Diagnostics; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; using Firebase.Database.Query; using Newtonsoft.Json.Linq; using System.Net; /// <summary> /// The firebase subscription. /// </summary> /// <typeparam name="T"> Type of object to be streaming back to the called. </typeparam> internal class FirebaseSubscription<T> : IDisposable { private readonly CancellationTokenSource cancel; private readonly IObserver<FirebaseEvent<T>> observer; private readonly IFirebaseQuery query; private readonly FirebaseCache<T> cache; private readonly string elementRoot; private readonly FirebaseClient client; private static HttpClient http; static FirebaseSubscription() { var handler = new HttpClientHandler { AllowAutoRedirect = true, MaxAutomaticRedirections = 10, CookieContainer = new CookieContainer() }; var httpClient = new HttpClient(handler, true); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/event-stream")); http = httpClient; } /// <summary> /// Initializes a new instance of the <see cref="FirebaseSubscription{T}"/> class. /// </summary> /// <param name="observer"> The observer. </param> /// <param name="query"> The query. </param> /// <param name="elementRoot"> Optional custom root element of received json items. </param> /// <param name="cache"> The cache. </param> public FirebaseSubscription(IObserver<FirebaseEvent<T>> observer, IFirebaseQuery query, string elementRoot, FirebaseCache<T> cache) { this.observer = observer; this.query = query; this.elementRoot = elementRoot; this.cancel = new CancellationTokenSource(); this.cache = cache; this.client = query.Client; } public event EventHandler<ContinueExceptionEventArgs<FirebaseException>> ExceptionThrown; public void Dispose() { this.cancel.Cancel(); } public IDisposable Run() { Task.Run(() => this.ReceiveThread()); return this; } private async void ReceiveThread() { while (true) { var url = string.Empty; var line = string.Empty; var statusCode = HttpStatusCode.OK; try { this.cancel.Token.ThrowIfCancellationRequested(); // initialize network connection url = await this.query.BuildUrlAsync().ConfigureAwait(false); var request = new HttpRequestMessage(HttpMethod.Get, url); var serverEvent = FirebaseServerEventType.KeepAlive; var client = this.GetHttpClient(); var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, this.cancel.Token).ConfigureAwait(false); statusCode = response.StatusCode; response.EnsureSuccessStatusCode(); using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) using (var reader = this.client.Options.SubscriptionStreamReaderFactory(stream)) { while (true) { this.cancel.Token.ThrowIfCancellationRequested(); line = reader.ReadLine()?.Trim(); if (string.IsNullOrWhiteSpace(line)) { continue; } var tuple = line.Split(new[] { ':' }, 2, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToArray(); switch (tuple[0].ToLower()) { case "event": serverEvent = this.ParseServerEvent(serverEvent, tuple[1]); break; case "data": this.ProcessServerData(url, serverEvent, tuple[1]); break; } if (serverEvent == FirebaseServerEventType.AuthRevoked) { // auth token no longer valid, reconnect break; } } } } catch (OperationCanceledException) { break; } catch (Exception ex) { var args = new FirebaseException(url, string.Empty, line, statusCode, ex); if (!this.OnExceptionThrown(args, statusCode == HttpStatusCode.OK)) { this.observer.OnError(new FirebaseException(url, string.Empty, line, statusCode, ex)); this.Dispose(); break; } await Task.Delay(2000).ConfigureAwait(false); } } } protected bool OnExceptionThrown(FirebaseException ex, bool ignore) { var args = new ContinueExceptionEventArgs<FirebaseException>(ex, ignore); this.ExceptionThrown?.Invoke(this, args); return args.IgnoreAndContinue; } private FirebaseServerEventType ParseServerEvent(FirebaseServerEventType serverEvent, string eventName) { switch (eventName) { case "put": serverEvent = FirebaseServerEventType.Put; break; case "patch": serverEvent = FirebaseServerEventType.Patch; break; case "keep-alive": serverEvent = FirebaseServerEventType.KeepAlive; break; case "cancel": serverEvent = FirebaseServerEventType.Cancel; break; case "auth_revoked": serverEvent = FirebaseServerEventType.AuthRevoked; break; } return serverEvent; } private void ProcessServerData(string url, FirebaseServerEventType serverEvent, string serverData) { switch (serverEvent) { case FirebaseServerEventType.Put: case FirebaseServerEventType.Patch: var result = JObject.Parse(serverData); var path = result["path"].ToString(); var data = result["data"].ToString(); // If an elementRoot parameter is provided, but it's not in the cache, it was already deleted. So we can return an empty object. if(string.IsNullOrWhiteSpace(this.elementRoot) || !this.cache.Contains(this.elementRoot)) { if(path == "/" && data == string.Empty) { this.observer.OnNext(FirebaseEvent<T>.Empty(FirebaseEventSource.OnlineStream)); return; } } var eventType = string.IsNullOrWhiteSpace(data) ? FirebaseEventType.Delete : FirebaseEventType.InsertOrUpdate; var items = this.cache.PushData(this.elementRoot + path, data); foreach (var i in items.ToList()) { this.observer.OnNext(new FirebaseEvent<T>(i.Key, i.Object, eventType, FirebaseEventSource.OnlineStream)); } break; case FirebaseServerEventType.KeepAlive: break; case FirebaseServerEventType.Cancel: this.observer.OnError(new FirebaseException(url, string.Empty, serverData, HttpStatusCode.Unauthorized)); this.Dispose(); break; } } private HttpClient GetHttpClient() { return http; } } }
using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif using System.Collections; using System.Collections.Generic; using UMA.PoseTools; namespace UMA.CharacterSystem { public class DynamicDNAConverterCustomizer : MonoBehaviour { #if UNITY_EDITOR public GameObject dynamicDnaConverterPrefab;//used for saving dnaConverter as new public RuntimeAnimatorController TposeAnimatorController; public RuntimeAnimatorController AposeAnimatorController; public RuntimeAnimatorController MovementAnimatorController; public UMAAvatarBase targetUMA; /*Texture2D targetAlphaTex; float targetAlpha = 1; bool targetAlphaSet = true;*/ public UMAAvatarBase guideUMA; /*Texture2D guideAlphaTex; float guideAlpha = 0.5f; bool guideAlphaSet = false;*/ [System.NonSerialized] UMAAvatarBase activeUMA; [System.NonSerialized] string activeUMARace; [SerializeField] public List<DynamicDNAConverterBehaviour> availableConverters = new List<DynamicDNAConverterBehaviour>(); [SerializeField] public DynamicDNAConverterBehaviour selectedConverter; GameObject converterBackupsFolder = null; public DynamicDNAConverterBehaviour converterToImport; Dictionary<string, DynamicDNAConverterBehaviour> converterBackups = new Dictionary<string, DynamicDNAConverterBehaviour>(); Dictionary<string, string[]> dnaAssetNamesBackups = new Dictionary<string, string[]>(); Dictionary<string, UMABonePose.PoseBone[]> poseBonesBackups = new Dictionary<string, UMABonePose.PoseBone[]>(); public bool drawBoundsGizmo = true; private string bonePoseSaveName; private GameObject tempAvatarPreDNA; private GameObject tempAvatarPostDNA; //used as the 'epsilon' value when comparing bones during a 'create starting Pose from Current DNA' operation //decent values are between around 0.000005f and 0.0005f public float bonePoseAccuracy = 0.00005f; //UndoRedoDelegate void OnUndo() { UpdateUMA(); } public void StartListeningForUndo() { Undo.undoRedoPerformed += OnUndo; } public void StopListeningForUndo() { Undo.undoRedoPerformed -= OnUndo; } // Use this for initialization void Start() { //TODO make the guide/target semi transparent /*targetAlphaTex = new Texture2D(2,2); guideAlphaTex = new Texture2D(2,2); var AlphaColor = new Color(guideAlpha, guideAlpha, guideAlpha, 1f); guideAlphaTex.SetPixel(0, 0, AlphaColor); guideAlphaTex.SetPixel(0, 1, AlphaColor); guideAlphaTex.SetPixel(1, 0, AlphaColor); guideAlphaTex.SetPixel(1, 1, AlphaColor);*/ if (targetUMA != null) { activeUMA = targetUMA; activeUMA.CharacterUpdated.AddListener(SetAvailableConverters); } } // Update is called once per frame void Update() { if (activeUMA != targetUMA) { activeUMA = targetUMA; if(activeUMA.umaData != null) SetAvailableConverters(activeUMA.umaData); else availableConverters.Clear(); } if (activeUMA != null) if(activeUMA.umaData != null) if(activeUMA.umaData.umaRecipe != null) if (activeUMA.umaData.umaRecipe.raceData != null) if (activeUMA.umaData.umaRecipe.raceData.raceName != activeUMARace) { activeUMARace = activeUMA.umaData.umaRecipe.raceData.raceName; SetAvailableConverters(activeUMA.umaData); } //TODO make the guide /target semi transparent... } public void SetAvatar(GameObject newAvatarObject) { if(guideUMA != null) if (newAvatarObject == guideUMA.gameObject) { //reset guide transparency one we have sussed out how to do this guideUMA = null; } if (targetUMA == null || newAvatarObject != targetUMA.gameObject) { if (newAvatarObject.GetComponent<UMAAvatarBase>() != null) { targetUMA = newAvatarObject.GetComponent<UMAAvatarBase>(); activeUMA = newAvatarObject.GetComponent<UMAAvatarBase>(); SetAvailableConverters(activeUMA.umaData); selectedConverter = null; } else { targetUMA = null; activeUMA = null; availableConverters.Clear(); selectedConverter = null; } } } void OnApplicationQuit() { RestoreBackupVersion(); } public void SetAvailableConverters(UMAData umaData) { activeUMA.CharacterUpdated.RemoveListener(SetAvailableConverters); if (activeUMARace == "") activeUMARace = umaData.umaRecipe.raceData.raceName; availableConverters.Clear(); foreach (DnaConverterBehaviour converter in umaData.umaRecipe.raceData.dnaConverterList) { if(converter.GetType() == typeof(DynamicDNAConverterBehaviour)) { availableConverters.Add(converter as DynamicDNAConverterBehaviour); } } } public void SetTPoseAni() { if (TposeAnimatorController == null) return; SwapAnimator(TposeAnimatorController); } public void SetAPoseAni() { if (AposeAnimatorController == null) return; SwapAnimator(AposeAnimatorController); } public void SetMovementAni() { if (MovementAnimatorController == null) return; SwapAnimator(MovementAnimatorController); } private void SwapAnimator(RuntimeAnimatorController animatorToUse) { //changing the animationController in 5.6 resets the rotation of this game object so store the rotation and set it back if (guideUMA != null) { if (guideUMA.gameObject.GetComponent<Animator>()) { var guideOriginalRot = Quaternion.identity; if (guideUMA.umaData != null) guideOriginalRot = guideUMA.umaData.transform.localRotation; guideUMA.gameObject.GetComponent<Animator>().runtimeAnimatorController = animatorToUse; if (guideUMA.umaData != null) guideUMA.umaData.transform.localRotation = guideOriginalRot; } } if (activeUMA != null) { if (activeUMA.gameObject.GetComponent<Animator>()) { var originalRot = Quaternion.identity; if (activeUMA.umaData != null) originalRot = activeUMA.umaData.transform.localRotation; activeUMA.gameObject.GetComponent<Animator>().runtimeAnimatorController = animatorToUse; if (activeUMA.umaData != null) activeUMA.umaData.transform.localRotation = originalRot; } } UpdateUMA(); } void OnDrawGizmos() { if (drawBoundsGizmo && activeUMA != null) { if (activeUMA.umaData == null || activeUMA.umaData.GetRenderer(0) == null) return; Gizmos.color = Color.white; Gizmos.DrawWireCube(activeUMA.umaData.GetRenderer(0).bounds.center, activeUMA.umaData.GetRenderer(0).bounds.size); } } /// <summary> /// Aligns the guide UMA to the Target UMA's position /// </summary> public void AlignGuideToTarget() { if (guideUMA == null || activeUMA == null) { Debug.LogWarning("Both the Gude UMA and the UMA to Customize need to be set to align them to each other!"); return; } var activeUMAPosition = activeUMA.gameObject.transform.position; guideUMA.gameObject.transform.position = activeUMAPosition; } #region Value Modification Methods /// <summary> /// Set the Target UMA's DNA to match the Guide UMA's dna /// </summary> public void ImportGuideDNAValues() { if (guideUMA == null) { Debug.LogWarning("No Guide UMA was set to get DNA from!"); return; } UMADnaBase[] activeUmaDNA = activeUMA.umaData.GetAllDna(); UMADnaBase[] guideUmaDNA = guideUMA.umaData.GetAllDna(); foreach (UMADnaBase gdna in guideUmaDNA) { foreach (UMADnaBase dna in activeUmaDNA) { if (dna is DynamicUMADnaBase) { ((DynamicUMADnaBase)dna).ImportUMADnaValues(gdna); } } } UpdateUMA(); } /// <summary> /// Imports the settings and assets from another DynamicDNAConverterBehaviour /// </summary> /// <returns></returns> public bool ImportConverterValues() { if (converterToImport == null) { Debug.LogWarning("There was no converter to import from"); return false; } if (selectedConverter == null) { Debug.LogWarning("There was no converter to import to"); return false; } selectedConverter.startingPose = converterToImport.startingPose; selectedConverter.startingPoseWeight = converterToImport.startingPoseWeight; selectedConverter.dnaAsset = converterToImport.dnaAsset; selectedConverter.skeletonModifiers = converterToImport.skeletonModifiers; selectedConverter.hashList = converterToImport.hashList; selectedConverter.overallModifiersEnabled = converterToImport.overallModifiersEnabled; //.heightModifiers = converterToImport.heightModifiers; selectedConverter.radiusAdjust = converterToImport.radiusAdjust; selectedConverter.massModifiers = converterToImport.massModifiers; Debug.Log("Imported " + converterToImport.name + " settings into " + selectedConverter.name); return true; } private bool LocalTransformsMatch(Transform t1, Transform t2) { if ((t1.localPosition - t2.localPosition).sqrMagnitude > bonePoseAccuracy) return false; if ((t1.localScale - t2.localScale).sqrMagnitude > bonePoseAccuracy) return false; if (t1.localRotation != t2.localRotation) return false; return true; } protected void CreateBonePoseCallback(UMAData umaData) { UMA.PoseTools.UMABonePose bonePose = null; if (selectedConverter.startingPose == null) { bonePose = CreatePoseAsset("", bonePoseSaveName); } else { bonePose = selectedConverter.startingPose; bonePose.poses = new UMABonePose.PoseBone[1]; } UMASkeleton skeletonPreDNA = tempAvatarPreDNA.GetComponent<UMADynamicAvatar>().umaData.skeleton; UMASkeleton skeletonPostDNA = tempAvatarPostDNA.GetComponent<UMADynamicAvatar>().umaData.skeleton; Transform transformPreDNA; Transform transformPostDNA; bool transformDirty; int parentHash; foreach (int boneHash in skeletonPreDNA.BoneHashes) { skeletonPreDNA.TryGetBoneTransform(boneHash, out transformPreDNA, out transformDirty, out parentHash); skeletonPostDNA.TryGetBoneTransform(boneHash, out transformPostDNA, out transformDirty, out parentHash); if ((transformPreDNA == null) || (transformPostDNA == null)) { Debug.LogWarning("Bad bone hash in skeleton: " + boneHash); continue; } if (!LocalTransformsMatch(transformPreDNA, transformPostDNA)) { bonePose.AddBone(transformPreDNA, transformPostDNA.localPosition, transformPostDNA.localRotation, transformPostDNA.localScale); } } UMAUtils.DestroySceneObject(tempAvatarPreDNA); UMAUtils.DestroySceneObject(tempAvatarPostDNA); // This can be very helpful for testing /* bonePose.ApplyPose(skeletonPreDNA, 1.0f); */ EditorUtility.SetDirty(bonePose); AssetDatabase.SaveAssets(); // Set this asset as the converters pose asset selectedConverter.startingPose = bonePose; //make sure its fully applied selectedConverter.startingPoseWeight = 1f; // Reset all the DNA values for target Avatar to default UMADnaBase[] targetDNA = activeUMA.umaData.GetAllDna(); foreach (UMADnaBase dnaEntry in targetDNA) { for (int i = 0; i < dnaEntry.Values.Length; i++) { dnaEntry.SetValue(i, 0.5f); } } // Optionally clear the DNA from the base recipe, // since it's now included in the new starting pose UMARecipeBase baseRaceRecipe = activeUMA.umaData.umaRecipe.GetRace().baseRaceRecipe; if (baseRaceRecipe != null) { if (EditorUtility.DisplayDialog("Base Recipe Cleanup", "Starting Pose created. Remove DNA from base recipe of active race?", "Remove DNA", "Keep DNA")) { UMAData.UMARecipe baseRecipeData = new UMAData.UMARecipe(); baseRaceRecipe.Load(baseRecipeData, activeUMA.context); baseRecipeData.ClearDna(); baseRaceRecipe.Save(baseRecipeData, activeUMA.context); } } } /// <summary> /// Calculates the required poses necessary for an UMABonePose asset to render the Avatar in its current post DNA state, /// adds these to the selected converters 'Starting Pose' asset- creating one if necessary and resets current Dna values to 0. /// </summary> public bool CreateBonePosesFromCurrentDna(string createdAssetName = "") { if (activeUMA == null || selectedConverter == null) { Debug.LogWarning("activeUMA == null || selectedConverter == null"); return false; } bonePoseSaveName = createdAssetName; // Build a temporary version of the Avatar with no DNA to get original state UMADnaBase[] activeDNA = activeUMA.umaData.umaRecipe.GetAllDna(); SlotData[] activeSlots = activeUMA.umaData.umaRecipe.GetAllSlots(); int slotIndex; tempAvatarPreDNA = new GameObject("Temp Raw Avatar"); tempAvatarPreDNA.transform.parent = activeUMA.transform.parent; tempAvatarPreDNA.transform.localPosition = Vector3.zero; tempAvatarPreDNA.transform.localRotation = activeUMA.transform.localRotation; UMADynamicAvatar tempAvatar = tempAvatarPreDNA.AddComponent<UMADynamicAvatar>(); tempAvatar.umaGenerator = activeUMA.umaGenerator; tempAvatar.Initialize(); tempAvatar.umaData.umaRecipe = new UMAData.UMARecipe(); tempAvatar.umaData.umaRecipe.raceData = activeUMA.umaData.umaRecipe.raceData; slotIndex = 0; foreach (SlotData slotEntry in activeSlots) { if ((slotEntry == null) || slotEntry.dontSerialize) continue; tempAvatar.umaData.umaRecipe.SetSlot(slotIndex++, slotEntry); } tempAvatar.Show(); tempAvatarPostDNA = new GameObject("Temp DNA Avatar"); tempAvatarPostDNA.transform.parent = activeUMA.transform.parent; tempAvatarPostDNA.transform.localPosition = Vector3.zero; tempAvatarPostDNA.transform.localRotation = activeUMA.transform.localRotation; UMADynamicAvatar tempAvatar2 = tempAvatarPostDNA.AddComponent<UMADynamicAvatar>(); tempAvatar2.umaGenerator = activeUMA.umaGenerator; tempAvatar2.Initialize(); tempAvatar2.umaData.umaRecipe = new UMAData.UMARecipe(); tempAvatar2.umaData.umaRecipe.raceData = activeUMA.umaData.umaRecipe.raceData; tempAvatar2.umaData.umaRecipe.slotDataList = activeUMA.umaData.umaRecipe.slotDataList; slotIndex = 0; foreach (SlotData slotEntry in activeSlots) { if ((slotEntry == null) || slotEntry.dontSerialize) continue; tempAvatar2.umaData.umaRecipe.SetSlot(slotIndex++, slotEntry); } foreach (UMADnaBase dnaEntry in activeDNA) { tempAvatar2.umaData.umaRecipe.AddDna(dnaEntry); } tempAvatar2.umaData.OnCharacterCreated += CreateBonePoseCallback; tempAvatar2.Show(); return true; } #endregion #region Save and Backup Methods /// <summary> /// Makes a backup of the currently selected converter whose values are restored to the current converter when the Application stops playing (unless you Save the changes) /// </summary> /// <param name="converterToBU"></param> public void BackupConverter(DynamicDNAConverterBehaviour converterToBU = null) { if(converterToBU == null) { converterToBU = selectedConverter; } if(converterBackupsFolder == null) { converterBackupsFolder = new GameObject(); converterBackupsFolder.name = "CONVERTER BACKUPS DO NOT DELETE"; } if(converterToBU != null) { if (!converterBackups.ContainsKey(converterToBU.name)) { var thisConverterBackup = Instantiate<DynamicDNAConverterBehaviour>(converterToBU); thisConverterBackup.transform.parent = converterBackupsFolder.transform; converterBackups[converterToBU.name] = thisConverterBackup; } if (converterToBU.dnaAsset != null) { dnaAssetNamesBackups[converterToBU.dnaAsset.name] = (string[])converterToBU.dnaAsset.Names.Clone(); } if (converterToBU.startingPose != null) { poseBonesBackups[converterToBU.startingPose.name] = DeepPoseBoneClone(converterToBU.startingPose.poses); } } } private UMABonePose.PoseBone[] DeepPoseBoneClone(UMABonePose.PoseBone[] posesToCopy) { var poseBonesCopy = new UMABonePose.PoseBone[posesToCopy.Length]; for(int i = 0; i < posesToCopy.Length; i++) { poseBonesCopy[i] = new UMABonePose.PoseBone(); poseBonesCopy[i].bone = posesToCopy[i].bone; poseBonesCopy[i].hash = posesToCopy[i].hash; poseBonesCopy[i].position = new Vector3(posesToCopy[i].position.x, posesToCopy[i].position.y, posesToCopy[i].position.z); poseBonesCopy[i].rotation = new Quaternion(posesToCopy[i].rotation.x, posesToCopy[i].rotation.y, posesToCopy[i].rotation.z, posesToCopy[i].rotation.w); poseBonesCopy[i].scale = new Vector3(posesToCopy[i].scale.x, posesToCopy[i].scale.y, posesToCopy[i].scale.z); } return poseBonesCopy; } /// <summary> /// Restores the converters values back to the original or saved values. Also called when the application stops playing so that any changes made while the game is running are not saved (unless the user calls the SaveChanges method previously). /// </summary> /// <param name="converterName"></param> public void RestoreBackupVersion(string converterName = "") { if(availableConverters.Count > 0) { for (int i = 0; i < availableConverters.Count; i++) { DynamicDNAConverterBehaviour buConverter; if (converterBackups.TryGetValue(availableConverters[i].name, out buConverter)) { if(converterName == "" || converterName == availableConverters[i].name) { availableConverters[i].dnaAsset = buConverter.dnaAsset; if(availableConverters[i].dnaAsset != null) { string[] buNames; if(dnaAssetNamesBackups.TryGetValue(availableConverters[i].dnaAsset.name, out buNames)) { availableConverters[i].dnaAsset.Names = buNames; } } //we need to restore these regardless of whether the converter had a startingPose or not when we started playing if (availableConverters[i].startingPose != null) { UMABonePose.PoseBone[] buPoses; if (poseBonesBackups.TryGetValue(availableConverters[i].startingPose.name, out buPoses)) { availableConverters[i].startingPose.poses = buPoses; EditorUtility.SetDirty(availableConverters[i].startingPose); AssetDatabase.SaveAssets(); } } availableConverters[i].startingPose = buConverter.startingPose; // availableConverters[i].skeletonModifiers = buConverter.skeletonModifiers; availableConverters[i].hashList = buConverter.hashList; availableConverters[i].overallModifiersEnabled = buConverter.overallModifiersEnabled; //new availableConverters[i].tightenBounds = buConverter.tightenBounds; availableConverters[i].boundsAdjust = buConverter.boundsAdjust; //end new availableConverters[i].overallScale = buConverter.overallScale; //availableConverters[i].heightModifiers = buConverter.heightModifiers; availableConverters[i].radiusAdjust = buConverter.radiusAdjust; availableConverters[i].massModifiers = buConverter.massModifiers; } } } } } /// <summary> /// Saves the current changes to the converter by removing the backup that would otherwise reset the converter when the Application stops playing. /// </summary> /// <param name="all"></param> public void SaveChanges(bool all = false) { bool doSave = true; #if UNITY_EDITOR doSave = EditorUtility.DisplayDialog("Confirm Save", "This will overwrite the values in the currently selected dna converter. Are you sure?", "Save", "Cancel"); #endif if (doSave) { if (all) { foreach(KeyValuePair<string, DynamicDNAConverterBehaviour> kp in converterBackups) { if (kp.Value.dnaAsset != null && dnaAssetNamesBackups.ContainsKey(kp.Value.dnaAsset.name)) { EditorUtility.SetDirty(kp.Value.dnaAsset); dnaAssetNamesBackups.Remove(kp.Value.dnaAsset.name); } if (kp.Value.startingPose != null && poseBonesBackups.ContainsKey(kp.Value.startingPose.name)) { EditorUtility.SetDirty(kp.Value.startingPose); poseBonesBackups.Remove(kp.Value.startingPose.name); } } if (availableConverters.Count > 0) { for (int i = 0; i < availableConverters.Count; i++) { EditorUtility.SetDirty(availableConverters[i]); } } AssetDatabase.SaveAssets(); foreach (KeyValuePair<string, DynamicDNAConverterBehaviour> kp in converterBackups) { Destroy(kp.Value); } converterBackups.Clear(); if(availableConverters.Count > 0) { for(int i = 0; i < availableConverters.Count; i++) { BackupConverter(availableConverters[i]); } } } else { if (selectedConverter != null) { if (converterBackups.ContainsKey(selectedConverter.name)) { if(converterBackups[selectedConverter.name].dnaAsset != null) { EditorUtility.SetDirty(converterBackups[selectedConverter.name].dnaAsset); dnaAssetNamesBackups.Remove(converterBackups[selectedConverter.name].dnaAsset.name); } if (converterBackups[selectedConverter.name].startingPose != null) { EditorUtility.SetDirty(converterBackups[selectedConverter.name].startingPose); poseBonesBackups.Remove(converterBackups[selectedConverter.name].startingPose.name); } EditorUtility.SetDirty(selectedConverter); AssetDatabase.SaveAssets(); Destroy(converterBackups[selectedConverter.name]); converterBackups.Remove(selectedConverter.name); BackupConverter(); } } } } } #if UNITY_EDITOR /// <summary> /// Creates a new Converter Behaviour Prefab with a converter on it that has the current settings. This can then be applied to a Race's Dna Converters. /// </summary> public void SaveChangesAsNew() { if(dynamicDnaConverterPrefab == null) { Debug.LogWarning("There was no prefab set up in the DynamicDnaConverterCustomizer. This must be set in order to save a new prefab."); return; } if(selectedConverter == null) { Debug.LogWarning("No converter was selected to save!"); return; } var fullPath = EditorUtility.SaveFilePanel("Save New DynamicDnaConverterBehaviour", Application.dataPath, "", "prefab"); var path = fullPath.Replace(Application.dataPath,"Assets"); var filename = System.IO.Path.GetFileNameWithoutExtension(path); var thisNewPrefabGO = Instantiate(dynamicDnaConverterPrefab); thisNewPrefabGO.name = filename; var newPrefabConverter = thisNewPrefabGO.GetComponent<DynamicDNAConverterBehaviour>(); if (newPrefabConverter != null) { newPrefabConverter.dnaAsset = selectedConverter.dnaAsset; newPrefabConverter.startingPose = selectedConverter.startingPose; newPrefabConverter.skeletonModifiers = selectedConverter.skeletonModifiers; newPrefabConverter.hashList = selectedConverter.hashList; newPrefabConverter.overallModifiersEnabled = selectedConverter.overallModifiersEnabled; newPrefabConverter.overallScale = selectedConverter.overallScale; //newPrefabConverter.heightModifiers = selectedConverter.heightModifiers; newPrefabConverter.radiusAdjust = selectedConverter.radiusAdjust; newPrefabConverter.massModifiers = selectedConverter.massModifiers; } var newPrefab = PrefabUtility.CreatePrefab(path, thisNewPrefabGO);//couldn't create asset try instantiating first if(newPrefab != null) { EditorUtility.SetDirty(newPrefab); AssetDatabase.SaveAssets(); Debug.Log("Saved your changes to a new converter prefab at " + path); Destroy(thisNewPrefabGO); } } #endif #endregion #region Asset Creation public UMABonePose CreatePoseAsset(string assetFolder = "", string assetName = "") { if(assetFolder == "") { assetFolder = AssetDatabase.GetAssetPath(selectedConverter); assetFolder = assetFolder.Substring(0, assetFolder.LastIndexOf('/')); } if(assetName == "") { assetName = selectedConverter.name + "StartingPose"; var uniquePath = AssetDatabase.GenerateUniqueAssetPath(assetFolder + "/" + assetName + ".asset"); assetName = uniquePath.Replace(assetFolder + "/", "").Replace(".asset", ""); } if (!System.IO.Directory.Exists(assetFolder)) { System.IO.Directory.CreateDirectory(assetFolder); } UMABonePose asset = ScriptableObject.CreateInstance<UMABonePose>(); AssetDatabase.CreateAsset(asset, assetFolder + "/" + assetName + ".asset"); AssetDatabase.SaveAssets(); return asset; } public DynamicUMADnaAsset CreateDNAAsset(string assetFolder = "", string assetName = "") { if (assetFolder == "") { assetFolder = AssetDatabase.GetAssetPath(selectedConverter); assetFolder = assetFolder.Substring(0, assetFolder.LastIndexOf('/')); } if (assetName == "") { assetName = selectedConverter.name + "DNAAsset"; var uniquePath = AssetDatabase.GenerateUniqueAssetPath(assetFolder + "/" + assetName + ".asset"); assetName = uniquePath.Replace(assetFolder + "/", "").Replace(".asset", ""); } if (!System.IO.Directory.Exists(assetFolder)) { System.IO.Directory.CreateDirectory(assetFolder); } DynamicUMADnaAsset asset = ScriptableObject.CreateInstance<DynamicUMADnaAsset>(); AssetDatabase.CreateAsset(asset, assetFolder + "/" + assetName + ".asset"); AssetDatabase.SaveAssets(); return asset; } #endregion #region UMA Update Methods /// <summary> /// Updates the current Target UMA so any changes are shown. /// </summary> public void UpdateUMA() { if (activeUMA) { StopCoroutine("UpdateUMACoroutine"); StartCoroutine("UpdateUMACoroutine"); } } IEnumerator UpdateUMACoroutine()//Trying to stop things slowing down after lots of modifications- helps a little bit { yield return null;//wait for a frame if (activeUMA) { activeUMA.umaData.Dirty(true, false, false); } } #endregion #endif } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.OpenECry.OpenECry File: Extensions.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.OpenECry { using System; using System.Collections.Generic; using System.Linq; using Ecng.Collections; using Ecng.Common; using Ecng.ComponentModel; using OEC.Data; using StockSharp.Algo; using StockSharp.Messages; using StockSharp.Localization; static class Extensions { public static SecurityTypes GetSecurityType(this OEC.API.Contract contract) { if (contract == null) throw new ArgumentNullException(nameof(contract)); if (contract.IsCompound) return SecurityTypes.Index; if (contract.IsContinuous) return SecurityTypes.Future; if (contract.IsEquityAsset) return SecurityTypes.Stock; if (contract.IsForex) return SecurityTypes.Currency; if (contract.IsFuture) return SecurityTypes.Future; if (contract.IsOption) return SecurityTypes.Option; return SecurityTypes.Stock; } public static decimal? Cast(this OEC.API.Contract contract, double value) { var d = value.ToDecimal(); if (d == null) return null; var priceStep = (decimal)contract.TickSize; return MathHelper.Round(d.Value, priceStep, priceStep.GetCachedDecimals()); } public static CurrencyTypes ToCurrency(this string str) { return str.Replace("*", string.Empty).To<CurrencyTypes>(); } public static SecurityId ToSecurityId(this OEC.API.Contract contract) { return new SecurityId { SecurityCode = contract.Symbol, BoardCode = contract.Exchange.Name, }; } /// <summary> /// To get <see cref="SecurityStates"/> for the instrument according to the <paramref name="contract" /> contract. /// </summary> /// <param name="contract">The OEC contract.</param> /// <returns>The instrument condition <see cref="SecurityStates"/>.</returns> public static SecurityStates GetSecurityState(this OEC.API.Contract contract) { var times = contract.GetWorkingTimesUtc(); var now = DateTime.UtcNow.TimeOfDay; return times.IsEmpty() || times.Any(range => range.Contains(now)) ? SecurityStates.Trading : SecurityStates.Stoped; } /// <summary> /// To get the trading time by the instrument. /// </summary> /// <param name="contract">The OEC contract.</param> /// <returns>The list of time ranges of day (UTC), during which the instrument is traded.</returns> public static Range<TimeSpan>[] GetWorkingTimesUtc(this OEC.API.Contract contract) { // sometimes OEC returns timespans for working time > 24 hours (some internal oec date conversion problem) // all OEC StartTimes and StopTimes are in local timezone // convert back to UTC var offset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now); var cstart = new TimeSpan(contract.StartTime.Hours + 24, contract.StartTime.Minutes, contract.StartTime.Seconds) - offset; var cstop = new TimeSpan(contract.StopTime.Hours + 24, contract.StopTime.Minutes, contract.StopTime.Seconds) - offset; cstart = new TimeSpan(cstart.Hours, cstart.Minutes, cstart.Seconds); cstop = new TimeSpan(cstop.Hours, cstop.Minutes, cstop.Seconds); if (cstart == cstop) return new Range<TimeSpan>[0]; if (cstart < cstop) { return new[] { new Range<TimeSpan>(cstart, cstop) }; } var times = new List<Range<TimeSpan>>(); var daybegin = new TimeSpan(0); if (cstop > daybegin) times.Add(new Range<TimeSpan>(daybegin, cstop)); times.Add(new Range<TimeSpan>(cstart, new TimeSpan(24, 0, 0))); return times.ToArray(); } public static OrderSide ToOec(this Sides od) { return od == Sides.Buy ? OrderSide.Buy : od == Sides.Sell ? OrderSide.Sell : OrderSide.None; } public static Sides ToStockSharp(this OrderSide os) { switch (os) { case OrderSide.Buy: case OrderSide.BuyToCover: return Sides.Buy; case OrderSide.Sell: case OrderSide.SellShort: return Sides.Sell; default: throw new ArgumentOutOfRangeException(); } } public static Level1Fields ToStockSharp(this TriggerType type) { switch (type) { case TriggerType.Last: return Level1Fields.LastTradePrice; case TriggerType.Bid: return Level1Fields.BestBidPrice; case TriggerType.Ask: return Level1Fields.BestAskPrice; default: throw new ArgumentOutOfRangeException(nameof(type)); } } public static TriggerType ToOec(this Level1Fields? type) { switch (type) { case null: case Level1Fields.LastTradePrice: return TriggerType.Last; case Level1Fields.BestBidPrice: return TriggerType.Bid; case Level1Fields.BestAskPrice: return TriggerType.Ask; default: throw new ArgumentOutOfRangeException(nameof(type)); } } public static OrderType ToOec(this OrderTypes type) { switch (type) { case OrderTypes.Limit: return OrderType.Limit; case OrderTypes.Market: return OrderType.Market; default: throw new ArgumentException(LocalizedStrings.Str2579Params.Put(type)); } } public static OrderTypes ToStockSharp(this OrderType type) { switch (type) { case OrderType.Market: return OrderTypes.Market; case OrderType.Limit: return OrderTypes.Limit; case OrderType.Stop: case OrderType.StopLimit: case OrderType.MarketIfTouched: case OrderType.MarketToLimit: case OrderType.MarketOnOpen: case OrderType.MarketOnClose: case OrderType.MarketOnPitOpen: case OrderType.MarketOnPitClose: case OrderType.TrailingStopLoss: case OrderType.TrailingStopLimit: return OrderTypes.Conditional; case OrderType.Iceberg: return OrderTypes.Limit; default: throw new ArgumentOutOfRangeException(nameof(type)); } } public static string GetDescription(this FailReason reason) { switch (reason) { case FailReason.DataError: return LocalizedStrings.Str2580; case FailReason.Disabled: return LocalizedStrings.Str2581; case FailReason.DisconnectedByOwner: return LocalizedStrings.Str2582; case FailReason.Expired: return LocalizedStrings.Str2583; case FailReason.InvalidClientVersion: return LocalizedStrings.Str2584; case FailReason.InvalidUserOrPassword: return LocalizedStrings.Str2585; case FailReason.Locked: return LocalizedStrings.Str2586; case FailReason.SoftwareNotPermitted: return LocalizedStrings.Str2587; case FailReason.UserAlreadyConnected: return LocalizedStrings.Str2588; } return reason.ToString(); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: PointField.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; /// <summary>Holder for reflection information generated from PointField.proto</summary> public static partial class PointFieldReflection { #region Descriptor /// <summary>File descriptor for PointField.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static PointFieldReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChBQb2ludEZpZWxkLnByb3RvIksKClBvaW50RmllbGQSDAoEbmFtZRgBIAEo", "CRIOCgZvZmZzZXQYAiABKAUSEAoIZGF0YXR5cGUYAyABKAUSDQoFY291bnQY", "BCABKAViBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::PointField), global::PointField.Parser, new[]{ "Name", "Offset", "Datatype", "Count" }, null, null, null) })); } #endregion } #region Messages public sealed partial class PointField : pb::IMessage<PointField> { private static readonly pb::MessageParser<PointField> _parser = new pb::MessageParser<PointField>(() => new PointField()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<PointField> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::PointFieldReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PointField() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PointField(PointField other) : this() { name_ = other.name_; offset_ = other.offset_; datatype_ = other.datatype_; count_ = other.count_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PointField Clone() { return new PointField(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "offset" field.</summary> public const int OffsetFieldNumber = 2; private int offset_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Offset { get { return offset_; } set { offset_ = value; } } /// <summary>Field number for the "datatype" field.</summary> public const int DatatypeFieldNumber = 3; private int datatype_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Datatype { get { return datatype_; } set { datatype_ = value; } } /// <summary>Field number for the "count" field.</summary> public const int CountFieldNumber = 4; private int count_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Count { get { return count_; } set { count_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as PointField); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(PointField other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (Offset != other.Offset) return false; if (Datatype != other.Datatype) return false; if (Count != other.Count) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (Offset != 0) hash ^= Offset.GetHashCode(); if (Datatype != 0) hash ^= Datatype.GetHashCode(); if (Count != 0) hash ^= Count.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (Offset != 0) { output.WriteRawTag(16); output.WriteInt32(Offset); } if (Datatype != 0) { output.WriteRawTag(24); output.WriteInt32(Datatype); } if (Count != 0) { output.WriteRawTag(32); output.WriteInt32(Count); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (Offset != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Offset); } if (Datatype != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Datatype); } if (Count != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Count); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(PointField other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.Offset != 0) { Offset = other.Offset; } if (other.Datatype != 0) { Datatype = other.Datatype; } if (other.Count != 0) { Count = other.Count; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 16: { Offset = input.ReadInt32(); break; } case 24: { Datatype = input.ReadInt32(); break; } case 32: { Count = input.ReadInt32(); break; } } } } } #endregion #endregion Designer generated code
using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.Msagl.Core.DataStructures; using Microsoft.Msagl.Core.Geometry.Curves; using Microsoft.Msagl.GraphmapsWithMesh; using Microsoft.Msagl.Routing.Visibility; namespace Microsoft.Msagl.Routing { internal class SingleSourceSingleTargetShortestPathOnVisibilityGraph { public Tiling _g; readonly VisibilityVertex _source; readonly VisibilityVertex _target; VisibilityGraph _visGraph; double _lengthMultiplier = 1; public double LengthMultiplier { get { return _lengthMultiplier; } set { _lengthMultiplier = value; } } double _lengthMultiplierForAStar = 1; public double LengthMultiplierForAStar { get { return _lengthMultiplierForAStar; } set { _lengthMultiplierForAStar = value; } } internal SingleSourceSingleTargetShortestPathOnVisibilityGraph(VisibilityGraph visGraph, VisibilityVertex sourceVisVertex, VisibilityVertex targetVisVertex, Tiling g) { _visGraph = visGraph; _source = sourceVisVertex; _target = targetVisVertex; _source.Distance = 0; _g = g; } internal SingleSourceSingleTargetShortestPathOnVisibilityGraph(VisibilityGraph visGraph, VisibilityVertex sourceVisVertex, VisibilityVertex targetVisVertex) { _visGraph = visGraph; _source = sourceVisVertex; _target = targetVisVertex; _source.Distance = 0; } /// <summary> /// Returns a path /// </summary> /// <returns>a path or null if the target is not reachable from the source</returns> internal IEnumerable<VisibilityVertex> GetPath(bool shrinkEdgeLength) { var pq = new GenericBinaryHeapPriorityQueue<VisibilityVertex>(); _source.Distance = 0; _target.Distance = double.PositiveInfinity; pq.Enqueue(_source, H(_source)); while (!pq.IsEmpty()) { double hu; var u = pq.Dequeue(out hu); if (hu >= _target.Distance) break; foreach (var e in u.OutEdges) { if (PassableOutEdge(e)) { var v = e.Target; if (u != _source && u.isReal) ProcessNeighbor(pq, u, e, v, 1000); else ProcessNeighbor(pq, u, e, v); } } foreach (var e in u.InEdges) { if (PassableInEdge(e)) { var v = e.Source; ProcessNeighbor(pq, u, e, v); } } } return _visGraph.PreviosVertex(_target) == null ? null : CalculatePath(shrinkEdgeLength); } internal void AssertEdgesPassable(List<VisibilityEdge> path) { foreach (var edge in path) { Debug.Assert(PassableOutEdge(edge) || PassableInEdge(edge)); } } bool PassableOutEdge(VisibilityEdge e) { return e.Source == _source || e.Target == _target || !IsForbidden(e); } bool PassableInEdge(VisibilityEdge e) { return e.Source == _target || e.Target == _source || !IsForbidden(e); } internal static bool IsForbidden(VisibilityEdge e) { return e.IsPassable != null && !e.IsPassable() || e is TollFreeVisibilityEdge; } void ProcessNeighbor(GenericBinaryHeapPriorityQueue<VisibilityVertex> pq, VisibilityVertex u, VisibilityEdge l, VisibilityVertex v, int penalty) { var len = l.Length + penalty; var c = u.Distance + len; /* if (_visGraph.visVertexToId[l.Source] < _g.N || _visGraph.visVertexToId[l.Target] < _g.N) { if (!(l.Source == _source || l.Target == _source || l.Source == _target || l.Target == _target)) { c = 500; } } */ // (v != _source && _visGraph.PreviosVertex(v) == null) if (v != _source && _visGraph.PreviosVertex(v) == null) { v.Distance = c; _visGraph.SetPreviousEdge(v, l); if (v != _target) { pq.Enqueue(v, H(v)); } } else if (v != _source && c < v.Distance) { //This condition should never hold for the dequeued nodes. //However because of a very rare case of an epsilon error it might! //In this case DecreasePriority will fail to find "v" and the algorithm will continue working. //Since v is not in the queue changing its .Distance will not influence other nodes. //Changing v.Prev is fine since we come up with the path with an insignificantly //smaller distance. var prevV = _visGraph.PreviosVertex(v); v.Distance = c; _visGraph.SetPreviousEdge(v, l); if (v != _target) pq.DecreasePriority(v, H(v)); } } void ProcessNeighbor(GenericBinaryHeapPriorityQueue<VisibilityVertex> pq, VisibilityVertex u, VisibilityEdge l, VisibilityVertex v) { var len = l.Length; var c = u.Distance + len; /* if (_visGraph.visVertexToId[l.Source] < _g.N || _visGraph.visVertexToId[l.Target] < _g.N) { if (!(l.Source == _source || l.Target == _source || l.Source == _target || l.Target == _target)) { c = 500; } } */ // (v != _source && _visGraph.PreviosVertex(v) == null) if (v != _source && _visGraph.PreviosVertex(v) == null) { v.Distance = c; _visGraph.SetPreviousEdge(v, l); if (v != _target) { pq.Enqueue(v, H(v)); } } else if (v != _source && c < v.Distance) { //This condition should never hold for the dequeued nodes. //However because of a very rare case of an epsilon error it might! //In this case DecreasePriority will fail to find "v" and the algorithm will continue working. //Since v is not in the queue changing its .Distance will not influence other nodes. //Changing v.Prev is fine since we come up with the path with an insignificantly //smaller distance. var prevV = _visGraph.PreviosVertex(v); v.Distance = c; _visGraph.SetPreviousEdge(v, l); if (v != _target) pq.DecreasePriority(v, H(v)); } } double H(VisibilityVertex visibilityVertex) { return visibilityVertex.Distance + (visibilityVertex.Point - _target.Point).Length * LengthMultiplierForAStar; } IEnumerable<VisibilityVertex> CalculatePath(bool shrinkEdgeLength) { var ret = new List<VisibilityVertex>(); var v = _target; do { ret.Add(v); if (shrinkEdgeLength) _visGraph.ShrinkLengthOfPrevEdge(v, LengthMultiplier); v = _visGraph.PreviosVertex(v); } while (v != _source); ret.Add(_source); for (int i = ret.Count - 1; i >= 0; i--) yield return ret[i]; } } }
namespace WebMConverter { partial class MainForm { /// <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(MainForm)); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel(); this.buttonBrowseOut = new System.Windows.Forms.Button(); this.textBoxOut = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.textBoxIn = new System.Windows.Forms.TextBox(); this.buttonGo = new System.Windows.Forms.Button(); this.buttonBrowseIn = new System.Windows.Forms.Button(); this.tabControl1 = new System.Windows.Forms.TabControl(); this.tabPage1 = new System.Windows.Forms.TabPage(); this.tableLayoutPanel3 = new System.Windows.Forms.TableLayoutPanel(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.tableLayoutPanel13 = new System.Windows.Forms.TableLayoutPanel(); this.label23 = new System.Windows.Forms.Label(); this.boxAudio = new System.Windows.Forms.CheckBox(); this.groupBox5 = new System.Windows.Forms.GroupBox(); this.tableLayoutPanel11 = new System.Windows.Forms.TableLayoutPanel(); this.label19 = new System.Windows.Forms.Label(); this.boxMetadataTitle = new System.Windows.Forms.TextBox(); this.label20 = new System.Windows.Forms.Label(); this.groupBox4 = new System.Windows.Forms.GroupBox(); this.tableLayoutPanel5 = new System.Windows.Forms.TableLayoutPanel(); this.label25 = new System.Windows.Forms.Label(); this.boxHQ = new System.Windows.Forms.CheckBox(); this.label24 = new System.Windows.Forms.Label(); this.label22 = new System.Windows.Forms.Label(); this.tableLayoutPanel9 = new System.Windows.Forms.TableLayoutPanel(); this.boxCropTo = new System.Windows.Forms.TextBox(); this.boxCropFrom = new System.Windows.Forms.TextBox(); this.label17 = new System.Windows.Forms.Label(); this.tableLayoutPanel7 = new System.Windows.Forms.TableLayoutPanel(); this.boxLimit = new System.Windows.Forms.TextBox(); this.label16 = new System.Windows.Forms.Label(); this.label15 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.label14 = new System.Windows.Forms.Label(); this.tableLayoutPanel8 = new System.Windows.Forms.TableLayoutPanel(); this.boxBitrate = new System.Windows.Forms.TextBox(); this.label13 = new System.Windows.Forms.Label(); this.label12 = new System.Windows.Forms.Label(); this.label11 = new System.Windows.Forms.Label(); this.label10 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.tableLayoutPanel6 = new System.Windows.Forms.TableLayoutPanel(); this.boxResH = new System.Windows.Forms.TextBox(); this.boxResW = new System.Windows.Forms.TextBox(); this.label8 = new System.Windows.Forms.Label(); this.tableLayoutPanel14 = new System.Windows.Forms.TableLayoutPanel(); this.buttonOpenCrop = new System.Windows.Forms.Button(); this.labelCrop = new System.Windows.Forms.Label(); this.tabPage2 = new System.Windows.Forms.TabPage(); this.tableLayoutPanel4 = new System.Windows.Forms.TableLayoutPanel(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.tableLayoutPanel10 = new System.Windows.Forms.TableLayoutPanel(); this.label7 = new System.Windows.Forms.Label(); this.label9 = new System.Windows.Forms.Label(); this.tableLayoutPanel12 = new System.Windows.Forms.TableLayoutPanel(); this.trackThreads = new System.Windows.Forms.TrackBar(); this.labelThreads = new System.Windows.Forms.Label(); this.label18 = new System.Windows.Forms.Label(); this.checkBox2Pass = new System.Windows.Forms.CheckBox(); this.label3 = new System.Windows.Forms.Label(); this.textBoxArguments = new System.Windows.Forms.TextBox(); this.label21 = new System.Windows.Forms.Label(); this.tabPage3 = new System.Windows.Forms.TabPage(); this.tableLayoutPanel15 = new System.Windows.Forms.TableLayoutPanel(); this.groupBox6 = new System.Windows.Forms.GroupBox(); this.tableLayoutPanel16 = new System.Windows.Forms.TableLayoutPanel(); this.radioSubNone = new System.Windows.Forms.RadioButton(); this.radioSubInternal = new System.Windows.Forms.RadioButton(); this.radioSubExternal = new System.Windows.Forms.RadioButton(); this.label26 = new System.Windows.Forms.Label(); this.label27 = new System.Windows.Forms.Label(); this.tableLayoutPanel17 = new System.Windows.Forms.TableLayoutPanel(); this.buttonSubBrowse = new System.Windows.Forms.Button(); this.textBox1 = new System.Windows.Forms.TextBox(); this.label28 = new System.Windows.Forms.Label(); this.label29 = new System.Windows.Forms.Label(); this.label30 = new System.Windows.Forms.Label(); this.label31 = new System.Windows.Forms.Label(); this.tableLayoutPanel1.SuspendLayout(); this.groupBox1.SuspendLayout(); this.tableLayoutPanel2.SuspendLayout(); this.tabControl1.SuspendLayout(); this.tabPage1.SuspendLayout(); this.tableLayoutPanel3.SuspendLayout(); this.groupBox2.SuspendLayout(); this.tableLayoutPanel13.SuspendLayout(); this.groupBox5.SuspendLayout(); this.tableLayoutPanel11.SuspendLayout(); this.groupBox4.SuspendLayout(); this.tableLayoutPanel5.SuspendLayout(); this.tableLayoutPanel9.SuspendLayout(); this.tableLayoutPanel7.SuspendLayout(); this.tableLayoutPanel8.SuspendLayout(); this.tableLayoutPanel6.SuspendLayout(); this.tableLayoutPanel14.SuspendLayout(); this.tabPage2.SuspendLayout(); this.tableLayoutPanel4.SuspendLayout(); this.groupBox3.SuspendLayout(); this.tableLayoutPanel10.SuspendLayout(); this.tableLayoutPanel12.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.trackThreads)).BeginInit(); this.tabPage3.SuspendLayout(); this.tableLayoutPanel15.SuspendLayout(); this.groupBox6.SuspendLayout(); this.tableLayoutPanel16.SuspendLayout(); this.tableLayoutPanel17.SuspendLayout(); this.SuspendLayout(); // // tableLayoutPanel1 // this.tableLayoutPanel1.ColumnCount = 1; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel1.Controls.Add(this.groupBox1, 0, 0); this.tableLayoutPanel1.Controls.Add(this.tabControl1, 0, 1); this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel1.Location = new System.Drawing.Point(3, 3); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 2; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 84F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel1.Size = new System.Drawing.Size(1067, 440); this.tableLayoutPanel1.TabIndex = 0; // // groupBox1 // this.groupBox1.Controls.Add(this.tableLayoutPanel2); this.groupBox1.Dock = System.Windows.Forms.DockStyle.Fill; this.groupBox1.Location = new System.Drawing.Point(3, 3); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(1061, 78); this.groupBox1.TabIndex = 0; this.groupBox1.TabStop = false; this.groupBox1.Text = "Main"; // // tableLayoutPanel2 // this.tableLayoutPanel2.ColumnCount = 4; this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 69F)); this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 68F)); this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 77F)); this.tableLayoutPanel2.Controls.Add(this.buttonBrowseOut, 2, 1); this.tableLayoutPanel2.Controls.Add(this.textBoxOut, 1, 1); this.tableLayoutPanel2.Controls.Add(this.label4, 0, 1); this.tableLayoutPanel2.Controls.Add(this.label1, 0, 0); this.tableLayoutPanel2.Controls.Add(this.textBoxIn, 1, 0); this.tableLayoutPanel2.Controls.Add(this.buttonGo, 3, 0); this.tableLayoutPanel2.Controls.Add(this.buttonBrowseIn, 2, 0); this.tableLayoutPanel2.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel2.Location = new System.Drawing.Point(3, 16); this.tableLayoutPanel2.Name = "tableLayoutPanel2"; this.tableLayoutPanel2.RowCount = 2; this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel2.Size = new System.Drawing.Size(1055, 59); this.tableLayoutPanel2.TabIndex = 0; // // buttonBrowseOut // this.buttonBrowseOut.Dock = System.Windows.Forms.DockStyle.Fill; this.buttonBrowseOut.Location = new System.Drawing.Point(913, 32); this.buttonBrowseOut.Name = "buttonBrowseOut"; this.buttonBrowseOut.Size = new System.Drawing.Size(62, 24); this.buttonBrowseOut.TabIndex = 5; this.buttonBrowseOut.Text = "Browse"; this.buttonBrowseOut.UseVisualStyleBackColor = true; this.buttonBrowseOut.Click += new System.EventHandler(this.buttonBrowseOut_Click); // // textBoxOut // this.textBoxOut.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); this.textBoxOut.Location = new System.Drawing.Point(72, 34); this.textBoxOut.Name = "textBoxOut"; this.textBoxOut.Size = new System.Drawing.Size(835, 20); this.textBoxOut.TabIndex = 4; // // label4 // this.label4.AutoSize = true; this.label4.Dock = System.Windows.Forms.DockStyle.Fill; this.label4.Location = new System.Drawing.Point(3, 29); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(63, 30); this.label4.TabIndex = 3; this.label4.Text = "Output file:"; this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // label1 // this.label1.AutoSize = true; this.label1.Dock = System.Windows.Forms.DockStyle.Fill; this.label1.Location = new System.Drawing.Point(3, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(63, 29); this.label1.TabIndex = 0; this.label1.Text = "Input file:"; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // textBoxIn // this.textBoxIn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); this.textBoxIn.Location = new System.Drawing.Point(72, 4); this.textBoxIn.Name = "textBoxIn"; this.textBoxIn.Size = new System.Drawing.Size(835, 20); this.textBoxIn.TabIndex = 1; // // buttonGo // this.buttonGo.Dock = System.Windows.Forms.DockStyle.Fill; this.buttonGo.Location = new System.Drawing.Point(981, 3); this.buttonGo.Name = "buttonGo"; this.tableLayoutPanel2.SetRowSpan(this.buttonGo, 2); this.buttonGo.Size = new System.Drawing.Size(71, 53); this.buttonGo.TabIndex = 6; this.buttonGo.Text = "Convert"; this.buttonGo.UseVisualStyleBackColor = true; this.buttonGo.Click += new System.EventHandler(this.buttonGo_Click); // // buttonBrowseIn // this.buttonBrowseIn.Dock = System.Windows.Forms.DockStyle.Fill; this.buttonBrowseIn.Location = new System.Drawing.Point(913, 3); this.buttonBrowseIn.Name = "buttonBrowseIn"; this.buttonBrowseIn.Size = new System.Drawing.Size(62, 23); this.buttonBrowseIn.TabIndex = 2; this.buttonBrowseIn.Text = "Browse"; this.buttonBrowseIn.UseVisualStyleBackColor = true; this.buttonBrowseIn.Click += new System.EventHandler(this.buttonBrowseIn_Click); // // tabControl1 // this.tabControl1.Controls.Add(this.tabPage1); this.tabControl1.Controls.Add(this.tabPage3); this.tabControl1.Controls.Add(this.tabPage2); this.tabControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.tabControl1.Location = new System.Drawing.Point(3, 87); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(1061, 350); this.tabControl1.TabIndex = 6; // // tabPage1 // this.tabPage1.BackColor = System.Drawing.SystemColors.Control; this.tabPage1.Controls.Add(this.tableLayoutPanel3); this.tabPage1.Location = new System.Drawing.Point(4, 22); this.tabPage1.Name = "tabPage1"; this.tabPage1.Padding = new System.Windows.Forms.Padding(3); this.tabPage1.Size = new System.Drawing.Size(1053, 324); this.tabPage1.TabIndex = 0; this.tabPage1.Text = "Basic"; // // tableLayoutPanel3 // this.tableLayoutPanel3.ColumnCount = 1; this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel3.Controls.Add(this.groupBox2, 0, 2); this.tableLayoutPanel3.Controls.Add(this.groupBox5, 0, 0); this.tableLayoutPanel3.Controls.Add(this.groupBox4, 0, 1); this.tableLayoutPanel3.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel3.Location = new System.Drawing.Point(3, 3); this.tableLayoutPanel3.Name = "tableLayoutPanel3"; this.tableLayoutPanel3.RowCount = 3; this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 22.55639F)); this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 77.44361F)); this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 51F)); this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableLayoutPanel3.Size = new System.Drawing.Size(1047, 318); this.tableLayoutPanel3.TabIndex = 0; // // groupBox2 // this.groupBox2.Controls.Add(this.tableLayoutPanel13); this.groupBox2.Dock = System.Windows.Forms.DockStyle.Fill; this.groupBox2.Location = new System.Drawing.Point(3, 269); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(1041, 46); this.groupBox2.TabIndex = 7; this.groupBox2.TabStop = false; this.groupBox2.Text = "Audio"; // // tableLayoutPanel13 // this.tableLayoutPanel13.ColumnCount = 3; this.tableLayoutPanel13.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 76F)); this.tableLayoutPanel13.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 203F)); this.tableLayoutPanel13.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel13.Controls.Add(this.label23, 2, 0); this.tableLayoutPanel13.Controls.Add(this.boxAudio, 0, 0); this.tableLayoutPanel13.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel13.Location = new System.Drawing.Point(3, 16); this.tableLayoutPanel13.Name = "tableLayoutPanel13"; this.tableLayoutPanel13.RowCount = 1; this.tableLayoutPanel13.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel13.Size = new System.Drawing.Size(1035, 27); this.tableLayoutPanel13.TabIndex = 0; // // label23 // this.label23.AutoSize = true; this.label23.Dock = System.Windows.Forms.DockStyle.Fill; this.label23.Location = new System.Drawing.Point(282, 0); this.label23.Name = "label23"; this.label23.Size = new System.Drawing.Size(750, 27); this.label23.TabIndex = 2; this.label23.Text = "Keep this disabled until Moot allows audio."; this.label23.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // boxAudio // this.boxAudio.AutoSize = true; this.boxAudio.CheckAlign = System.Drawing.ContentAlignment.MiddleRight; this.tableLayoutPanel13.SetColumnSpan(this.boxAudio, 2); this.boxAudio.Dock = System.Windows.Forms.DockStyle.Fill; this.boxAudio.Location = new System.Drawing.Point(6, 3); this.boxAudio.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3); this.boxAudio.Name = "boxAudio"; this.boxAudio.Size = new System.Drawing.Size(267, 21); this.boxAudio.TabIndex = 3; this.boxAudio.Text = "Enable audio:"; this.boxAudio.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.boxAudio.UseVisualStyleBackColor = true; this.boxAudio.CheckedChanged += new System.EventHandler(this.UpdateArguments); // // groupBox5 // this.groupBox5.Controls.Add(this.tableLayoutPanel11); this.groupBox5.Dock = System.Windows.Forms.DockStyle.Fill; this.groupBox5.Location = new System.Drawing.Point(3, 3); this.groupBox5.Name = "groupBox5"; this.groupBox5.Size = new System.Drawing.Size(1041, 54); this.groupBox5.TabIndex = 6; this.groupBox5.TabStop = false; this.groupBox5.Text = "Metadata"; // // tableLayoutPanel11 // this.tableLayoutPanel11.ColumnCount = 3; this.tableLayoutPanel11.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 76F)); this.tableLayoutPanel11.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 413F)); this.tableLayoutPanel11.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel11.Controls.Add(this.label19, 0, 0); this.tableLayoutPanel11.Controls.Add(this.boxMetadataTitle, 1, 0); this.tableLayoutPanel11.Controls.Add(this.label20, 2, 0); this.tableLayoutPanel11.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel11.Location = new System.Drawing.Point(3, 16); this.tableLayoutPanel11.Name = "tableLayoutPanel11"; this.tableLayoutPanel11.RowCount = 1; this.tableLayoutPanel11.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel11.Size = new System.Drawing.Size(1035, 35); this.tableLayoutPanel11.TabIndex = 0; // // label19 // this.label19.AutoSize = true; this.label19.Dock = System.Windows.Forms.DockStyle.Fill; this.label19.Location = new System.Drawing.Point(3, 0); this.label19.Name = "label19"; this.label19.Size = new System.Drawing.Size(70, 35); this.label19.TabIndex = 0; this.label19.Text = "Title:"; this.label19.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // boxMetadataTitle // this.boxMetadataTitle.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); this.boxMetadataTitle.Location = new System.Drawing.Point(82, 7); this.boxMetadataTitle.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3); this.boxMetadataTitle.Name = "boxMetadataTitle"; this.boxMetadataTitle.Size = new System.Drawing.Size(401, 20); this.boxMetadataTitle.TabIndex = 1; this.boxMetadataTitle.TextChanged += new System.EventHandler(this.UpdateArguments); // // label20 // this.label20.AutoSize = true; this.label20.Dock = System.Windows.Forms.DockStyle.Fill; this.label20.Location = new System.Drawing.Point(492, 0); this.label20.Name = "label20"; this.label20.Size = new System.Drawing.Size(540, 35); this.label20.TabIndex = 2; this.label20.Text = "Adds a string of text to the metadata of the video, which can be used to indicate" + " the source of a video, for example. Leave blank for no title."; this.label20.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // groupBox4 // this.groupBox4.Controls.Add(this.tableLayoutPanel5); this.groupBox4.Dock = System.Windows.Forms.DockStyle.Fill; this.groupBox4.Location = new System.Drawing.Point(3, 63); this.groupBox4.Name = "groupBox4"; this.groupBox4.Size = new System.Drawing.Size(1041, 200); this.groupBox4.TabIndex = 5; this.groupBox4.TabStop = false; this.groupBox4.Text = "Video"; // // tableLayoutPanel5 // this.tableLayoutPanel5.ColumnCount = 3; this.tableLayoutPanel5.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 76F)); this.tableLayoutPanel5.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 202F)); this.tableLayoutPanel5.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel5.Controls.Add(this.label25, 2, 5); this.tableLayoutPanel5.Controls.Add(this.boxHQ, 0, 5); this.tableLayoutPanel5.Controls.Add(this.label24, 2, 2); this.tableLayoutPanel5.Controls.Add(this.label22, 0, 2); this.tableLayoutPanel5.Controls.Add(this.tableLayoutPanel9, 1, 1); this.tableLayoutPanel5.Controls.Add(this.tableLayoutPanel7, 1, 4); this.tableLayoutPanel5.Controls.Add(this.label15, 0, 4); this.tableLayoutPanel5.Controls.Add(this.label6, 2, 4); this.tableLayoutPanel5.Controls.Add(this.label14, 2, 3); this.tableLayoutPanel5.Controls.Add(this.tableLayoutPanel8, 1, 3); this.tableLayoutPanel5.Controls.Add(this.label12, 0, 3); this.tableLayoutPanel5.Controls.Add(this.label11, 2, 1); this.tableLayoutPanel5.Controls.Add(this.label10, 0, 1); this.tableLayoutPanel5.Controls.Add(this.label5, 2, 0); this.tableLayoutPanel5.Controls.Add(this.label2, 0, 0); this.tableLayoutPanel5.Controls.Add(this.tableLayoutPanel6, 1, 0); this.tableLayoutPanel5.Controls.Add(this.tableLayoutPanel14, 1, 2); this.tableLayoutPanel5.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel5.Location = new System.Drawing.Point(3, 16); this.tableLayoutPanel5.Name = "tableLayoutPanel5"; this.tableLayoutPanel5.RowCount = 6; this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 16.66667F)); this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 16.66667F)); this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 16.66667F)); this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 16.66667F)); this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 16.66667F)); this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 16.66667F)); this.tableLayoutPanel5.Size = new System.Drawing.Size(1035, 181); this.tableLayoutPanel5.TabIndex = 0; // // label25 // this.label25.AutoSize = true; this.label25.Dock = System.Windows.Forms.DockStyle.Fill; this.label25.Location = new System.Drawing.Point(281, 150); this.label25.Name = "label25"; this.label25.Size = new System.Drawing.Size(751, 31); this.label25.TabIndex = 16; this.label25.Text = "Will greatly increase the quality/size ratio. Be warned, this will make the conve" + "rsion take forever."; this.label25.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // boxHQ // this.boxHQ.AutoSize = true; this.boxHQ.CheckAlign = System.Drawing.ContentAlignment.MiddleRight; this.tableLayoutPanel5.SetColumnSpan(this.boxHQ, 2); this.boxHQ.Dock = System.Windows.Forms.DockStyle.Fill; this.boxHQ.Location = new System.Drawing.Point(6, 153); this.boxHQ.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3); this.boxHQ.Name = "boxHQ"; this.boxHQ.Size = new System.Drawing.Size(266, 25); this.boxHQ.TabIndex = 15; this.boxHQ.Text = "Enable high quality mode:"; this.boxHQ.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.boxHQ.UseVisualStyleBackColor = true; this.boxHQ.CheckedChanged += new System.EventHandler(this.UpdateArguments); // // label24 // this.label24.AutoSize = true; this.label24.Dock = System.Windows.Forms.DockStyle.Fill; this.label24.Location = new System.Drawing.Point(281, 60); this.label24.Name = "label24"; this.label24.Size = new System.Drawing.Size(751, 30); this.label24.TabIndex = 13; this.label24.Text = "Crop a region out of the video. Click the Crop... button to select the region to " + "be cropped. Useful for reaction videos."; this.label24.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label22 // this.label22.AutoSize = true; this.label22.Dock = System.Windows.Forms.DockStyle.Fill; this.label22.Location = new System.Drawing.Point(3, 60); this.label22.Name = "label22"; this.label22.Size = new System.Drawing.Size(70, 30); this.label22.TabIndex = 12; this.label22.Text = "Crop size:"; this.label22.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // tableLayoutPanel9 // this.tableLayoutPanel9.ColumnCount = 3; this.tableLayoutPanel9.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel9.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 16F)); this.tableLayoutPanel9.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel9.Controls.Add(this.boxCropTo, 2, 0); this.tableLayoutPanel9.Controls.Add(this.boxCropFrom, 0, 0); this.tableLayoutPanel9.Controls.Add(this.label17, 1, 0); this.tableLayoutPanel9.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel9.Location = new System.Drawing.Point(79, 30); this.tableLayoutPanel9.Margin = new System.Windows.Forms.Padding(3, 0, 3, 0); this.tableLayoutPanel9.Name = "tableLayoutPanel9"; this.tableLayoutPanel9.RowCount = 1; this.tableLayoutPanel9.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel9.Size = new System.Drawing.Size(196, 30); this.tableLayoutPanel9.TabIndex = 4; // // boxCropTo // this.boxCropTo.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); this.boxCropTo.Location = new System.Drawing.Point(109, 5); this.boxCropTo.Name = "boxCropTo"; this.boxCropTo.Size = new System.Drawing.Size(84, 20); this.boxCropTo.TabIndex = 2; this.boxCropTo.TextChanged += new System.EventHandler(this.UpdateArguments); // // boxCropFrom // this.boxCropFrom.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); this.boxCropFrom.Location = new System.Drawing.Point(3, 5); this.boxCropFrom.Name = "boxCropFrom"; this.boxCropFrom.Size = new System.Drawing.Size(84, 20); this.boxCropFrom.TabIndex = 0; this.boxCropFrom.TextChanged += new System.EventHandler(this.UpdateArguments); // // label17 // this.label17.AutoSize = true; this.label17.Dock = System.Windows.Forms.DockStyle.Fill; this.label17.Location = new System.Drawing.Point(90, 0); this.label17.Margin = new System.Windows.Forms.Padding(0); this.label17.Name = "label17"; this.label17.Size = new System.Drawing.Size(16, 30); this.label17.TabIndex = 1; this.label17.Text = "to"; this.label17.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // tableLayoutPanel7 // this.tableLayoutPanel7.ColumnCount = 2; this.tableLayoutPanel7.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel7.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 40F)); this.tableLayoutPanel7.Controls.Add(this.boxLimit, 0, 0); this.tableLayoutPanel7.Controls.Add(this.label16, 1, 0); this.tableLayoutPanel7.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel7.Location = new System.Drawing.Point(79, 120); this.tableLayoutPanel7.Margin = new System.Windows.Forms.Padding(3, 0, 3, 0); this.tableLayoutPanel7.Name = "tableLayoutPanel7"; this.tableLayoutPanel7.RowCount = 1; this.tableLayoutPanel7.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel7.Size = new System.Drawing.Size(196, 30); this.tableLayoutPanel7.TabIndex = 10; // // boxLimit // this.boxLimit.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); this.boxLimit.Location = new System.Drawing.Point(3, 5); this.boxLimit.Name = "boxLimit"; this.boxLimit.Size = new System.Drawing.Size(150, 20); this.boxLimit.TabIndex = 0; this.boxLimit.TextChanged += new System.EventHandler(this.UpdateArguments); // // label16 // this.label16.AutoSize = true; this.label16.Dock = System.Windows.Forms.DockStyle.Fill; this.label16.Location = new System.Drawing.Point(159, 0); this.label16.Name = "label16"; this.label16.Size = new System.Drawing.Size(34, 30); this.label16.TabIndex = 1; this.label16.Text = "MB"; this.label16.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label15 // this.label15.AutoSize = true; this.label15.Dock = System.Windows.Forms.DockStyle.Fill; this.label15.Location = new System.Drawing.Point(3, 120); this.label15.Name = "label15"; this.label15.Size = new System.Drawing.Size(70, 30); this.label15.TabIndex = 9; this.label15.Text = "Size limit:"; this.label15.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // label6 // this.label6.AutoSize = true; this.label6.Dock = System.Windows.Forms.DockStyle.Fill; this.label6.Location = new System.Drawing.Point(281, 120); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(751, 30); this.label6.TabIndex = 11; this.label6.Text = "Will adjust the quality to attempt to stay below this limit, and cut off the end " + "of a video if needed. Leave blank for no limit. The limit on 4chan is 3 MB. If e" + "ntering decimals use dots, not commas."; this.label6.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label14 // this.label14.AutoSize = true; this.label14.Dock = System.Windows.Forms.DockStyle.Fill; this.label14.Location = new System.Drawing.Point(281, 90); this.label14.Name = "label14"; this.label14.Size = new System.Drawing.Size(751, 30); this.label14.TabIndex = 8; this.label14.Text = "Determines the quality of the video. Keep blank to let the program pick one based" + " on size limit and duration."; this.label14.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // tableLayoutPanel8 // this.tableLayoutPanel8.ColumnCount = 2; this.tableLayoutPanel8.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel8.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 40F)); this.tableLayoutPanel8.Controls.Add(this.boxBitrate, 0, 0); this.tableLayoutPanel8.Controls.Add(this.label13, 1, 0); this.tableLayoutPanel8.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel8.Location = new System.Drawing.Point(79, 90); this.tableLayoutPanel8.Margin = new System.Windows.Forms.Padding(3, 0, 3, 0); this.tableLayoutPanel8.Name = "tableLayoutPanel8"; this.tableLayoutPanel8.RowCount = 1; this.tableLayoutPanel8.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel8.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 30F)); this.tableLayoutPanel8.Size = new System.Drawing.Size(196, 30); this.tableLayoutPanel8.TabIndex = 7; // // boxBitrate // this.boxBitrate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); this.boxBitrate.Location = new System.Drawing.Point(3, 5); this.boxBitrate.Name = "boxBitrate"; this.boxBitrate.Size = new System.Drawing.Size(150, 20); this.boxBitrate.TabIndex = 0; this.boxBitrate.TextChanged += new System.EventHandler(this.UpdateArguments); // // label13 // this.label13.AutoSize = true; this.label13.Dock = System.Windows.Forms.DockStyle.Fill; this.label13.Location = new System.Drawing.Point(159, 0); this.label13.Name = "label13"; this.label13.Size = new System.Drawing.Size(34, 30); this.label13.TabIndex = 1; this.label13.Text = "Kb/s"; this.label13.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label12 // this.label12.AutoSize = true; this.label12.Dock = System.Windows.Forms.DockStyle.Fill; this.label12.Location = new System.Drawing.Point(3, 90); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(70, 30); this.label12.TabIndex = 6; this.label12.Text = "Bitrate:"; this.label12.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // label11 // this.label11.AutoSize = true; this.label11.Dock = System.Windows.Forms.DockStyle.Fill; this.label11.Location = new System.Drawing.Point(281, 30); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(751, 30); this.label11.TabIndex = 5; this.label11.Text = resources.GetString("label11.Text"); this.label11.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label10 // this.label10.AutoSize = true; this.label10.Dock = System.Windows.Forms.DockStyle.Fill; this.label10.Location = new System.Drawing.Point(3, 30); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(70, 30); this.label10.TabIndex = 3; this.label10.Text = "Trim video:"; this.label10.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // label5 // this.label5.AutoSize = true; this.label5.Dock = System.Windows.Forms.DockStyle.Fill; this.label5.Location = new System.Drawing.Point(281, 0); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(751, 30); this.label5.TabIndex = 2; this.label5.Text = "Enter nothing to keep resolution intact. Enter -1 in one of the fields to scale a" + "ccording to aspect ratio."; this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label2 // this.label2.AutoSize = true; this.label2.Dock = System.Windows.Forms.DockStyle.Fill; this.label2.Location = new System.Drawing.Point(3, 0); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(70, 30); this.label2.TabIndex = 0; this.label2.Text = "Resolution:"; this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // tableLayoutPanel6 // this.tableLayoutPanel6.ColumnCount = 3; this.tableLayoutPanel6.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel6.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 16F)); this.tableLayoutPanel6.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel6.Controls.Add(this.boxResH, 2, 0); this.tableLayoutPanel6.Controls.Add(this.boxResW, 0, 0); this.tableLayoutPanel6.Controls.Add(this.label8, 1, 0); this.tableLayoutPanel6.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel6.Location = new System.Drawing.Point(79, 0); this.tableLayoutPanel6.Margin = new System.Windows.Forms.Padding(3, 0, 3, 0); this.tableLayoutPanel6.Name = "tableLayoutPanel6"; this.tableLayoutPanel6.RowCount = 1; this.tableLayoutPanel6.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel6.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 30F)); this.tableLayoutPanel6.Size = new System.Drawing.Size(196, 30); this.tableLayoutPanel6.TabIndex = 1; // // boxResH // this.boxResH.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); this.boxResH.Location = new System.Drawing.Point(109, 5); this.boxResH.Name = "boxResH"; this.boxResH.Size = new System.Drawing.Size(84, 20); this.boxResH.TabIndex = 2; this.boxResH.TextChanged += new System.EventHandler(this.UpdateArguments); // // boxResW // this.boxResW.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); this.boxResW.Location = new System.Drawing.Point(3, 5); this.boxResW.Name = "boxResW"; this.boxResW.Size = new System.Drawing.Size(84, 20); this.boxResW.TabIndex = 0; this.boxResW.TextChanged += new System.EventHandler(this.UpdateArguments); // // label8 // this.label8.AutoSize = true; this.label8.Dock = System.Windows.Forms.DockStyle.Fill; this.label8.Location = new System.Drawing.Point(90, 0); this.label8.Margin = new System.Windows.Forms.Padding(0); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(16, 30); this.label8.TabIndex = 1; this.label8.Text = "x"; this.label8.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // tableLayoutPanel14 // this.tableLayoutPanel14.ColumnCount = 2; this.tableLayoutPanel14.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel14.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 56F)); this.tableLayoutPanel14.Controls.Add(this.buttonOpenCrop, 1, 0); this.tableLayoutPanel14.Controls.Add(this.labelCrop, 0, 0); this.tableLayoutPanel14.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel14.Location = new System.Drawing.Point(79, 60); this.tableLayoutPanel14.Margin = new System.Windows.Forms.Padding(3, 0, 3, 0); this.tableLayoutPanel14.Name = "tableLayoutPanel14"; this.tableLayoutPanel14.RowCount = 1; this.tableLayoutPanel14.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel14.Size = new System.Drawing.Size(196, 30); this.tableLayoutPanel14.TabIndex = 14; // // buttonOpenCrop // this.buttonOpenCrop.Dock = System.Windows.Forms.DockStyle.Fill; this.buttonOpenCrop.Location = new System.Drawing.Point(143, 3); this.buttonOpenCrop.Name = "buttonOpenCrop"; this.buttonOpenCrop.Size = new System.Drawing.Size(50, 24); this.buttonOpenCrop.TabIndex = 0; this.buttonOpenCrop.Text = "Crop..."; this.buttonOpenCrop.UseVisualStyleBackColor = true; this.buttonOpenCrop.Click += new System.EventHandler(this.buttonOpenCrop_Click); // // labelCrop // this.labelCrop.AutoSize = true; this.labelCrop.Dock = System.Windows.Forms.DockStyle.Fill; this.labelCrop.Font = new System.Drawing.Font("Microsoft Sans Serif", 6.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelCrop.Location = new System.Drawing.Point(3, 0); this.labelCrop.Name = "labelCrop"; this.labelCrop.Size = new System.Drawing.Size(134, 30); this.labelCrop.TabIndex = 1; this.labelCrop.Text = "Don\'t crop"; this.labelCrop.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // tabPage2 // this.tabPage2.BackColor = System.Drawing.SystemColors.Control; this.tabPage2.Controls.Add(this.tableLayoutPanel4); this.tabPage2.Location = new System.Drawing.Point(4, 22); this.tabPage2.Name = "tabPage2"; this.tabPage2.Padding = new System.Windows.Forms.Padding(3); this.tabPage2.Size = new System.Drawing.Size(1053, 324); this.tabPage2.TabIndex = 1; this.tabPage2.Text = "Advanced"; // // tableLayoutPanel4 // this.tableLayoutPanel4.ColumnCount = 1; this.tableLayoutPanel4.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel4.Controls.Add(this.groupBox3, 0, 0); this.tableLayoutPanel4.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel4.Location = new System.Drawing.Point(3, 3); this.tableLayoutPanel4.Name = "tableLayoutPanel4"; this.tableLayoutPanel4.RowCount = 2; this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 163F)); this.tableLayoutPanel4.Size = new System.Drawing.Size(1047, 318); this.tableLayoutPanel4.TabIndex = 0; // // groupBox3 // this.groupBox3.AutoSize = true; this.groupBox3.Controls.Add(this.tableLayoutPanel10); this.groupBox3.Dock = System.Windows.Forms.DockStyle.Fill; this.groupBox3.Location = new System.Drawing.Point(3, 3); this.groupBox3.Name = "groupBox3"; this.groupBox3.Size = new System.Drawing.Size(1041, 149); this.groupBox3.TabIndex = 8; this.groupBox3.TabStop = false; this.groupBox3.Text = "Advanced"; // // tableLayoutPanel10 // this.tableLayoutPanel10.ColumnCount = 3; this.tableLayoutPanel10.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 79F)); this.tableLayoutPanel10.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 148F)); this.tableLayoutPanel10.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel10.Controls.Add(this.label7, 0, 1); this.tableLayoutPanel10.Controls.Add(this.label9, 2, 1); this.tableLayoutPanel10.Controls.Add(this.tableLayoutPanel12, 1, 1); this.tableLayoutPanel10.Controls.Add(this.label18, 2, 2); this.tableLayoutPanel10.Controls.Add(this.checkBox2Pass, 0, 2); this.tableLayoutPanel10.Controls.Add(this.label3, 0, 3); this.tableLayoutPanel10.Controls.Add(this.textBoxArguments, 1, 3); this.tableLayoutPanel10.Controls.Add(this.label21, 0, 0); this.tableLayoutPanel10.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel10.Location = new System.Drawing.Point(3, 16); this.tableLayoutPanel10.Name = "tableLayoutPanel10"; this.tableLayoutPanel10.RowCount = 4; this.tableLayoutPanel10.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 28F)); this.tableLayoutPanel10.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333F)); this.tableLayoutPanel10.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333F)); this.tableLayoutPanel10.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333F)); this.tableLayoutPanel10.Size = new System.Drawing.Size(1035, 130); this.tableLayoutPanel10.TabIndex = 0; // // label7 // this.label7.AutoSize = true; this.label7.Dock = System.Windows.Forms.DockStyle.Fill; this.label7.Location = new System.Drawing.Point(3, 28); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(73, 34); this.label7.TabIndex = 28; this.label7.Text = "Threads:"; this.label7.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // label9 // this.label9.AutoSize = true; this.label9.Dock = System.Windows.Forms.DockStyle.Fill; this.label9.Location = new System.Drawing.Point(230, 28); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(802, 34); this.label9.TabIndex = 27; this.label9.Text = "Determines amount of threads ffmpeg uses. Try setting this to 1 if ffmpeg.exe cra" + "shes as soon as you click Convert."; this.label9.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // tableLayoutPanel12 // this.tableLayoutPanel12.ColumnCount = 2; this.tableLayoutPanel12.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 86.18421F)); this.tableLayoutPanel12.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 13.81579F)); this.tableLayoutPanel12.Controls.Add(this.trackThreads, 0, 0); this.tableLayoutPanel12.Controls.Add(this.labelThreads, 1, 0); this.tableLayoutPanel12.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel12.Location = new System.Drawing.Point(82, 31); this.tableLayoutPanel12.Name = "tableLayoutPanel12"; this.tableLayoutPanel12.RowCount = 1; this.tableLayoutPanel12.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel12.Size = new System.Drawing.Size(142, 28); this.tableLayoutPanel12.TabIndex = 26; // // trackThreads // this.trackThreads.Dock = System.Windows.Forms.DockStyle.Fill; this.trackThreads.Location = new System.Drawing.Point(0, 0); this.trackThreads.Margin = new System.Windows.Forms.Padding(0); this.trackThreads.Maximum = 16; this.trackThreads.Minimum = 1; this.trackThreads.Name = "trackThreads"; this.trackThreads.Size = new System.Drawing.Size(122, 28); this.trackThreads.TabIndex = 0; this.trackThreads.Value = 1; this.trackThreads.Scroll += new System.EventHandler(this.trackThreads_Scroll); // // labelThreads // this.labelThreads.AutoSize = true; this.labelThreads.Dock = System.Windows.Forms.DockStyle.Fill; this.labelThreads.Location = new System.Drawing.Point(122, 0); this.labelThreads.Margin = new System.Windows.Forms.Padding(0); this.labelThreads.Name = "labelThreads"; this.labelThreads.Size = new System.Drawing.Size(20, 28); this.labelThreads.TabIndex = 1; this.labelThreads.Text = "1"; this.labelThreads.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label18 // this.label18.AutoSize = true; this.label18.Dock = System.Windows.Forms.DockStyle.Fill; this.label18.Location = new System.Drawing.Point(230, 62); this.label18.Name = "label18"; this.label18.Size = new System.Drawing.Size(802, 34); this.label18.TabIndex = 16; this.label18.Text = "Will make ffmpeg use two passes, which can increase the quality/size ratio, but a" + "lso increases the time it takes to encode. Disable if you run into any issues."; this.label18.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // checkBox2Pass // this.checkBox2Pass.CheckAlign = System.Drawing.ContentAlignment.MiddleRight; this.tableLayoutPanel10.SetColumnSpan(this.checkBox2Pass, 2); this.checkBox2Pass.Dock = System.Windows.Forms.DockStyle.Fill; this.checkBox2Pass.Location = new System.Drawing.Point(6, 65); this.checkBox2Pass.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3); this.checkBox2Pass.Name = "checkBox2Pass"; this.checkBox2Pass.Size = new System.Drawing.Size(215, 28); this.checkBox2Pass.TabIndex = 12; this.checkBox2Pass.Text = "Enable 2-pass encoding:"; this.checkBox2Pass.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.checkBox2Pass.UseVisualStyleBackColor = true; // // label3 // this.label3.AutoSize = true; this.label3.Dock = System.Windows.Forms.DockStyle.Fill; this.label3.ImageAlign = System.Drawing.ContentAlignment.MiddleRight; this.label3.Location = new System.Drawing.Point(3, 96); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(73, 34); this.label3.TabIndex = 29; this.label3.Text = "Arguments:"; this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // textBoxArguments // this.textBoxArguments.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); this.tableLayoutPanel10.SetColumnSpan(this.textBoxArguments, 2); this.textBoxArguments.Location = new System.Drawing.Point(85, 103); this.textBoxArguments.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3); this.textBoxArguments.Name = "textBoxArguments"; this.textBoxArguments.Size = new System.Drawing.Size(944, 20); this.textBoxArguments.TabIndex = 30; // // label21 // this.label21.AutoSize = true; this.tableLayoutPanel10.SetColumnSpan(this.label21, 3); this.label21.Dock = System.Windows.Forms.DockStyle.Fill; this.label21.Location = new System.Drawing.Point(3, 3); this.label21.Margin = new System.Windows.Forms.Padding(3); this.label21.Name = "label21"; this.label21.Size = new System.Drawing.Size(1029, 22); this.label21.TabIndex = 31; this.label21.Text = "Don\'t modify these unless you know what you\'re doing!"; this.label21.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // tabPage3 // this.tabPage3.BackColor = System.Drawing.SystemColors.Control; this.tabPage3.Controls.Add(this.tableLayoutPanel15); this.tabPage3.Location = new System.Drawing.Point(4, 22); this.tabPage3.Name = "tabPage3"; this.tabPage3.Padding = new System.Windows.Forms.Padding(3); this.tabPage3.Size = new System.Drawing.Size(1053, 324); this.tabPage3.TabIndex = 2; this.tabPage3.Text = "Subtitles"; // // tableLayoutPanel15 // this.tableLayoutPanel15.ColumnCount = 1; this.tableLayoutPanel15.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel15.Controls.Add(this.groupBox6, 0, 0); this.tableLayoutPanel15.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel15.Location = new System.Drawing.Point(3, 3); this.tableLayoutPanel15.Name = "tableLayoutPanel15"; this.tableLayoutPanel15.RowCount = 2; this.tableLayoutPanel15.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 38.99371F)); this.tableLayoutPanel15.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 61.00629F)); this.tableLayoutPanel15.Size = new System.Drawing.Size(1047, 318); this.tableLayoutPanel15.TabIndex = 0; // // groupBox6 // this.groupBox6.Controls.Add(this.tableLayoutPanel16); this.groupBox6.Dock = System.Windows.Forms.DockStyle.Fill; this.groupBox6.Location = new System.Drawing.Point(3, 3); this.groupBox6.Name = "groupBox6"; this.groupBox6.Size = new System.Drawing.Size(1041, 117); this.groupBox6.TabIndex = 0; this.groupBox6.TabStop = false; this.groupBox6.Text = "Subtitles"; // // tableLayoutPanel16 // this.tableLayoutPanel16.ColumnCount = 3; this.tableLayoutPanel16.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 79F)); this.tableLayoutPanel16.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 233F)); this.tableLayoutPanel16.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel16.Controls.Add(this.label31, 2, 3); this.tableLayoutPanel16.Controls.Add(this.label30, 2, 2); this.tableLayoutPanel16.Controls.Add(this.label29, 2, 1); this.tableLayoutPanel16.Controls.Add(this.radioSubNone, 1, 0); this.tableLayoutPanel16.Controls.Add(this.radioSubInternal, 1, 1); this.tableLayoutPanel16.Controls.Add(this.radioSubExternal, 1, 2); this.tableLayoutPanel16.Controls.Add(this.label26, 0, 0); this.tableLayoutPanel16.Controls.Add(this.label27, 0, 3); this.tableLayoutPanel16.Controls.Add(this.tableLayoutPanel17, 1, 3); this.tableLayoutPanel16.Controls.Add(this.label28, 2, 0); this.tableLayoutPanel16.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel16.Location = new System.Drawing.Point(3, 16); this.tableLayoutPanel16.Name = "tableLayoutPanel16"; this.tableLayoutPanel16.RowCount = 4; this.tableLayoutPanel16.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333F)); this.tableLayoutPanel16.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333F)); this.tableLayoutPanel16.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333F)); this.tableLayoutPanel16.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 27F)); this.tableLayoutPanel16.Size = new System.Drawing.Size(1035, 98); this.tableLayoutPanel16.TabIndex = 0; // // radioSubNone // this.radioSubNone.AutoSize = true; this.radioSubNone.Checked = true; this.radioSubNone.Dock = System.Windows.Forms.DockStyle.Fill; this.radioSubNone.Enabled = false; this.radioSubNone.Location = new System.Drawing.Point(82, 0); this.radioSubNone.Margin = new System.Windows.Forms.Padding(3, 0, 3, 0); this.radioSubNone.Name = "radioSubNone"; this.radioSubNone.Size = new System.Drawing.Size(227, 23); this.radioSubNone.TabIndex = 0; this.radioSubNone.TabStop = true; this.radioSubNone.Text = "None"; this.radioSubNone.UseVisualStyleBackColor = true; // // radioSubInternal // this.radioSubInternal.AutoSize = true; this.radioSubInternal.Dock = System.Windows.Forms.DockStyle.Fill; this.radioSubInternal.Enabled = false; this.radioSubInternal.Location = new System.Drawing.Point(82, 23); this.radioSubInternal.Margin = new System.Windows.Forms.Padding(3, 0, 3, 0); this.radioSubInternal.Name = "radioSubInternal"; this.radioSubInternal.Size = new System.Drawing.Size(227, 23); this.radioSubInternal.TabIndex = 1; this.radioSubInternal.Text = "Use internal"; this.radioSubInternal.UseVisualStyleBackColor = true; // // radioSubExternal // this.radioSubExternal.AutoSize = true; this.radioSubExternal.Dock = System.Windows.Forms.DockStyle.Fill; this.radioSubExternal.Enabled = false; this.radioSubExternal.Location = new System.Drawing.Point(82, 46); this.radioSubExternal.Margin = new System.Windows.Forms.Padding(3, 0, 3, 0); this.radioSubExternal.Name = "radioSubExternal"; this.radioSubExternal.Size = new System.Drawing.Size(227, 23); this.radioSubExternal.TabIndex = 2; this.radioSubExternal.Text = "Use from file"; this.radioSubExternal.UseVisualStyleBackColor = true; // // label26 // this.label26.AutoSize = true; this.label26.Dock = System.Windows.Forms.DockStyle.Fill; this.label26.Location = new System.Drawing.Point(3, 0); this.label26.Name = "label26"; this.tableLayoutPanel16.SetRowSpan(this.label26, 3); this.label26.Size = new System.Drawing.Size(73, 69); this.label26.TabIndex = 3; this.label26.Text = "Subtitles:"; this.label26.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // label27 // this.label27.AutoSize = true; this.label27.Dock = System.Windows.Forms.DockStyle.Fill; this.label27.Location = new System.Drawing.Point(3, 69); this.label27.Name = "label27"; this.label27.Size = new System.Drawing.Size(73, 29); this.label27.TabIndex = 4; this.label27.Text = "Subtitle file:"; this.label27.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // tableLayoutPanel17 // this.tableLayoutPanel17.ColumnCount = 2; this.tableLayoutPanel17.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel17.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 59F)); this.tableLayoutPanel17.Controls.Add(this.buttonSubBrowse, 1, 0); this.tableLayoutPanel17.Controls.Add(this.textBox1, 0, 0); this.tableLayoutPanel17.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel17.Location = new System.Drawing.Point(82, 69); this.tableLayoutPanel17.Margin = new System.Windows.Forms.Padding(3, 0, 3, 0); this.tableLayoutPanel17.Name = "tableLayoutPanel17"; this.tableLayoutPanel17.RowCount = 1; this.tableLayoutPanel17.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel17.Size = new System.Drawing.Size(227, 29); this.tableLayoutPanel17.TabIndex = 5; // // buttonSubBrowse // this.buttonSubBrowse.Dock = System.Windows.Forms.DockStyle.Fill; this.buttonSubBrowse.Enabled = false; this.buttonSubBrowse.Location = new System.Drawing.Point(171, 3); this.buttonSubBrowse.Name = "buttonSubBrowse"; this.buttonSubBrowse.Size = new System.Drawing.Size(53, 23); this.buttonSubBrowse.TabIndex = 0; this.buttonSubBrowse.Text = "Browse"; this.buttonSubBrowse.UseVisualStyleBackColor = true; // // textBox1 // this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); this.textBox1.Enabled = false; this.textBox1.Location = new System.Drawing.Point(3, 4); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(162, 20); this.textBox1.TabIndex = 1; // // label28 // this.label28.AutoSize = true; this.label28.Dock = System.Windows.Forms.DockStyle.Fill; this.label28.Location = new System.Drawing.Point(315, 0); this.label28.Name = "label28"; this.label28.Size = new System.Drawing.Size(717, 23); this.label28.TabIndex = 6; this.label28.Text = "Don\'t add any subtitles to the video."; this.label28.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label29 // this.label29.AutoSize = true; this.label29.Dock = System.Windows.Forms.DockStyle.Fill; this.label29.Location = new System.Drawing.Point(315, 23); this.label29.Name = "label29"; this.label29.Size = new System.Drawing.Size(717, 23); this.label29.TabIndex = 7; this.label29.Text = "Add subtitles which are taken from the input video."; this.label29.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label30 // this.label30.AutoSize = true; this.label30.Dock = System.Windows.Forms.DockStyle.Fill; this.label30.Location = new System.Drawing.Point(315, 46); this.label30.Name = "label30"; this.label30.Size = new System.Drawing.Size(717, 23); this.label30.TabIndex = 8; this.label30.Text = "Add subtitles which are taken from an external file. Use the box below to select " + "the file."; this.label30.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label31 // this.label31.AutoSize = true; this.label31.Dock = System.Windows.Forms.DockStyle.Fill; this.label31.Location = new System.Drawing.Point(315, 69); this.label31.Name = "label31"; this.label31.Size = new System.Drawing.Size(717, 29); this.label31.TabIndex = 9; this.label31.Text = "Select the subtitle file to use for the video. Supports *.ass and *.srt format."; this.label31.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // MainForm // this.AcceptButton = this.buttonGo; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1073, 446); this.Controls.Add(this.tableLayoutPanel1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimumSize = new System.Drawing.Size(975, 270); this.Name = "MainForm"; this.Padding = new System.Windows.Forms.Padding(3); this.Text = "WebM for bakas"; this.Load += new System.EventHandler(this.MainForm_Load); this.tableLayoutPanel1.ResumeLayout(false); this.groupBox1.ResumeLayout(false); this.tableLayoutPanel2.ResumeLayout(false); this.tableLayoutPanel2.PerformLayout(); this.tabControl1.ResumeLayout(false); this.tabPage1.ResumeLayout(false); this.tableLayoutPanel3.ResumeLayout(false); this.groupBox2.ResumeLayout(false); this.tableLayoutPanel13.ResumeLayout(false); this.tableLayoutPanel13.PerformLayout(); this.groupBox5.ResumeLayout(false); this.tableLayoutPanel11.ResumeLayout(false); this.tableLayoutPanel11.PerformLayout(); this.groupBox4.ResumeLayout(false); this.tableLayoutPanel5.ResumeLayout(false); this.tableLayoutPanel5.PerformLayout(); this.tableLayoutPanel9.ResumeLayout(false); this.tableLayoutPanel9.PerformLayout(); this.tableLayoutPanel7.ResumeLayout(false); this.tableLayoutPanel7.PerformLayout(); this.tableLayoutPanel8.ResumeLayout(false); this.tableLayoutPanel8.PerformLayout(); this.tableLayoutPanel6.ResumeLayout(false); this.tableLayoutPanel6.PerformLayout(); this.tableLayoutPanel14.ResumeLayout(false); this.tableLayoutPanel14.PerformLayout(); this.tabPage2.ResumeLayout(false); this.tableLayoutPanel4.ResumeLayout(false); this.tableLayoutPanel4.PerformLayout(); this.groupBox3.ResumeLayout(false); this.tableLayoutPanel10.ResumeLayout(false); this.tableLayoutPanel10.PerformLayout(); this.tableLayoutPanel12.ResumeLayout(false); this.tableLayoutPanel12.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.trackThreads)).EndInit(); this.tabPage3.ResumeLayout(false); this.tableLayoutPanel15.ResumeLayout(false); this.groupBox6.ResumeLayout(false); this.tableLayoutPanel16.ResumeLayout(false); this.tableLayoutPanel16.PerformLayout(); this.tableLayoutPanel17.ResumeLayout(false); this.tableLayoutPanel17.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2; private System.Windows.Forms.Button buttonBrowseOut; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button buttonGo; private System.Windows.Forms.Button buttonBrowseIn; private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage tabPage1; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel3; private System.Windows.Forms.GroupBox groupBox5; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel11; private System.Windows.Forms.Label label19; private System.Windows.Forms.TextBox boxMetadataTitle; private System.Windows.Forms.Label label20; private System.Windows.Forms.GroupBox groupBox4; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel5; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel9; private System.Windows.Forms.Label label17; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel7; private System.Windows.Forms.TextBox boxLimit; private System.Windows.Forms.Label label16; private System.Windows.Forms.Label label15; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label14; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel8; private System.Windows.Forms.TextBox boxBitrate; private System.Windows.Forms.Label label13; private System.Windows.Forms.Label label12; private System.Windows.Forms.Label label11; private System.Windows.Forms.Label label10; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label2; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel6; private System.Windows.Forms.Label label8; private System.Windows.Forms.TabPage tabPage2; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel4; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel10; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label9; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel12; private System.Windows.Forms.TrackBar trackThreads; private System.Windows.Forms.Label labelThreads; private System.Windows.Forms.Label label18; private System.Windows.Forms.CheckBox checkBox2Pass; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox textBoxArguments; private System.Windows.Forms.Label label21; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel13; private System.Windows.Forms.Label label23; private System.Windows.Forms.CheckBox boxAudio; private System.Windows.Forms.Label label24; private System.Windows.Forms.Label label22; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel14; private System.Windows.Forms.Button buttonOpenCrop; private System.Windows.Forms.Label labelCrop; public System.Windows.Forms.TextBox textBoxIn; public System.Windows.Forms.TextBox boxCropTo; public System.Windows.Forms.TextBox boxCropFrom; public System.Windows.Forms.TextBox boxResH; public System.Windows.Forms.TextBox boxResW; public System.Windows.Forms.TextBox textBoxOut; private System.Windows.Forms.Label label25; private System.Windows.Forms.CheckBox boxHQ; private System.Windows.Forms.TabPage tabPage3; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel15; private System.Windows.Forms.GroupBox groupBox6; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel16; private System.Windows.Forms.RadioButton radioSubNone; private System.Windows.Forms.RadioButton radioSubInternal; private System.Windows.Forms.RadioButton radioSubExternal; private System.Windows.Forms.Label label26; private System.Windows.Forms.Label label27; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel17; private System.Windows.Forms.Button buttonSubBrowse; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Label label31; private System.Windows.Forms.Label label30; private System.Windows.Forms.Label label29; private System.Windows.Forms.Label label28; } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using Microsoft.Azure.Cosmos.Table; using Microsoft.Extensions.Logging; using Orleans.Internal; using Orleans.Runtime; using LogLevel = Microsoft.Extensions.Logging.LogLevel; // // Number of #ifs can be reduced (or removed), once we separate test projects by feature/area, otherwise we are ending up with ambigous types and build errors. // #if ORLEANS_CLUSTERING namespace Orleans.Clustering.AzureStorage #elif ORLEANS_PERSISTENCE namespace Orleans.Persistence.AzureStorage #elif ORLEANS_REMINDERS namespace Orleans.Reminders.AzureStorage #elif ORLEANS_STREAMING namespace Orleans.Streaming.AzureStorage #elif ORLEANS_EVENTHUBS namespace Orleans.Streaming.EventHubs #elif TESTER_AZUREUTILS namespace Orleans.Tests.AzureUtils #elif ORLEANS_TRANSACTIONS namespace Orleans.Transactions.AzureStorage #else // No default namespace intentionally to cause compile errors if something is not defined #endif { /// <summary> /// Utility class to encapsulate row-based access to Azure table storage. /// </summary> /// <typeparam name="T">Table data entry used by this table / manager.</typeparam> internal class AzureTableDataManager<T> where T : class, ITableEntity, new() { /// <summary> Name of the table this instance is managing. </summary> public string TableName { get; private set; } /// <summary> Logger for this table manager instance. </summary> protected internal ILogger Logger { get; private set; } /// <summary> Connection string for the Azure storage account used to host this table. </summary> protected string ConnectionString { get; set; } private CloudTable tableReference; public CloudTable Table => tableReference; /// <summary> /// Constructor /// </summary> /// <param name="tableName">Name of the table to be connected to.</param> /// <param name="storageConnectionString">Connection string for the Azure storage account used to host this table.</param> /// <param name="loggerFactory">Logger factory to use.</param> public AzureTableDataManager(string tableName, string storageConnectionString, ILoggerFactory loggerFactory) { Logger = loggerFactory.CreateLogger<AzureTableDataManager<T>>(); TableName = tableName; ConnectionString = storageConnectionString; AzureTableUtils.ValidateTableName(tableName); } /// <summary> /// Connects to, or creates and initializes a new Azure table if it does not already exist. /// </summary> /// <returns>Completion promise for this operation.</returns> public async Task InitTableAsync() { const string operation = "InitTable"; var startTime = DateTime.UtcNow; try { CloudTableClient tableCreationClient = GetCloudTableCreationClient(); CloudTable tableRef = tableCreationClient.GetTableReference(TableName); bool didCreate = await tableRef.CreateIfNotExistsAsync(); Logger.Info((int)Utilities.ErrorCode.AzureTable_01, "{0} Azure storage table {1}", (didCreate ? "Created" : "Attached to"), TableName); CloudTableClient tableOperationsClient = GetCloudTableOperationsClient(); tableReference = tableOperationsClient.GetTableReference(TableName); } catch (Exception exc) { Logger.Error((int)Utilities.ErrorCode.AzureTable_02, $"Could not initialize connection to storage table {TableName}", exc); throw; } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Deletes the Azure table. /// </summary> /// <returns>Completion promise for this operation.</returns> public async Task DeleteTableAsync() { const string operation = "DeleteTable"; var startTime = DateTime.UtcNow; try { CloudTableClient tableCreationClient = GetCloudTableCreationClient(); CloudTable tableRef = tableCreationClient.GetTableReference(TableName); bool didDelete = await tableRef.DeleteIfExistsAsync(); if (didDelete) { Logger.Info((int)Utilities.ErrorCode.AzureTable_03, "Deleted Azure storage table {0}", TableName); } } catch (Exception exc) { Logger.Error((int)Utilities.ErrorCode.AzureTable_04, "Could not delete storage table {0}", exc); throw; } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Deletes all entities the Azure table. /// </summary> /// <returns>Completion promise for this operation.</returns> public async Task ClearTableAsync() { IEnumerable<Tuple<T,string>> items = await ReadAllTableEntriesAsync(); IEnumerable<Task> work = items.GroupBy(item => item.Item1.PartitionKey) .SelectMany(partition => partition.ToBatch(AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS)) .Select(batch => DeleteTableEntriesAsync(batch.ToList())); await Task.WhenAll(work); } /// <summary> /// Create a new data entry in the Azure table (insert new, not update existing). /// Fails if the data already exists. /// </summary> /// <param name="data">Data to be inserted into the table.</param> /// <returns>Value promise with new Etag for this data entry after completing this storage operation.</returns> public async Task<string> CreateTableEntryAsync(T data) { const string operation = "CreateTableEntry"; var startTime = DateTime.UtcNow; if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("Creating {0} table entry: {1}", TableName, data); try { // WAS: // svc.AddObject(TableName, data); // SaveChangesOptions.None try { // Presumably FromAsync(BeginExecute, EndExecute) has a slightly better performance then CreateIfNotExistsAsync. var opResult = await tableReference.ExecuteAsync(TableOperation.Insert(data)); return opResult.Etag; } catch (Exception exc) { CheckAlertWriteError(operation, data, null, exc); throw; } } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Inserts a data entry in the Azure table: creates a new one if does not exists or overwrites (without eTag) an already existing version (the "update in place" semantics). /// </summary> /// <param name="data">Data to be inserted or replaced in the table.</param> /// <returns>Value promise with new Etag for this data entry after completing this storage operation.</returns> public async Task<string> UpsertTableEntryAsync(T data) { const string operation = "UpsertTableEntry"; var startTime = DateTime.UtcNow; if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("{0} entry {1} into table {2}", operation, data, TableName); try { try { // WAS: // svc.AttachTo(TableName, data, null); // svc.UpdateObject(data); // SaveChangesOptions.ReplaceOnUpdate, var opResult = await tableReference.ExecuteAsync(TableOperation.InsertOrReplace(data)); return opResult.Etag; } catch (Exception exc) { Logger.Warn((int)Utilities.ErrorCode.AzureTable_06, $"Intermediate error upserting entry {(data == null ? "null" : data.ToString())} to the table {TableName}", exc); throw; } } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Merges a data entry in the Azure table. /// </summary> /// <param name="data">Data to be merged in the table.</param> /// <param name="eTag">ETag to apply.</param> /// <returns>Value promise with new Etag for this data entry after completing this storage operation.</returns> internal async Task<string> MergeTableEntryAsync(T data, string eTag) { const string operation = "MergeTableEntry"; var startTime = DateTime.UtcNow; if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("{0} entry {1} into table {2}", operation, data, TableName); try { try { // WAS: // svc.AttachTo(TableName, data, ANY_ETAG); // svc.UpdateObject(data); data.ETag = eTag; // Merge requires an ETag (which may be the '*' wildcard). var opResult = await tableReference.ExecuteAsync(TableOperation.Merge(data)); return opResult.Etag; } catch (Exception exc) { Logger.Warn((int)Utilities.ErrorCode.AzureTable_07, $"Intermediate error merging entry {(data == null ? "null" : data.ToString())} to the table {TableName}", exc); throw; } } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Updates a data entry in the Azure table: updates an already existing data in the table, by using eTag. /// Fails if the data does not already exist or of eTag does not match. /// </summary> /// <param name="data">Data to be updated into the table.</param> /// /// <param name="dataEtag">ETag to use.</param> /// <returns>Value promise with new Etag for this data entry after completing this storage operation.</returns> public async Task<string> UpdateTableEntryAsync(T data, string dataEtag) { const string operation = "UpdateTableEntryAsync"; var startTime = DateTime.UtcNow; if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("{0} table {1} entry {2}", operation, TableName, data); try { try { data.ETag = dataEtag; var opResult = await tableReference.ExecuteAsync(TableOperation.Replace(data)); //The ETag of data is needed in further operations. return opResult.Etag; } catch (Exception exc) { CheckAlertWriteError(operation, data, null, exc); throw; } } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Deletes an already existing data in the table, by using eTag. /// Fails if the data does not already exist or if eTag does not match. /// </summary> /// <param name="data">Data entry to be deleted from the table.</param> /// <param name="eTag">ETag to use.</param> /// <returns>Completion promise for this storage operation.</returns> public async Task DeleteTableEntryAsync(T data, string eTag) { const string operation = "DeleteTableEntryAsync"; var startTime = DateTime.UtcNow; if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("{0} table {1} entry {2}", operation, TableName, data); try { data.ETag = eTag; try { await tableReference.ExecuteAsync(TableOperation.Delete(data)); } catch (Exception exc) { Logger.Warn((int)Utilities.ErrorCode.AzureTable_08, $"Intermediate error deleting entry {data} from the table {TableName}.", exc); throw; } } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Read a single table entry from the storage table. /// </summary> /// <param name="partitionKey">The partition key for the entry.</param> /// <param name="rowKey">The row key for the entry.</param> /// <returns>Value promise for tuple containing the data entry and its corresponding etag.</returns> public async Task<Tuple<T, string>> ReadSingleTableEntryAsync(string partitionKey, string rowKey) { const string operation = "ReadSingleTableEntryAsync"; var startTime = DateTime.UtcNow; if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("{0} table {1} partitionKey {2} rowKey = {3}", operation, TableName, partitionKey, rowKey); T retrievedResult = default(T); try { try { string queryString = TableQueryFilterBuilder.MatchPartitionKeyAndRowKeyFilter(partitionKey, rowKey); var query = new TableQuery<T>().Where(queryString); TableQuerySegment<T> segment = await tableReference.ExecuteQuerySegmentedAsync(query, null); retrievedResult = segment.Results.SingleOrDefault(); } catch (StorageException exception) { if (!AzureTableUtils.TableStorageDataNotFound(exception)) throw; } //The ETag of data is needed in further operations. if (retrievedResult != null) return new Tuple<T, string>(retrievedResult, retrievedResult.ETag); if (Logger.IsEnabled(LogLevel.Debug)) Logger.Debug("Could not find table entry for PartitionKey={0} RowKey={1}", partitionKey, rowKey); return null; // No data } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Read all entries in one partition of the storage table. /// NOTE: This could be an expensive and slow operation for large table partitions! /// </summary> /// <param name="partitionKey">The key for the partition to be searched.</param> /// <returns>Enumeration of all entries in the specified table partition.</returns> public Task<IEnumerable<Tuple<T, string>>> ReadAllTableEntriesForPartitionAsync(string partitionKey) { string query = TableQuery.GenerateFilterCondition(nameof(ITableEntity.PartitionKey), QueryComparisons.Equal, partitionKey); return ReadTableEntriesAndEtagsAsync(query); } /// <summary> /// Read all entries in the table. /// NOTE: This could be a very expensive and slow operation for large tables! /// </summary> /// <returns>Enumeration of all entries in the table.</returns> public Task<IEnumerable<Tuple<T, string>>> ReadAllTableEntriesAsync() { return ReadTableEntriesAndEtagsAsync(null); } /// <summary> /// Deletes a set of already existing data entries in the table, by using eTag. /// Fails if the data does not already exist or if eTag does not match. /// </summary> /// <param name="collection">Data entries and their corresponding etags to be deleted from the table.</param> /// <returns>Completion promise for this storage operation.</returns> public async Task DeleteTableEntriesAsync(IReadOnlyCollection<Tuple<T, string>> collection) { const string operation = "DeleteTableEntries"; var startTime = DateTime.UtcNow; if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("Deleting {0} table entries: {1}", TableName, Utils.EnumerableToString(collection)); if (collection == null) throw new ArgumentNullException("collection"); if (collection.Count > AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS) { throw new ArgumentOutOfRangeException("collection", collection.Count, "Too many rows for bulk delete - max " + AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS); } if (collection.Count == 0) { return; } try { var entityBatch = new TableBatchOperation(); foreach (var tuple in collection) { // WAS: // svc.AttachTo(TableName, tuple.Item1, tuple.Item2); // svc.DeleteObject(tuple.Item1); // SaveChangesOptions.ReplaceOnUpdate | SaveChangesOptions.Batch, T item = tuple.Item1; item.ETag = tuple.Item2; entityBatch.Delete(item); } try { await tableReference.ExecuteBatchAsync(entityBatch); } catch (Exception exc) { Logger.Warn((int)Utilities.ErrorCode.AzureTable_08, $"Intermediate error deleting entries {Utils.EnumerableToString(collection)} from the table {TableName}.", exc); throw; } } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Read data entries and their corresponding eTags from the Azure table. /// </summary> /// <param name="filter">Filter string to use for querying the table and filtering the results.</param> /// <returns>Enumeration of entries in the table which match the query condition.</returns> public async Task<IEnumerable<Tuple<T, string>>> ReadTableEntriesAndEtagsAsync(string filter) { const string operation = "ReadTableEntriesAndEtags"; var startTime = DateTime.UtcNow; try { TableQuery<T> cloudTableQuery = filter == null ? new TableQuery<T>() : new TableQuery<T>().Where(filter); try { Func<Task<List<T>>> executeQueryHandleContinuations = async () => { TableQuerySegment<T> querySegment = null; var list = new List<T>(); //ExecuteSegmentedAsync not supported in "WindowsAzure.Storage": "7.2.1" yet while (querySegment == null || querySegment.ContinuationToken != null) { querySegment = await tableReference.ExecuteQuerySegmentedAsync(cloudTableQuery, querySegment?.ContinuationToken); list.AddRange(querySegment); } return list; }; #if !ORLEANS_TRANSACTIONS IBackoffProvider backoff = new FixedBackoff(AzureTableDefaultPolicies.PauseBetweenTableOperationRetries); List<T> results = await AsyncExecutorWithRetries.ExecuteWithRetries( counter => executeQueryHandleContinuations(), AzureTableDefaultPolicies.MaxTableOperationRetries, (exc, counter) => AzureTableUtils.AnalyzeReadException(exc.GetBaseException(), counter, TableName, Logger), AzureTableDefaultPolicies.TableOperationTimeout, backoff); #else List<T> results = await executeQueryHandleContinuations(); #endif // Data was read successfully if we got to here return results.Select(i => Tuple.Create(i, i.ETag)).ToList(); } catch (Exception exc) { // Out of retries... var errorMsg = $"Failed to read Azure storage table {TableName}: {exc.Message}"; if (!AzureTableUtils.TableStorageDataNotFound(exc)) { Logger.Warn((int)Utilities.ErrorCode.AzureTable_09, errorMsg, exc); } throw new OrleansException(errorMsg, exc); } } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Inserts a set of new data entries into the table. /// Fails if the data does already exists. /// </summary> /// <param name="collection">Data entries to be inserted into the table.</param> /// <returns>Completion promise for this storage operation.</returns> public async Task BulkInsertTableEntries(IReadOnlyCollection<T> collection) { const string operation = "BulkInsertTableEntries"; if (collection == null) throw new ArgumentNullException("collection"); if (collection.Count > AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS) { throw new ArgumentOutOfRangeException("collection", collection.Count, "Too many rows for bulk update - max " + AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS); } if (collection.Count == 0) { return; } var startTime = DateTime.UtcNow; if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("Bulk inserting {0} entries to {1} table", collection.Count, TableName); try { // WAS: // svc.AttachTo(TableName, entry); // svc.UpdateObject(entry); // SaveChangesOptions.None | SaveChangesOptions.Batch, // SaveChangesOptions.None == Insert-or-merge operation, SaveChangesOptions.Batch == Batch transaction // http://msdn.microsoft.com/en-us/library/hh452241.aspx var entityBatch = new TableBatchOperation(); foreach (T entry in collection) { entityBatch.Insert(entry); } try { // http://msdn.microsoft.com/en-us/library/hh452241.aspx await tableReference.ExecuteBatchAsync(entityBatch); } catch (Exception exc) { Logger.Warn((int)Utilities.ErrorCode.AzureTable_37, $"Intermediate error bulk inserting {collection.Count} entries in the table {TableName}", exc); } } finally { CheckAlertSlowAccess(startTime, operation); } } internal async Task<Tuple<string, string>> InsertTwoTableEntriesConditionallyAsync(T data1, T data2, string data2Etag) { const string operation = "InsertTableEntryConditionally"; string data2Str = (data2 == null ? "null" : data2.ToString()); var startTime = DateTime.UtcNow; if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("{0} into table {1} data1 {2} data2 {3}", operation, TableName, data1, data2Str); try { try { // WAS: // Only AddObject, do NOT AttachTo. If we did both UpdateObject and AttachTo, it would have been equivalent to InsertOrReplace. // svc.AddObject(TableName, data); // --- // svc.AttachTo(TableName, tableVersion, tableVersionEtag); // svc.UpdateObject(tableVersion); // SaveChangesOptions.ReplaceOnUpdate | SaveChangesOptions.Batch, // EntityDescriptor dataResult = svc.GetEntityDescriptor(data); // return dataResult.ETag; var entityBatch = new TableBatchOperation(); entityBatch.Add(TableOperation.Insert(data1)); data2.ETag = data2Etag; entityBatch.Add(TableOperation.Replace(data2)); var opResults = await tableReference.ExecuteBatchAsync(entityBatch); //The batch results are returned in order of execution, //see reference at https://msdn.microsoft.com/en-us/library/microsoft.windowsazure.storage.table.cloudtable.executebatch.aspx. //The ETag of data is needed in further operations. return new Tuple<string, string>(opResults[0].Etag, opResults[1].Etag); } catch (Exception exc) { CheckAlertWriteError(operation, data1, data2Str, exc); throw; } } finally { CheckAlertSlowAccess(startTime, operation); } } internal async Task<Tuple<string, string>> UpdateTwoTableEntriesConditionallyAsync(T data1, string data1Etag, T data2, string data2Etag) { const string operation = "UpdateTableEntryConditionally"; string data2Str = (data2 == null ? "null" : data2.ToString()); var startTime = DateTime.UtcNow; if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("{0} table {1} data1 {2} data2 {3}", operation, TableName, data1, data2Str); try { try { // WAS: // Only AddObject, do NOT AttachTo. If we did both UpdateObject and AttachTo, it would have been equivalent to InsertOrReplace. // svc.AttachTo(TableName, data, dataEtag); // svc.UpdateObject(data); // ---- // svc.AttachTo(TableName, tableVersion, tableVersionEtag); // svc.UpdateObject(tableVersion); // SaveChangesOptions.ReplaceOnUpdate | SaveChangesOptions.Batch, // EntityDescriptor dataResult = svc.GetEntityDescriptor(data); // return dataResult.ETag; var entityBatch = new TableBatchOperation(); data1.ETag = data1Etag; entityBatch.Add(TableOperation.Replace(data1)); if (data2 != null && data2Etag != null) { data2.ETag = data2Etag; entityBatch.Add(TableOperation.Replace(data2)); } var opResults = await tableReference.ExecuteBatchAsync(entityBatch); //The batch results are returned in order of execution, //see reference at https://msdn.microsoft.com/en-us/library/microsoft.windowsazure.storage.table.cloudtable.executebatch.aspx. //The ETag of data is needed in further operations. return new Tuple<string, string>(opResults[0].Etag, opResults[1].Etag); } catch (Exception exc) { CheckAlertWriteError(operation, data1, data2Str, exc); throw; } } finally { CheckAlertSlowAccess(startTime, operation); } } // Utility methods private CloudTableClient GetCloudTableOperationsClient() { try { CloudStorageAccount storageAccount = AzureTableUtils.GetCloudStorageAccount(ConnectionString); CloudTableClient operationsClient = storageAccount.CreateCloudTableClient(); operationsClient.DefaultRequestOptions.RetryPolicy = AzureTableDefaultPolicies.TableOperationRetryPolicy; operationsClient.DefaultRequestOptions.ServerTimeout = AzureTableDefaultPolicies.TableOperationTimeout; // Values supported can be AtomPub, Json, JsonFullMetadata or JsonNoMetadata with Json being the default value operationsClient.DefaultRequestOptions.PayloadFormat = TablePayloadFormat.JsonNoMetadata; return operationsClient; } catch (Exception exc) { Logger.Error((int)Utilities.ErrorCode.AzureTable_17, "Error creating CloudTableOperationsClient.", exc); throw; } } private CloudTableClient GetCloudTableCreationClient() { try { CloudStorageAccount storageAccount = AzureTableUtils.GetCloudStorageAccount(ConnectionString); CloudTableClient creationClient = storageAccount.CreateCloudTableClient(); creationClient.DefaultRequestOptions.RetryPolicy = AzureTableDefaultPolicies.TableCreationRetryPolicy; creationClient.DefaultRequestOptions.ServerTimeout = AzureTableDefaultPolicies.TableCreationTimeout; // Values supported can be AtomPub, Json, JsonFullMetadata or JsonNoMetadata with Json being the default value creationClient.DefaultRequestOptions.PayloadFormat = TablePayloadFormat.JsonNoMetadata; return creationClient; } catch (Exception exc) { Logger.Error((int)Utilities.ErrorCode.AzureTable_18, "Error creating CloudTableCreationClient.", exc); throw; } } private void CheckAlertWriteError(string operation, object data1, string data2, Exception exc) { HttpStatusCode httpStatusCode; string restStatus; if (AzureTableUtils.EvaluateException(exc, out httpStatusCode, out restStatus) && AzureTableUtils.IsContentionError(httpStatusCode)) { // log at Verbose, since failure on conditional is not not an error. Will analyze and warn later, if required. if(Logger.IsEnabled(LogLevel.Debug)) Logger.Debug((int)Utilities.ErrorCode.AzureTable_13, $"Intermediate Azure table write error {operation} to table {TableName} data1 {(data1 ?? "null")} data2 {(data2 ?? "null")}", exc); } else { Logger.Error((int)Utilities.ErrorCode.AzureTable_14, $"Azure table access write error {operation} to table {TableName} entry {data1}", exc); } } private void CheckAlertSlowAccess(DateTime startOperation, string operation) { var timeSpan = DateTime.UtcNow - startOperation; if (timeSpan > AzureTableDefaultPolicies.TableOperationTimeout) { Logger.Warn((int)Utilities.ErrorCode.AzureTable_15, "Slow access to Azure Table {0} for {1}, which took {2}.", TableName, operation, timeSpan); } } /// <summary> /// Helper functions for building table queries. /// </summary> private class TableQueryFilterBuilder { /// <summary> /// Builds query string to match partitionkey /// </summary> /// <param name="partitionKey"></param> /// <returns></returns> public static string MatchPartitionKeyFilter(string partitionKey) { return TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, partitionKey); } /// <summary> /// Builds query string to match rowkey /// </summary> /// <param name="rowKey"></param> /// <returns></returns> public static string MatchRowKeyFilter(string rowKey) { return TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, rowKey); } /// <summary> /// Builds a query string that matches a specific partitionkey and rowkey. /// </summary> /// <param name="partitionKey"></param> /// <param name="rowKey"></param> /// <returns></returns> public static string MatchPartitionKeyAndRowKeyFilter(string partitionKey, string rowKey) { return TableQuery.CombineFilters(MatchPartitionKeyFilter(partitionKey), TableOperators.And, MatchRowKeyFilter(rowKey)); } } } internal static class TableDataManagerInternalExtensions { internal static IEnumerable<IEnumerable<TItem>> ToBatch<TItem>(this IEnumerable<TItem> source, int size) { using (IEnumerator<TItem> enumerator = source.GetEnumerator()) while (enumerator.MoveNext()) yield return Take(enumerator, size); } private static IEnumerable<TItem> Take<TItem>(IEnumerator<TItem> source, int size) { int i = 0; do yield return source.Current; while (++i < size && source.MoveNext()); } } }
using System; using System.Threading; using System.Threading.Tasks; using Medallion.Threading.Internal; namespace Medallion.Threading.SqlServer { public partial class SqlDistributedReaderWriterLock { // AUTO-GENERATED IDistributedSynchronizationHandle? IDistributedReaderWriterLock.TryAcquireReadLock(TimeSpan timeout, CancellationToken cancellationToken) => this.TryAcquireReadLock(timeout, cancellationToken); IDistributedSynchronizationHandle IDistributedReaderWriterLock.AcquireReadLock(TimeSpan? timeout, CancellationToken cancellationToken) => this.AcquireReadLock(timeout, cancellationToken); ValueTask<IDistributedSynchronizationHandle?> IDistributedReaderWriterLock.TryAcquireReadLockAsync(TimeSpan timeout, CancellationToken cancellationToken) => this.TryAcquireReadLockAsync(timeout, cancellationToken).Convert(To<IDistributedSynchronizationHandle?>.ValueTask); ValueTask<IDistributedSynchronizationHandle> IDistributedReaderWriterLock.AcquireReadLockAsync(TimeSpan? timeout, CancellationToken cancellationToken) => this.AcquireReadLockAsync(timeout, cancellationToken).Convert(To<IDistributedSynchronizationHandle>.ValueTask); IDistributedLockUpgradeableHandle? IDistributedUpgradeableReaderWriterLock.TryAcquireUpgradeableReadLock(TimeSpan timeout, CancellationToken cancellationToken) => this.TryAcquireUpgradeableReadLock(timeout, cancellationToken); IDistributedLockUpgradeableHandle IDistributedUpgradeableReaderWriterLock.AcquireUpgradeableReadLock(TimeSpan? timeout, CancellationToken cancellationToken) => this.AcquireUpgradeableReadLock(timeout, cancellationToken); ValueTask<IDistributedLockUpgradeableHandle?> IDistributedUpgradeableReaderWriterLock.TryAcquireUpgradeableReadLockAsync(TimeSpan timeout, CancellationToken cancellationToken) => this.TryAcquireUpgradeableReadLockAsync(timeout, cancellationToken).Convert(To<IDistributedLockUpgradeableHandle?>.ValueTask); ValueTask<IDistributedLockUpgradeableHandle> IDistributedUpgradeableReaderWriterLock.AcquireUpgradeableReadLockAsync(TimeSpan? timeout, CancellationToken cancellationToken) => this.AcquireUpgradeableReadLockAsync(timeout, cancellationToken).Convert(To<IDistributedLockUpgradeableHandle>.ValueTask); IDistributedSynchronizationHandle? IDistributedReaderWriterLock.TryAcquireWriteLock(TimeSpan timeout, CancellationToken cancellationToken) => this.TryAcquireWriteLock(timeout, cancellationToken); IDistributedSynchronizationHandle IDistributedReaderWriterLock.AcquireWriteLock(TimeSpan? timeout, CancellationToken cancellationToken) => this.AcquireWriteLock(timeout, cancellationToken); ValueTask<IDistributedSynchronizationHandle?> IDistributedReaderWriterLock.TryAcquireWriteLockAsync(TimeSpan timeout, CancellationToken cancellationToken) => this.TryAcquireWriteLockAsync(timeout, cancellationToken).Convert(To<IDistributedSynchronizationHandle?>.ValueTask); ValueTask<IDistributedSynchronizationHandle> IDistributedReaderWriterLock.AcquireWriteLockAsync(TimeSpan? timeout, CancellationToken cancellationToken) => this.AcquireWriteLockAsync(timeout, cancellationToken).Convert(To<IDistributedSynchronizationHandle>.ValueTask); /// <summary> /// Attempts to acquire a READ lock synchronously. Multiple readers are allowed. Not compatible with a WRITE lock. Usage: /// <code> /// using (var handle = myLock.TryAcquireReadLock(...)) /// { /// if (handle != null) { /* we have the lock! */ } /// } /// // dispose releases the lock if we took it /// </code> /// </summary> /// <param name="timeout">How long to wait before giving up on the acquisition attempt. Defaults to 0</param> /// <param name="cancellationToken">Specifies a token by which the wait can be canceled</param> /// <returns>A <see cref="SqlDistributedReaderWriterLockHandle"/> which can be used to release the lock or null on failure</returns> public SqlDistributedReaderWriterLockHandle? TryAcquireReadLock(TimeSpan timeout = default, CancellationToken cancellationToken = default) => DistributedLockHelpers.TryAcquire(this, timeout, cancellationToken, isWrite: false); /// <summary> /// Acquires a READ lock synchronously, failing with <see cref="TimeoutException"/> if the attempt times out. Multiple readers are allowed. Not compatible with a WRITE lock. Usage: /// <code> /// using (myLock.AcquireReadLock(...)) /// { /// /* we have the lock! */ /// } /// // dispose releases the lock /// </code> /// </summary> /// <param name="timeout">How long to wait before giving up on the acquisition attempt. Defaults to <see cref="Timeout.InfiniteTimeSpan"/></param> /// <param name="cancellationToken">Specifies a token by which the wait can be canceled</param> /// <returns>A <see cref="SqlDistributedReaderWriterLockHandle"/> which can be used to release the lock</returns> public SqlDistributedReaderWriterLockHandle AcquireReadLock(TimeSpan? timeout = null, CancellationToken cancellationToken = default) => DistributedLockHelpers.Acquire(this, timeout, cancellationToken, isWrite: false); /// <summary> /// Attempts to acquire a READ lock asynchronously. Multiple readers are allowed. Not compatible with a WRITE lock. Usage: /// <code> /// await using (var handle = await myLock.TryAcquireReadLockAsync(...)) /// { /// if (handle != null) { /* we have the lock! */ } /// } /// // dispose releases the lock if we took it /// </code> /// </summary> /// <param name="timeout">How long to wait before giving up on the acquisition attempt. Defaults to 0</param> /// <param name="cancellationToken">Specifies a token by which the wait can be canceled</param> /// <returns>A <see cref="SqlDistributedReaderWriterLockHandle"/> which can be used to release the lock or null on failure</returns> public ValueTask<SqlDistributedReaderWriterLockHandle?> TryAcquireReadLockAsync(TimeSpan timeout = default, CancellationToken cancellationToken = default) => this.As<IInternalDistributedReaderWriterLock<SqlDistributedReaderWriterLockHandle>>().InternalTryAcquireAsync(timeout, cancellationToken, isWrite: false); /// <summary> /// Acquires a READ lock asynchronously, failing with <see cref="TimeoutException"/> if the attempt times out. Multiple readers are allowed. Not compatible with a WRITE lock. Usage: /// <code> /// await using (await myLock.AcquireReadLockAsync(...)) /// { /// /* we have the lock! */ /// } /// // dispose releases the lock /// </code> /// </summary> /// <param name="timeout">How long to wait before giving up on the acquisition attempt. Defaults to <see cref="Timeout.InfiniteTimeSpan"/></param> /// <param name="cancellationToken">Specifies a token by which the wait can be canceled</param> /// <returns>A <see cref="SqlDistributedReaderWriterLockHandle"/> which can be used to release the lock</returns> public ValueTask<SqlDistributedReaderWriterLockHandle> AcquireReadLockAsync(TimeSpan? timeout = null, CancellationToken cancellationToken = default) => DistributedLockHelpers.AcquireAsync(this, timeout, cancellationToken, isWrite: false); /// <summary> /// Attempts to acquire an UPGRADE lock synchronously. Not compatible with another UPGRADE lock or a WRITE lock. Usage: /// <code> /// using (var handle = myLock.TryAcquireUpgradeableReadLock(...)) /// { /// if (handle != null) { /* we have the lock! */ } /// } /// // dispose releases the lock if we took it /// </code> /// </summary> /// <param name="timeout">How long to wait before giving up on the acquisition attempt. Defaults to 0</param> /// <param name="cancellationToken">Specifies a token by which the wait can be canceled</param> /// <returns>A <see cref="SqlDistributedReaderWriterLockUpgradeableHandle"/> which can be used to release the lock or null on failure</returns> public SqlDistributedReaderWriterLockUpgradeableHandle? TryAcquireUpgradeableReadLock(TimeSpan timeout = default, CancellationToken cancellationToken = default) => DistributedLockHelpers.TryAcquireUpgradeableReadLock(this, timeout, cancellationToken); /// <summary> /// Acquires an UPGRADE lock synchronously, failing with <see cref="TimeoutException"/> if the attempt times out. Not compatible with another UPGRADE lock or a WRITE lock. Usage: /// <code> /// using (myLock.AcquireUpgradeableReadLock(...)) /// { /// /* we have the lock! */ /// } /// // dispose releases the lock /// </code> /// </summary> /// <param name="timeout">How long to wait before giving up on the acquisition attempt. Defaults to <see cref="Timeout.InfiniteTimeSpan"/></param> /// <param name="cancellationToken">Specifies a token by which the wait can be canceled</param> /// <returns>A <see cref="SqlDistributedReaderWriterLockUpgradeableHandle"/> which can be used to release the lock</returns> public SqlDistributedReaderWriterLockUpgradeableHandle AcquireUpgradeableReadLock(TimeSpan? timeout = null, CancellationToken cancellationToken = default) => DistributedLockHelpers.AcquireUpgradeableReadLock(this, timeout, cancellationToken); /// <summary> /// Attempts to acquire an UPGRADE lock asynchronously. Not compatible with another UPGRADE lock or a WRITE lock. Usage: /// <code> /// await using (var handle = await myLock.TryAcquireUpgradeableReadLockAsync(...)) /// { /// if (handle != null) { /* we have the lock! */ } /// } /// // dispose releases the lock if we took it /// </code> /// </summary> /// <param name="timeout">How long to wait before giving up on the acquisition attempt. Defaults to 0</param> /// <param name="cancellationToken">Specifies a token by which the wait can be canceled</param> /// <returns>A <see cref="SqlDistributedReaderWriterLockUpgradeableHandle"/> which can be used to release the lock or null on failure</returns> public ValueTask<SqlDistributedReaderWriterLockUpgradeableHandle?> TryAcquireUpgradeableReadLockAsync(TimeSpan timeout = default, CancellationToken cancellationToken = default) => this.As<IInternalDistributedUpgradeableReaderWriterLock<SqlDistributedReaderWriterLockHandle, SqlDistributedReaderWriterLockUpgradeableHandle>>().InternalTryAcquireUpgradeableReadLockAsync(timeout, cancellationToken); /// <summary> /// Acquires an UPGRADE lock asynchronously, failing with <see cref="TimeoutException"/> if the attempt times out. Not compatible with another UPGRADE lock or a WRITE lock. Usage: /// <code> /// await using (await myLock.AcquireUpgradeableReadLockAsync(...)) /// { /// /* we have the lock! */ /// } /// // dispose releases the lock /// </code> /// </summary> /// <param name="timeout">How long to wait before giving up on the acquisition attempt. Defaults to <see cref="Timeout.InfiniteTimeSpan"/></param> /// <param name="cancellationToken">Specifies a token by which the wait can be canceled</param> /// <returns>A <see cref="SqlDistributedReaderWriterLockUpgradeableHandle"/> which can be used to release the lock</returns> public ValueTask<SqlDistributedReaderWriterLockUpgradeableHandle> AcquireUpgradeableReadLockAsync(TimeSpan? timeout = null, CancellationToken cancellationToken = default) => DistributedLockHelpers.AcquireUpgradeableReadLockAsync(this, timeout, cancellationToken); /// <summary> /// Attempts to acquire a WRITE lock synchronously. Not compatible with another WRITE lock or an UPGRADE lock. Usage: /// <code> /// using (var handle = myLock.TryAcquireWriteLock(...)) /// { /// if (handle != null) { /* we have the lock! */ } /// } /// // dispose releases the lock if we took it /// </code> /// </summary> /// <param name="timeout">How long to wait before giving up on the acquisition attempt. Defaults to 0</param> /// <param name="cancellationToken">Specifies a token by which the wait can be canceled</param> /// <returns>A <see cref="SqlDistributedReaderWriterLockHandle"/> which can be used to release the lock or null on failure</returns> public SqlDistributedReaderWriterLockHandle? TryAcquireWriteLock(TimeSpan timeout = default, CancellationToken cancellationToken = default) => DistributedLockHelpers.TryAcquire(this, timeout, cancellationToken, isWrite: true); /// <summary> /// Acquires a WRITE lock synchronously, failing with <see cref="TimeoutException"/> if the attempt times out. Not compatible with another WRITE lock or an UPGRADE lock. Usage: /// <code> /// using (myLock.AcquireWriteLock(...)) /// { /// /* we have the lock! */ /// } /// // dispose releases the lock /// </code> /// </summary> /// <param name="timeout">How long to wait before giving up on the acquisition attempt. Defaults to <see cref="Timeout.InfiniteTimeSpan"/></param> /// <param name="cancellationToken">Specifies a token by which the wait can be canceled</param> /// <returns>A <see cref="SqlDistributedReaderWriterLockHandle"/> which can be used to release the lock</returns> public SqlDistributedReaderWriterLockHandle AcquireWriteLock(TimeSpan? timeout = null, CancellationToken cancellationToken = default) => DistributedLockHelpers.Acquire(this, timeout, cancellationToken, isWrite: true); /// <summary> /// Attempts to acquire a WRITE lock asynchronously. Not compatible with another WRITE lock or an UPGRADE lock. Usage: /// <code> /// await using (var handle = await myLock.TryAcquireWriteLockAsync(...)) /// { /// if (handle != null) { /* we have the lock! */ } /// } /// // dispose releases the lock if we took it /// </code> /// </summary> /// <param name="timeout">How long to wait before giving up on the acquisition attempt. Defaults to 0</param> /// <param name="cancellationToken">Specifies a token by which the wait can be canceled</param> /// <returns>A <see cref="SqlDistributedReaderWriterLockHandle"/> which can be used to release the lock or null on failure</returns> public ValueTask<SqlDistributedReaderWriterLockHandle?> TryAcquireWriteLockAsync(TimeSpan timeout = default, CancellationToken cancellationToken = default) => this.As<IInternalDistributedReaderWriterLock<SqlDistributedReaderWriterLockHandle>>().InternalTryAcquireAsync(timeout, cancellationToken, isWrite: true); /// <summary> /// Acquires a WRITE lock asynchronously, failing with <see cref="TimeoutException"/> if the attempt times out. Not compatible with another WRITE lock or an UPGRADE lock. Usage: /// <code> /// await using (await myLock.AcquireWriteLockAsync(...)) /// { /// /* we have the lock! */ /// } /// // dispose releases the lock /// </code> /// </summary> /// <param name="timeout">How long to wait before giving up on the acquisition attempt. Defaults to <see cref="Timeout.InfiniteTimeSpan"/></param> /// <param name="cancellationToken">Specifies a token by which the wait can be canceled</param> /// <returns>A <see cref="SqlDistributedReaderWriterLockHandle"/> which can be used to release the lock</returns> public ValueTask<SqlDistributedReaderWriterLockHandle> AcquireWriteLockAsync(TimeSpan? timeout = null, CancellationToken cancellationToken = default) => DistributedLockHelpers.AcquireAsync(this, timeout, cancellationToken, isWrite: true); } }
namespace InControl { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using UnityEngine; /// <summary> /// An action set represents a set of actions, usually for a single player. This class must be subclassed to be used. /// An action set can contain both explicit, bindable single value actions (for example, "Jump", "Left" and "Right") and implicit, /// aggregate actions which combine together other actions into one or two axes, for example "Move", which might consist /// of "Left", "Right", "Up" and "Down" filtered into a single two-axis control with its own applied circular deadzone, /// queryable vector value, etc. /// </summary> public abstract class PlayerActionSet { /// <summary> /// Optionally specifies a device which this action set should query from, if applicable. /// When set to <c>null</c> (default) this action set will try to find an active device when required. /// </summary> public InputDevice Device { get; set; } /// <summary> /// A list of devices which this action set should include when searching for an active device. /// When empty, all attached devices will be considered. /// </summary> public List<InputDevice> IncludeDevices { get; private set; } /// <summary> /// A list of devices which this action set should exclude when searching for an active device. /// </summary> public List<InputDevice> ExcludeDevices { get; private set; } /// <summary> /// Gets the actions in this action set as a readonly collection. /// </summary> public ReadOnlyCollection<PlayerAction> Actions { get; private set; } /// <summary> /// The last update tick on which any action in this set changed value. /// </summary> public ulong UpdateTick { get; protected set; } /// <summary> /// The binding source type that last provided input to this action set. /// </summary> public BindingSourceType LastInputType = BindingSourceType.None; /// <summary> /// Occurs when the binding source type that last provided input to this action set changes. /// </summary> public event Action<BindingSourceType> OnLastInputTypeChanged; /// <summary> /// Updated when <see cref="LastInputType"/> changes. /// </summary> public ulong LastInputTypeChangedTick; /// <summary> /// The <see cref="InputDeviceClass"/> of the binding source that last provided input to this action set. /// </summary> public InputDeviceClass LastDeviceClass = InputDeviceClass.Unknown; /// <summary> /// The <see cref="InputDeviceStyle"/> of the binding source that last provided input to this action set. /// </summary> public InputDeviceStyle LastDeviceStyle = InputDeviceStyle.Unknown; /// <summary> /// Whether this action set should produce input. Default: <c>true</c> /// </summary> public bool Enabled { get; set; } /// <summary> /// The prevent input to all actions while any action in the set is listening for a binding. /// </summary> public bool PreventInputWhileListeningForBinding { get; set; } /// <summary> /// This property can be used to store whatever arbitrary game data you want on this action set. /// </summary> public object UserData { get; set; } List<PlayerAction> actions = new List<PlayerAction>(); List<PlayerOneAxisAction> oneAxisActions = new List<PlayerOneAxisAction>(); List<PlayerTwoAxisAction> twoAxisActions = new List<PlayerTwoAxisAction>(); Dictionary<string, PlayerAction> actionsByName = new Dictionary<string, PlayerAction>(); BindingListenOptions listenOptions = new BindingListenOptions(); internal PlayerAction listenWithAction; protected PlayerActionSet() { Enabled = true; PreventInputWhileListeningForBinding = true; Device = null; IncludeDevices = new List<InputDevice>(); ExcludeDevices = new List<InputDevice>(); Actions = new ReadOnlyCollection<PlayerAction>( actions ); InputManager.AttachPlayerActionSet( this ); } /// <summary> /// Properly dispose of this action set. You should make sure to call this when the action set /// will no longer be used or it will result in unnecessary internal processing every frame. /// </summary> public void Destroy() { OnLastInputTypeChanged = null; InputManager.DetachPlayerActionSet( this ); } /// <summary> /// Create an action on this set. This should be performed in the constructor of your PlayerActionSet subclass. /// </summary> /// <param name="name">A unique identifier for this action within the context of this set.</param> /// <exception cref="InControlException">Thrown when trying to create an action with a non-unique name for this set.</exception> protected PlayerAction CreatePlayerAction( string name ) { return new PlayerAction( name, this ); } internal void AddPlayerAction( PlayerAction action ) { action.Device = FindActiveDevice(); if (actionsByName.ContainsKey( action.Name )) { throw new InControlException( "Action '" + action.Name + "' already exists in this set." ); } actions.Add( action ); actionsByName.Add( action.Name, action ); } /// <summary> /// Create an aggregate, single-axis action on this set. This should be performed in the constructor of your PlayerActionSet subclass. /// </summary> /// <example> /// <code> /// Throttle = CreateOneAxisPlayerAction( Brake, Accelerate ); /// </code> /// </example> /// <param name="negativeAction">The action to query for the negative component of the axis.</param> /// <param name="positiveAction">The action to query for the positive component of the axis.</param> protected PlayerOneAxisAction CreateOneAxisPlayerAction( PlayerAction negativeAction, PlayerAction positiveAction ) { var action = new PlayerOneAxisAction( negativeAction, positiveAction ); oneAxisActions.Add( action ); return action; } /// <summary> /// Create an aggregate, double-axis action on this set. This should be performed in the constructor of your PlayerActionSet subclass. /// </summary> /// <example> /// Note that, due to Unity's positive up-vector, the parameter order of <c>negativeYAction</c> and <c>positiveYAction</c> might seem counter-intuitive. /// <code> /// Move = CreateTwoAxisPlayerAction( Left, Right, Down, Up ); /// </code> /// </example> /// <param name="negativeXAction">The action to query for the negative component of the X axis.</param> /// <param name="positiveXAction">The action to query for the positive component of the X axis.</param> /// <param name="negativeYAction">The action to query for the negative component of the Y axis.</param> /// <param name="positiveYAction">The action to query for the positive component of the Y axis.</param> protected PlayerTwoAxisAction CreateTwoAxisPlayerAction( PlayerAction negativeXAction, PlayerAction positiveXAction, PlayerAction negativeYAction, PlayerAction positiveYAction ) { var action = new PlayerTwoAxisAction( negativeXAction, positiveXAction, negativeYAction, positiveYAction ); twoAxisActions.Add( action ); return action; } /// <summary> /// Gets the action with the specified action name. If the action does not exist, <c>KeyNotFoundException</c> is thrown. /// </summary> /// <param name="actionName">The name of the action to get.</param> public PlayerAction this[string actionName] { get { PlayerAction action; if (actionsByName.TryGetValue( actionName, out action )) { return action; } throw new KeyNotFoundException( "Action '" + actionName + "' does not exist in this action set." ); } } /// <summary> /// Gets the action with the specified action name. If the action does not exist, it returns <c>null</c>. /// </summary> /// <param name="actionName">The name of the action to get.</param> public PlayerAction GetPlayerActionByName( string actionName ) { PlayerAction action; if (actionsByName.TryGetValue( actionName, out action )) { return action; } return null; } internal void Update( ulong updateTick, float deltaTime ) { var device = Device ?? FindActiveDevice(); var lastInputType = LastInputType; var lastInputTypeChangedTick = LastInputTypeChangedTick; var lastDeviceClass = LastDeviceClass; var lastDeviceStyle = LastDeviceStyle; var actionsCount = actions.Count; for (var i = 0; i < actionsCount; i++) { var action = actions[i]; action.Update( updateTick, deltaTime, device ); if (action.UpdateTick > UpdateTick) { UpdateTick = action.UpdateTick; activeDevice = action.ActiveDevice; } if (action.LastInputTypeChangedTick > lastInputTypeChangedTick) { lastInputType = action.LastInputType; lastInputTypeChangedTick = action.LastInputTypeChangedTick; lastDeviceClass = action.LastDeviceClass; lastDeviceStyle = action.LastDeviceStyle; } } var oneAxisActionsCount = oneAxisActions.Count; for (var i = 0; i < oneAxisActionsCount; i++) { oneAxisActions[i].Update( updateTick, deltaTime ); } var twoAxisActionsCount = twoAxisActions.Count; for (var i = 0; i < twoAxisActionsCount; i++) { twoAxisActions[i].Update( updateTick, deltaTime ); } if (lastInputTypeChangedTick > LastInputTypeChangedTick) { var triggerEvent = lastInputType != LastInputType; LastInputType = lastInputType; LastInputTypeChangedTick = lastInputTypeChangedTick; LastDeviceClass = lastDeviceClass; LastDeviceStyle = lastDeviceStyle; if (OnLastInputTypeChanged != null && triggerEvent) { OnLastInputTypeChanged.Invoke( lastInputType ); } } } /// <summary> /// Reset the bindings on all actions in this set. /// </summary> public void Reset() { var actionCount = actions.Count; for (var i = 0; i < actionCount; i++) { actions[i].ResetBindings(); } } InputDevice FindActiveDevice() { var hasIncludeDevices = IncludeDevices.Count > 0; var hasExcludeDevices = ExcludeDevices.Count > 0; if (hasIncludeDevices || hasExcludeDevices) { var foundDevice = InputDevice.Null; var deviceCount = InputManager.Devices.Count; for (var i = 0; i < deviceCount; i++) { var device = InputManager.Devices[i]; if (device != foundDevice && device.LastChangedAfter( foundDevice )) { if (hasExcludeDevices && ExcludeDevices.Contains( device )) { continue; } if (!hasIncludeDevices || IncludeDevices.Contains( device )) { foundDevice = device; } } } return foundDevice; } return InputManager.ActiveDevice; } public void ClearInputState() { var actionsCount = actions.Count; for (var i = 0; i < actionsCount; i++) { actions[i].ClearInputState(); } var oneAxisActionsCount = oneAxisActions.Count; for (var i = 0; i < oneAxisActionsCount; i++) { oneAxisActions[i].ClearInputState(); } var twoAxisActionsCount = twoAxisActions.Count; for (var i = 0; i < twoAxisActionsCount; i++) { twoAxisActions[i].ClearInputState(); } } /// <summary> /// Searches all the bindings on all the actions on this set to see if any /// match the provided binding object. /// </summary> /// <returns><c>true</c>, if a matching binding is found on any action on /// this set, <c>false</c> otherwise.</returns> /// <param name="binding">The BindingSource template to search for.</param> public bool HasBinding( BindingSource binding ) { if (binding == null) { return false; } var actionsCount = actions.Count; for (var i = 0; i < actionsCount; i++) { if (actions[i].HasBinding( binding )) { return true; } } return false; } /// <summary> /// Searches all the bindings on all the actions on this set to see if any /// match the provided binding object and, if found, removes it. /// </summary> /// <param name="binding">The BindingSource template to search for.</param> public void RemoveBinding( BindingSource binding ) { if (binding == null) { return; } var actionsCount = actions.Count; for (var i = 0; i < actionsCount; i++) { actions[i].RemoveBinding( binding ); } } /// <summary> /// Query whether any action in this set is currently listening for a new binding. /// </summary> public bool IsListeningForBinding { get { return listenWithAction != null; } } /// <summary> /// Configures how in an action in this set listens for new bindings when the action does not /// explicitly define its own listen options. /// </summary> public BindingListenOptions ListenOptions { get { return listenOptions; } set { listenOptions = value ?? new BindingListenOptions(); } } InputDevice activeDevice; /// <summary> /// Gets the currently active device (controller) if present, otherwise returns a null device which does nothing. /// The currently active device is defined as the last device that provided input to an action on this set. /// When LastInputType is not a device (controller), this will return the null device. /// </summary> public InputDevice ActiveDevice { get { return (activeDevice == null) ? InputDevice.Null : activeDevice; } } const UInt16 currentDataFormatVersion = 2; /// <summary> /// Returns the state of this action set and all bindings encoded into a string /// that you can save somewhere. /// Pass this string to Load() to restore the state of this action set. /// </summary> public string Save() { using (var stream = new MemoryStream()) { using (var writer = new BinaryWriter( stream, System.Text.Encoding.UTF8 )) { // Write header. writer.Write( (byte) 'B' ); writer.Write( (byte) 'I' ); writer.Write( (byte) 'N' ); writer.Write( (byte) 'D' ); // Write version. writer.Write( currentDataFormatVersion ); // Write actions. var actionCount = actions.Count; writer.Write( actionCount ); for (var i = 0; i < actionCount; i++) { actions[i].Save( writer ); } } return Convert.ToBase64String( stream.ToArray() ); } } /// <summary> /// Load a state returned by calling Save() at a prior time. /// </summary> /// <param name="data">The data string.</param> public void Load( string data ) { if (data == null) { return; } try { using (var stream = new MemoryStream( Convert.FromBase64String( data ) )) { using (var reader = new BinaryReader( stream )) { if (reader.ReadUInt32() != 0x444E4942) { throw new Exception( "Unknown data format." ); } var dataFormatVersion = reader.ReadUInt16(); if (dataFormatVersion < 1 || dataFormatVersion > currentDataFormatVersion) { throw new Exception( "Unknown data format version: " + dataFormatVersion ); } var actionCount = reader.ReadInt32(); for (var i = 0; i < actionCount; i++) { PlayerAction action; if (actionsByName.TryGetValue( reader.ReadString(), out action )) { action.Load( reader, dataFormatVersion ); } } } } } catch (Exception e) { Debug.LogError( "Provided state could not be loaded:\n" + e.Message ); Reset(); } } } }
using UnityEngine; //using Windows.Kinect; using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System.IO; using System.Text; [RequireComponent(typeof(Animator))] public class AvatarController : MonoBehaviour { // The index of the player, whose movements the model represents. Default 0 (first player) public int playerIndex = 0; // Bool that has the characters (facing the player) actions become mirrored. Default false. public bool mirroredMovement = false; // Bool that determines whether the avatar is allowed to do vertical movement public bool verticalMovement = false; // Rate at which avatar will move through the scene. protected int moveRate = 1; // Slerp smooth factor public float smoothFactor = 5f; // Whether the offset node must be repositioned to the user's coordinates, as reported by the sensor or not. public bool offsetRelativeToSensor = false; // The body root node protected Transform bodyRoot; // Avatar's offset/parent object that may be used to rotate and position the model in space. protected GameObject offsetNode; // Variable to hold all them bones. It will initialize the same size as initialRotations. protected Transform[] bones; // Rotations of the bones when the Kinect tracking starts. protected Quaternion[] initialRotations; protected Quaternion[] initialLocalRotations; // Directions of the bones when the Kinect tracking starts. //private Vector3[] initialDirections; // Initial position and rotation of the transform protected Vector3 initialPosition; protected Quaternion initialRotation; // Calibration Offset Variables for Character Position. protected bool offsetCalibrated = false; protected float xOffset, yOffset, zOffset; //private Quaternion originalRotation; // private instance of the KinectManager protected KinectManager kinectManager; // transform caching gives performance boost since Unity calls GetComponent<Transform>() each time you call transform private Transform _transformCache; public new Transform transform { get { if (!_transformCache) _transformCache = base.transform; return _transformCache; } } public void Awake() { // check for double start if(bones != null) return; // inits the bones array bones = new Transform[27]; // Initial rotations and directions of the bones. initialRotations = new Quaternion[bones.Length]; initialLocalRotations = new Quaternion[bones.Length]; //initialDirections = new Vector3[bones.Length]; // Map bones to the points the Kinect tracks MapBones(); // Get initial bone rotations GetInitialRotations(); } // Update the avatar each frame. public void UpdateAvatar(Int64 UserID) { if(!transform.gameObject.activeInHierarchy) return; // Get the KinectManager instance if(kinectManager == null) { kinectManager = KinectManager.Instance; } // move the avatar to its Kinect position MoveAvatar(UserID); for (var boneIndex = 0; boneIndex < bones.Length; boneIndex++) { if (!bones[boneIndex]) continue; if(boneIndex2JointMap.ContainsKey(boneIndex)) { KinectInterop.JointType joint = !mirroredMovement ? boneIndex2JointMap[boneIndex] : boneIndex2MirrorJointMap[boneIndex]; TransformBone(UserID, joint, boneIndex, !mirroredMovement); } else if(specIndex2JointMap.ContainsKey(boneIndex)) { // special bones (clavicles) List<KinectInterop.JointType> alJoints = !mirroredMovement ? specIndex2JointMap[boneIndex] : specIndex2MirrorJointMap[boneIndex]; if(alJoints.Count >= 2) { //Debug.Log(alJoints[0].ToString()); Vector3 baseDir = alJoints[0].ToString().EndsWith("Left") ? Vector3.left : Vector3.right; TransformSpecialBone(UserID, alJoints[0], alJoints[1], boneIndex, baseDir, !mirroredMovement); } } } } // Set bones to their initial positions and rotations. public void ResetToInitialPosition() { if(bones == null) return; if(offsetNode != null) { offsetNode.transform.rotation = Quaternion.identity; } else { transform.rotation = Quaternion.identity; } //transform.position = initialPosition; //transform.rotation = initialRotation; // For each bone that was defined, reset to initial position. for(int pass = 0; pass < 2; pass++) // 2 passes because clavicles are at the end { for(int i = 0; i < bones.Length; i++) { if(bones[i] != null) { bones[i].rotation = initialRotations[i]; } } } if(bodyRoot != null) { bodyRoot.localPosition = Vector3.zero; bodyRoot.localRotation = Quaternion.identity; } // Restore the offset's position and rotation if(offsetNode != null) { offsetNode.transform.position = initialPosition; offsetNode.transform.rotation = initialRotation; } else { transform.position = initialPosition; transform.rotation = initialRotation; } } // Invoked on the successful calibration of a player. public void SuccessfulCalibration(Int64 userId) { // reset the models position if(offsetNode != null) { offsetNode.transform.rotation = initialRotation; } else { transform.rotation = initialRotation; } // re-calibrate the position offset offsetCalibrated = false; } // Apply the rotations tracked by kinect to the joints. protected void TransformBone(Int64 userId, KinectInterop.JointType joint, int boneIndex, bool flip) { Transform boneTransform = bones[boneIndex]; if(boneTransform == null || kinectManager == null) return; int iJoint = (int)joint; if(iJoint < 0 || !kinectManager.IsJointTracked(userId, iJoint)) return; // Get Kinect joint orientation Quaternion jointRotation = kinectManager.GetJointOrientation(userId, iJoint, flip); if(jointRotation == Quaternion.identity) return; // Smoothly transition to the new rotation Quaternion newRotation = Kinect2AvatarRot(jointRotation, boneIndex); if(smoothFactor != 0f) boneTransform.rotation = Quaternion.Slerp(boneTransform.rotation, newRotation, smoothFactor * Time.deltaTime); else boneTransform.rotation = newRotation; } // Apply the rotations tracked by kinect to a special joint protected void TransformSpecialBone(Int64 userId, KinectInterop.JointType joint, KinectInterop.JointType jointParent, int boneIndex, Vector3 baseDir, bool flip) { Transform boneTransform = bones[boneIndex]; if(boneTransform == null || kinectManager == null) return; if(!kinectManager.IsJointTracked(userId, (int)joint) || !kinectManager.IsJointTracked(userId, (int)jointParent)) { return; } Vector3 jointDir = kinectManager.GetJointDirection(userId, (int)joint, false, true); Quaternion jointRotation = Quaternion.FromToRotation(baseDir, jointDir); if(!flip) { Vector3 mirroredAngles = jointRotation.eulerAngles; mirroredAngles.y = -mirroredAngles.y; mirroredAngles.z = -mirroredAngles.z; jointRotation = Quaternion.Euler(mirroredAngles); } if(jointRotation != Quaternion.identity) { // Smoothly transition to the new rotation Quaternion newRotation = Kinect2AvatarRot(jointRotation, boneIndex); if(smoothFactor != 0f) boneTransform.rotation = Quaternion.Slerp(boneTransform.rotation, newRotation, smoothFactor * Time.deltaTime); else boneTransform.rotation = newRotation; } } // Moves the avatar in 3D space - pulls the tracked position of the user and applies it to root. protected void MoveAvatar(Int64 UserID) { if(!kinectManager || !kinectManager.IsJointTracked(UserID, (int)KinectInterop.JointType.SpineBase)) return; // Get the position of the body and store it. Vector3 trans = kinectManager.GetUserPosition(UserID); // If this is the first time we're moving the avatar, set the offset. Otherwise ignore it. if (!offsetCalibrated) { offsetCalibrated = true; xOffset = !mirroredMovement ? trans.x * moveRate : -trans.x * moveRate; yOffset = trans.y * moveRate; zOffset = -trans.z * moveRate; if(offsetRelativeToSensor) { Vector3 cameraPos = Camera.main.transform.position; float yRelToAvatar = (offsetNode != null ? offsetNode.transform.position.y : transform.position.y) - cameraPos.y; Vector3 relativePos = new Vector3(trans.x * moveRate, yRelToAvatar, trans.z * moveRate); Vector3 offsetPos = cameraPos + relativePos; if(offsetNode != null) { offsetNode.transform.position = offsetPos; } else { transform.position = offsetPos; } } } // Smoothly transition to the new position Vector3 targetPos = Kinect2AvatarPos(trans, verticalMovement); if(bodyRoot != null) { bodyRoot.localPosition = smoothFactor != 0f ? Vector3.Lerp(bodyRoot.localPosition, targetPos, smoothFactor * Time.deltaTime) : targetPos; } else { transform.localPosition = smoothFactor != 0f ? Vector3.Lerp(transform.localPosition, targetPos, smoothFactor * Time.deltaTime) : targetPos; } } // If the bones to be mapped have been declared, map that bone to the model. protected virtual void MapBones() { // make OffsetNode as a parent of model transform. offsetNode = new GameObject(name + "Ctrl") { layer = transform.gameObject.layer, tag = transform.gameObject.tag }; offsetNode.transform.position = transform.position; offsetNode.transform.rotation = transform.rotation; // take model transform as body root transform.parent = offsetNode.transform; transform.localPosition = Vector3.zero; transform.localRotation = Quaternion.identity; bodyRoot = transform; // get bone transforms from the animator component var animatorComponent = GetComponent<Animator>(); for (int boneIndex = 0; boneIndex < bones.Length; boneIndex++) { if (!boneIndex2MecanimMap.ContainsKey(boneIndex)) continue; bones[boneIndex] = animatorComponent.GetBoneTransform(boneIndex2MecanimMap[boneIndex]); } } // Capture the initial rotations of the bones protected void GetInitialRotations() { // save the initial rotation if(offsetNode != null) { initialPosition = offsetNode.transform.position; initialRotation = offsetNode.transform.rotation; offsetNode.transform.rotation = Quaternion.identity; } else { initialPosition = transform.position; initialRotation = transform.rotation; transform.rotation = Quaternion.identity; } for (int i = 0; i < bones.Length; i++) { if (bones[i] != null) { initialRotations[i] = bones[i].rotation; // * Quaternion.Inverse(initialRotation); initialLocalRotations[i] = bones[i].localRotation; } } // Restore the initial rotation if(offsetNode != null) { offsetNode.transform.rotation = initialRotation; } else { transform.rotation = initialRotation; } } // Converts kinect joint rotation to avatar joint rotation, depending on joint initial rotation and offset rotation protected Quaternion Kinect2AvatarRot(Quaternion jointRotation, int boneIndex) { Quaternion newRotation = jointRotation * initialRotations[boneIndex]; if (offsetNode != null) { Vector3 totalRotation = newRotation.eulerAngles + offsetNode.transform.rotation.eulerAngles; newRotation = Quaternion.Euler(totalRotation); } return newRotation; } // Converts Kinect position to avatar skeleton position, depending on initial position, mirroring and move rate protected Vector3 Kinect2AvatarPos(Vector3 jointPosition, bool bMoveVertically) { float xPos; if(!mirroredMovement) xPos = jointPosition.x * moveRate - xOffset; else xPos = -jointPosition.x * moveRate - xOffset; float yPos = jointPosition.y * moveRate - yOffset; float zPos = -jointPosition.z * moveRate - zOffset; Vector3 newPosition = new Vector3(xPos, bMoveVertically ? yPos : 0f, zPos); return newPosition; } // dictionaries to speed up bones' processing // the author of the terrific idea for kinect-joints to mecanim-bones mapping // along with its initial implementation, including following dictionary is // Mikhail Korchun (korchoon@gmail.com). Big thanks to this guy! private readonly Dictionary<int, HumanBodyBones> boneIndex2MecanimMap = new Dictionary<int, HumanBodyBones> { {0, HumanBodyBones.Hips}, {1, HumanBodyBones.Spine}, // {2, HumanBodyBones.Chest}, {3, HumanBodyBones.Neck}, {4, HumanBodyBones.Head}, {5, HumanBodyBones.LeftUpperArm}, {6, HumanBodyBones.LeftLowerArm}, {7, HumanBodyBones.LeftHand}, {8, HumanBodyBones.LeftIndexProximal}, {9, HumanBodyBones.LeftIndexIntermediate}, {10, HumanBodyBones.LeftThumbProximal}, {11, HumanBodyBones.RightUpperArm}, {12, HumanBodyBones.RightLowerArm}, {13, HumanBodyBones.RightHand}, {14, HumanBodyBones.RightIndexProximal}, {15, HumanBodyBones.RightIndexIntermediate}, {16, HumanBodyBones.RightThumbProximal}, {17, HumanBodyBones.LeftUpperLeg}, {18, HumanBodyBones.LeftLowerLeg}, {19, HumanBodyBones.LeftFoot}, {20, HumanBodyBones.LeftToes}, {21, HumanBodyBones.RightUpperLeg}, {22, HumanBodyBones.RightLowerLeg}, {23, HumanBodyBones.RightFoot}, {24, HumanBodyBones.RightToes}, {25, HumanBodyBones.LeftShoulder}, {26, HumanBodyBones.RightShoulder}, }; protected readonly Dictionary<int, KinectInterop.JointType> boneIndex2JointMap = new Dictionary<int, KinectInterop.JointType> { {0, KinectInterop.JointType.SpineBase}, {1, KinectInterop.JointType.SpineMid}, {2, KinectInterop.JointType.SpineShoulder}, {3, KinectInterop.JointType.Neck}, {4, KinectInterop.JointType.Head}, {5, KinectInterop.JointType.ShoulderLeft}, {6, KinectInterop.JointType.ElbowLeft}, {7, KinectInterop.JointType.WristLeft}, {8, KinectInterop.JointType.HandLeft}, {9, KinectInterop.JointType.HandTipLeft}, {10, KinectInterop.JointType.ThumbLeft}, {11, KinectInterop.JointType.ShoulderRight}, {12, KinectInterop.JointType.ElbowRight}, {13, KinectInterop.JointType.WristRight}, {14, KinectInterop.JointType.HandRight}, {15, KinectInterop.JointType.HandTipRight}, {16, KinectInterop.JointType.ThumbRight}, {17, KinectInterop.JointType.HipLeft}, {18, KinectInterop.JointType.KneeLeft}, {19, KinectInterop.JointType.AnkleLeft}, {20, KinectInterop.JointType.FootLeft}, {21, KinectInterop.JointType.HipRight}, {22, KinectInterop.JointType.KneeRight}, {23, KinectInterop.JointType.AnkleRight}, {24, KinectInterop.JointType.FootRight}, }; protected readonly Dictionary<int, List<KinectInterop.JointType>> specIndex2JointMap = new Dictionary<int, List<KinectInterop.JointType>> { {25, new List<KinectInterop.JointType> {KinectInterop.JointType.ShoulderLeft, KinectInterop.JointType.SpineShoulder} }, {26, new List<KinectInterop.JointType> {KinectInterop.JointType.ShoulderRight, KinectInterop.JointType.SpineShoulder} }, }; protected readonly Dictionary<int, KinectInterop.JointType> boneIndex2MirrorJointMap = new Dictionary<int, KinectInterop.JointType> { {0, KinectInterop.JointType.SpineBase}, {1, KinectInterop.JointType.SpineMid}, {2, KinectInterop.JointType.SpineShoulder}, {3, KinectInterop.JointType.Neck}, {4, KinectInterop.JointType.Head}, {5, KinectInterop.JointType.ShoulderRight}, {6, KinectInterop.JointType.ElbowRight}, {7, KinectInterop.JointType.WristRight}, {8, KinectInterop.JointType.HandRight}, {9, KinectInterop.JointType.HandTipRight}, {10, KinectInterop.JointType.ThumbRight}, {11, KinectInterop.JointType.ShoulderLeft}, {12, KinectInterop.JointType.ElbowLeft}, {13, KinectInterop.JointType.WristLeft}, {14, KinectInterop.JointType.HandLeft}, {15, KinectInterop.JointType.HandTipLeft}, {16, KinectInterop.JointType.ThumbLeft}, {17, KinectInterop.JointType.HipRight}, {18, KinectInterop.JointType.KneeRight}, {19, KinectInterop.JointType.AnkleRight}, {20, KinectInterop.JointType.FootRight}, {21, KinectInterop.JointType.HipLeft}, {22, KinectInterop.JointType.KneeLeft}, {23, KinectInterop.JointType.AnkleLeft}, {24, KinectInterop.JointType.FootLeft}, }; protected readonly Dictionary<int, List<KinectInterop.JointType>> specIndex2MirrorJointMap = new Dictionary<int, List<KinectInterop.JointType>> { {25, new List<KinectInterop.JointType> {KinectInterop.JointType.ShoulderRight, KinectInterop.JointType.SpineShoulder} }, {26, new List<KinectInterop.JointType> {KinectInterop.JointType.ShoulderLeft, KinectInterop.JointType.SpineShoulder} }, }; }
// 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.Compute.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedFirewallsClientTest { [xunit::FactAttribute] public void GetRequestObject() { moq::Mock<Firewalls.FirewallsClient> mockGrpcClient = new moq::Mock<Firewalls.FirewallsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetFirewallRequest request = new GetFirewallRequest { Project = "projectaa6ff846", Firewall = "firewall1a37e536", }; Firewall expectedResponse = new Firewall { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", CreationTimestamp = "creation_timestamp235e59a1", TargetTags = { "target_tags29e39aea", }, SourceServiceAccounts = { "source_service_accounts462c1c37", }, Direction = Firewall.Types.Direction.Ingress, Allowed = { new Allowed(), }, SourceRanges = { "source_ranges5dbeae62", }, Network = "networkd22ce091", Disabled = false, Denied = { new Denied(), }, DestinationRanges = { "destination_rangesf67f2379", }, LogConfig = new FirewallLogConfig(), Description = "description2cf9da67", Priority = 1546225849, SourceTags = { "source_tags7a2648e1", }, SelfLink = "self_link7e87f12d", TargetServiceAccounts = { "target_service_accounts61bf1663", }, }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); FirewallsClient client = new FirewallsClientImpl(mockGrpcClient.Object, null); Firewall response = client.Get(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRequestObjectAsync() { moq::Mock<Firewalls.FirewallsClient> mockGrpcClient = new moq::Mock<Firewalls.FirewallsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetFirewallRequest request = new GetFirewallRequest { Project = "projectaa6ff846", Firewall = "firewall1a37e536", }; Firewall expectedResponse = new Firewall { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", CreationTimestamp = "creation_timestamp235e59a1", TargetTags = { "target_tags29e39aea", }, SourceServiceAccounts = { "source_service_accounts462c1c37", }, Direction = Firewall.Types.Direction.Ingress, Allowed = { new Allowed(), }, SourceRanges = { "source_ranges5dbeae62", }, Network = "networkd22ce091", Disabled = false, Denied = { new Denied(), }, DestinationRanges = { "destination_rangesf67f2379", }, LogConfig = new FirewallLogConfig(), Description = "description2cf9da67", Priority = 1546225849, SourceTags = { "source_tags7a2648e1", }, SelfLink = "self_link7e87f12d", TargetServiceAccounts = { "target_service_accounts61bf1663", }, }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Firewall>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FirewallsClient client = new FirewallsClientImpl(mockGrpcClient.Object, null); Firewall responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Firewall responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void Get() { moq::Mock<Firewalls.FirewallsClient> mockGrpcClient = new moq::Mock<Firewalls.FirewallsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetFirewallRequest request = new GetFirewallRequest { Project = "projectaa6ff846", Firewall = "firewall1a37e536", }; Firewall expectedResponse = new Firewall { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", CreationTimestamp = "creation_timestamp235e59a1", TargetTags = { "target_tags29e39aea", }, SourceServiceAccounts = { "source_service_accounts462c1c37", }, Direction = Firewall.Types.Direction.Ingress, Allowed = { new Allowed(), }, SourceRanges = { "source_ranges5dbeae62", }, Network = "networkd22ce091", Disabled = false, Denied = { new Denied(), }, DestinationRanges = { "destination_rangesf67f2379", }, LogConfig = new FirewallLogConfig(), Description = "description2cf9da67", Priority = 1546225849, SourceTags = { "source_tags7a2648e1", }, SelfLink = "self_link7e87f12d", TargetServiceAccounts = { "target_service_accounts61bf1663", }, }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); FirewallsClient client = new FirewallsClientImpl(mockGrpcClient.Object, null); Firewall response = client.Get(request.Project, request.Firewall); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAsync() { moq::Mock<Firewalls.FirewallsClient> mockGrpcClient = new moq::Mock<Firewalls.FirewallsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetFirewallRequest request = new GetFirewallRequest { Project = "projectaa6ff846", Firewall = "firewall1a37e536", }; Firewall expectedResponse = new Firewall { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", CreationTimestamp = "creation_timestamp235e59a1", TargetTags = { "target_tags29e39aea", }, SourceServiceAccounts = { "source_service_accounts462c1c37", }, Direction = Firewall.Types.Direction.Ingress, Allowed = { new Allowed(), }, SourceRanges = { "source_ranges5dbeae62", }, Network = "networkd22ce091", Disabled = false, Denied = { new Denied(), }, DestinationRanges = { "destination_rangesf67f2379", }, LogConfig = new FirewallLogConfig(), Description = "description2cf9da67", Priority = 1546225849, SourceTags = { "source_tags7a2648e1", }, SelfLink = "self_link7e87f12d", TargetServiceAccounts = { "target_service_accounts61bf1663", }, }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Firewall>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FirewallsClient client = new FirewallsClientImpl(mockGrpcClient.Object, null); Firewall responseCallSettings = await client.GetAsync(request.Project, request.Firewall, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Firewall responseCancellationToken = await client.GetAsync(request.Project, request.Firewall, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS) // Modeling Virtual Environments and Simulation (MOVES) Institute // (http://www.nps.edu and http://www.MovesInstitute.org) // nor the names of its contributors may be used to endorse or // promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All // rights reserved. This work is licensed under the BSD open source license, // available at https://www.movesinstitute.org/licenses/bsd.html // // Author: DMcG // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si) using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Xml.Serialization; using OpenDis.Core; namespace OpenDis.Dis1998 { /// <summary> /// 5.2.48: Linear segment parameters /// </summary> [Serializable] [XmlRoot] [XmlInclude(typeof(SixByteChunk))] [XmlInclude(typeof(Vector3Double))] [XmlInclude(typeof(Orientation))] public partial class LinearSegmentParameter { /// <summary> /// number of segments /// </summary> private byte _segmentNumber; /// <summary> /// segment appearance /// </summary> private SixByteChunk _segmentAppearance = new SixByteChunk(); /// <summary> /// location /// </summary> private Vector3Double _location = new Vector3Double(); /// <summary> /// orientation /// </summary> private Orientation _orientation = new Orientation(); /// <summary> /// segmentLength /// </summary> private ushort _segmentLength; /// <summary> /// segmentWidth /// </summary> private ushort _segmentWidth; /// <summary> /// segmentHeight /// </summary> private ushort _segmentHeight; /// <summary> /// segment Depth /// </summary> private ushort _segmentDepth; /// <summary> /// segment Depth /// </summary> private uint _pad1; /// <summary> /// Initializes a new instance of the <see cref="LinearSegmentParameter"/> class. /// </summary> public LinearSegmentParameter() { } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator !=(LinearSegmentParameter left, LinearSegmentParameter right) { return !(left == right); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(LinearSegmentParameter left, LinearSegmentParameter right) { if (object.ReferenceEquals(left, right)) { return true; } if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } public virtual int GetMarshalledSize() { int marshalSize = 0; marshalSize += 1; // this._segmentNumber marshalSize += this._segmentAppearance.GetMarshalledSize(); // this._segmentAppearance marshalSize += this._location.GetMarshalledSize(); // this._location marshalSize += this._orientation.GetMarshalledSize(); // this._orientation marshalSize += 2; // this._segmentLength marshalSize += 2; // this._segmentWidth marshalSize += 2; // this._segmentHeight marshalSize += 2; // this._segmentDepth marshalSize += 4; // this._pad1 return marshalSize; } /// <summary> /// Gets or sets the number of segments /// </summary> [XmlElement(Type = typeof(byte), ElementName = "segmentNumber")] public byte SegmentNumber { get { return this._segmentNumber; } set { this._segmentNumber = value; } } /// <summary> /// Gets or sets the segment appearance /// </summary> [XmlElement(Type = typeof(SixByteChunk), ElementName = "segmentAppearance")] public SixByteChunk SegmentAppearance { get { return this._segmentAppearance; } set { this._segmentAppearance = value; } } /// <summary> /// Gets or sets the location /// </summary> [XmlElement(Type = typeof(Vector3Double), ElementName = "location")] public Vector3Double Location { get { return this._location; } set { this._location = value; } } /// <summary> /// Gets or sets the orientation /// </summary> [XmlElement(Type = typeof(Orientation), ElementName = "orientation")] public Orientation Orientation { get { return this._orientation; } set { this._orientation = value; } } /// <summary> /// Gets or sets the segmentLength /// </summary> [XmlElement(Type = typeof(ushort), ElementName = "segmentLength")] public ushort SegmentLength { get { return this._segmentLength; } set { this._segmentLength = value; } } /// <summary> /// Gets or sets the segmentWidth /// </summary> [XmlElement(Type = typeof(ushort), ElementName = "segmentWidth")] public ushort SegmentWidth { get { return this._segmentWidth; } set { this._segmentWidth = value; } } /// <summary> /// Gets or sets the segmentHeight /// </summary> [XmlElement(Type = typeof(ushort), ElementName = "segmentHeight")] public ushort SegmentHeight { get { return this._segmentHeight; } set { this._segmentHeight = value; } } /// <summary> /// Gets or sets the segment Depth /// </summary> [XmlElement(Type = typeof(ushort), ElementName = "segmentDepth")] public ushort SegmentDepth { get { return this._segmentDepth; } set { this._segmentDepth = value; } } /// <summary> /// Gets or sets the segment Depth /// </summary> [XmlElement(Type = typeof(uint), ElementName = "pad1")] public uint Pad1 { get { return this._pad1; } set { this._pad1 = value; } } /// <summary> /// Occurs when exception when processing PDU is caught. /// </summary> public event EventHandler<PduExceptionEventArgs> ExceptionOccured; /// <summary> /// Called when exception occurs (raises the <see cref="Exception"/> event). /// </summary> /// <param name="e">The exception.</param> protected void RaiseExceptionOccured(Exception e) { if (Pdu.FireExceptionEvents && this.ExceptionOccured != null) { this.ExceptionOccured(this, new PduExceptionEventArgs(e)); } } /// <summary> /// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Marshal(DataOutputStream dos) { if (dos != null) { try { dos.WriteUnsignedByte((byte)this._segmentNumber); this._segmentAppearance.Marshal(dos); this._location.Marshal(dos); this._orientation.Marshal(dos); dos.WriteUnsignedShort((ushort)this._segmentLength); dos.WriteUnsignedShort((ushort)this._segmentWidth); dos.WriteUnsignedShort((ushort)this._segmentHeight); dos.WriteUnsignedShort((ushort)this._segmentDepth); dos.WriteUnsignedInt((uint)this._pad1); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Unmarshal(DataInputStream dis) { if (dis != null) { try { this._segmentNumber = dis.ReadUnsignedByte(); this._segmentAppearance.Unmarshal(dis); this._location.Unmarshal(dis); this._orientation.Unmarshal(dis); this._segmentLength = dis.ReadUnsignedShort(); this._segmentWidth = dis.ReadUnsignedShort(); this._segmentHeight = dis.ReadUnsignedShort(); this._segmentDepth = dis.ReadUnsignedShort(); this._pad1 = dis.ReadUnsignedInt(); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } /// <summary> /// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging. /// This will be modified in the future to provide a better display. Usage: /// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb }); /// where pdu is an object representing a single pdu and sb is a StringBuilder. /// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality /// </summary> /// <param name="sb">The StringBuilder instance to which the PDU is written to.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Reflection(StringBuilder sb) { sb.AppendLine("<LinearSegmentParameter>"); try { sb.AppendLine("<segmentNumber type=\"byte\">" + this._segmentNumber.ToString(CultureInfo.InvariantCulture) + "</segmentNumber>"); sb.AppendLine("<segmentAppearance>"); this._segmentAppearance.Reflection(sb); sb.AppendLine("</segmentAppearance>"); sb.AppendLine("<location>"); this._location.Reflection(sb); sb.AppendLine("</location>"); sb.AppendLine("<orientation>"); this._orientation.Reflection(sb); sb.AppendLine("</orientation>"); sb.AppendLine("<segmentLength type=\"ushort\">" + this._segmentLength.ToString(CultureInfo.InvariantCulture) + "</segmentLength>"); sb.AppendLine("<segmentWidth type=\"ushort\">" + this._segmentWidth.ToString(CultureInfo.InvariantCulture) + "</segmentWidth>"); sb.AppendLine("<segmentHeight type=\"ushort\">" + this._segmentHeight.ToString(CultureInfo.InvariantCulture) + "</segmentHeight>"); sb.AppendLine("<segmentDepth type=\"ushort\">" + this._segmentDepth.ToString(CultureInfo.InvariantCulture) + "</segmentDepth>"); sb.AppendLine("<pad1 type=\"uint\">" + this._pad1.ToString(CultureInfo.InvariantCulture) + "</pad1>"); sb.AppendLine("</LinearSegmentParameter>"); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return this == obj as LinearSegmentParameter; } /// <summary> /// Compares for reference AND value equality. /// </summary> /// <param name="obj">The object to compare with this instance.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public bool Equals(LinearSegmentParameter obj) { bool ivarsEqual = true; if (obj.GetType() != this.GetType()) { return false; } if (this._segmentNumber != obj._segmentNumber) { ivarsEqual = false; } if (!this._segmentAppearance.Equals(obj._segmentAppearance)) { ivarsEqual = false; } if (!this._location.Equals(obj._location)) { ivarsEqual = false; } if (!this._orientation.Equals(obj._orientation)) { ivarsEqual = false; } if (this._segmentLength != obj._segmentLength) { ivarsEqual = false; } if (this._segmentWidth != obj._segmentWidth) { ivarsEqual = false; } if (this._segmentHeight != obj._segmentHeight) { ivarsEqual = false; } if (this._segmentDepth != obj._segmentDepth) { ivarsEqual = false; } if (this._pad1 != obj._pad1) { ivarsEqual = false; } return ivarsEqual; } /// <summary> /// HashCode Helper /// </summary> /// <param name="hash">The hash value.</param> /// <returns>The new hash value.</returns> private static int GenerateHash(int hash) { hash = hash << (5 + hash); return hash; } /// <summary> /// Gets the hash code. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { int result = 0; result = GenerateHash(result) ^ this._segmentNumber.GetHashCode(); result = GenerateHash(result) ^ this._segmentAppearance.GetHashCode(); result = GenerateHash(result) ^ this._location.GetHashCode(); result = GenerateHash(result) ^ this._orientation.GetHashCode(); result = GenerateHash(result) ^ this._segmentLength.GetHashCode(); result = GenerateHash(result) ^ this._segmentWidth.GetHashCode(); result = GenerateHash(result) ^ this._segmentHeight.GetHashCode(); result = GenerateHash(result) ^ this._segmentDepth.GetHashCode(); result = GenerateHash(result) ^ this._pad1.GetHashCode(); return result; } } }
using System; using System.Collections.Generic; using System.Text; using System.Web.Security; using System.Web.Profile; namespace Rainbow.Framework.Providers.RainbowMembershipProvider { /// <summary> /// Rainbow-specific membership provider API, implements ASP.NET's membership plus extra funcionality Rainbow needs. /// </summary> public abstract class RainbowMembershipProvider : MembershipProvider { /// <summary> /// Gets the error message. /// </summary> /// <param name="status">The status.</param> /// <returns></returns> public string GetErrorMessage( MembershipCreateStatus status ) { switch ( status ) { case MembershipCreateStatus.DuplicateUserName: return "Username already exists. Please enter a different user name."; case MembershipCreateStatus.DuplicateEmail: return "A username for that e-mail address already exists. Please enter a different e-mail address."; case MembershipCreateStatus.InvalidPassword: return "The password provided is invalid. Please enter a valid password value."; case MembershipCreateStatus.InvalidEmail: return "The e-mail address provided is invalid. Please check the value and try again."; case MembershipCreateStatus.InvalidAnswer: return "The password retrieval answer provided is invalid. Please check the value and try again."; case MembershipCreateStatus.InvalidQuestion: return "The password retrieval question provided is invalid. Please check the value and try again."; case MembershipCreateStatus.InvalidUserName: return "The user name provided is invalid. Please check the value and try again."; case MembershipCreateStatus.ProviderError: return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator."; case MembershipCreateStatus.UserRejected: return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator."; default: return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator."; } } /// <summary> /// Loads the user profile. /// </summary> /// <param name="user">The user.</param> protected virtual void LoadUserProfile( RainbowUser user ) { ProfileBase profile = ProfileBase.Create( user.UserName ); user.Name = profile.GetPropertyValue( "Name" ).ToString(); user.Company = profile.GetPropertyValue( "Company" ).ToString(); user.Address = profile.GetPropertyValue( "Address" ).ToString(); user.Zip = profile.GetPropertyValue( "Zip" ).ToString(); user.City = profile.GetPropertyValue( "City" ).ToString(); user.CountryID = profile.GetPropertyValue( "CountryID" ).ToString(); user.StateID = Convert.ToInt32( profile.GetPropertyValue( "StateID" ) ); user.Fax = profile.GetPropertyValue( "Fax" ).ToString(); user.Phone = profile.GetPropertyValue( "Phone" ).ToString(); user.SendNewsletter = Convert.ToBoolean( profile.GetPropertyValue( "SendNewsletter" ) ); } /// <summary> /// Saves the user profile. /// </summary> /// <param name="user">The user.</param> protected virtual void SaveUserProfile( RainbowUser user ) { ProfileBase profile = ProfileBase.Create( user.UserName ); profile.SetPropertyValue( "Name", user.Name == null ? string.Empty : user.Name ); profile.SetPropertyValue( "Company", user.Company == null ? string.Empty : user.Company); profile.SetPropertyValue( "Address", user.Address == null ? string.Empty : user.Address ); profile.SetPropertyValue( "Zip", user.Zip == null ? string.Empty : user.Zip ); profile.SetPropertyValue( "City", user.City == null ? string.Empty : user.City ); profile.SetPropertyValue( "CountryID", user.CountryID == null ? string.Empty : user.CountryID ); profile.SetPropertyValue( "StateID", user.StateID ); profile.SetPropertyValue( "Fax", user.Fax == null ? string.Empty : user.Fax ); profile.SetPropertyValue( "Phone", user.Phone == null ? string.Empty : user.Phone ); profile.SetPropertyValue( "SendNewsletter", user.SendNewsletter ); profile.Save(); } /// <summary> /// Deletes the user profile. /// </summary> /// <param name="userName">Name of the user.</param> protected virtual bool DeleteUserProfile( string userName ) { return ProfileManager.DeleteProfile( userName ); } /// <summary> /// Instanciates a new user. /// </summary> /// <param name="providerName">Name of the provider.</param> /// <param name="name">The name.</param> /// <param name="providerUserKey">The provider user key.</param> /// <param name="email">The email.</param> /// <param name="passwordQuestion">The password question.</param> /// <param name="comment">The comment.</param> /// <param name="isApproved">if set to <c>true</c> [is approved].</param> /// <param name="isLockedOut">if set to <c>true</c> [is locked out].</param> /// <param name="creationDate">The creation date.</param> /// <param name="lastLoginDate">The last login date.</param> /// <param name="lastActivityDate">The last activity date.</param> /// <param name="lastPasswordChangeDate">The last password change date.</param> /// <param name="lastLockoutDate">The last lockout date.</param> /// <returns></returns> protected virtual RainbowUser InstanciateNewUser( string providerName, string name, Guid providerUserKey, string email, string passwordQuestion, string comment, bool isApproved, bool isLockedOut, DateTime creationDate, DateTime lastLoginDate, DateTime lastActivityDate, DateTime lastPasswordChangeDate, DateTime lastLockoutDate ) { return new RainbowUser( providerName, name, providerUserKey, email, passwordQuestion, comment, isApproved, isLockedOut, creationDate, lastLoginDate, lastActivityDate, lastPasswordChangeDate, lastLockoutDate); } /// <summary> /// Instanciates a new user. /// </summary> /// <param name="name">The name.</param> /// <returns></returns> protected virtual RainbowUser InstanciateNewUser( string name ) { return new RainbowUser( name ); } /// <summary> /// Takes, as input, a user name, password, e-mail address, and other information and adds a new user to the membership data source. /// CreateUser returns a MembershipUser object representing the newly created user. /// Before creating a new user, CreateUser calls the provider's virtual OnValidatingPassword method to validate the supplied password. /// It then creates the user or cancels the action based on the outcome of the call. /// </summary> /// <param name="portalAlias">Rainbow's portal alias</param> /// <param name="username">New user's name</param> /// <param name="password">New user's password</param> /// <param name="email">New user's email</param> /// <param name="passwordQuestion">The password question</param> /// <param name="passwordAnswer">The password answer</param> /// <param name="isApproved">Whether the user is approved or not</param> /// <param name="status">An out parameter (in Visual Basic, ByRef) that returns a MembershipCreateStatus value indicating whether the user was /// successfully created or, if the user was not created, the reason why.</param> /// <returns>A new <code>MembershipUser</code>. If the user was not created, CreateUser returns null.</returns> public abstract MembershipUser CreateUser( string portalAlias, string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, out MembershipCreateStatus status ); /// <summary> /// Takes as an input a RainbowMembershipUser, a password and a passwordAnswer and creates a user saving its profile. /// </summary> /// <param name="user">A <code>RainbowMembershipUser</code> with most of the user's data</param> /// <param name="password">the user's account password (it can't be passed in user)</param> /// <param name="passwordAnswer">the user's account password answer (it can't be passed in user)</param> /// <returns>A new <code>MembershipUser</code>. If the user was not created, CreateUser returns null.</returns> public virtual MembershipUser CreateUser( RainbowUser user, string password, string passwordAnswer ) { MembershipCreateStatus status; RainbowUser membershipUser = ( RainbowUser )CreateUser( user.UserName, password, user.Email, user.PasswordQuestion, passwordAnswer, user.IsApproved, user.ProviderUserKey, out status ); if ( user != null ) { SaveUserProfile( membershipUser ); } return membershipUser; } /// <summary> /// Takes, as input, a user name, password, password question, and password answer and updates the password question and answer /// in the data source if the user name and password are valid. /// </summary> /// <param name="portalAlias">Rainbow's portal alias</param> /// <param name="username">The user's name</param> /// <param name="password">The user's password</param> /// <param name="newPasswordQuestion">The user's new password question</param> /// <param name="newPasswordAnswer">The user's new password answer</param> /// <returns>This method returns true if the password question and answer /// are successfully updated. It returns false if either the user name or password is invalid.</returns> public abstract bool ChangePasswordQuestionAndAnswer( string portalAlias, string username, string password, string newPasswordQuestion, string newPasswordAnswer ); /// <summary> /// Takes, as input, a user name, a password (the user's current password), and a new password and updates /// the password in the membership data source. /// Before changing a password, ChangePassword calls the provider's virtual OnValidatingPassword method to /// validate the new password. It then changes the password or cancels the action based on the outcome of the call. /// If the user name, password, new password, or password answer is not valid, ChangePassword /// does not throw an exception; it simply returns false. /// Following a successful password change, ChangePassword updates the user's LastPasswordChangedDate. /// </summary> /// <param name="portalAlias">Rainbow's portal alias</param> /// <param name="username">The user's name</param> /// <param name="oldPassword">The user's old password</param> /// <param name="newPassword">The user's new password</param> /// <returns>ChangePassword returns true if the password was updated successfully. /// Otherwise, it returns false.</returns> public abstract bool ChangePassword( string portalAlias, string username, string oldPassword, string newPassword ); /// <summary> /// Takes, as input, a user name and deletes that user from the membership data source. /// </summary> /// <param name="portalAlias">Rainbow's portal alias</param> /// <param name="username">The user's name</param> /// <param name="deleteAllRelatedData">Specifies whether /// related data for that user should be deleted also. If deleteAllRelatedData is true, DeleteUser /// should delete role data, profile data, and all other data associated with that user.</param> /// <returns>DeleteUser returns true if the user was successfully deleted. Otherwise, it returns false.</returns> public abstract bool DeleteUser( string portalAlias, string username, bool deleteAllRelatedData ); /// <summary> /// The results returned by GetAllUsers are constrained by the pageIndex and pageSize input parameters. /// pageSize specifies the maximum number of MembershipUser objects to return. pageIndex /// identifies which page of results to return. Page indexes are 0-based. /// GetAllUsers also takes an out parameter (in Visual Basic, ByRef) named totalRecords that, on return, holds a count of all registered users. /// </summary> /// <param name="portalAlias">Rainbow's portal alias</param> /// <returns>Returns a MembershipUserCollection containing MembershipUser objects representing all registered users. /// If there are no registered users, GetAllUsers returns an empty MembershipUserCollection.</returns> public abstract MembershipUserCollection GetAllUsers( string portalAlias ); /// <summary> /// The results returned by GetAllUsers are constrained by the pageIndex and pageSize input parameters. /// pageSize specifies the maximum number of MembershipUser objects to return. pageIndex /// identifies which page of results to return. Page indexes are 0-based. /// GetAllUsers also takes an out parameter (in Visual Basic, ByRef) named totalRecords that, on return, holds a count of all registered users. /// </summary> /// <param name="portalAlias">Rainbow's portal alias</param> /// <param name="pageIndex">Page index to retrieve</param> /// <param name="pageSize">Page size</param> /// <param name="totalRecords">Holds a count of all records.</param> /// <returns>Returns a MembershipUserCollection containing MembershipUser objects representing all registered users. /// If there are no registered users, GetAllUsers returns an empty MembershipUserCollection.</returns> public abstract MembershipUserCollection GetAllUsers( string portalAlias, int pageIndex, int pageSize, out int totalRecords ); /// <summary> /// Returns a count of users that are currently online; that is, whose LastActivityDate is /// greater than the current date and time minus the value of the membership service's /// UserIsOnlineTimeWindow property, which can be read from Membership.UserIsOnlineTimeWindow. /// UserIsOnlineTimeWindow specifies a time in minutes and is set using the <code>&lt;membership&gt;</code> /// element's userIsOnlineTimeWindow attribute. /// </summary> /// <param name="portalAlias">Rainbow's portal alias</param> /// <returns>Returns a count of users that are currently online</returns> public abstract int GetNumberOfUsersOnline( string portalAlias ); /// <summary> /// Takes, as input, a user name and a password answer and returns that user's password. /// Before retrieving a password, GetPassword verifies that EnablePasswordRetrieval is true. /// GetPassword also checks the value of the RequiresQuestionAndAnswer property before retrieving a password. /// If RequiresQuestionAndAnswer is true, GetPassword compares the supplied password answer to the stored password answer /// and throws a MembershipPasswordException if the two don't match. /// </summary> /// <param name="portalAlias">Rainbow's portal alias</param> /// <param name="username">The user's name</param> /// <param name="answer">The password answer</param> /// <exception cref="System.Configuration.Provider.ProviderException">If the user name is not valid, GetPassword throws a ProviderException.</exception> /// <exception cref="NotSupportedException">If EnablePasswordRetrieval is false, GetPassword throws a NotSupportedException.</exception> /// <exception cref="System.Configuration.Provider.ProviderException">If EnablePasswordRetrieval is true but the password format is hashed, GetPassword throws a /// ProviderException since hashed passwords cannot, by definition, be retrieved.</exception> /// <exception cref="MembershipPasswordException">GetPassword also throws a MembershipPasswordException /// if the user whose password is being retrieved is currently locked out.</exception> /// <exception cref="MembershipPasswordException">If RequiresQuestionAndAnswer is true, GetPassword compares the supplied password answer to the stored password answer /// and throws a MembershipPasswordException if the two don't match. </exception> /// <returns>Returns the user's password</returns> public abstract string GetPassword( string portalAlias, string username, string answer ); /// <summary> /// Takes, as input, a user name or user ID (the method is overloaded) and a Boolean value indicating whether to /// update the user's LastActivityDate to show that the user is currently online. /// </summary> /// <param name="portalAlias">Rainbow's portal alias</param> /// <param name="username">The user's name</param> /// <param name="userIsOnline"></param> /// <returns>GetUser returns a /// MembershipUser object representing the specified user. If the user name or user ID is invalid (that is, /// if it doesn't represent a registered user) GetUser returns null (Nothing in Visual Basic).</returns> public abstract MembershipUser GetUser( string portalAlias, string username, bool userIsOnline ); /// <summary> /// Unlocks (that is, restores login privileges for) the specified user. /// </summary> /// <param name="portalAlias">Rainbow's portal alias</param> /// <param name="username">The user's name</param> /// <returns>UnlockUser returns true if the user is successfully /// unlocked. Otherwise, it returns false. If the user is already unlocked, UnlockUser simply returns true.</returns> public abstract bool UnlockUser( string portalAlias, string username ); /// <summary> /// Takes, as input, an e-mail address and returns the first registered user name whose e-mail address matches the one supplied. /// If it doesn't find a user with a matching e-mail address, GetUserNameByEmail returns an empty string. /// </summary> /// <param name="portalAlias">Rainbow's portal alias</param> /// <param name="email"></param> /// <returns>The first registered user name whose e-mail address matches the one supplied. /// If it doesn't find a user with a matching e-mail address, GetUserNameByEmail returns an empty string.</returns> public abstract string GetUserNameByEmail( string portalAlias, string email ); /// <summary> /// Takes, as input, a MembershipUser object representing a registered user and updates the information stored /// for that user in the membership data source. /// Note that UpdateUser is not obligated to allow all the data that can be encapsulated in a /// MembershipUser object to be updated in the data source. /// </summary> /// <param name="portalAlias">Rainbow's portal alias</param> /// <exception cref="System.Configuration.Provider.ProviderException">If any of the input submitted in the MembershipUser object /// is not valid, UpdateUser throws a ProviderException.</exception> /// <param name="user">A MembershipUser object representing a registered user</param> public abstract void UpdateUser( string portalAlias, MembershipUser user ); /// <summary> /// Returns a MembershipUserCollection containing MembershipUser objects representing users whose user names match /// the usernameToMatch input parameter. Wildcard syntax is data source-dependent. MembershipUser objects in the /// MembershipUserCollection are sorted by user name. /// For an explanation of the pageIndex, pageSize, and totalRecords parameters, see the GetAllUsers method. /// </summary> /// <param name="portalAlias">Rainbow's portal alias</param> /// <param name="usernameToMatch"></param> /// <param name="pageIndex">Page index to retrieve</param> /// <param name="pageSize">Page size</param> /// <param name="totalRecords">Holds a count of all records.</param> /// <returns>A <code>MembershipUserCollection</code>. If FindUsersByName finds no matching users, it returns an /// empty MembershipUserCollection.</returns> public abstract MembershipUserCollection FindUsersByName( string portalAlias, string usernameToMatch, int pageIndex, int pageSize, out int totalRecords ); /// <summary> /// Returns a MembershipUserCollection containing MembershipUser objects representing users whose e-mail /// addresses match the emailToMatch input parameter. Wildcard syntax is data source-dependent. MembershipUser /// objects in the MembershipUserCollection are sorted by e-mail address. /// For an explanation of the pageIndex, pageSize, and totalRecords parameters, see the GetAllUsers method. /// </summary> /// <param name="portalAlias">Rainbow's portal alias</param> /// <param name="emailToMatch"></param> /// <param name="pageIndex">Page index to retrieve</param> /// <param name="pageSize">Page size</param> /// <param name="totalRecords">Holds a count of all records.</param> /// <returns>A <code>MembershipUserCollection</code>. If FindUsersByEmail finds no /// matching users, it returns an empty MembershipUserCollection.</returns> public abstract MembershipUserCollection FindUsersByEmail( string portalAlias, string emailToMatch, int pageIndex, int pageSize, out int totalRecords ); /// <summary> /// Takes, as input, a user name and a password answer and replaces the user's current password with a new, /// random password. A convenient mechanism for generating a random password is the Membership.GeneratePassword method. /// ResetPassword also checks the value of the RequiresQuestionAndAnswer property before resetting a password. /// Before resetting a password, ResetPassword verifies that EnablePasswordReset is true. /// Before resetting a password, ResetPassword calls the provider's virtual OnValidatingPassword method to /// validate the new password. It then resets the password or cancels the action based on the outcome of /// the call. /// Following a successful password reset, ResetPassword updates the user's LastPasswordChangedDate. /// </summary> /// <param name="portalAlias">Rainbow's portal alias</param> /// <param name="username">The user's name</param> /// <param name="answer">The password answer</param> /// <exception cref="NotSupportedException">If EnablePasswordReset is false, ResetPassword throws a NotSupportedException. </exception> /// <exception cref="System.Configuration.Provider.ProviderException">If the user name is not valid, ResetPassword throws a ProviderException.</exception> /// <exception cref="System.Configuration.Provider.ProviderException">If the new password is invalid, ResetPassword throws a ProviderException.</exception> /// <exception cref="MembershipPasswordException">If the user whose password is being changed is currently locked out, ResetPassword throws a MembershipPasswordException.</exception> /// <exception cref="MembershipPasswordException">If RequiresQuestionAndAnswer is true, ResetPassword compares the supplied password /// answer to the stored password answer and throws a MembershipPasswordException if the two don't match.</exception> /// <returns>ResetPassword then returns the new password.</returns> public abstract string ResetPassword( string portalAlias, string username, string answer ); /// <summary> /// Takes, as input, a user name and a password and verifies that they are valid-that is, that the membership /// data source contains a matching user name and password. ValidateUser returns true if the user name and /// password are valid, if the user is approved (that is, if MembershipUser.IsApproved is true), and if the /// user isn't currently locked out. Otherwise, it returns false. /// Following a successful validation, ValidateUser updates the user's LastLoginDate and fires an /// AuditMembershipAuthenticationSuccess Web event. Following a failed validation, it fires an /// AuditMembershipAuthenticationFailure Web event. /// </summary> /// <param name="portalAlias">Rainbow's portal alias</param> /// <param name="username">The user's name</param> /// <param name="password">The user's password</param> /// <returns></returns> public abstract bool ValidateUser( string portalAlias, string username, string password ); } }
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using DecodeHintType = com.google.zxing.DecodeHintType; using ReaderException = com.google.zxing.ReaderException; using ResultPoint = com.google.zxing.ResultPoint; using ResultPointCallback = com.google.zxing.ResultPointCallback; using Collections = com.google.zxing.common.Collections; using Comparator = com.google.zxing.common.Comparator; using BitMatrix = com.google.zxing.common.BitMatrix; namespace com.google.zxing.microqrcode.detector { /// <summary> <p>This class attempts to find finder patterns in a QR Code. Finder patterns are the square /// markers at three corners of a QR Code.</p> /// /// <p>This class is thread-safe but not reentrant. Each thread must allocate its own object. /// /// </summary> /// <author> Sean Owen /// </author> /// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source /// </author> public class FinderPatternFinder { virtual protected internal BitMatrix Image { get { return image; } } virtual protected internal System.Collections.ArrayList PossibleCenters { get { return possibleCenters; } } private int[] CrossCheckStateCount { get { crossCheckStateCount[0] = 0; crossCheckStateCount[1] = 0; crossCheckStateCount[2] = 0; crossCheckStateCount[3] = 0; crossCheckStateCount[4] = 0; return crossCheckStateCount; } } private const int CENTER_QUORUM = 2; protected internal const int MIN_SKIP = 3; // 1 pixel/module times 3 modules/center protected internal const int MAX_MODULES = 57; // support up to version 10 for mobile clients private const int INTEGER_MATH_SHIFT = 8; //UPGRADE_NOTE: Final was removed from the declaration of 'image '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" private BitMatrix image; //UPGRADE_NOTE: Final was removed from the declaration of 'possibleCenters '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" private System.Collections.ArrayList possibleCenters; private bool hasSkipped; //UPGRADE_NOTE: Final was removed from the declaration of 'crossCheckStateCount '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" private int[] crossCheckStateCount; //UPGRADE_NOTE: Final was removed from the declaration of 'resultPointCallback '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" private ResultPointCallback resultPointCallback; /// <summary> <p>Creates a finder that will search the image for three finder patterns.</p> /// /// </summary> /// <param name="image">image to search /// </param> public FinderPatternFinder(BitMatrix image) : this(image, null) { } public FinderPatternFinder(BitMatrix image, ResultPointCallback resultPointCallback) { this.image = image; this.possibleCenters = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); this.crossCheckStateCount = new int[5]; this.resultPointCallback = resultPointCallback; } /// <summary> /// /// </summary> /// <param name="hints"></param> /// <returns></returns> internal virtual FinderPatternInfo find(System.Collections.Hashtable hints) { bool tryHarder = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER); int maxI = image.Height; int maxJ = image.Width; // We are looking for black/white/black/white/black modules in // 1:1:3:1:1 ratio; this tracks the number of such modules seen so far // Let's assume that the maximum version QR Code we support takes up 1/4 the height of the // image, and then account for the center being 3 modules in size. This gives the smallest // number of pixels the center could be, so skip this often. When trying harder, look for all // QR versions regardless of how dense they are. int iSkip = (3 * maxI) / (4 * MAX_MODULES); if (iSkip < MIN_SKIP || tryHarder) { iSkip = MIN_SKIP; } bool done = false; int[] stateCount = new int[5]; for (int i = iSkip - 1; i < maxI && !done; i += iSkip) { // Get a row of black/white values stateCount[0] = 0; stateCount[1] = 0; stateCount[2] = 0; stateCount[3] = 0; stateCount[4] = 0; int currentState = 0; for (int j = 0; j < maxJ; j++) { if (image.get_Renamed(j, i)) { // Black pixel if ((currentState & 1) == 1) { // Counting white pixels currentState++; } stateCount[currentState]++; } else { // White pixel if ((currentState & 1) == 0) { // Counting black pixels if (currentState == 4) { // A winner? if (foundPatternCross(stateCount)) { // Yes bool confirmed = handlePossibleCenter(stateCount, i, j); if (confirmed) { // Start examining every other line. Checking each line turned out to be too // expensive and didn't improve performance. iSkip = 2; if (hasSkipped) { done = haveMultiplyConfirmedCenters(); } else { int rowSkip = findRowSkip(); if (rowSkip > stateCount[2]) { // Skip rows between row of lower confirmed center // and top of presumed third confirmed center // but back up a bit to get a full chance of detecting // it, entire width of center of finder pattern // Skip by rowSkip, but back off by stateCount[2] (size of last center // of pattern we saw) to be conservative, and also back off by iSkip which // is about to be re-added i += rowSkip - stateCount[2] - iSkip; j = maxJ - 1; } } } else { // Advance to next black pixel do { j++; } while (j < maxJ && !image.get_Renamed(j, i)); j--; // back up to that last white pixel } // Clear state to start looking again currentState = 0; stateCount[0] = 0; stateCount[1] = 0; stateCount[2] = 0; stateCount[3] = 0; stateCount[4] = 0; } else { // No, shift counts back by two stateCount[0] = stateCount[2]; stateCount[1] = stateCount[3]; stateCount[2] = stateCount[4]; stateCount[3] = 1; stateCount[4] = 0; currentState = 3; } } else { stateCount[++currentState]++; } } else { // Counting white pixels stateCount[currentState]++; } } } if (foundPatternCross(stateCount)) { bool confirmed = handlePossibleCenter(stateCount, i, maxJ); if (confirmed) { iSkip = stateCount[0]; if (hasSkipped) { // Found a third one done = haveMultiplyConfirmedCenters(); } } } } FinderPattern[] patternInfo = selectBestPatterns(); //FinderPattern[] patternInfo = new FinderPattern[] { (FinderPattern) possibleCenters[0] }; ResultPoint.orderBestPatterns(patternInfo); return new FinderPatternInfo(patternInfo); } /// <summary> Given a count of black/white/black/white/black pixels just seen and an end position, /// figures the location of the center of this run. /// </summary> private static float centerFromEnd(int[] stateCount, int end) { //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" return (float)(end - stateCount[4] - stateCount[3]) - stateCount[2] / 2.0f; } /// <param name="stateCount">count of black/white/black/white/black pixels just read /// </param> /// <returns> true iff the proportions of the counts is close enough to the 1/1/3/1/1 ratios /// used by finder patterns to be considered a match /// </returns> protected internal static bool foundPatternCross(int[] stateCount) { int totalModuleSize = 0; for (int i = 0; i < 5; i++) { int count = stateCount[i]; if (count == 0) { return false; } totalModuleSize += count; } if (totalModuleSize < 7) { return false; } int moduleSize = (totalModuleSize << INTEGER_MATH_SHIFT) / 7; int maxVariance = moduleSize / 2; // Allow less than 50% variance from 1-1-3-1-1 proportions return System.Math.Abs(moduleSize - (stateCount[0] << INTEGER_MATH_SHIFT)) < maxVariance && System.Math.Abs(moduleSize - (stateCount[1] << INTEGER_MATH_SHIFT)) < maxVariance && System.Math.Abs(3 * moduleSize - (stateCount[2] << INTEGER_MATH_SHIFT)) < 3 * maxVariance && System.Math.Abs(moduleSize - (stateCount[3] << INTEGER_MATH_SHIFT)) < maxVariance && System.Math.Abs(moduleSize - (stateCount[4] << INTEGER_MATH_SHIFT)) < maxVariance; } /// <summary> <p>After a horizontal scan finds a potential finder pattern, this method /// "cross-checks" by scanning down vertically through the center of the possible /// finder pattern to see if the same proportion is detected.</p> /// /// </summary> /// <param name="startI">row where a finder pattern was detected /// </param> /// <param name="centerJ">center of the section that appears to cross a finder pattern /// </param> /// <param name="maxCount">maximum reasonable number of modules that should be /// observed in any reading state, based on the results of the horizontal scan /// </param> /// <returns> vertical center of finder pattern, or {@link Float#NaN} if not found /// </returns> private float crossCheckVertical(int startI, int centerJ, int maxCount, int originalStateCountTotal) { BitMatrix image = this.image; int maxI = image.Height; int[] stateCount = CrossCheckStateCount; // Start counting up from center int i = startI; while (i >= 0 && image.get_Renamed(centerJ, i)) { stateCount[2]++; i--; } if (i < 0) { return System.Single.NaN; } while (i >= 0 && !image.get_Renamed(centerJ, i) && stateCount[1] <= maxCount) { stateCount[1]++; i--; } // If already too many modules in this state or ran off the edge: if (i < 0 || stateCount[1] > maxCount) { return System.Single.NaN; } while (i >= 0 && image.get_Renamed(centerJ, i) && stateCount[0] <= maxCount) { stateCount[0]++; i--; } if (stateCount[0] > maxCount) { return System.Single.NaN; } // Now also count down from center i = startI + 1; while (i < maxI && image.get_Renamed(centerJ, i)) { stateCount[2]++; i++; } if (i == maxI) { return System.Single.NaN; } while (i < maxI && !image.get_Renamed(centerJ, i) && stateCount[3] < maxCount) { stateCount[3]++; i++; } if (i == maxI || stateCount[3] >= maxCount) { return System.Single.NaN; } while (i < maxI && image.get_Renamed(centerJ, i) && stateCount[4] < maxCount) { stateCount[4]++; i++; } if (stateCount[4] >= maxCount) { return System.Single.NaN; } // If we found a finder-pattern-like section, but its size is more than 40% different than // the original, assume it's a false positive int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; if (5 * System.Math.Abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) { return System.Single.NaN; } return foundPatternCross(stateCount) ? centerFromEnd(stateCount, i) : System.Single.NaN; } /// <summary> <p>Like {@link #crossCheckVertical(int, int, int, int)}, and in fact is basically identical, /// except it reads horizontally instead of vertically. This is used to cross-cross /// check a vertical cross check and locate the real center of the alignment pattern.</p> /// </summary> private float crossCheckHorizontal(int startJ, int centerI, int maxCount, int originalStateCountTotal) { BitMatrix image = this.image; int maxJ = image.Width; int[] stateCount = CrossCheckStateCount; int j = startJ; while (j >= 0 && image.get_Renamed(j, centerI)) { stateCount[2]++; j--; } if (j < 0) { return System.Single.NaN; } while (j >= 0 && !image.get_Renamed(j, centerI) && stateCount[1] <= maxCount) { stateCount[1]++; j--; } if (j < 0 || stateCount[1] > maxCount) { return System.Single.NaN; } while (j >= 0 && image.get_Renamed(j, centerI) && stateCount[0] <= maxCount) { stateCount[0]++; j--; } if (stateCount[0] > maxCount) { return System.Single.NaN; } j = startJ + 1; while (j < maxJ && image.get_Renamed(j, centerI)) { stateCount[2]++; j++; } if (j == maxJ) { return System.Single.NaN; } while (j < maxJ && !image.get_Renamed(j, centerI) && stateCount[3] < maxCount) { stateCount[3]++; j++; } if (j == maxJ || stateCount[3] >= maxCount) { return System.Single.NaN; } while (j < maxJ && image.get_Renamed(j, centerI) && stateCount[4] < maxCount) { stateCount[4]++; j++; } if (stateCount[4] >= maxCount) { return System.Single.NaN; } // If we found a finder-pattern-like section, but its size is significantly different than // the original, assume it's a false positive int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; if (5 * System.Math.Abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) { return System.Single.NaN; } return foundPatternCross(stateCount) ? centerFromEnd(stateCount, j) : System.Single.NaN; } /// <summary> <p>This is called when a horizontal scan finds a possible alignment pattern. It will /// cross check with a vertical scan, and if successful, will, ah, cross-cross-check /// with another horizontal scan. This is needed primarily to locate the real horizontal /// center of the pattern in cases of extreme skew.</p> /// /// <p>If that succeeds the finder pattern location is added to a list that tracks /// the number of times each location has been nearly-matched as a finder pattern. /// Each additional find is more evidence that the location is in fact a finder /// pattern center /// /// </summary> /// <param name="stateCount">reading state module counts from horizontal scan /// </param> /// <param name="i">row where finder pattern may be found /// </param> /// <param name="j">end of possible finder pattern in row /// </param> /// <returns> true if a finder pattern candidate was found this time /// </returns> protected internal virtual bool handlePossibleCenter(int[] stateCount, int i, int j) { int stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4]; float centerJ = centerFromEnd(stateCount, j); //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" float centerI = crossCheckVertical(i, (int)centerJ, stateCount[2], stateCountTotal); if (!System.Single.IsNaN(centerI)) { // Re-cross check //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" centerJ = crossCheckHorizontal((int)centerJ, (int)centerI, stateCount[2], stateCountTotal); if (!System.Single.IsNaN(centerJ)) { //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" float estimatedModuleSize = (float)stateCountTotal / 7.0f; bool found = false; int max = possibleCenters.Count; for (int index = 0; index < max; index++) { FinderPattern center = (FinderPattern)possibleCenters[index]; // Look for about the same center and module size: if (center.aboutEquals(estimatedModuleSize, centerI, centerJ)) { center.incrementCount(); found = true; break; } } if (!found) { ResultPoint point = new FinderPattern(centerJ, centerI, estimatedModuleSize); possibleCenters.Add(point); if (resultPointCallback != null) { resultPointCallback.foundPossibleResultPoint(point); } } return true; } } return false; } /// <returns> number of rows we could safely skip during scanning, based on the first /// two finder patterns that have been located. In some cases their position will /// allow us to infer that the third pattern must lie below a certain point farther /// down in the image. /// </returns> private int findRowSkip() { int max = possibleCenters.Count; if (max <= 1) { return 0; } FinderPattern firstConfirmedCenter = null; for (int i = 0; i < max; i++) { FinderPattern center = (FinderPattern)possibleCenters[i]; if (center.Count >= CENTER_QUORUM) { if (firstConfirmedCenter == null) { firstConfirmedCenter = center; } else { // We have two confirmed centers // How far down can we skip before resuming looking for the next // pattern? In the worst case, only the difference between the // difference in the x / y coordinates of the two centers. // This is the case where you find top left last. hasSkipped = true; //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" return (int)(System.Math.Abs(firstConfirmedCenter.X - center.X) - System.Math.Abs(firstConfirmedCenter.Y - center.Y)) / 2; } } } return 0; } /// <returns> true iff we have found at least 3 finder patterns that have been detected /// at least {@link #CENTER_QUORUM} times each, and, the estimated module size of the /// candidates is "pretty similar" /// </returns> private bool haveMultiplyConfirmedCenters() { int confirmedCount = 0; float totalModuleSize = 0.0f; int max = possibleCenters.Count; for (int i = 0; i < max; i++) { FinderPattern pattern = (FinderPattern)possibleCenters[i]; if (pattern.Count >= CENTER_QUORUM) { confirmedCount++; totalModuleSize += pattern.EstimatedModuleSize; } } if (confirmedCount < 3) { return false; } // OK, we have at least 3 confirmed centers, but, it's possible that one is a "false positive" // and that we need to keep looking. We detect this by asking if the estimated module sizes // vary too much. We arbitrarily say that when the total deviation from average exceeds // 5% of the total module size estimates, it's too much. //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" float average = totalModuleSize / (float)max; float totalDeviation = 0.0f; for (int i = 0; i < max; i++) { FinderPattern pattern = (FinderPattern)possibleCenters[i]; totalDeviation += System.Math.Abs(pattern.EstimatedModuleSize - average); } return totalDeviation <= 0.05f * totalModuleSize; } /// <returns> the 3 best {@link FinderPattern}s from our list of candidates. The "best" are /// those that have been detected at least {@link #CENTER_QUORUM} times, and whose module /// size differs from the average among those patterns the least /// </returns> /// <throws> ReaderException if 3 such finder patterns do not exist </throws> private FinderPattern[] selectBestPatterns() { int startSize = possibleCenters.Count; if (startSize < 3) { // Couldn't find enough finder patterns throw ReaderException.Instance; } // Filter outlier possibilities whose module size is too different if (startSize > 3) { // But we can only afford to do so if we have at least 4 possibilities to choose from float totalModuleSize = 0.0f; for (int i = 0; i < startSize; i++) { totalModuleSize += ((FinderPattern)possibleCenters[i]).EstimatedModuleSize; } //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" float average = totalModuleSize / (float)startSize; for (int i = 0; i < possibleCenters.Count && possibleCenters.Count > 3; i++) { FinderPattern pattern = (FinderPattern)possibleCenters[i]; if (System.Math.Abs(pattern.EstimatedModuleSize - average) > 0.2f * average) { possibleCenters.RemoveAt(i); i--; } } } if (possibleCenters.Count > 3) { // Throw away all but those first size candidate points we found. Collections.insertionSort(possibleCenters, new CenterComparator()); SupportClass.SetCapacity(possibleCenters, 3); } return new FinderPattern[] { (FinderPattern)possibleCenters[0], (FinderPattern)possibleCenters[1], (FinderPattern)possibleCenters[2] }; } /// <summary> <p>Orders by {@link FinderPattern#getCount()}, descending.</p></summary> private class CenterComparator : Comparator { public virtual int compare(System.Object center1, System.Object center2) { return ((FinderPattern)center2).Count - ((FinderPattern)center1).Count; } } } }
// 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 gagvc = Google.Ads.GoogleAds.V8.Common; using gagve = Google.Ads.GoogleAds.V8.Enums; using gagvr = Google.Ads.GoogleAds.V8.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V8.Services; namespace Google.Ads.GoogleAds.Tests.V8.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedAdGroupCriterionSimulationServiceClientTest { [Category("Autogenerated")][Test] public void GetAdGroupCriterionSimulationRequestObject() { moq::Mock<AdGroupCriterionSimulationService.AdGroupCriterionSimulationServiceClient> mockGrpcClient = new moq::Mock<AdGroupCriterionSimulationService.AdGroupCriterionSimulationServiceClient>(moq::MockBehavior.Strict); GetAdGroupCriterionSimulationRequest request = new GetAdGroupCriterionSimulationRequest { ResourceNameAsAdGroupCriterionSimulationName = gagvr::AdGroupCriterionSimulationName.FromCustomerAdGroupCriterionTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"), }; gagvr::AdGroupCriterionSimulation expectedResponse = new gagvr::AdGroupCriterionSimulation { ResourceNameAsAdGroupCriterionSimulationName = gagvr::AdGroupCriterionSimulationName.FromCustomerAdGroupCriterionTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"), Type = gagve::SimulationTypeEnum.Types.SimulationType.BidModifier, ModificationMethod = gagve::SimulationModificationMethodEnum.Types.SimulationModificationMethod.Default, CpcBidPointList = new gagvc::CpcBidSimulationPointList(), AdGroupId = -2072405675042603230L, CriterionId = 8584655242409302840L, StartDate = "start_date11b9dbea", EndDate = "end_date89dae890", PercentCpcBidPointList = new gagvc::PercentCpcBidSimulationPointList(), }; mockGrpcClient.Setup(x => x.GetAdGroupCriterionSimulation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AdGroupCriterionSimulationServiceClient client = new AdGroupCriterionSimulationServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupCriterionSimulation response = client.GetAdGroupCriterionSimulation(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAdGroupCriterionSimulationRequestObjectAsync() { moq::Mock<AdGroupCriterionSimulationService.AdGroupCriterionSimulationServiceClient> mockGrpcClient = new moq::Mock<AdGroupCriterionSimulationService.AdGroupCriterionSimulationServiceClient>(moq::MockBehavior.Strict); GetAdGroupCriterionSimulationRequest request = new GetAdGroupCriterionSimulationRequest { ResourceNameAsAdGroupCriterionSimulationName = gagvr::AdGroupCriterionSimulationName.FromCustomerAdGroupCriterionTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"), }; gagvr::AdGroupCriterionSimulation expectedResponse = new gagvr::AdGroupCriterionSimulation { ResourceNameAsAdGroupCriterionSimulationName = gagvr::AdGroupCriterionSimulationName.FromCustomerAdGroupCriterionTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"), Type = gagve::SimulationTypeEnum.Types.SimulationType.BidModifier, ModificationMethod = gagve::SimulationModificationMethodEnum.Types.SimulationModificationMethod.Default, CpcBidPointList = new gagvc::CpcBidSimulationPointList(), AdGroupId = -2072405675042603230L, CriterionId = 8584655242409302840L, StartDate = "start_date11b9dbea", EndDate = "end_date89dae890", PercentCpcBidPointList = new gagvc::PercentCpcBidSimulationPointList(), }; mockGrpcClient.Setup(x => x.GetAdGroupCriterionSimulationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AdGroupCriterionSimulation>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AdGroupCriterionSimulationServiceClient client = new AdGroupCriterionSimulationServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupCriterionSimulation responseCallSettings = await client.GetAdGroupCriterionSimulationAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::AdGroupCriterionSimulation responseCancellationToken = await client.GetAdGroupCriterionSimulationAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetAdGroupCriterionSimulation() { moq::Mock<AdGroupCriterionSimulationService.AdGroupCriterionSimulationServiceClient> mockGrpcClient = new moq::Mock<AdGroupCriterionSimulationService.AdGroupCriterionSimulationServiceClient>(moq::MockBehavior.Strict); GetAdGroupCriterionSimulationRequest request = new GetAdGroupCriterionSimulationRequest { ResourceNameAsAdGroupCriterionSimulationName = gagvr::AdGroupCriterionSimulationName.FromCustomerAdGroupCriterionTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"), }; gagvr::AdGroupCriterionSimulation expectedResponse = new gagvr::AdGroupCriterionSimulation { ResourceNameAsAdGroupCriterionSimulationName = gagvr::AdGroupCriterionSimulationName.FromCustomerAdGroupCriterionTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"), Type = gagve::SimulationTypeEnum.Types.SimulationType.BidModifier, ModificationMethod = gagve::SimulationModificationMethodEnum.Types.SimulationModificationMethod.Default, CpcBidPointList = new gagvc::CpcBidSimulationPointList(), AdGroupId = -2072405675042603230L, CriterionId = 8584655242409302840L, StartDate = "start_date11b9dbea", EndDate = "end_date89dae890", PercentCpcBidPointList = new gagvc::PercentCpcBidSimulationPointList(), }; mockGrpcClient.Setup(x => x.GetAdGroupCriterionSimulation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AdGroupCriterionSimulationServiceClient client = new AdGroupCriterionSimulationServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupCriterionSimulation response = client.GetAdGroupCriterionSimulation(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAdGroupCriterionSimulationAsync() { moq::Mock<AdGroupCriterionSimulationService.AdGroupCriterionSimulationServiceClient> mockGrpcClient = new moq::Mock<AdGroupCriterionSimulationService.AdGroupCriterionSimulationServiceClient>(moq::MockBehavior.Strict); GetAdGroupCriterionSimulationRequest request = new GetAdGroupCriterionSimulationRequest { ResourceNameAsAdGroupCriterionSimulationName = gagvr::AdGroupCriterionSimulationName.FromCustomerAdGroupCriterionTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"), }; gagvr::AdGroupCriterionSimulation expectedResponse = new gagvr::AdGroupCriterionSimulation { ResourceNameAsAdGroupCriterionSimulationName = gagvr::AdGroupCriterionSimulationName.FromCustomerAdGroupCriterionTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"), Type = gagve::SimulationTypeEnum.Types.SimulationType.BidModifier, ModificationMethod = gagve::SimulationModificationMethodEnum.Types.SimulationModificationMethod.Default, CpcBidPointList = new gagvc::CpcBidSimulationPointList(), AdGroupId = -2072405675042603230L, CriterionId = 8584655242409302840L, StartDate = "start_date11b9dbea", EndDate = "end_date89dae890", PercentCpcBidPointList = new gagvc::PercentCpcBidSimulationPointList(), }; mockGrpcClient.Setup(x => x.GetAdGroupCriterionSimulationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AdGroupCriterionSimulation>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AdGroupCriterionSimulationServiceClient client = new AdGroupCriterionSimulationServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupCriterionSimulation responseCallSettings = await client.GetAdGroupCriterionSimulationAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::AdGroupCriterionSimulation responseCancellationToken = await client.GetAdGroupCriterionSimulationAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetAdGroupCriterionSimulationResourceNames() { moq::Mock<AdGroupCriterionSimulationService.AdGroupCriterionSimulationServiceClient> mockGrpcClient = new moq::Mock<AdGroupCriterionSimulationService.AdGroupCriterionSimulationServiceClient>(moq::MockBehavior.Strict); GetAdGroupCriterionSimulationRequest request = new GetAdGroupCriterionSimulationRequest { ResourceNameAsAdGroupCriterionSimulationName = gagvr::AdGroupCriterionSimulationName.FromCustomerAdGroupCriterionTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"), }; gagvr::AdGroupCriterionSimulation expectedResponse = new gagvr::AdGroupCriterionSimulation { ResourceNameAsAdGroupCriterionSimulationName = gagvr::AdGroupCriterionSimulationName.FromCustomerAdGroupCriterionTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"), Type = gagve::SimulationTypeEnum.Types.SimulationType.BidModifier, ModificationMethod = gagve::SimulationModificationMethodEnum.Types.SimulationModificationMethod.Default, CpcBidPointList = new gagvc::CpcBidSimulationPointList(), AdGroupId = -2072405675042603230L, CriterionId = 8584655242409302840L, StartDate = "start_date11b9dbea", EndDate = "end_date89dae890", PercentCpcBidPointList = new gagvc::PercentCpcBidSimulationPointList(), }; mockGrpcClient.Setup(x => x.GetAdGroupCriterionSimulation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AdGroupCriterionSimulationServiceClient client = new AdGroupCriterionSimulationServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupCriterionSimulation response = client.GetAdGroupCriterionSimulation(request.ResourceNameAsAdGroupCriterionSimulationName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAdGroupCriterionSimulationResourceNamesAsync() { moq::Mock<AdGroupCriterionSimulationService.AdGroupCriterionSimulationServiceClient> mockGrpcClient = new moq::Mock<AdGroupCriterionSimulationService.AdGroupCriterionSimulationServiceClient>(moq::MockBehavior.Strict); GetAdGroupCriterionSimulationRequest request = new GetAdGroupCriterionSimulationRequest { ResourceNameAsAdGroupCriterionSimulationName = gagvr::AdGroupCriterionSimulationName.FromCustomerAdGroupCriterionTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"), }; gagvr::AdGroupCriterionSimulation expectedResponse = new gagvr::AdGroupCriterionSimulation { ResourceNameAsAdGroupCriterionSimulationName = gagvr::AdGroupCriterionSimulationName.FromCustomerAdGroupCriterionTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"), Type = gagve::SimulationTypeEnum.Types.SimulationType.BidModifier, ModificationMethod = gagve::SimulationModificationMethodEnum.Types.SimulationModificationMethod.Default, CpcBidPointList = new gagvc::CpcBidSimulationPointList(), AdGroupId = -2072405675042603230L, CriterionId = 8584655242409302840L, StartDate = "start_date11b9dbea", EndDate = "end_date89dae890", PercentCpcBidPointList = new gagvc::PercentCpcBidSimulationPointList(), }; mockGrpcClient.Setup(x => x.GetAdGroupCriterionSimulationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AdGroupCriterionSimulation>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AdGroupCriterionSimulationServiceClient client = new AdGroupCriterionSimulationServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupCriterionSimulation responseCallSettings = await client.GetAdGroupCriterionSimulationAsync(request.ResourceNameAsAdGroupCriterionSimulationName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::AdGroupCriterionSimulation responseCancellationToken = await client.GetAdGroupCriterionSimulationAsync(request.ResourceNameAsAdGroupCriterionSimulationName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
/* Copyright (c) 2012, Yahoo! Inc. All rights reserved. Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ // [AUTO_HEADER] namespace TakaoPreference { partial class PanelMisc { /// <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 Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Windows.Forms.Label u_labelTitle; System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PanelMisc)); this.u_beepCheckBox = new System.Windows.Forms.CheckBox(); this.u_beepPanel = new System.Windows.Forms.Panel(); this.u_soundListComboBox = new System.Windows.Forms.ComboBox(); this.u_testSoundButton = new System.Windows.Forms.Button(); this.u_radioCustomizedSound = new System.Windows.Forms.RadioButton(); this.u_radioDefaultSound = new System.Windows.Forms.RadioButton(); this.u_highlightColorLabel = new System.Windows.Forms.Label(); this.u_highlightColorComboBox = new System.Windows.Forms.ComboBox(); this.u_backgroundPatternCheckBox = new System.Windows.Forms.CheckBox(); this.u_colorDialog = new System.Windows.Forms.ColorDialog(); this.u_transparentStatusBarCheckBox = new System.Windows.Forms.CheckBox(); this.u_minimizeToSystemTrayCheckBox = new System.Windows.Forms.CheckBox(); this.u_chkKeyboardFormShouldFollowCursor = new System.Windows.Forms.CheckBox(); this.u_backgroundColorLabel = new System.Windows.Forms.Label(); this.u_backgroundColorComboBox = new System.Windows.Forms.ComboBox(); this.u_textColorLabel = new System.Windows.Forms.Label(); this.u_textColorComboBox = new System.Windows.Forms.ComboBox(); this.u_statusBarGroup = new System.Windows.Forms.GroupBox(); this.u_candidateWindowGroup = new System.Windows.Forms.GroupBox(); this.u_extraGroup = new System.Windows.Forms.GroupBox(); this.u_removePluginButton = new System.Windows.Forms.Button(); this.u_pluginLabel = new System.Windows.Forms.Label(); this.u_pluginComboBox = new System.Windows.Forms.ComboBox(); u_labelTitle = new System.Windows.Forms.Label(); this.u_beepPanel.SuspendLayout(); this.u_statusBarGroup.SuspendLayout(); this.u_candidateWindowGroup.SuspendLayout(); this.u_extraGroup.SuspendLayout(); this.SuspendLayout(); // // u_labelTitle // u_labelTitle.AccessibleDescription = null; u_labelTitle.AccessibleName = null; resources.ApplyResources(u_labelTitle, "u_labelTitle"); u_labelTitle.Font = null; u_labelTitle.Name = "u_labelTitle"; // // u_beepCheckBox // this.u_beepCheckBox.AccessibleDescription = null; this.u_beepCheckBox.AccessibleName = null; resources.ApplyResources(this.u_beepCheckBox, "u_beepCheckBox"); this.u_beepCheckBox.BackgroundImage = null; this.u_beepCheckBox.Font = null; this.u_beepCheckBox.Name = "u_beepCheckBox"; this.u_beepCheckBox.UseVisualStyleBackColor = true; this.u_beepCheckBox.CheckedChanged += new System.EventHandler(this.u_beepCheckBox_CheckedChanged); // // u_beepPanel // this.u_beepPanel.AccessibleDescription = null; this.u_beepPanel.AccessibleName = null; resources.ApplyResources(this.u_beepPanel, "u_beepPanel"); this.u_beepPanel.BackgroundImage = null; this.u_beepPanel.Controls.Add(this.u_soundListComboBox); this.u_beepPanel.Controls.Add(this.u_testSoundButton); this.u_beepPanel.Controls.Add(this.u_radioCustomizedSound); this.u_beepPanel.Controls.Add(this.u_radioDefaultSound); this.u_beepPanel.Font = null; this.u_beepPanel.Name = "u_beepPanel"; // // u_soundListComboBox // this.u_soundListComboBox.AccessibleDescription = null; this.u_soundListComboBox.AccessibleName = null; resources.ApplyResources(this.u_soundListComboBox, "u_soundListComboBox"); this.u_soundListComboBox.BackgroundImage = null; this.u_soundListComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.u_soundListComboBox.Font = null; this.u_soundListComboBox.FormattingEnabled = true; this.u_soundListComboBox.Name = "u_soundListComboBox"; this.u_soundListComboBox.SelectedIndexChanged += new System.EventHandler(this.u_soundListComboBox_SelectedIndexChanged); // // u_testSoundButton // this.u_testSoundButton.AccessibleDescription = null; this.u_testSoundButton.AccessibleName = null; resources.ApplyResources(this.u_testSoundButton, "u_testSoundButton"); this.u_testSoundButton.BackgroundImage = null; this.u_testSoundButton.Font = null; this.u_testSoundButton.Name = "u_testSoundButton"; this.u_testSoundButton.UseVisualStyleBackColor = true; this.u_testSoundButton.Click += new System.EventHandler(this.u_testSoundButton_Click); // // u_radioCustomizedSound // this.u_radioCustomizedSound.AccessibleDescription = null; this.u_radioCustomizedSound.AccessibleName = null; resources.ApplyResources(this.u_radioCustomizedSound, "u_radioCustomizedSound"); this.u_radioCustomizedSound.BackgroundImage = null; this.u_radioCustomizedSound.Font = null; this.u_radioCustomizedSound.Name = "u_radioCustomizedSound"; this.u_radioCustomizedSound.UseVisualStyleBackColor = true; this.u_radioCustomizedSound.CheckedChanged += new System.EventHandler(this.u_radioCustomizedSound_CheckedChanged); // // u_radioDefaultSound // this.u_radioDefaultSound.AccessibleDescription = null; this.u_radioDefaultSound.AccessibleName = null; resources.ApplyResources(this.u_radioDefaultSound, "u_radioDefaultSound"); this.u_radioDefaultSound.BackgroundImage = null; this.u_radioDefaultSound.Font = null; this.u_radioDefaultSound.Name = "u_radioDefaultSound"; this.u_radioDefaultSound.UseVisualStyleBackColor = true; this.u_radioDefaultSound.CheckedChanged += new System.EventHandler(this.u_radioDefaultSound_CheckedChanged); // // u_highlightColorLabel // this.u_highlightColorLabel.AccessibleDescription = null; this.u_highlightColorLabel.AccessibleName = null; resources.ApplyResources(this.u_highlightColorLabel, "u_highlightColorLabel"); this.u_highlightColorLabel.Font = null; this.u_highlightColorLabel.Name = "u_highlightColorLabel"; // // u_highlightColorComboBox // this.u_highlightColorComboBox.AccessibleDescription = null; this.u_highlightColorComboBox.AccessibleName = null; resources.ApplyResources(this.u_highlightColorComboBox, "u_highlightColorComboBox"); this.u_highlightColorComboBox.BackgroundImage = null; this.u_highlightColorComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.u_highlightColorComboBox.Font = null; this.u_highlightColorComboBox.FormattingEnabled = true; this.u_highlightColorComboBox.Items.AddRange(new object[] { resources.GetString("u_highlightColorComboBox.Items"), resources.GetString("u_highlightColorComboBox.Items1"), resources.GetString("u_highlightColorComboBox.Items2"), resources.GetString("u_highlightColorComboBox.Items3"), resources.GetString("u_highlightColorComboBox.Items4")}); this.u_highlightColorComboBox.Name = "u_highlightColorComboBox"; this.u_highlightColorComboBox.SelectedIndexChanged += new System.EventHandler(this.u_colorComboBox_SelectedIndexChanged); // // u_backgroundPatternCheckBox // this.u_backgroundPatternCheckBox.AccessibleDescription = null; this.u_backgroundPatternCheckBox.AccessibleName = null; resources.ApplyResources(this.u_backgroundPatternCheckBox, "u_backgroundPatternCheckBox"); this.u_backgroundPatternCheckBox.BackgroundImage = null; this.u_backgroundPatternCheckBox.Font = null; this.u_backgroundPatternCheckBox.Name = "u_backgroundPatternCheckBox"; this.u_backgroundPatternCheckBox.UseVisualStyleBackColor = true; this.u_backgroundPatternCheckBox.CheckedChanged += new System.EventHandler(this.u_backgroundPatternCheckBox_CheckedChanged); // // u_colorDialog // this.u_colorDialog.AnyColor = true; this.u_colorDialog.Color = System.Drawing.Color.Indigo; // // u_transparentStatusBarCheckBox // this.u_transparentStatusBarCheckBox.AccessibleDescription = null; this.u_transparentStatusBarCheckBox.AccessibleName = null; resources.ApplyResources(this.u_transparentStatusBarCheckBox, "u_transparentStatusBarCheckBox"); this.u_transparentStatusBarCheckBox.BackgroundImage = null; this.u_transparentStatusBarCheckBox.Font = null; this.u_transparentStatusBarCheckBox.Name = "u_transparentStatusBarCheckBox"; this.u_transparentStatusBarCheckBox.UseVisualStyleBackColor = true; this.u_transparentStatusBarCheckBox.CheckedChanged += new System.EventHandler(this.u_transparentStatusBarCheckBox_CheckedChanged); // // u_minimizeToSystemTrayCheckBox // this.u_minimizeToSystemTrayCheckBox.AccessibleDescription = null; this.u_minimizeToSystemTrayCheckBox.AccessibleName = null; resources.ApplyResources(this.u_minimizeToSystemTrayCheckBox, "u_minimizeToSystemTrayCheckBox"); this.u_minimizeToSystemTrayCheckBox.BackgroundImage = null; this.u_minimizeToSystemTrayCheckBox.Font = null; this.u_minimizeToSystemTrayCheckBox.Name = "u_minimizeToSystemTrayCheckBox"; this.u_minimizeToSystemTrayCheckBox.UseVisualStyleBackColor = true; this.u_minimizeToSystemTrayCheckBox.CheckedChanged += new System.EventHandler(this.u_minimizeToSystemTrayCheckBox_CheckedChanged); // // u_chkKeyboardFormShouldFollowCursor // this.u_chkKeyboardFormShouldFollowCursor.AccessibleDescription = null; this.u_chkKeyboardFormShouldFollowCursor.AccessibleName = null; resources.ApplyResources(this.u_chkKeyboardFormShouldFollowCursor, "u_chkKeyboardFormShouldFollowCursor"); this.u_chkKeyboardFormShouldFollowCursor.BackgroundImage = null; this.u_chkKeyboardFormShouldFollowCursor.Font = null; this.u_chkKeyboardFormShouldFollowCursor.Name = "u_chkKeyboardFormShouldFollowCursor"; this.u_chkKeyboardFormShouldFollowCursor.UseVisualStyleBackColor = true; this.u_chkKeyboardFormShouldFollowCursor.CheckedChanged += new System.EventHandler(this.u_chkKeyboardFormShouldFollowCursor_CheckedChanged); // // u_backgroundColorLabel // this.u_backgroundColorLabel.AccessibleDescription = null; this.u_backgroundColorLabel.AccessibleName = null; resources.ApplyResources(this.u_backgroundColorLabel, "u_backgroundColorLabel"); this.u_backgroundColorLabel.Font = null; this.u_backgroundColorLabel.Name = "u_backgroundColorLabel"; // // u_backgroundColorComboBox // this.u_backgroundColorComboBox.AccessibleDescription = null; this.u_backgroundColorComboBox.AccessibleName = null; resources.ApplyResources(this.u_backgroundColorComboBox, "u_backgroundColorComboBox"); this.u_backgroundColorComboBox.BackgroundImage = null; this.u_backgroundColorComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.u_backgroundColorComboBox.Font = null; this.u_backgroundColorComboBox.FormattingEnabled = true; this.u_backgroundColorComboBox.Items.AddRange(new object[] { resources.GetString("u_backgroundColorComboBox.Items"), resources.GetString("u_backgroundColorComboBox.Items1"), resources.GetString("u_backgroundColorComboBox.Items2")}); this.u_backgroundColorComboBox.Name = "u_backgroundColorComboBox"; this.u_backgroundColorComboBox.SelectedIndexChanged += new System.EventHandler(this.u_backgroundColorComboBox_SelectedIndexChanged); // // u_textColorLabel // this.u_textColorLabel.AccessibleDescription = null; this.u_textColorLabel.AccessibleName = null; resources.ApplyResources(this.u_textColorLabel, "u_textColorLabel"); this.u_textColorLabel.Font = null; this.u_textColorLabel.Name = "u_textColorLabel"; // // u_textColorComboBox // this.u_textColorComboBox.AccessibleDescription = null; this.u_textColorComboBox.AccessibleName = null; resources.ApplyResources(this.u_textColorComboBox, "u_textColorComboBox"); this.u_textColorComboBox.BackgroundImage = null; this.u_textColorComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.u_textColorComboBox.Font = null; this.u_textColorComboBox.FormattingEnabled = true; this.u_textColorComboBox.Items.AddRange(new object[] { resources.GetString("u_textColorComboBox.Items"), resources.GetString("u_textColorComboBox.Items1"), resources.GetString("u_textColorComboBox.Items2")}); this.u_textColorComboBox.Name = "u_textColorComboBox"; this.u_textColorComboBox.SelectedIndexChanged += new System.EventHandler(this.u_textColorComboBox_SelectedIndexChanged); // // u_statusBarGroup // this.u_statusBarGroup.AccessibleDescription = null; this.u_statusBarGroup.AccessibleName = null; resources.ApplyResources(this.u_statusBarGroup, "u_statusBarGroup"); this.u_statusBarGroup.BackgroundImage = null; this.u_statusBarGroup.Controls.Add(this.u_transparentStatusBarCheckBox); this.u_statusBarGroup.Controls.Add(this.u_minimizeToSystemTrayCheckBox); this.u_statusBarGroup.Font = null; this.u_statusBarGroup.Name = "u_statusBarGroup"; this.u_statusBarGroup.TabStop = false; // // u_candidateWindowGroup // this.u_candidateWindowGroup.AccessibleDescription = null; this.u_candidateWindowGroup.AccessibleName = null; resources.ApplyResources(this.u_candidateWindowGroup, "u_candidateWindowGroup"); this.u_candidateWindowGroup.BackgroundImage = null; this.u_candidateWindowGroup.Controls.Add(this.u_highlightColorLabel); this.u_candidateWindowGroup.Controls.Add(this.u_highlightColorComboBox); this.u_candidateWindowGroup.Controls.Add(this.u_textColorLabel); this.u_candidateWindowGroup.Controls.Add(this.u_backgroundPatternCheckBox); this.u_candidateWindowGroup.Controls.Add(this.u_textColorComboBox); this.u_candidateWindowGroup.Controls.Add(this.u_backgroundColorComboBox); this.u_candidateWindowGroup.Controls.Add(this.u_backgroundColorLabel); this.u_candidateWindowGroup.Font = null; this.u_candidateWindowGroup.Name = "u_candidateWindowGroup"; this.u_candidateWindowGroup.TabStop = false; // // u_extraGroup // this.u_extraGroup.AccessibleDescription = null; this.u_extraGroup.AccessibleName = null; resources.ApplyResources(this.u_extraGroup, "u_extraGroup"); this.u_extraGroup.BackgroundImage = null; this.u_extraGroup.Controls.Add(this.u_beepCheckBox); this.u_extraGroup.Controls.Add(this.u_beepPanel); this.u_extraGroup.Controls.Add(this.u_chkKeyboardFormShouldFollowCursor); this.u_extraGroup.Font = null; this.u_extraGroup.Name = "u_extraGroup"; this.u_extraGroup.TabStop = false; // // u_removePluginButton // this.u_removePluginButton.AccessibleDescription = null; this.u_removePluginButton.AccessibleName = null; resources.ApplyResources(this.u_removePluginButton, "u_removePluginButton"); this.u_removePluginButton.BackgroundImage = null; this.u_removePluginButton.Font = null; this.u_removePluginButton.Name = "u_removePluginButton"; this.u_removePluginButton.UseVisualStyleBackColor = true; this.u_removePluginButton.Click += new System.EventHandler(this.u_removePluginButton_Click); // // u_pluginLabel // this.u_pluginLabel.AccessibleDescription = null; this.u_pluginLabel.AccessibleName = null; resources.ApplyResources(this.u_pluginLabel, "u_pluginLabel"); this.u_pluginLabel.Font = null; this.u_pluginLabel.Name = "u_pluginLabel"; // // u_pluginComboBox // this.u_pluginComboBox.AccessibleDescription = null; this.u_pluginComboBox.AccessibleName = null; resources.ApplyResources(this.u_pluginComboBox, "u_pluginComboBox"); this.u_pluginComboBox.BackgroundImage = null; this.u_pluginComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.u_pluginComboBox.Font = null; this.u_pluginComboBox.FormattingEnabled = true; this.u_pluginComboBox.Name = "u_pluginComboBox"; this.u_pluginComboBox.SelectedIndexChanged += new System.EventHandler(this.u_pluginComboBox_SelectedIndexChanged); // // PanelMisc // this.AccessibleDescription = null; this.AccessibleName = null; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None; resources.ApplyResources(this, "$this"); this.BackgroundImage = null; this.Controls.Add(this.u_removePluginButton); this.Controls.Add(this.u_pluginLabel); this.Controls.Add(this.u_extraGroup); this.Controls.Add(this.u_pluginComboBox); this.Controls.Add(this.u_candidateWindowGroup); this.Controls.Add(this.u_statusBarGroup); this.Controls.Add(u_labelTitle); this.Font = null; this.Name = "PanelMisc"; this.u_beepPanel.ResumeLayout(false); this.u_beepPanel.PerformLayout(); this.u_statusBarGroup.ResumeLayout(false); this.u_statusBarGroup.PerformLayout(); this.u_candidateWindowGroup.ResumeLayout(false); this.u_candidateWindowGroup.PerformLayout(); this.u_extraGroup.ResumeLayout(false); this.u_extraGroup.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.CheckBox u_beepCheckBox; private System.Windows.Forms.Panel u_beepPanel; private System.Windows.Forms.RadioButton u_radioDefaultSound; private System.Windows.Forms.RadioButton u_radioCustomizedSound; private System.Windows.Forms.Button u_testSoundButton; private System.Windows.Forms.ComboBox u_soundListComboBox; private System.Windows.Forms.Label u_highlightColorLabel; private System.Windows.Forms.ComboBox u_highlightColorComboBox; private System.Windows.Forms.CheckBox u_backgroundPatternCheckBox; private System.Windows.Forms.ColorDialog u_colorDialog; private System.Windows.Forms.CheckBox u_transparentStatusBarCheckBox; private System.Windows.Forms.CheckBox u_minimizeToSystemTrayCheckBox; private System.Windows.Forms.CheckBox u_chkKeyboardFormShouldFollowCursor; private System.Windows.Forms.Label u_backgroundColorLabel; private System.Windows.Forms.ComboBox u_backgroundColorComboBox; private System.Windows.Forms.Label u_textColorLabel; private System.Windows.Forms.ComboBox u_textColorComboBox; private System.Windows.Forms.GroupBox u_statusBarGroup; private System.Windows.Forms.GroupBox u_candidateWindowGroup; private System.Windows.Forms.GroupBox u_extraGroup; private System.Windows.Forms.Label u_pluginLabel; private System.Windows.Forms.ComboBox u_pluginComboBox; private System.Windows.Forms.Button u_removePluginButton; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsHead { using Fixtures.Azure; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; /// <summary> /// Test Infrastructure for AutoRest /// </summary> public partial class AutoRestHeadTestService : ServiceClient<AutoRestHeadTestService>, IAutoRestHeadTestService, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IHttpSuccessOperations. /// </summary> public virtual IHttpSuccessOperations HttpSuccess { get; private set; } /// <summary> /// Initializes a new instance of the AutoRestHeadTestService class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestHeadTestService(params DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestHeadTestService class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestHeadTestService(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestHeadTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutoRestHeadTestService(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestHeadTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutoRestHeadTestService(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestHeadTestService class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestHeadTestService(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestHeadTestService class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestHeadTestService(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestHeadTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestHeadTestService(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestHeadTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestHeadTestService(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { HttpSuccess = new HttpSuccessOperations(this); BaseUri = new System.Uri("http://localhost"); AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
using System; using System.IO; using System.Runtime.InteropServices; namespace SDRSharp.Radio.PortAudio { public sealed unsafe class WaveFile : IDisposable { private static readonly float* _lutu8; private static readonly UnsafeBuffer _lutu8Buffer = UnsafeBuffer.Create(256, sizeof(float)); private static readonly float* _lut16; private static readonly UnsafeBuffer _lut16Buffer = UnsafeBuffer.Create(65536, sizeof(float)); private readonly Stream _stream; private bool _isPCM; private long _dataPos; private short _formatTag; private int _sampleRate; private int _avgBytesPerSec; private int _length; private short _blockAlign; private short _bitsPerSample; private UnsafeBuffer _tempBuffer; private byte[] _temp; private byte* _tempPtr; static WaveFile() { _lutu8 = (float*) _lutu8Buffer; const float scale8 = 1.0f / 127.0f; for (var i = 0; i < 256; i++) { _lutu8[i] = (i - 128) * scale8; } _lut16 = (float*) _lut16Buffer; const float scale16 = 1.0f / 32767.0f; for (var i = 0; i < 65536; i++) { _lut16[i] = (i - 32768) * scale16; } } ~WaveFile() { Dispose(); } public WaveFile(string fileName) { _stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); ReadHeader(); } public void Dispose() { Close(); GC.SuppressFinalize(this); } public void Close() { if (_stream != null) _stream.Close(); } private static string ReadChunk(BinaryReader reader) { var ch = new byte[4]; reader.Read(ch, 0, ch.Length); return System.Text.Encoding.ASCII.GetString(ch); } private void ReadHeader() { var reader = new BinaryReader(_stream); if (ReadChunk(reader) != "RIFF") throw new Exception("Invalid file format"); reader.ReadInt32(); // File length minus first 8 bytes of RIFF description, we don't use it if (ReadChunk(reader) != "WAVE") throw new Exception("Invalid file format"); if (ReadChunk(reader) != "fmt ") throw new Exception("Invalid file format"); int len = reader.ReadInt32(); if (len < 16) // bad format chunk length throw new Exception("Invalid file format"); _formatTag = reader.ReadInt16(); _isPCM = _formatTag == 1; var nChannels = reader.ReadInt16(); if (nChannels != 2) throw new Exception("Invalid file format"); _sampleRate = reader.ReadInt32(); _avgBytesPerSec = reader.ReadInt32(); _blockAlign = reader.ReadInt16(); _bitsPerSample = reader.ReadInt16(); // advance in the stream to skip the wave format block len -= 16; // minimum format size while (len > 0) { reader.ReadByte(); len--; } // assume the data chunk is aligned while (_stream.Position < _stream.Length && ReadChunk(reader) != "data") { len = reader.ReadInt32(); while (_stream.Position < _stream.Length && len > 0) { reader.ReadByte(); len--; } } if (_stream.Position >= _stream.Length) throw new Exception("Invalid file format"); _length = reader.ReadInt32(); _dataPos = _stream.Position; } public void Read(Complex* iqBuffer, int length) { if (_temp == null || _temp.Length != _blockAlign * length) { _temp = new byte[_blockAlign * length]; _tempBuffer = UnsafeBuffer.Create(_temp); _tempPtr = (byte*) _tempBuffer; } var pos = 0; var size = _tempBuffer.Length; while (pos < size) { int toget = size - pos; int got = _stream.Read(_temp, pos, toget); if (got < toget) _stream.Position = _dataPos; // loop if the file ends if (got <= 0) break; pos += got; } FillIQ(iqBuffer, length); } private void FillIQ(Complex* iqPtr, int length) { if (_isPCM) { if (_blockAlign == 6) { const float scale = 1.0f / 8388607.0f; var ptr = (Int24*) _tempPtr; for (var i = 0; i < length; i++) { iqPtr->Real = *ptr++ * scale; iqPtr->Imag = *ptr++ * scale; iqPtr++; } } else if (_blockAlign == 4) { var ptr = (Int16*) _tempPtr; for (var i = 0; i < length; i++) { iqPtr->Real = _lut16[*ptr++ + 32768]; iqPtr->Imag = _lut16[*ptr++ + 32768]; iqPtr++; } } else if (_blockAlign == 2) { var ptr = _tempPtr; for (var i = 0; i < length; i++) { iqPtr->Real = _lutu8[*ptr++]; iqPtr->Imag = _lutu8[*ptr++]; iqPtr++; } } } else { var ptr = (float*) _tempPtr; for (var i = 0; i < length; i++) { iqPtr->Real = *ptr++; iqPtr->Imag = *ptr++; iqPtr++; } } } public long Position { get { return _stream.Position - _dataPos; } set { _stream.Seek(value + _dataPos, SeekOrigin.Begin); } } public short FormatTag { get { return _formatTag; } } public int SampleRate { get { return _sampleRate; } } public int AvgBytesPerSec { get { return _avgBytesPerSec; } } public short BlockAlign { get { return _blockAlign; } } public short BitsPerSample { get { return _bitsPerSample; } } public int Length { get { return _length; } } } [StructLayout(LayoutKind.Sequential)] public struct Int24 { public byte C; public byte B; public sbyte A; public static implicit operator float (Int24 i) { return (i.C << 8 | i.B << 16 | i.A << 24) >> 8; } } }
// // Copyright (C) Microsoft. All rights reserved. // using Microsoft.PowerShell.Activities; using System.Management.Automation; using System.Activities; using System.Collections.Generic; using System.ComponentModel; namespace Microsoft.PowerShell.Utility.Activities { /// <summary> /// Activity to invoke the Microsoft.PowerShell.Utility\Send-MailMessage command in a Workflow. /// </summary> [System.CodeDom.Compiler.GeneratedCode("Microsoft.PowerShell.Activities.ActivityGenerator.GenerateFromName", "3.0")] public sealed class SendMailMessage : PSRemotingActivity { /// <summary> /// Gets the display name of the command invoked by this activity. /// </summary> public SendMailMessage() { this.DisplayName = "Send-MailMessage"; } /// <summary> /// Gets the fully qualified name of the command invoked by this activity. /// </summary> public override string PSCommandName { get { return "Microsoft.PowerShell.Utility\\Send-MailMessage"; } } // Arguments /// <summary> /// Provides access to the Attachments parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String[]> Attachments { get; set; } /// <summary> /// Provides access to the Bcc parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String[]> Bcc { get; set; } /// <summary> /// Provides access to the Body parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String> Body { get; set; } /// <summary> /// Provides access to the BodyAsHtml parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.SwitchParameter> BodyAsHtml { get; set; } /// <summary> /// Provides access to the Encoding parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Text.Encoding> Encoding { get; set; } /// <summary> /// Provides access to the Cc parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String[]> Cc { get; set; } /// <summary> /// Provides access to the DeliveryNotificationOption parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Net.Mail.DeliveryNotificationOptions> DeliveryNotificationOption { get; set; } /// <summary> /// Provides access to the From parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String> From { get; set; } /// <summary> /// Provides access to the SmtpServer parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String> SmtpServer { get; set; } /// <summary> /// Provides access to the Priority parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Net.Mail.MailPriority> Priority { get; set; } /// <summary> /// Provides access to the Subject parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String> Subject { get; set; } /// <summary> /// Provides access to the To parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String[]> To { get; set; } /// <summary> /// Provides access to the Credential parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.PSCredential> Credential { get; set; } /// <summary> /// Provides access to the UseSsl parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.SwitchParameter> UseSsl { get; set; } /// <summary> /// Provides access to the Port parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Int32> Port { get; set; } // Module defining this command // Optional custom code for this activity /// <summary> /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run. /// </summary> /// <param name="context">The NativeActivityContext for the currently running activity.</param> /// <returns>A populated instance of System.Management.Automation.PowerShell</returns> /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks> protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context) { System.Management.Automation.PowerShell invoker = global::System.Management.Automation.PowerShell.Create(); System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName); // Initialize the arguments if(Attachments.Expression != null) { targetCommand.AddParameter("Attachments", Attachments.Get(context)); } if(Bcc.Expression != null) { targetCommand.AddParameter("Bcc", Bcc.Get(context)); } if(Body.Expression != null) { targetCommand.AddParameter("Body", Body.Get(context)); } if(BodyAsHtml.Expression != null) { targetCommand.AddParameter("BodyAsHtml", BodyAsHtml.Get(context)); } if(Encoding.Expression != null) { targetCommand.AddParameter("Encoding", Encoding.Get(context)); } if(Cc.Expression != null) { targetCommand.AddParameter("Cc", Cc.Get(context)); } if(DeliveryNotificationOption.Expression != null) { targetCommand.AddParameter("DeliveryNotificationOption", DeliveryNotificationOption.Get(context)); } if(From.Expression != null) { targetCommand.AddParameter("From", From.Get(context)); } if(SmtpServer.Expression != null) { targetCommand.AddParameter("SmtpServer", SmtpServer.Get(context)); } if(Priority.Expression != null) { targetCommand.AddParameter("Priority", Priority.Get(context)); } if(Subject.Expression != null) { targetCommand.AddParameter("Subject", Subject.Get(context)); } if(To.Expression != null) { targetCommand.AddParameter("To", To.Get(context)); } if(Credential.Expression != null) { targetCommand.AddParameter("Credential", Credential.Get(context)); } if(UseSsl.Expression != null) { targetCommand.AddParameter("UseSsl", UseSsl.Get(context)); } if(Port.Expression != null) { targetCommand.AddParameter("Port", Port.Get(context)); } return new ActivityImplementationContext() { PowerShellInstance = invoker }; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Windows; using Arma3LauncherWPF.Config; using Arma3LauncherWPF.Core; using Arma3LauncherWPF.Extensions; using Arma3LauncherWPF.Logging; using GalaSoft.MvvmLight; using Settings = Arma3LauncherWPF.Config.Settings; namespace Arma3LauncherWPF.ViewModel { /// <summary> /// This class contains properties that the main View can data bind to. /// <para> /// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel. /// </para> /// <para> /// You can also use Blend to data bind with the tool's support. /// </para> /// <para> /// See http://www.galasoft.ch/mvvm /// </para> /// </summary> public class MainViewModel : ViewModelBase { private SettingsDto.Profile _currentProfile; internal readonly Settings _settings; private readonly ServerSettings _serverSettings; private readonly ILog _log; /// <summary> /// Initializes a new instance of the MainViewModel class. /// </summary> public MainViewModel() { _log = new Log(); _serverSettings = new ServerSettings(_log); _settings = new Settings(_log, _serverSettings); } public SettingsDto SettingsDto { get { return _settings.Instance; } } private List<SettingsDto.Profile> _profiles; public List<SettingsDto.Profile> Profiles { get { if (_profiles == null) { var result = new List<SettingsDto.Profile>(); result.AddRange(_settings.Instance.Profiles); result.AddRange(_serverSettings.AvailibleProfiles.Select(x => new SettingsDto.Profile() { Mods = x.Mods.Select(y => new SettingsDto.ModInfo() { ModName = y.Name }).ToList(), ProfileName = x.ProfileName, CanDelete = false, CanEdit = false, ServerAddress = x.ServerAddress }).ToList()); _profiles = result; } return _profiles; } } public SettingsDto.Profile CurrentProfile { get { if (_currentProfile == null) { _currentProfile = LoadCurrentProfile(); } return _currentProfile; } set { _currentProfile = value; _modsForProfile = null; RaisePropertyChanged("ModsForProfile"); RaisePropertyChanged("CurrentProfile"); } } private List<ModInfoAdv> _modsForProfile; public List<ModInfoAdv> ModsForProfile { get { if (_modsForProfile == null) { _modsForProfile = _settings.Instance.InstalledMods.Select(x => x.ModName) .Union(_serverSettings.AvailibleMods.Select(x => x.Name)) .Distinct(StringComparer.InvariantCultureIgnoreCase) .OrderBy(x => x) .Select( x => new ModInfoAdv(_settings, _serverSettings) { ModInfo = new SettingsDto.ModInfo() { ModName = x }, IsChecked = CurrentProfile.Mods.Any(y => y.ModName == x) }) .ToList(); } return _modsForProfile; } set { _modsForProfile = value; RaisePropertyChanged("ModsForProfile"); } } public void Save() { CurrentProfile.Mods.Clear(); CurrentProfile.Mods.AddRange(ModsForProfile.Where(x => x.IsChecked).Select(x => x.ModInfo).ToList()); _settings.Instance.DefaultProfileName = CurrentProfile.ProfileName; _settings.Save(); RaisePropertyChanged("Profiles"); CurrentProfile = LoadCurrentProfile(); RaisePropertyChanged(""); } public void AddProfile(string profileName) { if (!string.IsNullOrEmpty(profileName)) { var set = _settings.Instance; if (!string.IsNullOrEmpty(profileName)) { var def = new SettingsDto.Profile(profileName, true); def.CanEdit = true; set.DefaultProfileName = profileName; set.Profiles.Add(def); _profiles = null; RaisePropertyChanged("Profiles"); CurrentProfile = def; } } } private SettingsDto.Profile LoadCurrentProfile() { var profile = Profiles.FirstOrDefault(x => x.ProfileName == SettingsDto.DefaultProfileName); if (profile == null) { profile = _settings.Instance.Profiles.FirstOrDefault(); if (profile == null) AddProfile("Default"); profile = _settings.Instance.Profiles.FirstOrDefault(); } return profile; } public void DeleteCurrentProfile() { if (CurrentProfile != null && CurrentProfile.CanDelete) { _settings.Instance.Profiles.Remove(CurrentProfile); _profiles = null; RaisePropertyChanged("Profiles"); CurrentProfile = LoadCurrentProfile(); } } public bool AllNeededModsDownloaded() { return !ModsForProfile.Any(x => x.IsChecked && !x.Downloaded); } public void Start() { Save(); var args = string.Empty; var path = AppSettingsHelper.ArmaFilePath; var filename = Path.GetFileName(path); if (!string.IsNullOrEmpty(filename) && string.Compare(filename.ToLower(), "arma3battleye.exe".ToLower(), StringComparison.InvariantCultureIgnoreCase) == 0) args += " 0 1 "; args += " -mod="; args = CurrentProfile.Mods.Aggregate(args, (current, modInfo) => current + (modInfo.ModName + ";")); if (SettingsDto.NoSplashScreen) args += " -nosplash "; if (SettingsDto.EmptyDefaultWorld) args += " -world=empty "; if (SettingsDto.ShowScriptErrors) args += " -showScriptErrors "; if (SettingsDto.NoPauseOnTaskSwitch) args += " -noPause "; if (SettingsDto.SkipIntro) args += " -skipIntro "; if (SettingsDto.Windowed) args += " -window "; if (SettingsDto.MaxMemory) args += string.Format(" -maxMem={0} ", SettingsDto.MaxMemoryInt); if (SettingsDto.MaxVRAM) args += string.Format(" -maxVRAM={0} ", SettingsDto.MaxVRAMInt); if (SettingsDto.CPUCount) args += string.Format(" -cpuCount={0} ", SettingsDto.CPUCountInt); if (SettingsDto.ExtraThreads) args += string.Format(" -exThreads={0} ", SettingsDto.ExtraThreadsInt); _log.Info(string.Format("run with args {0}", args)); //MessageBox.Show(args); if (!string.IsNullOrEmpty(path)) Process.Start(new ProcessStartInfo() { FileName = path, Arguments = args }); } public async void DownloadMod(ModInfoAdv mod, Window owner) { var progress = new Progress(); progress.Owner = owner; progress.Title = string.Format(Properties.Resources.Download_Mod_Text_Template, mod.ModInfo.ModName); var modDownloader = new ModDownloader(_log, _serverSettings, progress); var modInstaller = new ModInstaller(_log, _settings, _serverSettings, modDownloader); var cancel = new CancelEventHandler((sender, args) => modDownloader.CancelDownload()); progress.Closing += cancel; progress.Show(); await modInstaller.InstallModAsync(mod.ModInfo.ModName); progress.Close(); _modsForProfile = null; RaisePropertyChanged("ModsForProfile"); } public void Refresh() { _settings.Refresh(); _modsForProfile = null; _profiles = null; _currentProfile = null; RaisePropertyChanged("SettingsDto"); RaisePropertyChanged("ModsForProfile"); RaisePropertyChanged("Profiles"); RaisePropertyChanged("CurrentProfile"); } public void UpdateMod(ModInfoAdv modInfoAdv, Window owner) { DownloadMod(modInfoAdv, owner); } public void RemoveMod(ModInfoAdv modInfoAdv) { var modDownloader = new ModDownloader(_log, _serverSettings, null); var modInstaller = new ModInstaller(_log, _settings, _serverSettings, modDownloader); var dpn = CurrentProfile.ProfileName; modInstaller.RemoveMod(modInfoAdv.ModInfo.ModName); _settings.Instance.DefaultProfileName = dpn; CurrentProfile = LoadCurrentProfile(); Refresh(); } public void DownloadAll(Window getWindow) { var mods = ModsForProfile.Where(x => x.CanDownload && !x.Downloaded); foreach (var modInfoAdv in mods) { DownloadMod(modInfoAdv, getWindow); } } public void UpdateAll(Window getWindow) { var mods = ModsForProfile.Where(x => x.CanUpdate); foreach (var modInfoAdv in mods) { UpdateMod(modInfoAdv, getWindow); } } public class ModInfoAdv : ViewModelBase { private readonly Settings _settings; private readonly ServerSettings _serverSettings; private bool _isChecked; public SettingsDto.ModInfo ModInfo { get; set; } public ModInfoAdv(Settings settings, ServerSettings serverSettings) { _settings = settings; _serverSettings = serverSettings; } public bool Downloaded { get { return _settings.Instance.InstalledMods.Any(x => x.ModName.EqualIgnoreCase(ModInfo.ModName)); } } public bool CanDownload { get { return !Downloaded && _serverSettings.CanDownloadMod(ModInfo.ModName); } } public bool CanUpdate { get { var modedate = Settings.GetModeDate(ModInfo.ModName).ToUniversalTime(); var diff = _serverSettings.DateOfMod(ModInfo.ModName).ToUniversalTime() - modedate; return _serverSettings.CanDownloadMod(ModInfo.ModName) && diff.Minutes > 0; } } public bool IsChecked { get { return _isChecked; } set { _isChecked = value; RaisePropertyChanged("IsChecked"); } } } public void StartConnect() { Save(); var args = string.Empty; var path = AppSettingsHelper.ArmaFilePath; var filename = Path.GetFileName(path); if (!string.IsNullOrEmpty(filename) && string.Compare(filename.ToLower(), "arma3battleye.exe".ToLower(), StringComparison.InvariantCultureIgnoreCase) == 0) args += " 0 1 "; args += " -mod="; args = CurrentProfile.Mods.Aggregate(args, (current, modInfo) => current + (modInfo.ModName + ";")); if (SettingsDto.NoSplashScreen) args += " -nosplash "; if (SettingsDto.EmptyDefaultWorld) args += " -world=empty "; if (SettingsDto.ShowScriptErrors) args += " -showScriptErrors "; if (SettingsDto.NoPauseOnTaskSwitch) args += " -noPause "; if (SettingsDto.SkipIntro) args += " -skipIntro "; if (SettingsDto.Windowed) args += " -window "; if (SettingsDto.MaxMemory) args += string.Format(" -maxMem={0} ", SettingsDto.MaxMemoryInt); if (SettingsDto.MaxVRAM) args += string.Format(" -maxVRAM={0} ", SettingsDto.MaxVRAMInt); if (SettingsDto.CPUCount) args += string.Format(" -cpuCount={0} ", SettingsDto.CPUCountInt); if (SettingsDto.ExtraThreads) args += string.Format(" -exThreads={0} ", SettingsDto.ExtraThreadsInt); if (CurrentProfile != null && CurrentProfile.ServerAddress != null) { var addr = CurrentProfile.ServerAddress; if (!string.IsNullOrEmpty(addr.IP)) { args += string.Format(" -connect={0} ", addr.IP); if (!string.IsNullOrEmpty(addr.Port)) args += string.Format(" -port={0} ", addr.Port); if (!string.IsNullOrEmpty(addr.Password)) args += string.Format(" -password={0} ", addr.Password); } } _log.Info(string.Format("connect with args {0}", args)); //MessageBox.Show(args); if (!string.IsNullOrEmpty(path)) Process.Start(new ProcessStartInfo() { FileName = path, Arguments = args }); } } }
using System; /// <summary> /// Array.Sort (T[]) /// </summary> public class ArraySort6 { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Sort a string array"); try { string[] s1 = new string[6]{"Jack", "Mary", "Mike", "Peter", "Tom", "Allin"}; string[] s2 = new string[]{"Allin", "Jack", "Mary", "Mike", "Peter", "Tom"}; Array.Sort<string>(s1); for (int i = 0; i < 6; i++) { if (s1[i] != s2[i]) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Sort an int32 array"); try { int length = TestLibrary.Generator.GetByte(-55); int[] i1 = new int[length]; int[] i2 = new int[length]; for (int i = 0; i < length; i++) { int value = TestLibrary.Generator.GetInt32(-55); i1[i] = value; i2[i] = value; } Array.Sort<int>(i1); for (int i = 0; i < length - 1; i++) //manually quich sort { for (int j = i + 1; j < length; j++) { if (i2[i] > i2[j]) { int temp = i2[i]; i2[i] = i2[j]; i2[j] = temp; } } } for (int i = 0; i < length; i++) { if (i1[i] != i2[i]) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Sort a char array "); try { int length = TestLibrary.Generator.GetInt16(-55); char[] c1 = new char[length]; char[] c2 = new char[length]; for (int i = 0; i < length; i++) { char value = TestLibrary.Generator.GetChar(-55); c1[i] = value; c2[i] = value; } Array.Sort<char>(c1); for (int i = 0; i < length - 1; i++) //manually quich sort { for (int j = i + 1; j < length; j++) { if (c2[i] > c2[j]) { char temp = c2[i]; c2[i] = c2[j]; c2[j] = temp; } } } for (int i = 0; i < length; i++) { if (c1[i] != c2[i]) { TestLibrary.TestFramework.LogError("005", "The result is not the value as expected"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Sort a string array including null reference "); try { string[] s1 = new string[6]{"Jack", "Mary", null, "Peter", "Tom", "Allin"}; string[] s2 = new string[]{null, "Allin", "Jack", "Mary", "Peter", "Tom"}; Array.Sort<string>(s1); for (int i = 0; i < 6; i++) { if (s1[i] != s2[i]) { TestLibrary.TestFramework.LogError("007", "The result is not the value as expected"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: Sort customized type array"); try { C[] c_array = new C[5]; C[] c_result = new C[5]; for (int i = 0; i < 5; i++) { int value = TestLibrary.Generator.GetInt32(-55); C c1 = new C(value); c_array.SetValue(c1, i); c_result.SetValue(c1, i); } //sort manually C temp; for (int j = 0; j < 4; j++) { for (int i = 0; i < 4; i++) { if (c_result[i].c > c_result[i + 1].c) { temp = c_result[i]; c_result[i] = c_result[i + 1]; c_result[i + 1] = temp; } } } Array.Sort<C>(c_array); for (int i = 0; i < 5; i++) { if (c_result[i].c != c_array[i].c) { TestLibrary.TestFramework.LogError("009", "The result is not the value as expected"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: The array is null "); try { string[] s1 = null; Array.Sort<string>(s1); TestLibrary.TestFramework.LogError("101", "The ArgumentNullException is not throw as expected "); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: One or more elements in array do not implement the IComparable interface"); try { A<int>[] i1 = new A<int>[5] { new A<int>(7), new A<int>(99), new A<int>(-23), new A<int>(0), new A<int>(345) }; Array.Sort<A<int>>(i1); TestLibrary.TestFramework.LogError("103", "The InvalidOperationException is not throw as expected "); retVal = false; } catch (InvalidOperationException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #endregion public static int Main() { ArraySort6 test = new ArraySort6(); TestLibrary.TestFramework.BeginTestCase("ArraySort6"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } class C : IComparable { protected int c_value; public C(int a) { this.c_value = a; } public int c { get { return c_value; } } #region IComparable Members public int CompareTo(object obj) { if (this.c_value <= ((C)obj).c) { return -1; } else { return 1; } } #endregion } class A<T> { protected T a_value; public A(T a) { this.a_value = a; } } }
using UnityEngine; using System.Collections; using System.Runtime.InteropServices; using System.Threading; using System.IO; public class UseRenderingPlugin : MonoBehaviour { int width = 1024; int height = 576; // int width = 1280; // int height = 7; public Texture2D tex; int startCount = 0; int awakeCount = 0; Camera movingCamera; Color[] blackTexture; //public GameObject sys; //private MainScript mainScript; Color[] correctSelectionIndicator; Color[] incorrectSelectionIndicator; [DllImport("UnityServerPlugin")] private static extern void SetTextureFromUnity(System.IntPtr texture); [DllImport("UnityServerPlugin")] private static extern void setLog(); [DllImport("UnityServerPlugin")] private static extern void endServer(); [DllImport("UnityServerPlugin")] private static extern void SetTimeFromUnity(float t); void Awake() { setLog(); //Texture2D ci = (Texture2D)Resources.Load("CorrectSelection", typeof(Texture2D)); //Texture2D ii = (Texture2D)Resources.Load("IncorrectSelection", typeof(Texture2D)); //correctSelectionIndicator = ci.GetPixels(); //incorrectSelectionIndicator = ii.GetPixels(); blackTexture = new Color[width * height]; for (int i = 0; i < width * height; i++) { blackTexture[i] = Color.black; } //sys = GameObject.Find("System"); //mainScript = sys.GetComponent<MainScript>(); ServerThread server = new ServerThread(); Thread st = new Thread(new ThreadStart(server.startServer)); st.Start(); Debug.Log("Started Server"); OSCPhaseSpaceThread oscPSClient = new OSCPhaseSpaceThread(); Thread oscPSt = new Thread(new ThreadStart(oscPSClient.startServer)); oscPSt.Start(); Debug.Log("Started OSC Client"); OSCThread oscClient = new OSCThread(); Thread osct = new Thread(new ThreadStart(oscClient.startServer)); osct.Start(); } public float posX = 512f; //Position the DrawTexture command while testing. public float posY = 512f; Texture2D ARSelectionTexture; //void Start(){ //Debug.Log ("Started."); IEnumerator Start() { ARSelectionTexture = Resources.Load("GUISelectionBox") as Texture2D; CreateTextureAndPassToPlugin(); yield return StartCoroutine("CallPluginAtEndOfFrames"); } void OnApplicationQuit() { PlayerPrefs.Save(); endServer(); } bool drawIndicator = false; float startTime; public void drawSelectionIndication() { drawIndicator = true; startTime = Time.time; // set start time for timer } private void CreateTextureAndPassToPlugin() { //movingCamera = GameObject.Find("MonoCamera").GetComponent<Camera>();//Camera.allCameras[2]; movingCamera = /*GameObject.Find("Camera").*/GetComponent<Camera>();//Camera.allCameras[2]; //**This is the stereo renderer //movingCamera.rect = new Rect(0,0,width,height); // Create a texture tex = new Texture2D(width, height, TextureFormat.RGB24, false); // Set point filtering just so we can see the pixels clearly //tex.filterMode = FilterMode.Point; // Call Apply() so it's actually uploaded to the GPU tex.Apply(); // Set texture onto our matrial //renderer.material.mainTexture = tex; // Pass texture pointer to the plugin SetTextureFromUnity(tex.GetNativeTexturePtr()); } int num = 0; private IEnumerator CallPluginAtEndOfFrames() { while (true) { if (Input.GetKeyDown("f")) { Screen.fullScreen = !Screen.fullScreen; } if (Input.GetKeyDown("q")) { endServer(); Application.Quit(); } // Wait until all frame rendering is done yield return new WaitForEndOfFrame(); //Need to call this (or any plugin function) to keep calling native rendering events //SetTextureFromUnity(tex.GetNativeTexturePtr()); //movingCamera.Render(); RenderTexture.active = movingCamera.targetTexture; // if(mainScript.getExperimentInterface() == (int)MainScript.interfaces.Pointing) // { //tex.SetPixels(blackTexture); // } // else // { tex.ReadPixels(new Rect(0, 224 /*192*/, width, height), 0, 0); //tex.Apply (); //} // if(drawIndicator) // { // // tex.SetPixels (0,0,64,64,correctSelectionIndicator); // } //tex.ReadPixels(new Rect(0, 0, width, height), 0, 0); RenderTexture.active = null; //if(drawIndicator) // // RenderTexture.active = movingCamera.targetTexture; // //RenderTexture.active = cam3.targetTexture; //Set my RenderTexture active so DrawTexture will draw to it. // GL.PushMatrix (); //Saves both projection and modelview matrices to the matrix stack. // GL.LoadPixelMatrix (0, 1024, 1024, 0); //Setup a matrix for pixel-correct rendering. // //Draw my stampTexture on my RenderTexture positioned by posX and posY. // Graphics.DrawTexture (new Rect (posX - ARSelectionTexture.width / 2, (1024 - posY) - ARSelectionTexture.height / 2, ARSelectionTexture.width, ARSelectionTexture.height), ARSelectionTexture); // GL.PopMatrix (); //Restores both projection and modelview matrices off the top of the matrix stack. // RenderTexture.active = null; //De-activate my RenderTexture. tex.Apply(); //var bytes = tex.EncodeToPNG(); //File.WriteAllBytes(Application.dataPath + "/../SavedScreen" + num + ".png", bytes); //num++; GL.IssuePluginEvent(0); } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. // ORIGINAL HEADER FROM C++ source which was converted to C# by Ted Dunsford 2/24/2010 /****************************************************************************** * $Id: hfafield.cpp, v 1.21 2006/05/07 04:04:03 fwarmerdam Exp $ * * Project: Erdas Imagine (.img) Translator * Purpose: Implementation of the HFAField class for managing information * about one field in a HFA dictionary type. Managed by HFAType. * Author: Frank Warmerdam, warmerdam@pobox.com * ****************************************************************************** * Copyright (c) 1999, Intergraph Corporation * * 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. ****************************************************************************** * * $Log: hfafield.cpp, v $ * Revision 1.21 2006/05/07 04:04:03 fwarmerdam * fixed serious multithreading issue with ExtractInstValue (bug 1132) * * Revision 1.20 2006/04/03 04:33:16 fwarmerdam * Report basedata type. Support reading basedata as a 1D array. Fix * bug in basedata reading ... wasn't skippig 2 byte code before data. * * Revision 1.19 2006/03/29 14:24:04 fwarmerdam * added preliminary nodata support (readonly) * * Revision 1.18 2005/10/02 15:14:48 fwarmerdam * fixed size for <8bit basedata items * * Revision 1.17 2005/09/28 19:38:07 fwarmerdam * Added partial support for inline defined types. * * Revision 1.16 2005/05/10 00:56:17 fwarmerdam * fixed bug with setting entries in an array (with count setting) * * Revision 1.15 2004/02/13 15:58:11 warmerda * Fixed serious bug with GetInstBytes() for BASEDATA * fields with * a count of zero. Such as the Excluded field of most stats nodes! * * Revision 1.14 2003/12/08 19:09:34 warmerda * implemented DumpInstValue and GetInstBytes for basedata * * Revision 1.13 2003/05/21 15:35:05 warmerda * cleanup type conversion warnings * * Revision 1.12 2003/04/22 19:40:36 warmerda * fixed email address * * Revision 1.11 2001/07/18 04:51:57 warmerda * added CPL_CVSID * * Revision 1.10 2000/12/29 16:37:32 warmerda * Use GUInt32 for all file offsets * * Revision 1.9 2000/10/12 19:30:32 warmerda * substantially improved write support * * Revision 1.8 2000/09/29 21:42:38 warmerda * preliminary write support implemented * * Revision 1.7 1999/06/01 13:07:59 warmerda * added speed up for indexing into fixes size object arrays * * Revision 1.6 1999/02/15 19:06:18 warmerda * Disable warning on field offsets for Intergraph delivery * * Revision 1.5 1999/01/28 18:28:28 warmerda * minor simplification of code * * Revision 1.4 1999/01/28 18:03:07 warmerda * Fixed some byte swapping problems, and problems with accessing data from * the file that isn't on a word boundary. * * Revision 1.3 1999/01/22 19:23:11 warmerda * Fixed bug with offset into arrays of structures. * * Revision 1.2 1999/01/22 17:37:59 warmerda * Fixed up support for variable sizes, and arrays of variable sized objects * * Revision 1.1 1999/01/04 22:52:10 warmerda * New */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace DotSpatial.Data { /// <summary> /// HfaField /// </summary> public class HfaField { #region Fields private const int MaxEntryReport = 16; #endregion #region Properties /// <summary> /// Gets or sets the enum names. This is normally null unless this is an enum. /// </summary> public List<string> EnumNames { get; set; } /// <summary> /// Gets or sets the field name. /// </summary> public string FieldName { get; set; } /// <summary> /// Gets or sets the short integer item count. /// </summary> public int ItemCount { get; set; } /// <summary> /// Gets or sets the item object type. /// </summary> public HfaType ItemObjectType { get; set; } /// <summary> /// Gets or sets the item object type string. If ItemType == 'o'. /// </summary> public string ItemObjectTypeString { get; set; } /// <summary> /// Gets or sets 1|2|4|e|... /// </summary> public char ItemType { get; set; } /// <summary> /// Gets or sets the short integer number of bytes. /// </summary> public int NumBytes { get; set; } /// <summary> /// Gets or sets '\0', '*' or 'p' /// </summary> public char Pointer { get; set; } #endregion #region Methods /// <summary> /// Completes the defenition of this type based on the existing dictionary. /// </summary> /// <param name="dictionary">Dictionary used for completion.</param> public void CompleteDefn(HfaDictionary dictionary) { // Get a reference to the type object if we have a type name // for this field (not a build in). if (ItemObjectTypeString != null) { ItemObjectType = dictionary[ItemObjectTypeString]; } // Figure out the size if (Pointer == 'p') { NumBytes = -1; } else if (ItemObjectType != null) { ItemObjectType.CompleteDefn(dictionary); if (ItemObjectType.NumBytes == -1) { NumBytes = -1; } else { NumBytes = (short)(ItemObjectType.NumBytes * ItemCount); } if (Pointer == '*' && NumBytes != -1) NumBytes += 8; } else { NumBytes = (short)(HfaDictionary.GetItemSize(ItemType) * ItemCount); } } /// <summary> /// This writes formatted content for this field to the specified IO stream. /// </summary> /// <param name="stream">The stream to write to.</param> public void Dump(Stream stream) { string typename; StreamWriter sw = new StreamWriter(stream); switch (ItemType) { case '1': typename = "U1"; break; case '2': typename = "U2"; break; case '4': typename = "U4"; break; case 'c': typename = "UChar"; break; case 'C': typename = "CHAR"; break; case 'e': typename = "ENUM"; break; case 's': typename = "USHORT"; break; case 'S': typename = "SHORT"; break; case 't': typename = "TIME"; break; case 'l': typename = "ULONG"; break; case 'L': typename = "LONG"; break; case 'f': typename = "FLOAT"; break; case 'd': typename = "DOUBLE"; break; case 'm': typename = "COMPLEX"; break; case 'M': typename = "DCOMPLEX"; break; case 'b': typename = "BASEDATA"; break; case 'o': typename = ItemObjectTypeString; break; case 'x': typename = "InlineType"; break; default: typename = "Unknowm"; break; } string tc = (Pointer == 'p' || Pointer == '*') ? Pointer.ToString() : " "; string name = typename.PadRight(19); sw.WriteLine(" " + name + " " + tc + " " + FieldName + "[" + ItemCount + "];"); if (EnumNames == null || EnumNames.Count <= 0) return; for (int i = 0; i < EnumNames.Count; i++) { sw.Write(" " + EnumNames[i] + "=" + i); } } /// <summary> /// Dumps the fields value. /// </summary> /// <param name="fpOut">The output stream.</param> /// <param name="data">The data.</param> /// <param name="dataOffset">The offset to start from.</param> /// <param name="dataSize">The data size.</param> /// <param name="prefix">The prefix.</param> public void DumpInstValue(Stream fpOut, byte[] data, long dataOffset, int dataSize, string prefix) { StreamWriter sw = new StreamWriter(fpOut); int extraOffset; int nEntries = GetInstCount(data, dataOffset); // Special case for arrays of characters or uchars which are printed as a string if ((ItemType == 'c' || ItemType == 'C') && nEntries > 0) { object value; if (ExtractInstValue(null, 0, data, dataOffset, dataSize, 's', out value, out extraOffset)) { sw.WriteLine(prefix + FieldName + " = '" + (string)value + "'"); } else { sw.WriteLine(prefix + FieldName + " = (access failed)"); } } for (int iEntry = 0; iEntry < Math.Min(MaxEntryReport, nEntries); iEntry++) { sw.Write(prefix + FieldName); if (nEntries > 1) sw.Write("[" + iEntry + "]"); sw.Write(" = "); object value; switch (ItemType) { case 'f': case 'd': if (ExtractInstValue(null, iEntry, data, dataOffset, dataSize, 'd', out value, out extraOffset)) { sw.Write(value + "\n"); } else { sw.Write("(access failed)\n"); } break; case 'b': int nRows = Hfa.ReadInt32(data, dataOffset + 8); int nColumns = Hfa.ReadInt32(data, dataOffset + 12); HfaEpt type = Hfa.ReadType(data, dataOffset + 16); sw.Write(nRows + "x" + nColumns + " basedata of type " + type); break; case 'e': if (ExtractInstValue(null, iEntry, data, dataOffset, dataSize, 's', out value, out extraOffset)) { sw.Write((string)value); } else { sw.Write("(accessfailed)"); } break; case 'o': if (!ExtractInstValue(null, iEntry, data, dataOffset, dataSize, 'p', out value, out extraOffset)) { sw.WriteLine("(access failed)"); } else { // the pointer logic here is death! Originally the pointer address was used // nByteOffset = ((GByte*) val) - pabyData; // This doesn't work in a safe context. sw.Write("\n"); string szLongFieldName = prefix; if (prefix.Length > 256) szLongFieldName = prefix.Substring(0, 256); ItemObjectType.DumpInstValue(fpOut, data, dataOffset + extraOffset, dataSize - extraOffset, szLongFieldName); } break; default: if (ExtractInstValue(null, iEntry, data, dataOffset, dataSize, 'i', out value, out extraOffset)) { sw.WriteLine(value); } else { sw.WriteLine("(access failed)\n"); } break; } } if (nEntries > MaxEntryReport) { sw.Write(prefix + " ... remaining instances omitted ...\n"); } if (nEntries == 0) { sw.Write(prefix + FieldName + " = (no values)\n"); } } /// <summary> /// Extracts the value. /// </summary> /// <param name="pszField">The psz field.</param> /// <param name="nIndexValue">The index value.</param> /// <param name="data">The data.</param> /// <param name="dataOffset">The offset to start from.</param> /// <param name="nDataSize">The data size.</param> /// <param name="reqType">The req type.</param> /// <param name="pReqReturn">The req return.</param> /// <param name="extraOffset">This is used in the case of 'object' pointers where the indexed object is further in the data block.</param> /// <returns>True, if the value could be extracted.</returns> /// <exception cref="HfaInvalidCountException">Occurs if the count is less than zero for the header of a block of base data</exception> public bool ExtractInstValue(string pszField, int nIndexValue, byte[] data, long dataOffset, int nDataSize, char reqType, out object pReqReturn, out int extraOffset) { extraOffset = 0; pReqReturn = null; string returnString = null; int nIntRet = 0; double dfDoubleRet = 0.0; // it doesn't appear like remove this line will have side effects. // int size = GetInstBytes(data, dataOffset); int nInstItemCount = GetInstCount(data, dataOffset); byte[] rawData = null; long offset = dataOffset; // Check the index value is valid. Eventually this will have to account for variable fields. if (nIndexValue < 0 || nIndexValue >= nInstItemCount) return false; // if this field contains a pointer then we will adjust the data offset relative to it. if (Pointer != '\0') { long nOffset = Hfa.ReadUInt32(data, dataOffset + 4); if (nOffset != (uint)(dataOffset + 8)) { // It seems there was originally an exception that would have gone here. // Original exception would have been pszFieldname.pszField points at nOffset, not nDataOffset +8 as expected. } offset += 8; dataOffset += 8; nDataSize -= 8; } // pointers to chara or uchar arrays are read as strings and then handled as a special case. if ((ItemType == 'c' || ItemType == 'C') && reqType == 's') { // Ok, nasty, the original code simply "pointed" to the byte data at this point and cast the pointer. // We probably need to cycle through until we reach the null character. List<char> chars = new List<char>(); while ((char)data[offset] != '\0') { chars.Add((char)data[offset]); offset++; dataOffset++; } pReqReturn = new string(chars.ToArray()); } switch (ItemType) { case 'c': case 'C': nIntRet = data[dataOffset + nIndexValue]; dfDoubleRet = nIntRet; break; case 'e': case 's': { int nNumber = Hfa.ReadUInt16(data, dataOffset + (nIndexValue * 2)); nIntRet = nNumber; dfDoubleRet = nIntRet; if (ItemType == 'e' && nIntRet >= 0 && nIntRet < EnumNames.Count) { returnString = EnumNames[nIntRet]; } } break; case 'S': { short nNumber = Hfa.ReadInt16(data, dataOffset + (nIndexValue * 2)); nIntRet = nNumber; dfDoubleRet = nNumber; } break; case 't': case 'l': { long nNumber = Hfa.ReadUInt32(data, dataOffset + (nIndexValue * 2)); nIntRet = (int)nNumber; dfDoubleRet = nNumber; } break; case 'L': { int nNumber = Hfa.ReadInt32(data, dataOffset + (nIndexValue * 2)); nIntRet = nNumber; dfDoubleRet = nNumber; } break; case 'f': { float fNumber = Hfa.ReadSingle(data, dataOffset + (nIndexValue * 4)); dfDoubleRet = fNumber; nIntRet = Convert.ToInt32(fNumber); } break; case 'd': { dfDoubleRet = Hfa.ReadDouble(data, dataOffset + (nInstItemCount * 8)); nIntRet = Convert.ToInt32(dfDoubleRet); } break; case 'b': { // BASE DATA int nRows = Hfa.ReadInt32(data, dataOffset); int nColumns = Hfa.ReadInt32(data, dataOffset + 4); if (nIndexValue < 0 || nIndexValue >= nRows * nColumns) return false; HfaEpt type = (HfaEpt)Hfa.ReadUInt16(data, dataOffset + 8); // Ignore the 2 byte objecttype value dataOffset += 12; if (nRows < 0 || nColumns < 0) throw new HfaInvalidCountException(nRows, nColumns); switch (type) { case HfaEpt.U8: dfDoubleRet = data[dataOffset + nIndexValue]; nIntRet = data[offset + nIndexValue]; break; case HfaEpt.S16: short tShort = Hfa.ReadInt16(data, dataOffset + (nIndexValue * 2)); dfDoubleRet = tShort; nIntRet = tShort; break; case HfaEpt.U16: int tUShort = Hfa.ReadUInt16(data, dataOffset + (nIndexValue * 2)); dfDoubleRet = tUShort; nIntRet = tUShort; break; case HfaEpt.Single: float tSingle = Hfa.ReadSingle(data, dataOffset + (nIndexValue * 4)); dfDoubleRet = tSingle; nIntRet = Convert.ToInt32(tSingle); break; case HfaEpt.Double: dfDoubleRet = Hfa.ReadDouble(data, dataOffset + (nIndexValue * 8)); nIntRet = Convert.ToInt32(dfDoubleRet); break; default: pReqReturn = null; return false; } } break; case 'o': if (ItemObjectType != null) { if (ItemObjectType.NumBytes > 0) { extraOffset = ItemObjectType.NumBytes * nIndexValue; } else { for (int iIndexCounter = 0; iIndexCounter < nIndexValue; iIndexCounter++) { extraOffset += ItemObjectType.GetInstBytes(data, dataOffset + extraOffset); } } int len = ItemObjectType.GetInstBytes(data, dataOffset + extraOffset); rawData = new byte[len]; Array.Copy(data, dataOffset + extraOffset, rawData, 0, len); if (!string.IsNullOrEmpty(pszField)) { return ItemObjectType.ExtractInstValue(pszField, rawData, 0, rawData.Length, reqType, out pReqReturn); } } break; default: return false; } // Handle appropriate representations switch (reqType) { case 's': { if (returnString == null) { returnString = nIntRet.ToString(); } pReqReturn = returnString; return true; } case 'd': pReqReturn = dfDoubleRet; return true; case 'i': pReqReturn = nIntRet; return true; case 'p': pReqReturn = rawData; return true; default: return false; } } /// <summary> /// Scans through the array and estimates the byte size of the field in this case. /// </summary> /// <param name="data">The data.</param> /// <param name="dataOffset">The data offset.</param> /// <returns>The byte size of the field.</returns> public int GetInstBytes(byte[] data, long dataOffset) { int nCount; int nInstBytes = 0; long offset = dataOffset; // Hard sized fields just return their constant size if (NumBytes > -1) return NumBytes; // Pointers have a 4 byte integer count and a 4 byte uint offset if (Pointer != '\0') { nCount = Hfa.ReadInt32(data, offset); offset += 8; nInstBytes += 8; } else { // Anything other than a pointer only can have one item. nCount = 1; } if (ItemType == 'b' && nCount != 0) { // BASEDATA int nRows = Hfa.ReadInt32(data, offset); offset += 4; int nColumns = Hfa.ReadInt32(data, offset); offset += 4; HfaEpt baseItemType = (HfaEpt)Hfa.ReadInt16(data, offset); nInstBytes += 12; nInstBytes += ((baseItemType.GetBitCount() + 7) / 8) * nRows * nColumns; } else if (ItemObjectType == null) { nInstBytes += nCount * HfaDictionary.GetItemSize(ItemType); } else { for (int i = 0; i < nCount; i++) { nInstBytes += ItemObjectType.GetInstBytes(data, offset + nInstBytes); } } return nInstBytes; } /// <summary> /// Gets the count for a particular instance of a field. This will normally be /// the built in value, but for variable fields, this is extracted from the /// data itself. /// </summary> /// <param name="data">The data.</param> /// <param name="dataOffset">The data offset.</param> /// <returns>The count for a particular instance of a field.</returns> public int GetInstCount(byte[] data, long dataOffset) { if (Pointer == '\0') { return ItemCount; } if (ItemType == 'b') { int numRows = Hfa.ReadInt32(data, dataOffset + 8); int numColumns = Hfa.ReadInt32(data, dataOffset + 12); return numRows * numColumns; } return Hfa.ReadInt32(data, dataOffset); } /// <summary> /// Parses the input string into a valid HfaField, or returns null /// if one could not be created. /// </summary> /// <param name="input">The input string.</param> /// <returns>The parsed string, or null if the field could not be created.</returns> public string Initialize(string input) { int length = input.Length; int start = 0; // Read the number if (!input.Contains(":")) return null; ItemCount = short.Parse(input.ExtractTo(ref start, ":")); // is this a pointer? if (input[start] == 'p' || input[start] == '*') { start += 1; Pointer = input[start]; } // Get the general type start += 1; if (start == length) return null; ItemType = input[start]; if (!"124cCesStlLfdmMbox".Contains(ItemType.ToString())) { throw new HfaFieldTypeException(ItemType); } // If this is an object, we extract the type of the object if (ItemType == 'o') { ItemObjectTypeString = input.ExtractTo(ref start, ","); } // If this is an inline object, we need to skip past the // definition, and then extract the object class name. // we ignore the actual definition, so if the object type isn't // already defined, things will not work properly. See the // file lceugr250)00)pct.aus for an example of inline defs. if (ItemType == 'x' && input[start] == '{') { int braceDepth = 1; start += 1; // Skip past the definition in braces while (braceDepth > 0 && start < input.Length) { if (input[start] == '{') braceDepth++; if (input[start] == '}') braceDepth--; start++; } ItemType = 'o'; ItemObjectTypeString = input.ExtractTo(ref start, ","); } // If this is an enumeration, we have to extract all the values. if (ItemType == 'e') { if (!input.Contains(":")) return null; int enumCount = int.Parse(input.ExtractTo(ref start, ":")); if (EnumNames == null) EnumNames = new List<string>(); for (int ienum = 0; ienum < enumCount; ienum++) { EnumNames.Add(input.ExtractTo(ref start, ",")); } } // Extract the field name FieldName = input.ExtractTo(ref start, ","); // Return whatever is left in the string, which should be a new field. return input.Substring(start, input.Length - start); } /// <summary> /// Sets the value. /// </summary> /// <param name="sField">The field.</param> /// <param name="indexValue">The index value.</param> /// <param name="data">The data.</param> /// <param name="dataOffset">The data offset.</param> /// <param name="dataSize">The data size.</param> /// <param name="reqType">The req type.</param> /// <param name="value">The value.</param> /// <exception cref="HfaPointerInsertNotSupportedException">Attempting to insert a pointer is not supported.</exception> /// <exception cref="HfaEnumerationNotFoundException">Occurs if the specified value is not a valid member of the enumeration for this field.</exception> public void SetInstValue(string sField, int indexValue, byte[] data, long dataOffset, int dataSize, char reqType, object value) { // If this field contains a pointer, then we wil adjust the data offset relative to it. // This updates the offset info, but doesn't change the first four bytes. if (Pointer != '\0') { int nCount; if (NumBytes > -1) { nCount = ItemCount; } else if (reqType == 's' && (ItemType == 'c' || ItemType == 'C')) { // Either a string or a character array nCount = 0; IEnumerable<char> strVal = value as IEnumerable<char>; if (strVal != null) nCount = strVal.Count() + 1; } else { nCount = indexValue + 1; } uint nOffset = (uint)nCount; Array.Copy(Hfa.LittleEndian(nOffset), 0, data, dataOffset + 4, 4); dataOffset += 8; dataSize -= 8; } // Pointers to char or uchar arrays requested as strings are handled as a special case if ((ItemType == 'c' || ItemType == 'C') && reqType == 's') { int nBytesToCopy = NumBytes; var strVal = (value as IEnumerable<char>)?.ToArray(); if (strVal != null) nBytesToCopy = strVal.Length; if (NumBytes == -1 && strVal != null) nBytesToCopy = strVal.Length; // Force a blank erase to remove previous characters byte[] blank = new byte[nBytesToCopy]; Array.Copy(blank, 0, data, dataOffset, nBytesToCopy); if (strVal != null) { ASCIIEncoding ascii = new ASCIIEncoding(); string str = new string(strVal); byte[] charData = ascii.GetBytes(str); Array.Copy(charData, 0, data, dataOffset, charData.Length); } return; } // Translate the passed type into different representations int nIntValue; double dfDoubleValue; if (reqType == 's') { nIntValue = int.Parse((string)value); dfDoubleValue = double.Parse((string)value); } else if (reqType == 'd') { dfDoubleValue = (double)value; nIntValue = Convert.ToInt32((double)value); } else if (reqType == 'i') { dfDoubleValue = Convert.ToDouble((int)value); nIntValue = (int)value; } else if (reqType == 'p') { throw new HfaPointerInsertNotSupportedException(); } else { return; } // Handle by type switch (ItemType) { case 'c': // Char64 case 'C': // Char128 if (reqType == 's') { // handled earlier as special case, } else { data[dataOffset + nIntValue] = (byte)nIntValue; } break; case 'e': // enums are stored as ushort case 's': // little s = ushort type if (ItemType == 'e' && reqType == 's') { nIntValue = EnumNames.IndexOf((string)value); if (nIntValue == -1) { throw new HfaEnumerationNotFoundException((string)value); } } // Each enumeration is stored as a 2-bit unsigned short entry. ushort num = (ushort)nIntValue; Array.Copy(Hfa.LittleEndian(num), 0, data, dataOffset + (2 * indexValue), 2); break; case 'S': // signed short Array.Copy(Hfa.LittleEndian((short)nIntValue), 0, data, dataOffset + (indexValue * 2), 2); break; case 't': case 'l': Array.Copy(Hfa.LittleEndian((uint)nIntValue), 0, data, dataOffset + (indexValue * 4), 4); break; case 'L': // Int32 Array.Copy(Hfa.LittleEndian(nIntValue), 0, data, dataOffset + (indexValue * 4), 4); break; case 'f': // Float (32 bit) float dfNumber = Convert.ToSingle(dfDoubleValue); Array.Copy(Hfa.LittleEndian(dfNumber), 0, data, dataOffset + (indexValue * 4), 4); break; case 'd': // Double (float 64) Array.Copy(Hfa.LittleEndian(dfDoubleValue), 0, data, dataOffset + (8 * indexValue), 8); break; case 'o': // object if (ItemObjectType == null) break; int nExtraOffset = 0; if (ItemObjectType.NumBytes > 0) { nExtraOffset = ItemObjectType.NumBytes * indexValue; } else { for (int iIndexCounter = 0; iIndexCounter < indexValue; iIndexCounter++) { nExtraOffset += ItemObjectType.GetInstBytes(data, dataOffset + nExtraOffset); } } if (!string.IsNullOrEmpty(sField)) { ItemObjectType.SetInstValue(sField, data, dataOffset + nExtraOffset, dataSize - nExtraOffset, reqType, value); } break; default: throw new ArgumentException(); } } #endregion } }
//#define COSMOSDEBUG using System; using Cosmos.Core; using Cosmos.Core.IOGroup; namespace Cosmos.HAL.Drivers { /// <summary> /// VBEDriver class. Used to directly write registers values to the port. /// </summary> public class VBEDriver { private static readonly VBEIOGroup IO = Core.Global.BaseIOGroups.VBE; protected ManagedMemoryBlock lastbuffer; /// <summary> /// Register index. /// <para> /// Avilable indexs: /// <list type="bullet"> /// <item>DisplayID.</item> /// <item>DisplayXResolution.</item> /// <item>DisplayYResolution.</item> /// <item>DisplayBPP.</item> /// <item>DisplayEnable.</item> /// <item>DisplayBankMode.</item> /// <item>DisplayVirtualWidth.</item> /// <item>DisplayVirtualHeight.</item> /// <item>DisplayXOffset.</item> /// <item>DisplayYOffset.</item> /// </list> /// </para> /// </summary> private enum RegisterIndex { DisplayID = 0x00, DisplayXResolution, DisplayYResolution, DisplayBPP, DisplayEnable, DisplayBankMode, DisplayVirtualWidth, DisplayVirtualHeight, DisplayXOffset, DisplayYOffset }; /// <summary> /// Enable values. /// <para> /// Avilable values: /// <list type="bullet"> /// <item>Disabled.</item> /// <item>Enabled.</item> /// <item>UseLinearFrameBuffer.</item> /// <item>NoClearMemory.</item> /// </list> /// </para> /// </summary> [Flags] private enum EnableValues { Disabled = 0x00, Enabled, UseLinearFrameBuffer = 0x40, NoClearMemory = 0x80, }; /// <summary> /// Create new instance of the <see cref="VBEDriver"/> class. /// </summary> /// <param name="xres">X resolution.</param> /// <param name="yres">Y resolution.</param> /// <param name="bpp">BPP (color depth).</param> public VBEDriver(ushort xres, ushort yres, ushort bpp) { PCIDevice videocard; if (VBE.IsAvailable()) //VBE VESA Enabled Mulitboot Parsing { Global.mDebugger.SendInternal($"Creating VBE VESA driver with Mode {xres}*{yres}@{bpp}"); IO.LinearFrameBuffer = new MemoryBlock(VBE.getLfbOffset(), (uint)xres * yres * (uint)(bpp / 8)); lastbuffer = new ManagedMemoryBlock((uint)xres * yres * (uint)(bpp / 8)); } else if (ISAModeAvailable()) //Bochs Graphics Adaptor ISA Mode { Global.mDebugger.SendInternal($"Creating VBE BGA driver with Mode {xres}*{yres}@{bpp}."); IO.LinearFrameBuffer = new MemoryBlock(0xE0000000, 1920 * 1200 * 4); lastbuffer = new ManagedMemoryBlock(1920 * 1200 * 4); VBESet(xres, yres, bpp); } else if (((videocard = HAL.PCI.GetDevice(VendorID.VirtualBox, DeviceID.VBVGA)) != null) || //VirtualBox Video Adapter PCI Mode ((videocard = HAL.PCI.GetDevice(VendorID.Bochs, DeviceID.BGA)) != null)) // Bochs Graphics Adaptor PCI Mode { Global.mDebugger.SendInternal($"Creating VBE BGA driver with Mode {xres}*{yres}@{bpp}. Framebuffer address=" + videocard.BAR0); IO.LinearFrameBuffer = new MemoryBlock(videocard.BAR0, 1920 * 1200 * 4); lastbuffer = new ManagedMemoryBlock(1920 * 1200 * 4); VBESet(xres, yres, bpp); } else { throw new Exception("No supported VBE device found."); } } /// <summary> /// Write value to VBE index. /// </summary> /// <param name="index">Register index.</param> /// <param name="value">Value.</param> private static void VBEWrite(RegisterIndex index, ushort value) { IO.VbeIndex.Word = (ushort)index; IO.VbeData.Word = value; } private static ushort VBERead(RegisterIndex index) { IO.VbeIndex.Word = (ushort)index; return IO.VbeData.Word; } public static bool ISAModeAvailable() { //This code wont work as long as Bochs uses BGA ISA, since it wont discover it in PCI #if false return HAL.PCI.GetDevice(VendorID.Bochs, DeviceID.BGA) != null; #endif return VBERead(RegisterIndex.DisplayID) == 0xB0C5; } /// <summary> /// Disable display. /// </summary> public void DisableDisplay() { Global.mDebugger.SendInternal($"Disabling VBE display"); VBEWrite(RegisterIndex.DisplayEnable, (ushort)EnableValues.Disabled); } /// <summary> /// Set X resolution. /// </summary> /// <param name="xres">X resolution.</param> private void SetXResolution(ushort xres) { Global.mDebugger.SendInternal($"VBE Setting X resolution to {xres}"); VBEWrite(RegisterIndex.DisplayXResolution, xres); } /// <summary> /// Set Y resolution. /// </summary> /// <param name="yres">Y resolution.</param> private void SetYResolution(ushort yres) { Global.mDebugger.SendInternal($"VBE Setting Y resolution to {yres}"); VBEWrite(RegisterIndex.DisplayYResolution, yres); } /// <summary> /// Set BPP. /// </summary> /// <param name="bpp">BPP (color depth).</param> private void SetDisplayBPP(ushort bpp) { Global.mDebugger.SendInternal($"VBE Setting BPP to {bpp}"); VBEWrite(RegisterIndex.DisplayBPP, bpp); } /// <summary> /// Enable display. /// </summary> private void EnableDisplay(EnableValues EnableFlags) { //Global.mDebugger.SendInternal($"VBE Enabling display with EnableFlags (ushort){EnableFlags}"); VBEWrite(RegisterIndex.DisplayEnable, (ushort)EnableFlags); } /// <summary> /// Set VBE values. /// </summary> /// <param name="xres">X resolution.</param> /// <param name="yres">Y resolution.</param> /// <param name="bpp">BPP (color depth).</param> public void VBESet(ushort xres, ushort yres, ushort bpp, bool clear = false) { DisableDisplay(); SetXResolution(xres); SetYResolution(yres); SetDisplayBPP(bpp); if (clear) { EnableDisplay(EnableValues.Enabled | EnableValues.UseLinearFrameBuffer); } else { /* * Re-enable the Display with LinearFrameBuffer and without clearing video memory of previous value * (this permits to change Mode without losing the previous datas) */ EnableDisplay(EnableValues.Enabled | EnableValues.UseLinearFrameBuffer | EnableValues.NoClearMemory); } } /// <summary> /// Set VRAM. /// </summary> /// <param name="index">Index to set.</param> /// <param name="value">Value to set.</param> public void SetVRAM(uint index, byte value) { lastbuffer[index] = value; } /// <summary> /// Set VRAM. /// </summary> /// <param name="index">Index to set.</param> /// <param name="value">Value to set.</param> public void SetVRAM(uint index, ushort value) { lastbuffer[index] = (byte)((value >> 8) & 0xFF); lastbuffer[index + 1] = (byte)((value >> 0) & 0xFF); } /// <summary> /// Set VRAM. /// </summary> /// <param name="index">Index to set.</param> /// <param name="value">Value to set.</param> public void SetVRAM(uint index, uint value) { lastbuffer[index] = (byte)((value >> 24) & 0xFF); lastbuffer[index + 1] = (byte)((value >> 16) & 0xFF); lastbuffer[index + 2] = (byte)((value >> 8) & 0xFF); lastbuffer[index + 3] = (byte)((value >> 0) & 0xFF); } /// <summary> /// Get VRAM. /// </summary> /// <param name="index">Index to get.</param> /// <returns>byte value.</returns> public uint GetVRAM(uint index) { int pixel = (lastbuffer[index + 3] << 24) | (lastbuffer[index + 2] << 16) | (lastbuffer[index + 1] << 8) | lastbuffer[index]; return (uint)pixel; } /// <summary> /// Clear VRAM. /// </summary> /// <param name="value">Value of fill with.</param> public void ClearVRAM(uint value) { lastbuffer.Fill(value); } /// <summary> /// Clear VRAM. /// </summary> /// <param name="aStart">A start.</param> /// <param name="aCount">A count.</param> /// <param name="value">A volum.</param> public void ClearVRAM(int aStart, int aCount, int value) { lastbuffer.Fill(aStart, aCount, value); } /// <summary> /// Copy VRAM. /// </summary> /// <param name="aStart">A start.</param> /// <param name="aData">A data.</param> /// <param name="aIndex">A index.</param> /// <param name="aCount">A count.</param> public void CopyVRAM(int aStart, int[] aData, int aIndex, int aCount) { lastbuffer.Copy(aStart, aData, aIndex, aCount); } /// <summary> /// Copy VRAM. /// </summary> /// <param name="aStart">A start.</param> /// <param name="aData">A data.</param> /// <param name="aIndex">A index.</param> /// <param name="aCount">A count.</param> public void CopyVRAM(int aStart, byte[] aData, int aIndex, int aCount) { lastbuffer.Copy(aStart, aData, aIndex, aCount); } /// <summary> /// Swap back buffer to video memory /// </summary> public void Swap() { IO.LinearFrameBuffer.Copy(lastbuffer); } } }
using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Controls.Embedding; using Avalonia.Input; using Avalonia.Input.Raw; using Avalonia.Input.TextInput; using Avalonia.Web.Blazor.Interop; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Web; using Microsoft.JSInterop; using SkiaSharp; namespace Avalonia.Web.Blazor { public partial class AvaloniaView : ITextInputMethodImpl { private readonly RazorViewTopLevelImpl _topLevelImpl; private EmbeddableControlRoot _topLevel; // Interop private SKHtmlCanvasInterop _interop = null!; private SizeWatcherInterop _sizeWatcher = null!; private DpiWatcherInterop _dpiWatcher = null!; private SKHtmlCanvasInterop.GLInfo? _jsGlInfo = null!; private InputHelperInterop _inputHelper = null!; private ElementReference _htmlCanvas; private ElementReference _inputElement; private double _dpi; private SKSize _canvasSize; private GRContext? _context; private GRGlInterface? _glInterface; private const SKColorType ColorType = SKColorType.Rgba8888; private bool _initialised; [Inject] private IJSRuntime Js { get; set; } = null!; public AvaloniaView() { _topLevelImpl = new RazorViewTopLevelImpl(this); _topLevel = new EmbeddableControlRoot(_topLevelImpl); if (Application.Current.ApplicationLifetime is ISingleViewApplicationLifetime lifetime) { _topLevel.Content = lifetime.MainView; } } private void OnTouchStart(TouchEventArgs e) { foreach (var touch in e.ChangedTouches) { _topLevelImpl.RawTouchEvent(RawPointerEventType.TouchBegin, new Point(touch.ClientX, touch.ClientY), GetModifiers(e), touch.Identifier); } } private void OnTouchEnd(TouchEventArgs e) { foreach (var touch in e.ChangedTouches) { _topLevelImpl.RawTouchEvent(RawPointerEventType.TouchEnd, new Point(touch.ClientX, touch.ClientY), GetModifiers(e), touch.Identifier); } } private void OnTouchCancel(TouchEventArgs e) { foreach (var touch in e.ChangedTouches) { _topLevelImpl.RawTouchEvent(RawPointerEventType.TouchCancel, new Point(touch.ClientX, touch.ClientY), GetModifiers(e), touch.Identifier); } } private void OnTouchMove(TouchEventArgs e) { foreach (var touch in e.ChangedTouches) { _topLevelImpl.RawTouchEvent(RawPointerEventType.TouchUpdate, new Point(touch.ClientX, touch.ClientY), GetModifiers(e), touch.Identifier); } } private void OnMouseMove(MouseEventArgs e) { _topLevelImpl.RawMouseEvent(RawPointerEventType.Move, new Point(e.ClientX, e.ClientY), GetModifiers(e)); } private void OnMouseUp(MouseEventArgs e) { RawPointerEventType type = default; switch (e.Button) { case 0: type = RawPointerEventType.LeftButtonUp; break; case 1: type = RawPointerEventType.MiddleButtonUp; break; case 2: type = RawPointerEventType.RightButtonUp; break; } _topLevelImpl.RawMouseEvent(type, new Point(e.ClientX, e.ClientY), GetModifiers(e)); } private void OnMouseDown(MouseEventArgs e) { RawPointerEventType type = default; switch (e.Button) { case 0: type = RawPointerEventType.LeftButtonDown; break; case 1: type = RawPointerEventType.MiddleButtonDown; break; case 2: type = RawPointerEventType.RightButtonDown; break; } _topLevelImpl.RawMouseEvent(type, new Point(e.ClientX, e.ClientY), GetModifiers(e)); } private void OnWheel(WheelEventArgs e) { _topLevelImpl.RawMouseWheelEvent(new Point(e.ClientX, e.ClientY), new Vector(-(e.DeltaX / 50), -(e.DeltaY / 50)), GetModifiers(e)); } private static RawInputModifiers GetModifiers(WheelEventArgs e) { var modifiers = RawInputModifiers.None; if (e.CtrlKey) modifiers |= RawInputModifiers.Control; if (e.AltKey) modifiers |= RawInputModifiers.Alt; if (e.ShiftKey) modifiers |= RawInputModifiers.Shift; if (e.MetaKey) modifiers |= RawInputModifiers.Meta; if ((e.Buttons & 1L) == 1) modifiers |= RawInputModifiers.LeftMouseButton; if ((e.Buttons & 2L) == 2) modifiers |= RawInputModifiers.RightMouseButton; if ((e.Buttons & 4L) == 4) modifiers |= RawInputModifiers.MiddleMouseButton; return modifiers; } private static RawInputModifiers GetModifiers(TouchEventArgs e) { var modifiers = RawInputModifiers.None; if (e.CtrlKey) modifiers |= RawInputModifiers.Control; if (e.AltKey) modifiers |= RawInputModifiers.Alt; if (e.ShiftKey) modifiers |= RawInputModifiers.Shift; if (e.MetaKey) modifiers |= RawInputModifiers.Meta; return modifiers; } private static RawInputModifiers GetModifiers(MouseEventArgs e) { var modifiers = RawInputModifiers.None; if (e.CtrlKey) modifiers |= RawInputModifiers.Control; if (e.AltKey) modifiers |= RawInputModifiers.Alt; if (e.ShiftKey) modifiers |= RawInputModifiers.Shift; if (e.MetaKey) modifiers |= RawInputModifiers.Meta; if ((e.Buttons & 1L) == 1) modifiers |= RawInputModifiers.LeftMouseButton; if ((e.Buttons & 2L) == 2) modifiers |= RawInputModifiers.RightMouseButton; if ((e.Buttons & 4L) == 4) modifiers |= RawInputModifiers.MiddleMouseButton; return modifiers; } private static RawInputModifiers GetModifiers(KeyboardEventArgs e) { var modifiers = RawInputModifiers.None; if (e.CtrlKey) modifiers |= RawInputModifiers.Control; if (e.AltKey) modifiers |= RawInputModifiers.Alt; if (e.ShiftKey) modifiers |= RawInputModifiers.Shift; if (e.MetaKey) modifiers |= RawInputModifiers.Meta; return modifiers; } private void OnKeyDown(KeyboardEventArgs e) { _topLevelImpl.RawKeyboardEvent(RawKeyEventType.KeyDown, e.Key, GetModifiers(e)); } private void OnKeyUp(KeyboardEventArgs e) { _topLevelImpl.RawKeyboardEvent(RawKeyEventType.KeyUp, e.Code, GetModifiers(e)); } private void OnInput(ChangeEventArgs e) { if (e.Value != null) { var inputData = e.Value.ToString(); if (inputData != null) { _topLevelImpl.RawTextEvent(inputData); } } _inputHelper.Clear(); } [Parameter(CaptureUnmatchedValues = true)] public IReadOnlyDictionary<string, object>? AdditionalAttributes { get; set; } protected override void OnAfterRender(bool firstRender) { if (firstRender) { Threading.Dispatcher.UIThread.Post(async () => { _inputHelper = await InputHelperInterop.ImportAsync(Js, _inputElement); _inputHelper.Hide(); _inputHelper.SetCursor("default"); Console.WriteLine("starting html canvas setup"); _interop = await SKHtmlCanvasInterop.ImportAsync(Js, _htmlCanvas, OnRenderFrame); Console.WriteLine("Interop created"); _jsGlInfo = _interop.InitGL(); Console.WriteLine("jsglinfo created - init gl"); _sizeWatcher = await SizeWatcherInterop.ImportAsync(Js, _htmlCanvas, OnSizeChanged); _dpiWatcher = await DpiWatcherInterop.ImportAsync(Js, OnDpiChanged); Console.WriteLine("watchers created."); // create the SkiaSharp context if (_context == null) { Console.WriteLine("create glcontext"); _glInterface = GRGlInterface.Create(); _context = GRContext.CreateGl(_glInterface); // bump the default resource cache limit _context.SetResourceCacheLimit(256 * 1024 * 1024); Console.WriteLine("glcontext created and resource limit set"); } _topLevelImpl.SetSurface(_context, _jsGlInfo, ColorType, new PixelSize((int)_canvasSize.Width, (int)_canvasSize.Height), _dpi); _initialised = true; _topLevel.Prepare(); _topLevel.Renderer.Start(); Invalidate(); }); } } private void OnRenderFrame() { if (_canvasSize.Width <= 0 || _canvasSize.Height <= 0 || _dpi <= 0 || _jsGlInfo == null) { Console.WriteLine("nothing to render"); return; } ManualTriggerRenderTimer.Instance.RaiseTick(); } public void Dispose() { _dpiWatcher.Unsubscribe(OnDpiChanged); _sizeWatcher.Dispose(); _interop.Dispose(); } private void OnDpiChanged(double newDpi) { _dpi = newDpi; _topLevelImpl.SetClientSize(_canvasSize, _dpi); Invalidate(); } private void OnSizeChanged(SKSize newSize) { _canvasSize = newSize; _topLevelImpl.SetClientSize(_canvasSize, _dpi); Invalidate(); } public void Invalidate() { if (!_initialised || _canvasSize.Width <= 0 || _canvasSize.Height <= 0 || _dpi <= 0 || _jsGlInfo == null) { Console.WriteLine("invalidate ignored"); return; } _interop.RequestAnimationFrame(true, (int)(_canvasSize.Width * _dpi), (int)(_canvasSize.Height * _dpi)); } public void SetActive(bool active) { _inputHelper.Clear(); if (active) { _inputHelper.Show(); _inputHelper.Focus(); } else { _inputHelper.Hide(); } } public void SetCursorRect(Rect rect) { } public void SetOptions(TextInputOptionsQueryEventArgs options) { } public void Reset() { _inputHelper.Clear(); } } }
// Copyright (c) 2015 Alachisoft // // 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. #define PRINT_URI1 using System; using System.Data; using System.Collections; using System.Globalization; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using Alachisoft.NCache.Caching; using Alachisoft.NCache.Caching.Statistics; using Alachisoft.NCache.Config; using Alachisoft.NCache.Management; using Alachisoft.NCache.ServiceControl; using Alachisoft.NCache.Common; using Alachisoft.NCache.Common.Net; using Alachisoft.NCache.Runtime.Exceptions; using Alachisoft.NCache.Management.ServiceControl; using Alachisoft.NCache.Tools.Common; namespace Alachisoft.NCache.Tools.ListCaches { /// <summary> /// Main application class /// </summary> class Application { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { try { ListCachesTool.Run(args); } catch(Exception e) { Console.Error.WriteLine(e); } } } public class ListCachesParam : Alachisoft.NCache.Tools.Common.CommandLineParamsBase { private string _server = string.Empty; private int _port=-1; private bool _detailed, _printConf,_xmlSyntax; [ArgumentAttribute(@"/s", @"/server")] public string Server { get { return _server; } set { _server = value; } } [ArgumentAttribute(@"/p", @"/port")] public int Port { get { return _port; } set { _port = value; } } [ArgumentAttribute(@"/a", @"/detail",false)] public bool Detail { get { return _detailed; } set { _detailed = value; } } public bool XmlSyntax { get { return _xmlSyntax; } } public bool PrintConf { get { return _printConf; } } } /// <summary> /// Summary description for ListCachesTool. /// </summary> sealed class ListCachesTool { /// <summary> NCache service controller. </summary> static private NCacheRPCService NCache = new NCacheRPCService(""); /// <summary> Detailed information flag, specified at the command line. </summary> static private bool detailed; /// <summary> Print configuration flag, specified at the command line. </summary> static private bool printConf; /// <summary> xml configuration syntax flag, specified at the command line. </summary> static private bool xmlSyntax; /// <summary>arguments passed to ListCache </summary> static private ListCachesParam cParam = new ListCachesParam(); static private void PrintCacheInfo(CacheStatistics statistics, string partId, string cacheName, bool isRunning) { CacheStatistics s = statistics; string schemeName = s.ClassName.ToLower(CultureInfo.CurrentCulture); string running = isRunning ? "Running" : "Stopped"; Console.WriteLine("{0,-20} {1,-15} {2,-30} {3,-5}", cacheName, partId, schemeName, running); } static private void PrintCacheInfo(Cache cache, string partId) { CacheStatistics s = cache.Statistics; string schemeName = s.ClassName.ToLower(CultureInfo.CurrentCulture); string running = cache.IsRunning ? "Running" : "Stopped"; Console.WriteLine("{0,-20} {1,-15} {2,-30} {3,-5}", cache.Name, partId, schemeName, running); } static private void PrintDetailedCacheInfo(CacheStatistics statistics, string partId, bool printConf, bool xmlSyntax, bool isRunning, string cacheName, String configString) { CacheStatistics s = statistics; long MaxSize = 0; string schemeName = s.ClassName.ToLower(CultureInfo.CurrentCulture); bool running = isRunning; Console.WriteLine("Cache-ID: {0}", cacheName); if (partId != null && partId != string.Empty) Console.WriteLine("Partition-ID: {0}", partId); Console.WriteLine("Scheme: {0}", schemeName); Console.WriteLine("Status: {0}", isRunning ? "Running" : "Stopped"); if (running) { if (s is ClusterCacheStatistics) { System.Text.StringBuilder nodes = new System.Text.StringBuilder(); ClusterCacheStatistics cs = s as ClusterCacheStatistics; Console.WriteLine("Cluster size: {0}", cs.Nodes.Count); MaxSize = (cs.LocalNode.Statistics.MaxSize / 1024) / 1024; foreach (NodeInfo n in cs.Nodes) { nodes.Append(" ").Append(n.Address).Append("\n"); } Console.Write("{0}", nodes.ToString()); if (partId != null && partId != string.Empty) { if (cs.SubgroupNodes != null && cs.SubgroupNodes.Contains(partId.ToLower())) { nodes = new System.Text.StringBuilder(); ArrayList groupNodes = cs.SubgroupNodes[partId.ToLower()] as ArrayList; Console.WriteLine("Partition size: {0}", groupNodes.Count); foreach (Address address in groupNodes) { nodes.Append(" ").Append(address).Append("\n"); } } Console.Write("{0}", nodes.ToString()); } } Console.WriteLine("UpTime: {0}", s.UpTime); if (s.MaxSize != 0) Console.WriteLine("Capacity: {0} MB", ((s.MaxSize / 1024) / 1024)); else Console.WriteLine("Capacity: {0} MB", MaxSize); Console.WriteLine("Count: {0}", s.Count); } if (printConf) { try { if (xmlSyntax) { PropsConfigReader pr = new PropsConfigReader(configString); Console.WriteLine("Configuration:\n{0}", ConfigReader.ToPropertiesXml(pr.Properties, true)); } else { Console.WriteLine("Configuration:\n{0}", configString); } } catch (ConfigurationException) { } } Console.WriteLine(""); } static private void PrintDetailedCacheInfo(Cache cache, string partId, bool printConf, bool xmlSyntax) { CacheStatistics s = cache.Statistics; long MaxSize=0; string schemeName = s.ClassName.ToLower(CultureInfo.CurrentCulture); bool running = cache.IsRunning; Console.WriteLine("Cache-ID: {0}", cache.Name); if (partId != null && partId != string.Empty) Console.WriteLine("Partition-ID: {0}", partId); Console.WriteLine("Scheme: {0}", schemeName); Console.WriteLine("Status: {0}", cache.IsRunning ? "Running":"Stopped"); if(running) { if(s is ClusterCacheStatistics) { System.Text.StringBuilder nodes = new System.Text.StringBuilder(); ClusterCacheStatistics cs = s as ClusterCacheStatistics; Console.WriteLine("Cluster size: {0}", cs.Nodes.Count); MaxSize = (cs.LocalNode.Statistics.MaxSize/1024)/1024; foreach (NodeInfo n in cs.Nodes) { nodes.Append(" ").Append(n.Address).Append("\n"); } Console.Write("{0}", nodes.ToString()); if (partId != null && partId != string.Empty) { if (cs.SubgroupNodes != null && cs.SubgroupNodes.Contains(partId.ToLower())) { nodes = new System.Text.StringBuilder(); ArrayList groupNodes = cs.SubgroupNodes[partId.ToLower()] as ArrayList; Console.WriteLine("Partition size: {0}", groupNodes.Count); foreach (Address address in groupNodes) { nodes.Append(" ").Append(address).Append("\n"); } } Console.Write("{0}", nodes.ToString()); } } Console.WriteLine("UpTime: {0}", s.UpTime); if(s.MaxSize != 0) Console.WriteLine("Capacity: {0} MB", (( s.MaxSize / 1024) / 1024)); else Console.WriteLine("Capacity: {0} MB", MaxSize); Console.WriteLine("Count: {0}", s.Count); } if(printConf) { try { if(xmlSyntax) { PropsConfigReader pr = new PropsConfigReader(cache.ConfigString); Console.WriteLine("Configuration:\n{0}", ConfigReader.ToPropertiesXml(pr.Properties, true)); } else { Console.WriteLine("Configuration:\n{0}", cache.ConfigString); } } catch(ConfigurationException){} } Console.WriteLine(""); } /// <summary> /// Sets the application level parameters to those specified at the command line. /// </summary> /// <param name="args">array of command line parameters</param> /// <summary> /// The main entry point for the tool. /// </summary> static public void Run(string[] args) { object param = new ListCachesParam(); CommandLineArgumentParser.CommandLineParser(ref param, args); cParam = (ListCachesParam)param; AssemblyUsage.PrintLogo(cParam.IsLogo); if (cParam.IsUsage) { AssemblyUsage.PrintUsage(); return; } if (!cParam.Detail && string.IsNullOrEmpty(cParam.Server) && args.Length != 0 && cParam.Port == -1 && cParam.IsUsage) { AssemblyUsage.PrintUsage(); return; } if (cParam.Port != -1) { NCache.Port = cParam.Port; } if (cParam.Server != null && !cParam.Server.Equals("")) { NCache.ServerName = cParam.Server; } string getBindIp = string.Empty; try { ICacheServer m = NCache.GetCacheServer(new TimeSpan(0, 0, 0, 30)); getBindIp = m.GetBindIP(); Console.WriteLine("Listing registered caches on server {0}:{1}\n", getBindIp, NCache.Port); if(m != null) { Alachisoft.NCache.Common.Monitoring.ConfiguredCacheInfo[] caches = m.GetAllConfiguredCaches(); Alachisoft.NCache.Common.Monitoring.ConfiguredCacheInfo[] partitionedReplicaCaches = m.GetConfiguredPartitionedReplicaCaches();// PartitionedReplicaCaches; if (caches.Length > 0 || partitionedReplicaCaches.Length > 0) { if (!cParam.Detail) { Console.WriteLine("{0,-20} {1,-15} {2,-30} {3,-5}", "Cache-ID", "Partition Id", "Scheme", "Status"); Console.WriteLine("{0,-20} {1,-15} {2,-30} {3,-5}", "--------", "------------", "------", "------"); } if (caches.Length > 0) { for (int i = 0; i < caches.Length; i++) { Alachisoft.NCache.Common.Monitoring.ConfiguredCacheInfo cacheInfo = caches[i]; if (!cParam.Detail) { PrintCacheInfo(m.GetCacheStatistics2(cacheInfo.CacheId), "N/A", cacheInfo.CacheId, cacheInfo.IsRunning); } else { PrintDetailedCacheInfo(m.GetCacheStatistics2(cacheInfo.CacheId), null, cParam.PrintConf, cParam.XmlSyntax, cacheInfo.IsRunning, cacheInfo.CacheId, cacheInfo.CachePropString); } } } if (partitionedReplicaCaches.Length > 0) { IEnumerator ide = partitionedReplicaCaches.GetEnumerator(); while (ide.MoveNext()) { Hashtable cacheTbl = ide.Current as Hashtable; if (cacheTbl != null) { IDictionaryEnumerator e = cacheTbl.GetEnumerator(); while (e.MoveNext()) { string partId = e.Key as string; Cache cache = (Cache)e.Value; if (!detailed) { PrintCacheInfo(cache, partId); } else { PrintDetailedCacheInfo(cache, partId, printConf, xmlSyntax); } } } } } } else { Console.WriteLine("There are no registered caches on {0}", NCache.ServerName); } } } catch(Exception e) { Console.Error.WriteLine("Error: {0}", e.Message); Console.Error.WriteLine(); Console.Error.WriteLine(e.ToString()); } finally { NCache.Dispose(); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Bond.Expressions { using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Bond.Internal.Reflection; public class TaggedParser<R> : IParser { delegate Expression TypeHandlerCompiletime(BondDataType type); delegate Expression TypeHandlerRuntime(Expression type); readonly TaggedReader<R> reader = new TaggedReader<R>(); readonly PayloadBondedFactory bondedFactory; readonly TaggedParser<R> baseParser; readonly TaggedParser<R> fieldParser; readonly bool isBase; public TaggedParser(RuntimeSchema schema) : this(schema, null) { } public TaggedParser(RuntimeSchema schema, PayloadBondedFactory bondedFactory) : this(bondedFactory) { } public TaggedParser(Type type) : this(type, null) { } public TaggedParser(Type type, PayloadBondedFactory bondedFactory) : this(bondedFactory) { } private TaggedParser(PayloadBondedFactory bondedFactory) { isBase = false; this.bondedFactory = bondedFactory ?? NewBonded; baseParser = new TaggedParser<R>(this, isBase: true); fieldParser = this; } TaggedParser(TaggedParser<R> that, bool isBase) { this.isBase = isBase; bondedFactory = that.bondedFactory; reader = that.reader; baseParser = this; fieldParser = that; } public ParameterExpression ReaderParam { get { return reader.Param; } } public Expression ReaderValue { get { return reader.Param; } } public int HierarchyDepth { get { return 0; } } public bool IsBonded { get { return false; } } public Expression Apply(ITransform transform) { var fieldId = Expression.Variable(typeof(UInt16), "fieldId"); var fieldType = Expression.Variable(typeof(BondDataType), "fieldType"); var endLabel = Expression.Label("end"); var breakLoop = Expression.Break(endLabel); // (int)fieldType > (int)BT_STOP_BASE var notEndOrEndBase = Expression.GreaterThan( Expression.Convert(fieldType, typeof(int)), Expression.Constant((int)BondDataType.BT_STOP_BASE)); var notEnd = isBase ? notEndOrEndBase : Expression.NotEqual(fieldType, Expression.Constant(BondDataType.BT_STOP)); var isEndBase = Expression.Equal(fieldType, Expression.Constant(BondDataType.BT_STOP_BASE)); var body = new List<Expression> { isBase ? reader.ReadBaseBegin() : reader.ReadStructBegin(), transform.Begin, transform.Base(baseParser), reader.ReadFieldBegin(fieldType, fieldId) }; // known fields body.AddRange( from f in transform.Fields select Expression.Loop( Expression.IfThenElse(notEndOrEndBase, Expression.Block( Expression.IfThenElse( Expression.Equal(fieldId, Expression.Constant(f.Id)), Expression.Block( f.Value(fieldParser, fieldType), reader.ReadFieldEnd(), reader.ReadFieldBegin(fieldType, fieldId), breakLoop), Expression.IfThenElse( Expression.GreaterThan(fieldId, Expression.Constant(f.Id)), Expression.Block( f.Omitted, breakLoop), transform.UnknownField(fieldParser, fieldType, fieldId) ?? Skip(fieldType))), reader.ReadFieldEnd(), reader.ReadFieldBegin(fieldType, fieldId), Expression.IfThen( Expression.GreaterThan(fieldId, Expression.Constant(f.Id)), breakLoop)), Expression.Block( f.Omitted, breakLoop)), endLabel)); // unknown fields body.Add( ControlExpression.While(notEnd, Expression.Block( Expression.IfThenElse( isEndBase, transform.UnknownEnd, Expression.Block( transform.UnknownField(fieldParser, fieldType, fieldId) ?? Skip(fieldType), reader.ReadFieldEnd())), reader.ReadFieldBegin(fieldType, fieldId)))); body.Add(isBase ? reader.ReadBaseEnd() : reader.ReadStructEnd()); body.Add(transform.End); return Expression.Block( new[] { fieldType, fieldId }, body); } public Expression Container(BondDataType? expectedType, ContainerHandler handler) { var count = Expression.Variable(typeof(int), "count"); var elementType = Expression.Variable(typeof(BondDataType), "elementType"); var next = Expression.GreaterThan(Expression.PostDecrementAssign(count), Expression.Constant(0)); var loops = MatchOrCompatible( elementType, expectedType, type => handler(this, type, next, count, null)); return Expression.Block( new[] { count, elementType }, reader.ReadContainerBegin(count, elementType), loops, reader.ReadContainerEnd()); } public Expression Map(BondDataType? expectedKeyType, BondDataType? expectedValueType, MapHandler handler) { var count = Expression.Variable(typeof(int), "count"); var keyType = Expression.Variable(typeof(BondDataType), "keyType"); var valueType = Expression.Variable(typeof(BondDataType), "valueType"); var next = Expression.GreaterThan(Expression.PostDecrementAssign(count), Expression.Constant(0)); var loops = MatchOrCompatible(keyType, expectedKeyType, constantKeyType => MatchOrCompatible(valueType, expectedValueType, constantValueType => handler(this, this, constantKeyType, constantValueType, next, Expression.Empty(), count))); return Expression.Block( new[] { count, keyType, valueType }, reader.ReadContainerBegin(count, keyType, valueType), loops, reader.ReadContainerEnd()); } public Expression Blob(Expression count) { return reader.ReadBytes(count); } public Expression Scalar(Expression valueType, BondDataType expectedType, ValueHandler handler) { return MatchOrCompatible(valueType, expectedType, type => handler(reader.Read(type))); } public Expression Bonded(ValueHandler handler) { var newBonded = bondedFactory(reader.Param, Expression.Constant(RuntimeSchema.Empty)); return Expression.Block( handler(newBonded), reader.Skip(Expression.Constant(BondDataType.BT_STRUCT))); } public Expression Skip(Expression type) { return reader.Skip(type); } static Expression NewBonded(Expression reader, Expression schema) { var ctor = typeof(BondedVoid<>).MakeGenericType(reader.Type).GetConstructor(reader.Type); return Expression.New(ctor, reader); } static Expression MatchOrCompatible(Expression valueType, BondDataType? expectedType, TypeHandlerRuntime handler) { return (expectedType == null) ? handler(valueType) : MatchOrCompatible(valueType, expectedType.Value, type => handler(Expression.Constant(type))); } // Generate expression to handle exact match or compatible type static Expression MatchOrCompatible(Expression valueType, BondDataType expectedType, TypeHandlerCompiletime handler) { return MatchOrElse(valueType, expectedType, handler, TryCompatible(valueType, expectedType, handler)); } // valueType maybe a ConstantExpression and then Prune optimizes unreachable branches out static Expression MatchOrElse(Expression valueType, BondDataType expectedType, TypeHandlerCompiletime handler, Expression orElse) { return PrunedExpression.IfThenElse( Expression.Equal(valueType, Expression.Constant(expectedType)), handler(expectedType), orElse); } // Generates expression to handle value of type that is different but compatible with expected type static Expression TryCompatible(Expression valueType, BondDataType expectedType, TypeHandlerCompiletime handler) { if (expectedType == BondDataType.BT_DOUBLE) { return MatchOrElse(valueType, BondDataType.BT_FLOAT, handler, InvalidType(expectedType, valueType)); } if (expectedType == BondDataType.BT_UINT64) { return MatchOrElse(valueType, BondDataType.BT_UINT32, handler, MatchOrElse(valueType, BondDataType.BT_UINT16, handler, MatchOrElse(valueType, BondDataType.BT_UINT8, handler, InvalidType(expectedType, valueType)))); } if (expectedType == BondDataType.BT_UINT32) { return MatchOrElse(valueType, BondDataType.BT_UINT16, handler, MatchOrElse(valueType, BondDataType.BT_UINT8, handler, InvalidType(expectedType, valueType))); } if (expectedType == BondDataType.BT_UINT16) { return MatchOrElse(valueType, BondDataType.BT_UINT8, handler, InvalidType(expectedType, valueType)); } if (expectedType == BondDataType.BT_INT64) { return MatchOrElse(valueType, BondDataType.BT_INT32, handler, MatchOrElse(valueType, BondDataType.BT_INT16, handler, MatchOrElse(valueType, BondDataType.BT_INT8, handler, InvalidType(expectedType, valueType)))); } if (expectedType == BondDataType.BT_INT32) { return MatchOrElse(valueType, BondDataType.BT_INT16, handler, MatchOrElse(valueType, BondDataType.BT_INT8, handler, InvalidType(expectedType, valueType))); } if (expectedType == BondDataType.BT_INT16) { return MatchOrElse(valueType, BondDataType.BT_INT8, handler, InvalidType(expectedType, valueType)); } return InvalidType(expectedType, valueType); } static Expression InvalidType(BondDataType expectedType, Expression valueType) { return ThrowExpression.InvalidTypeException(Expression.Constant(expectedType), valueType); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using QuantConnect.Logging; using System.Globalization; using QuantConnect.Securities; using System.Collections.Generic; using QuantConnect.Securities.Future; using QuantConnect.Securities.FutureOption; using static QuantConnect.StringExtensions; namespace QuantConnect { /// <summary> /// Public static helper class that does parsing/generation of symbol representations (options, futures) /// </summary> public static class SymbolRepresentation { private static DateTime TodayUtc = DateTime.UtcNow; /// <summary> /// Class contains future ticker properties returned by ParseFutureTicker() /// </summary> public class FutureTickerProperties { /// <summary> /// Underlying name /// </summary> public string Underlying { get; set; } /// <summary> /// Short expiration year /// </summary> public int ExpirationYearShort { get; set; } /// <summary> /// Expiration month /// </summary> public int ExpirationMonth { get; set; } /// <summary> /// Expiration day /// </summary> public int ExpirationDay { get; set; } } /// <summary> /// Class contains option ticker properties returned by ParseOptionTickerIQFeed() /// </summary> public class OptionTickerProperties { /// <summary> /// Underlying name /// </summary> public string Underlying { get; set; } /// <summary> /// Option right /// </summary> public OptionRight OptionRight { get; set; } /// <summary> /// Option strike /// </summary> public decimal OptionStrike { get; set; } /// <summary> /// Expiration date /// </summary> public DateTime ExpirationDate { get; set; } } /// <summary> /// Function returns underlying name, expiration year, expiration month, expiration day for the future contract ticker. Function detects if /// the format used is either 1 or 2 digits year, and if day code is present (will default to 1rst day of month). Returns null, if parsing failed. /// Format [Ticker][2 digit day code OPTIONAL][1 char month code][2/1 digit year code] /// </summary> /// <param name="ticker"></param> /// <returns>Results containing 1) underlying name, 2) short expiration year, 3) expiration month</returns> public static FutureTickerProperties ParseFutureTicker(string ticker) { var doubleDigitYear = char.IsDigit(ticker.Substring(ticker.Length - 2, 1)[0]); var doubleDigitOffset = doubleDigitYear ? 1 : 0; var expirationDayOffset = 0; var expirationDay = 1; if (ticker.Length > 4 + doubleDigitOffset) { var potentialExpirationDay = ticker.Substring(ticker.Length - 4 - doubleDigitOffset, 2); var containsExpirationDay = char.IsDigit(potentialExpirationDay[0]) && char.IsDigit(potentialExpirationDay[1]); expirationDayOffset = containsExpirationDay ? 2 : 0; if (containsExpirationDay && !int.TryParse(potentialExpirationDay, out expirationDay)) { return null; } } var expirationYearString = ticker.Substring(ticker.Length - 1 - doubleDigitOffset, 1 + doubleDigitOffset); var expirationMonthString = ticker.Substring(ticker.Length - 2 - doubleDigitOffset, 1); var underlyingString = ticker.Substring(0, ticker.Length - 2 - doubleDigitOffset - expirationDayOffset); int expirationYearShort; if (!int.TryParse(expirationYearString, out expirationYearShort)) { return null; } if (!_futuresMonthCodeLookup.ContainsKey(expirationMonthString)) { return null; } var expirationMonth = _futuresMonthCodeLookup[expirationMonthString]; return new FutureTickerProperties { Underlying = underlyingString, ExpirationYearShort = expirationYearShort, ExpirationMonth = expirationMonth, ExpirationDay = expirationDay }; } /// <summary> /// Helper method to parse and generate a future symbol from a given user friendly representation /// </summary> /// <param name="ticker">The future ticker, for example 'ESZ1'</param> /// <param name="futureYear">Clarifies the year for the current future</param> /// <returns>The future symbol or null if failed</returns> public static Symbol ParseFutureSymbol(string ticker, int? futureYear = null) { var disambiguatedFutureYear = futureYear ?? TodayUtc.Year; var parsed = ParseFutureTicker(ticker); if (parsed == null) { return null; } var underlying = parsed.Underlying; var expirationYearShort = parsed.ExpirationYearShort; var expirationMonth = parsed.ExpirationMonth; var expirationYear = GetExpirationYear(expirationYearShort, disambiguatedFutureYear); if (!SymbolPropertiesDatabase.FromDataFolder().TryGetMarket(underlying, SecurityType.Future, out var market)) { Log.Debug($"SymbolRepresentation.ParseFutureSymbol(): Failed to get market for future '{ticker}' and underlying '{underlying}'"); return null; } var expiryFunc = FuturesExpiryFunctions.FuturesExpiryFunction(Symbol.Create(underlying, SecurityType.Future, market)); var expiryDate = expiryFunc(new DateTime(expirationYear, expirationMonth, 1)); return Symbol.CreateFuture(underlying, market, expiryDate); } /// <summary> /// Creates a future option Symbol from the provided ticker /// </summary> /// <param name="ticker">The future option ticker, for example 'ESZ0 P3590'</param> /// <param name="strikeScale">Optional the future option strike scale factor</param> public static Symbol ParseFutureOptionSymbol(string ticker, int strikeScale = 1) { var split = ticker.Split(' '); if (split.Length != 2) { return null; } var parsed = ParseFutureTicker(split[0]); if (parsed == null) { return null; } ticker = parsed.Underlying; OptionRight right; if (split[1][0] == 'P' || split[1][0] == 'p') { right = OptionRight.Put; } else if (split[1][0] == 'C' || split[1][0] == 'c') { right = OptionRight.Call; } else { return null; } var strike = split[1].Substring(1); if (parsed.ExpirationYearShort < 10) { parsed.ExpirationYearShort += 20; } var expirationYearParsed = 2000 + parsed.ExpirationYearShort; var expirationDate = new DateTime(expirationYearParsed, parsed.ExpirationMonth, 1); var strikePrice = decimal.Parse(strike, NumberStyles.Any, CultureInfo.InvariantCulture); var futureTicker = FuturesOptionsSymbolMappings.MapFromOption(ticker); if (!SymbolPropertiesDatabase.FromDataFolder().TryGetMarket(futureTicker, SecurityType.Future, out var market)) { Log.Debug($"SymbolRepresentation.ParseFutureOptionSymbol(): No market found for '{futureTicker}'"); return null; } var canonicalFuture = Symbol.Create(futureTicker, SecurityType.Future, market); var futureExpiry = FuturesExpiryFunctions.FuturesExpiryFunction(canonicalFuture)(expirationDate); var future = Symbol.CreateFuture(futureTicker, market, futureExpiry); var futureOptionExpiry = FuturesOptionsExpiryFunctions.GetFutureOptionExpiryFromFutureExpiry(future); return Symbol.CreateOption(future, market, OptionStyle.American, right, strikePrice / strikeScale, futureOptionExpiry); } /// <summary> /// Returns future symbol ticker from underlying and expiration date. Function can generate tickers of two formats: one and two digits year. /// Format [Ticker][2 digit day code][1 char month code][2/1 digit year code], more information at http://help.tradestation.com/09_01/tradestationhelp/symbology/futures_symbology.htm /// </summary> /// <param name="underlying">String underlying</param> /// <param name="expiration">Expiration date</param> /// <param name="doubleDigitsYear">True if year should represented by two digits; False - one digit</param> /// <returns></returns> public static string GenerateFutureTicker(string underlying, DateTime expiration, bool doubleDigitsYear = true) { var year = doubleDigitsYear ? expiration.Year % 100 : expiration.Year % 10; var month = expiration.Month; var contractMonthDelta = FuturesExpiryUtilityFunctions.GetDeltaBetweenContractMonthAndContractExpiry(underlying, expiration.Date); if (contractMonthDelta < 0) { // For futures that have an expiry after the contract month. // This is for dairy contracts, which can and do expire after the contract month. var expirationMonth = expiration.AddDays(-(expiration.Day - 1)) .AddMonths(contractMonthDelta); month = expirationMonth.Month; year = doubleDigitsYear ? expirationMonth.Year % 100 : expirationMonth.Year % 10; } else { // These futures expire in the month before or in the contract month month += contractMonthDelta; // Get the month back into the allowable range, allowing for a wrap // Below is a little algorithm for wrapping numbers with a certain bounds. // In this case, were dealing with months, wrapping to years once we get to January // As modulo works for [0, x), it's best to subtract 1 (as months are [1, 12] to convert to [0, 11]), // do the modulo/integer division, then add 1 back on to get into the correct range again month--; year += month / 12; month %= 12; month++; } return $"{underlying}{expiration.Day:00}{_futuresMonthLookup[month]}{year}"; } /// <summary> /// Returns option symbol ticker in accordance with OSI symbology /// More information can be found at http://www.optionsclearing.com/components/docs/initiatives/symbology/symbology_initiative_v1_8.pdf /// </summary> /// <param name="symbol">Symbol object to create OSI ticker from</param> /// <returns>The OSI ticker representation</returns> public static string GenerateOptionTickerOSI(this Symbol symbol) { if (!symbol.SecurityType.IsOption()) { throw new ArgumentException(Invariant($"{nameof(GenerateOptionTickerOSI)} returns symbol to be an option, received {symbol.SecurityType}.")); } return GenerateOptionTickerOSI(symbol.Underlying.Value, symbol.ID.OptionRight, symbol.ID.StrikePrice, symbol.ID.Date); } /// <summary> /// Returns option symbol ticker in accordance with OSI symbology /// More information can be found at http://www.optionsclearing.com/components/docs/initiatives/symbology/symbology_initiative_v1_8.pdf /// </summary> /// <param name="underlying">Underlying string</param> /// <param name="right">Option right</param> /// <param name="strikePrice">Option strike</param> /// <param name="expiration">Option expiration date</param> /// <returns>The OSI ticker representation</returns> public static string GenerateOptionTickerOSI(string underlying, OptionRight right, decimal strikePrice, DateTime expiration) { if (underlying.Length > 5) underlying += " "; return Invariant($"{underlying,-6}{expiration.ToStringInvariant(DateFormat.SixCharacter)}{right.ToStringPerformance()[0]}{(strikePrice * 1000m):00000000}"); } /// <summary> /// Parses the specified OSI options ticker into a Symbol object /// </summary> /// <param name="ticker">The OSI compliant option ticker string</param> /// <param name="securityType">The security type</param> /// <param name="market">The associated market</param> /// <returns>Symbol object for the specified OSI option ticker string</returns> public static Symbol ParseOptionTickerOSI(string ticker, SecurityType securityType = SecurityType.Option, string market = Market.USA) { var underlying = ticker.Substring(0, 6).Trim(); var expiration = DateTime.ParseExact(ticker.Substring(6, 6), DateFormat.SixCharacter, null); OptionRight right; if (ticker[12] == 'C' || ticker[12] == 'c') { right = OptionRight.Call; } else if (ticker[12] == 'P' || ticker[12] == 'p') { right = OptionRight.Put; } else { throw new FormatException($"Expected 12th character to be 'C' or 'P' for OptionRight: {ticker} but was '{ticker[12]}'"); } var strike = Parse.Decimal(ticker.Substring(13, 8)) / 1000m; SecurityIdentifier underlyingSid; if (securityType == SecurityType.Option) { underlyingSid = SecurityIdentifier.GenerateEquity(underlying, market); } else if(securityType == SecurityType.IndexOption) { underlyingSid = SecurityIdentifier.GenerateIndex(underlying, market); } else { throw new NotImplementedException($"ParseOptionTickerOSI(): security type {securityType} not implemented"); } var sid = SecurityIdentifier.GenerateOption(expiration, underlyingSid, market, strike, right, OptionStyle.American); return new Symbol(sid, ticker, new Symbol(underlyingSid, underlying)); } /// <summary> /// Function returns option contract parameters (underlying name, expiration date, strike, right) from IQFeed option ticker /// Symbology details: http://www.iqfeed.net/symbolguide/index.cfm?symbolguide=guide&amp;displayaction=support%C2%A7ion=guide&amp;web=iqfeed&amp;guide=options&amp;web=IQFeed&amp;type=stock /// </summary> /// <param name="ticker">IQFeed option ticker</param> /// <returns>Results containing 1) underlying name, 2) option right, 3) option strike 4) expiration date</returns> public static OptionTickerProperties ParseOptionTickerIQFeed(string ticker) { // This table describes IQFeed option symbology var symbology = new Dictionary<string, Tuple<int, OptionRight>> { { "A", Tuple.Create(1, OptionRight.Call) }, { "M", Tuple.Create(1, OptionRight.Put) }, { "B", Tuple.Create(2, OptionRight.Call) }, { "N", Tuple.Create(2, OptionRight.Put) }, { "C", Tuple.Create(3, OptionRight.Call) }, { "O", Tuple.Create(3, OptionRight.Put) }, { "D", Tuple.Create(4, OptionRight.Call) }, { "P", Tuple.Create(4, OptionRight.Put) }, { "E", Tuple.Create(5, OptionRight.Call) }, { "Q", Tuple.Create(5, OptionRight.Put) }, { "F", Tuple.Create(6, OptionRight.Call) }, { "R", Tuple.Create(6, OptionRight.Put) }, { "G", Tuple.Create(7, OptionRight.Call) }, { "S", Tuple.Create(7, OptionRight.Put) }, { "H", Tuple.Create(8, OptionRight.Call) }, { "T", Tuple.Create(8, OptionRight.Put) }, { "I", Tuple.Create(9, OptionRight.Call) }, { "U", Tuple.Create(9, OptionRight.Put) }, { "J", Tuple.Create(10, OptionRight.Call) }, { "V", Tuple.Create(10, OptionRight.Put) }, { "K", Tuple.Create(11, OptionRight.Call) }, { "W", Tuple.Create(11, OptionRight.Put) }, { "L", Tuple.Create(12, OptionRight.Call) }, { "X", Tuple.Create(12, OptionRight.Put) }, }; var letterRange = symbology.Keys .Select(x => x[0]) .ToArray(); var optionTypeDelimiter = ticker.LastIndexOfAny(letterRange); var strikePriceString = ticker.Substring(optionTypeDelimiter + 1, ticker.Length - optionTypeDelimiter - 1); var lookupResult = symbology[ticker[optionTypeDelimiter].ToStringInvariant()]; var month = lookupResult.Item1; var optionRight = lookupResult.Item2; var dayString = ticker.Substring(optionTypeDelimiter - 2, 2); var yearString = ticker.Substring(optionTypeDelimiter - 4, 2); var underlying = ticker.Substring(0, optionTypeDelimiter - 4); // if we cannot parse strike price, we ignore this contract, but log the information. decimal strikePrice; if (!Decimal.TryParse(strikePriceString, out strikePrice)) { return null; } int day; if (!int.TryParse(dayString, out day)) { return null; } int year; if (!int.TryParse(yearString, out year)) { return null; } var expirationDate = new DateTime(2000 + year, month, day); return new OptionTickerProperties { Underlying = underlying, OptionRight = optionRight, OptionStrike = strikePrice, ExpirationDate = expirationDate }; } private static IReadOnlyDictionary<string, int> _futuresMonthCodeLookup = new Dictionary<string, int> { { "F", 1 }, { "G", 2 }, { "H", 3 }, { "J", 4 }, { "K", 5 }, { "M", 6 }, { "N", 7 }, { "Q", 8 }, { "U", 9 }, { "V", 10 }, { "X", 11 }, { "Z", 12 } }; private static IReadOnlyDictionary<int, string> _futuresMonthLookup = _futuresMonthCodeLookup.ToDictionary(kv => kv.Value, kv => kv.Key); private static int GetExpirationYear(int year, int futureYear) { var baseNum = 2000; while (baseNum + year < futureYear) { baseNum += 10; } return baseNum + year; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.Authorization; using Microsoft.Azure.Management.Authorization.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Authorization { /// <summary> /// Get resource or resource group permissions (see http://TBD for more /// information) /// </summary> internal partial class PermissionOperations : IServiceOperations<AuthorizationManagementClient>, IPermissionOperations { /// <summary> /// Initializes a new instance of the PermissionOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal PermissionOperations(AuthorizationManagementClient client) { this._client = client; } private AuthorizationManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Authorization.AuthorizationManagementClient. /// </summary> public AuthorizationManagementClient Client { get { return this._client; } } /// <summary> /// Gets a resource permissions. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='identity'> /// Required. Resource /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Permissions information. /// </returns> public async Task<PermissionGetResult> ListForResourceAsync(string resourceGroupName, ResourceIdentity identity, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (identity == null) { throw new ArgumentNullException("identity"); } if (identity.ResourceName == null) { throw new ArgumentNullException("identity."); } if (identity.ResourceProviderNamespace == null) { throw new ArgumentNullException("identity."); } if (identity.ResourceType == null) { throw new ArgumentNullException("identity."); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("identity", identity); TracingAdapter.Enter(invocationId, this, "ListForResourceAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + Uri.EscapeDataString(identity.ResourceProviderNamespace); url = url + "/"; if (identity.ParentResourcePath != null) { url = url + identity.ParentResourcePath; } url = url + "/"; url = url + identity.ResourceType; url = url + "/"; url = url + Uri.EscapeDataString(identity.ResourceName); url = url + "/providers/Microsoft.Authorization/permissions"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-07-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result PermissionGetResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new PermissionGetResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Permission permissionInstance = new Permission(); result.Permissions.Add(permissionInstance); JToken actionsArray = valueValue["actions"]; if (actionsArray != null && actionsArray.Type != JTokenType.Null) { foreach (JToken actionsValue in ((JArray)actionsArray)) { permissionInstance.Actions.Add(((string)actionsValue)); } } JToken notActionsArray = valueValue["notActions"]; if (notActionsArray != null && notActionsArray.Type != JTokenType.Null) { foreach (JToken notActionsValue in ((JArray)notActionsArray)) { permissionInstance.NotActions.Add(((string)notActionsValue)); } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets a resource group permissions. /// </summary> /// <param name='resourceGroupName'> /// Required. Name of the resource group to get the permissions for.The /// name is case insensitive. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Permissions information. /// </returns> public async Task<PermissionGetResult> ListForResourceGroupAsync(string resourceGroupName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); TracingAdapter.Enter(invocationId, this, "ListForResourceGroupAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/Microsoft.Authorization/permissions"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-07-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result PermissionGetResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new PermissionGetResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Permission permissionInstance = new Permission(); result.Permissions.Add(permissionInstance); JToken actionsArray = valueValue["actions"]; if (actionsArray != null && actionsArray.Type != JTokenType.Null) { foreach (JToken actionsValue in ((JArray)actionsArray)) { permissionInstance.Actions.Add(((string)actionsValue)); } } JToken notActionsArray = valueValue["notActions"]; if (notActionsArray != null && notActionsArray.Type != JTokenType.Null) { foreach (JToken notActionsValue in ((JArray)notActionsArray)) { permissionInstance.NotActions.Add(((string)notActionsValue)); } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// <copyright file="WebSocketServer.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.Net; using System.Security.Cryptography.X509Certificates; namespace OpenQA.Selenium.Safari.Internal { /// <summary> /// Provides an implementation of a WebSocket server. /// </summary> public class WebSocketServer : IWebSocketServer { private readonly string scheme; private X509Certificate2 authenticationX509Certificate; /// <summary> /// Initializes a new instance of the <see cref="WebSocketServer"/> class. /// </summary> /// <param name="location">The location at which to listen for connections.</param> public WebSocketServer(string location) : this(8181, location) { } /// <summary> /// Initializes a new instance of the <see cref="WebSocketServer"/> class. /// </summary> /// <param name="port">The port on which to listen for connections.</param> /// <param name="location">The location at which to listen for connections.</param> public WebSocketServer(int port, string location) { var uri = new Uri(location); this.Port = port > 0 ? port : uri.Port; this.Location = location; this.scheme = uri.Scheme; this.ListenerSocket = new SocketWrapper(); this.ListenerSocket.Accepted += new EventHandler<AcceptEventArgs>(this.ListenerSocketAcceptedEventHandler); } /// <summary> /// Event raised when a message is received from the WebSocket. /// </summary> public event EventHandler<TextMessageHandledEventArgs> MessageReceived; /// <summary> /// Event raised when a connection is opened. /// </summary> public event EventHandler<ConnectionEventArgs> Opened; /// <summary> /// Event raised when a connection is closed. /// </summary> public event EventHandler<ConnectionEventArgs> Closed; /// <summary> /// Event raised when an error occurs. /// </summary> public event EventHandler<ErrorEventArgs> ErrorOccurred; /// <summary> /// Event raised when a non-WebSocket message is received. /// </summary> public event EventHandler<StandardHttpRequestReceivedEventArgs> StandardHttpRequestReceived; /// <summary> /// Gets or sets the <see cref="ISocket"/> on which communication occurs. /// </summary> public ISocket ListenerSocket { get; set; } /// <summary> /// Gets the location the server is listening on for connections. /// </summary> public string Location { get; private set; } /// <summary> /// Gets the port the server is listening on for connections. /// </summary> public int Port { get; private set; } /// <summary> /// Gets or sets the certificate used for authentication. /// </summary> public string Certificate { get; set; } /// <summary> /// Gets a value indicating whether the connection is secure. /// </summary> public bool IsSecure { get { return this.scheme == "wss" && this.Certificate != null; } } /// <summary> /// Starts the server. /// </summary> public void Start() { var localIPAddress = new IPEndPoint(IPAddress.Any, this.Port); this.ListenerSocket.Bind(localIPAddress); this.ListenerSocket.Listen(100); if (this.scheme == "wss") { if (this.Certificate == null) { return; } this.authenticationX509Certificate = new X509Certificate2(this.Certificate); } this.ListenForClients(); } /// <summary> /// Releases all resources used by the <see cref="WebSocketServer"/>. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Raises the ConnectionOpened event. /// </summary> /// <param name="e">A <see cref="ConnectionEventArgs"/> that contains the event data.</param> protected void OnConnectionOpened(ConnectionEventArgs e) { if (this.Opened != null) { this.Opened(this, e); } } /// <summary> /// Raises the ConnectionClosed event. /// </summary> /// <param name="e">A <see cref="ConnectionEventArgs"/> that contains the event data.</param> protected void OnConnectionClosed(ConnectionEventArgs e) { if (this.Closed != null) { this.Closed(this, e); } } /// <summary> /// Raises the StandardHttpRequestReceived event. /// </summary> /// <param name="e">A <see cref="StandardHttpRequestReceivedEventArgs"/> that contains the event data.</param> protected void OnStandardHttpRequestReceived(StandardHttpRequestReceivedEventArgs e) { if (this.StandardHttpRequestReceived != null) { this.StandardHttpRequestReceived(this, e); } } /// <summary> /// Raises the MessageReceived event. /// </summary> /// <param name="e">A <see cref="TextMessageHandledEventArgs"/> that contains the event data.</param> protected void OnMessageReceived(TextMessageHandledEventArgs e) { if (this.MessageReceived != null) { this.MessageReceived(this, e); } } /// <summary> /// Raises the ErrorOccurred event. /// </summary> /// <param name="e">An <see cref="ErrorEventArgs"/> that contains the event data.</param> protected void OnErrorOccurred(ErrorEventArgs e) { if (this.ErrorOccurred != null) { this.ErrorOccurred(this, e); } } /// <summary> /// Releases the unmanaged resources used by the <see cref="SocketWrapper"/> and optionally /// releases the managed resources. /// </summary> /// <param name="disposing"><see langword="true"/> to release managed and resources; /// <see langword="false"/> to only release unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (disposing) { this.ListenerSocket.Dispose(); } } private void ListenForClients() { this.ListenerSocket.Accept(); } private void OnClientConnect(ISocket clientSocket) { this.ListenForClients(); WebSocketConnection connection = null; connection = new WebSocketConnection(clientSocket, this.scheme); connection.MessageReceived += new EventHandler<TextMessageHandledEventArgs>(this.ConnectionMessageReceivedEventHandler); connection.BinaryMessageReceived += new EventHandler<BinaryMessageHandledEventArgs>(this.ConnectionBinaryMessageReceivedEventHandler); connection.Opened += new EventHandler<ConnectionEventArgs>(this.ConnectionOpenedEventHandler); connection.Closed += new EventHandler<ConnectionEventArgs>(this.ConnectionClosedEventHandler); connection.ErrorReceived += new EventHandler<ErrorEventArgs>(this.ConnectionErrorEventHandler); connection.StandardHttpRequestReceived += new EventHandler<StandardHttpRequestReceivedEventArgs>(this.ConnectionStandardHttpRequestReceivedEventHandler); if (this.IsSecure) { clientSocket.Authenticated += new EventHandler(this.SocketAuthenticatedEventHandler); clientSocket.Authenticate(this.authenticationX509Certificate); } else { connection.StartReceiving(); } } private void ListenerSocketAcceptedEventHandler(object sender, AcceptEventArgs e) { this.OnClientConnect(e.Socket); } private void ConnectionClosedEventHandler(object sender, ConnectionEventArgs e) { this.OnConnectionClosed(new ConnectionEventArgs(e.Connection)); } private void ConnectionOpenedEventHandler(object sender, ConnectionEventArgs e) { this.OnConnectionOpened(new ConnectionEventArgs(e.Connection)); } private void ConnectionBinaryMessageReceivedEventHandler(object sender, BinaryMessageHandledEventArgs e) { throw new NotImplementedException(); } private void ConnectionMessageReceivedEventHandler(object sender, TextMessageHandledEventArgs e) { this.OnMessageReceived(e); } private void ConnectionStandardHttpRequestReceivedEventHandler(object sender, StandardHttpRequestReceivedEventArgs e) { this.OnStandardHttpRequestReceived(e); } private void ConnectionErrorEventHandler(object sender, ErrorEventArgs e) { this.OnErrorOccurred(e); } private void SocketAuthenticatedEventHandler(object sender, EventArgs e) { throw new NotImplementedException(); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Net; using System.Reflection; using log4net; using Mono.Addins; using Nini.Config; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using OpenMetaverse; using OpenMetaverse.StructuredData; namespace OpenSim.Services.Connectors.SimianGrid { /// <summary> /// Connects avatar appearance data to the SimianGrid backend /// </summary> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")] public class SimianAvatarServiceConnector : IAvatarService, ISharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); // private static string ZeroID = UUID.Zero.ToString(); private string m_serverUrl = String.Empty; #region ISharedRegionModule public Type ReplaceableInterface { get { return null; } } public void RegionLoaded(Scene scene) { } public void PostInitialise() { } public void Close() { } public SimianAvatarServiceConnector() { } public string Name { get { return "SimianAvatarServiceConnector"; } } public void AddRegion(Scene scene) { if (!String.IsNullOrEmpty(m_serverUrl)) { scene.RegisterModuleInterface<IAvatarService>(this); } } public void RemoveRegion(Scene scene) { if (!String.IsNullOrEmpty(m_serverUrl)) { scene.UnregisterModuleInterface<IAvatarService>(this); } } #endregion ISharedRegionModule public SimianAvatarServiceConnector(IConfigSource source) { Initialise(source); } public void Initialise(IConfigSource source) { if (Simian.IsSimianEnabled(source, "AvatarServices", this.Name)) { IConfig gridConfig = source.Configs["AvatarService"]; if (gridConfig == null) { m_log.Error("[SIMIAN AVATAR CONNECTOR]: AvatarService missing from OpenSim.ini"); throw new Exception("Avatar connector init error"); } string serviceUrl = gridConfig.GetString("AvatarServerURI"); if (String.IsNullOrEmpty(serviceUrl)) { m_log.Error("[SIMIAN AVATAR CONNECTOR]: No AvatarServerURI in section AvatarService"); throw new Exception("Avatar connector init error"); } if (!serviceUrl.EndsWith("/")) serviceUrl = serviceUrl + '/'; m_serverUrl = serviceUrl; } } #region IAvatarService public AvatarData GetAvatar(UUID userID) { NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "GetUser" }, { "UserID", userID.ToString() } }; OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs); if (response["Success"].AsBoolean()) { OSDMap map = null; try { map = OSDParser.DeserializeJson(response["LLAppearance"].AsString()) as OSDMap; } catch { } if (map != null) { AvatarWearable[] wearables = new AvatarWearable[13]; wearables[0] = new AvatarWearable(map["ShapeItem"].AsUUID(), map["ShapeAsset"].AsUUID()); wearables[1] = new AvatarWearable(map["SkinItem"].AsUUID(), map["SkinAsset"].AsUUID()); wearables[2] = new AvatarWearable(map["HairItem"].AsUUID(), map["HairAsset"].AsUUID()); wearables[3] = new AvatarWearable(map["EyesItem"].AsUUID(), map["EyesAsset"].AsUUID()); wearables[4] = new AvatarWearable(map["ShirtItem"].AsUUID(), map["ShirtAsset"].AsUUID()); wearables[5] = new AvatarWearable(map["PantsItem"].AsUUID(), map["PantsAsset"].AsUUID()); wearables[6] = new AvatarWearable(map["ShoesItem"].AsUUID(), map["ShoesAsset"].AsUUID()); wearables[7] = new AvatarWearable(map["SocksItem"].AsUUID(), map["SocksAsset"].AsUUID()); wearables[8] = new AvatarWearable(map["JacketItem"].AsUUID(), map["JacketAsset"].AsUUID()); wearables[9] = new AvatarWearable(map["GlovesItem"].AsUUID(), map["GlovesAsset"].AsUUID()); wearables[10] = new AvatarWearable(map["UndershirtItem"].AsUUID(), map["UndershirtAsset"].AsUUID()); wearables[11] = new AvatarWearable(map["UnderpantsItem"].AsUUID(), map["UnderpantsAsset"].AsUUID()); wearables[12] = new AvatarWearable(map["SkirtItem"].AsUUID(), map["SkirtAsset"].AsUUID()); AvatarAppearance appearance = new AvatarAppearance(userID); appearance.Wearables = wearables; appearance.AvatarHeight = (float)map["Height"].AsReal(); AvatarData avatar = new AvatarData(appearance); // Get attachments map = null; try { map = OSDParser.DeserializeJson(response["LLAttachments"].AsString()) as OSDMap; } catch { } if (map != null) { foreach (KeyValuePair<string, OSD> kvp in map) avatar.Data[kvp.Key] = kvp.Value.AsString(); } return avatar; } else { m_log.Warn("[SIMIAN AVATAR CONNECTOR]: Failed to get user appearance for " + userID + ", LLAppearance is missing or invalid"); return null; } } else { m_log.Warn("[SIMIAN AVATAR CONNECTOR]: Failed to get user appearance for " + userID + ": " + response["Message"].AsString()); } return null; } public bool SetAvatar(UUID userID, AvatarData avatar) { m_log.Debug("[SIMIAN AVATAR CONNECTOR]: SetAvatar called for " + userID); if (avatar.AvatarType == 1) // LLAvatar { AvatarAppearance appearance = avatar.ToAvatarAppearance(userID); OSDMap map = new OSDMap(); map["Height"] = OSD.FromReal(appearance.AvatarHeight); map["ShapeItem"] = OSD.FromUUID(appearance.BodyItem); map["ShapeAsset"] = OSD.FromUUID(appearance.BodyAsset); map["SkinItem"] = OSD.FromUUID(appearance.SkinItem); map["SkinAsset"] = OSD.FromUUID(appearance.SkinAsset); map["HairItem"] = OSD.FromUUID(appearance.HairItem); map["HairAsset"] = OSD.FromUUID(appearance.HairAsset); map["EyesItem"] = OSD.FromUUID(appearance.EyesItem); map["EyesAsset"] = OSD.FromUUID(appearance.EyesAsset); map["ShirtItem"] = OSD.FromUUID(appearance.ShirtItem); map["ShirtAsset"] = OSD.FromUUID(appearance.ShirtAsset); map["PantsItem"] = OSD.FromUUID(appearance.PantsItem); map["PantsAsset"] = OSD.FromUUID(appearance.PantsAsset); map["ShoesItem"] = OSD.FromUUID(appearance.ShoesItem); map["ShoesAsset"] = OSD.FromUUID(appearance.ShoesAsset); map["SocksItem"] = OSD.FromUUID(appearance.SocksItem); map["SocksAsset"] = OSD.FromUUID(appearance.SocksAsset); map["JacketItem"] = OSD.FromUUID(appearance.JacketItem); map["JacketAsset"] = OSD.FromUUID(appearance.JacketAsset); map["GlovesItem"] = OSD.FromUUID(appearance.GlovesItem); map["GlovesAsset"] = OSD.FromUUID(appearance.GlovesAsset); map["UndershirtItem"] = OSD.FromUUID(appearance.UnderShirtItem); map["UndershirtAsset"] = OSD.FromUUID(appearance.UnderShirtAsset); map["UnderpantsItem"] = OSD.FromUUID(appearance.UnderPantsItem); map["UnderpantsAsset"] = OSD.FromUUID(appearance.UnderPantsAsset); map["SkirtItem"] = OSD.FromUUID(appearance.SkirtItem); map["SkirtAsset"] = OSD.FromUUID(appearance.SkirtAsset); OSDMap items = new OSDMap(); foreach (KeyValuePair<string, string> kvp in avatar.Data) { if (kvp.Key.StartsWith("_ap_")) items.Add(kvp.Key, OSD.FromString(kvp.Value)); } NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "AddUserData" }, { "UserID", userID.ToString() }, { "LLAppearance", OSDParser.SerializeJsonString(map) }, { "LLAttachments", OSDParser.SerializeJsonString(items) } }; OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs); bool success = response["Success"].AsBoolean(); if (!success) m_log.Warn("[SIMIAN AVATAR CONNECTOR]: Failed saving appearance for " + userID + ": " + response["Message"].AsString()); return success; } else { m_log.Error("[SIMIAN AVATAR CONNECTOR]: Can't save appearance for " + userID + ". Unhandled avatar type " + avatar.AvatarType); return false; } } public bool ResetAvatar(UUID userID) { m_log.Error("[SIMIAN AVATAR CONNECTOR]: ResetAvatar called for " + userID + ", implement this"); return false; } public bool SetItems(UUID userID, string[] names, string[] values) { m_log.Error("[SIMIAN AVATAR CONNECTOR]: SetItems called for " + userID + " with " + names.Length + " names and " + values.Length + " values, implement this"); return false; } public bool RemoveItems(UUID userID, string[] names) { m_log.Error("[SIMIAN AVATAR CONNECTOR]: RemoveItems called for " + userID + " with " + names.Length + " names, implement this"); return false; } #endregion IAvatarService } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Zenject.ReflectionBaking.Mono.Cecil; using Zenject.ReflectionBaking.Mono.Cecil.Cil; using NUnit.Framework; namespace Zenject.ReflectionBaking.Mono.Cecil.Tests { [TestFixture] public class ResolveTests : BaseTestFixture { [Test] public void StringEmpty () { var string_empty = GetReference<Func<string>, FieldReference> ( () => string.Empty); Assert.AreEqual ("System.String System.String::Empty", string_empty.FullName); var definition = string_empty.Resolve (); Assert.IsNotNull (definition); Assert.AreEqual ("System.String System.String::Empty", definition.FullName); Assert.AreEqual ("mscorlib", definition.Module.Assembly.Name.Name); } delegate string GetSubstring (string str, int start, int length); [Test] public void StringSubstring () { var string_substring = GetReference<GetSubstring, MethodReference> ( (s, start, length) => s.Substring (start, length)); var definition = string_substring.Resolve (); Assert.IsNotNull (definition); Assert.AreEqual ("System.String System.String::Substring(System.Int32,System.Int32)", definition.FullName); Assert.AreEqual ("mscorlib", definition.Module.Assembly.Name.Name); } [Test] public void StringLength () { var string_length = GetReference<Func<string, int>, MethodReference> (s => s.Length); var definition = string_length.Resolve (); Assert.IsNotNull (definition); Assert.AreEqual ("get_Length", definition.Name); Assert.AreEqual ("System.String", definition.DeclaringType.FullName); Assert.AreEqual ("mscorlib", definition.Module.Assembly.Name.Name); } [Test] public void ListOfStringAdd () { var list_add = GetReference<Action<List<string>>, MethodReference> ( list => list.Add ("coucou")); Assert.AreEqual ("System.Void System.Collections.Generic.List`1<System.String>::Add(!0)", list_add.FullName); var definition = list_add.Resolve (); Assert.IsNotNull (definition); Assert.AreEqual ("System.Void System.Collections.Generic.List`1::Add(T)", definition.FullName); Assert.AreEqual ("mscorlib", definition.Module.Assembly.Name.Name); } [Test] public void DictionaryOfStringTypeDefinitionTryGetValue () { var try_get_value = GetReference<Func<Dictionary<string, TypeDefinition>, string, bool>, MethodReference> ( (d, s) => { TypeDefinition type; return d.TryGetValue (s, out type); }); Assert.AreEqual ("System.Boolean System.Collections.Generic.Dictionary`2<System.String,Zenject.ReflectionBaking.Mono.Cecil.TypeDefinition>::TryGetValue(!0,!1&)", try_get_value.FullName); var definition = try_get_value.Resolve (); Assert.IsNotNull (definition); Assert.AreEqual ("System.Boolean System.Collections.Generic.Dictionary`2::TryGetValue(TKey,TValue&)", definition.FullName); Assert.AreEqual ("mscorlib", definition.Module.Assembly.Name.Name); } class CustomResolver : DefaultAssemblyResolver { public void Register (AssemblyDefinition assembly) { this.RegisterAssembly (assembly); this.AddSearchDirectory (Path.GetDirectoryName (assembly.MainModule.FullyQualifiedName)); } } [Test] public void ExportedTypeFromModule () { var resolver = new CustomResolver (); var parameters = new ReaderParameters { AssemblyResolver = resolver }; var mma = GetResourceModule ("mma.exe", parameters); resolver.Register (mma.Assembly); var current_module = GetCurrentModule (parameters); var reference = new TypeReference ("Module.A", "Foo", current_module, AssemblyNameReference.Parse (mma.Assembly.FullName), false); var definition = reference.Resolve (); Assert.IsNotNull (definition); Assert.AreEqual ("Module.A.Foo", definition.FullName); } [Test] public void TypeForwarder () { var resolver = new CustomResolver (); var parameters = new ReaderParameters { AssemblyResolver = resolver }; var types = ModuleDefinition.ReadModule ( CompilationService.CompileResource (GetCSharpResourcePath ("CustomAttributes.cs", typeof (ResolveTests).Assembly)), parameters); resolver.Register (types.Assembly); var current_module = GetCurrentModule (parameters); var reference = new TypeReference ("System.Diagnostics", "DebuggableAttribute", current_module, AssemblyNameReference.Parse (types.Assembly.FullName), false); var definition = reference.Resolve (); Assert.IsNotNull (definition); Assert.AreEqual ("System.Diagnostics.DebuggableAttribute", definition.FullName); Assert.AreEqual ("mscorlib", definition.Module.Assembly.Name.Name); } [Test] public void NestedTypeForwarder () { var resolver = new CustomResolver (); var parameters = new ReaderParameters { AssemblyResolver = resolver }; var types = ModuleDefinition.ReadModule ( CompilationService.CompileResource (GetCSharpResourcePath ("CustomAttributes.cs", typeof (ResolveTests).Assembly)), parameters); resolver.Register (types.Assembly); var current_module = GetCurrentModule (parameters); var reference = new TypeReference ("", "DebuggingModes", current_module, null, true); reference.DeclaringType = new TypeReference ("System.Diagnostics", "DebuggableAttribute", current_module, AssemblyNameReference.Parse (types.Assembly.FullName), false); var definition = reference.Resolve (); Assert.IsNotNull (definition); Assert.AreEqual ("System.Diagnostics.DebuggableAttribute/DebuggingModes", definition.FullName); Assert.AreEqual ("mscorlib", definition.Module.Assembly.Name.Name); } [Test] public void RectangularArrayResolveGetMethod () { var get_a_b = GetReference<Func<int[,], int>, MethodReference> (matrix => matrix [2, 2]); Assert.AreEqual ("Get", get_a_b.Name); Assert.IsNotNull (get_a_b.Module); Assert.IsNull (get_a_b.Resolve ()); } [Test] public void ResolveFunctionPointer () { var module = GetResourceModule ("cppcli.dll"); var global = module.GetType ("<Module>"); var field = global.GetField ("__onexitbegin_app_domain"); var type = field.FieldType as PointerType; Assert.IsNotNull(type); var fnptr = type.ElementType as FunctionPointerType; Assert.IsNotNull (fnptr); Assert.IsNull (fnptr.Resolve ()); } [Test] public void ResolveGenericParameter () { var collection = typeof (Mono.Collections.Generic.Collection<>).ToDefinition (); var parameter = collection.GenericParameters [0]; Assert.IsNotNull (parameter); Assert.IsNull (parameter.Resolve ()); } [Test] public void ResolveNullVersionAssembly () { var reference = AssemblyNameReference.Parse ("System.Core"); reference.Version = null; var resolver = new DefaultAssemblyResolver (); Assert.IsNotNull (resolver.Resolve (reference)); } [Test] public void ResolvePortableClassLibraryReference () { var resolver = new DefaultAssemblyResolver (); var parameters = new ReaderParameters { AssemblyResolver = resolver }; var pcl = GetResourceModule ("PortableClassLibrary.dll", parameters); foreach (var reference in pcl.AssemblyReferences) { Assert.IsTrue (reference.IsRetargetable); var assembly = resolver.Resolve (reference); Assert.IsNotNull (assembly); Assert.AreEqual (typeof (object).Assembly.GetName ().Version, assembly.Name.Version); } } TRet GetReference<TDel, TRet> (TDel code) { var @delegate = code as Delegate; if (@delegate == null) throw new InvalidOperationException (); var reference = (TRet) GetReturnee (GetMethodFromDelegate (@delegate)); Assert.IsNotNull (reference); return reference; } static object GetReturnee (MethodDefinition method) { Assert.IsTrue (method.HasBody); var instruction = method.Body.Instructions [method.Body.Instructions.Count - 1]; Assert.IsNotNull (instruction); while (instruction != null) { var opcode = instruction.OpCode; switch (opcode.OperandType) { case OperandType.InlineField: case OperandType.InlineTok: case OperandType.InlineType: case OperandType.InlineMethod: return instruction.Operand; default: instruction = instruction.Previous; break; } } throw new InvalidOperationException (); } MethodDefinition GetMethodFromDelegate (Delegate @delegate) { var method = @delegate.Method; var type = (TypeDefinition) TypeParser.ParseType (GetCurrentModule (), method.DeclaringType.FullName); Assert.IsNotNull (type); return type.Methods.Where (m => m.Name == method.Name).First (); } } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ namespace Adxstudio.Xrm.Cms { using System; using System.Web; using System.Linq; using Microsoft.Xrm.Client; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Client; public class AdDataAdapter : IAdDataAdapter { public const string AdRoute = "Ad"; public const string PlacementRoute = "AdPlacement"; public const string RandomAdRoute = "RandomAd"; public AdDataAdapter(IDataAdapterDependencies dependencies) { if (dependencies == null) { throw new ArgumentNullException("dependencies"); } Dependencies = dependencies; } protected IDataAdapterDependencies Dependencies { get; private set; } public IAd SelectAd(Guid adId) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Start: {0}", adId)); var ad = SelectAd(e => e.GetAttributeValue<Guid>("adx_adid") == adId); if (ad == null) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Not Found"); } ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("End: {0}", adId)); return ad; } public IAd SelectAd(string adName) { if (string.IsNullOrEmpty(adName)) { return null; } ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Start"); var ad = SelectAd(e => e.GetAttributeValue<string>("adx_name") == adName); if (ad == null) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Not Found"); } ADXTrace.Instance.TraceInfo(TraceCategory.Application, "End"); return ad; } protected virtual IAd SelectAd(Predicate<Entity> match) { var serviceContext = Dependencies.GetServiceContext(); var website = Dependencies.GetWebsite(); var publishingStateAccessProvider = new PublishingStateAccessProvider(Dependencies.GetRequestContext().HttpContext); // Bulk-load all ad entities into cache. var allEntities = serviceContext.CreateQuery("adx_ad") .Where(e => e.GetAttributeValue<EntityReference>("adx_websiteid") == website) .ToArray(); var entity = allEntities.FirstOrDefault(e => match(e) && IsActive(e) && publishingStateAccessProvider.TryAssert(serviceContext, e)); if (entity == null) { return null; } var ad = CreateAd(entity, serviceContext); return ad; } public IAdPlacement SelectAdPlacement(Guid adPlacementId) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Start: {0}", adPlacementId)); var adPlacement = SelectAdPlacement(e => e.GetAttributeValue<Guid>("adx_adplacementid") == adPlacementId); if (adPlacement == null) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Not Found"); } ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("End: {0}", adPlacementId)); return adPlacement; } public IAdPlacement SelectAdPlacement(string adPlacementName) { if (string.IsNullOrEmpty(adPlacementName)) { return null; } ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Start"); var adPlacement = SelectAdPlacement(e => e.GetAttributeValue<string>("adx_name") == adPlacementName); if (adPlacement == null) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Not Found"); } ADXTrace.Instance.TraceInfo(TraceCategory.Application, "End"); return adPlacement; } protected virtual IAdPlacement SelectAdPlacement(Predicate<Entity> match) { var serviceContext = Dependencies.GetServiceContext(); var website = Dependencies.GetWebsite(); // Bulk-load all ad placement entities into cache. var allEntities = serviceContext.CreateQuery("adx_adplacement") .Where(e => e.GetAttributeValue<EntityReference>("adx_websiteid") == website) .ToArray(); var entity = allEntities.FirstOrDefault(e => match(e) && IsActive(e)); if (entity == null) { return null; } var publishingStateAccessProvider = new PublishingStateAccessProvider(Dependencies.GetRequestContext().HttpContext); var ads = entity.GetRelatedEntities(serviceContext, new Relationship("adx_adplacement_ad")) .Where(e => publishingStateAccessProvider.TryAssert(serviceContext, e)) .Where(IsActive) .Select(e => CreateAd(e, serviceContext)); return new AdPlacement(entity, ads); } private static IAd CreateAd(Entity entity, OrganizationServiceContext serviceContext) { var note = entity.GetRelatedEntities(serviceContext, "adx_ad_Annotations").FirstOrDefault(); return new Ad(entity, note); } public IAd SelectRandomAd(Guid adPlacementId) { var placement = SelectAdPlacement(adPlacementId); return placement == null ? null : SelectRandomAd(placement); } public IAd SelectRandomAd(string adPlacementName) { var placement = SelectAdPlacement(adPlacementName); return placement == null ? null : SelectRandomAd(placement); } protected IAd SelectRandomAd(IAdPlacement placement) { if (placement == null) { return null; } var array = placement.Ads.ToArray(); if (array.Length == 0) return null; var random = new Random(DateTime.Now.Millisecond); return array[random.Next(0, array.Length)]; } private static bool IsActive(Entity entity) { if (entity == null) { return false; } var statecode = entity.GetAttributeValue<OptionSetValue>("statecode"); var expirationDate = entity.GetAttributeValue<DateTime?>("adx_expirationdate"); return statecode != null && statecode.Value == 0 && (expirationDate == null || expirationDate > DateTime.UtcNow); } } }
// SharpMath - C# Mathematical Library // Copyright (c) 2014 Morten Bakkedal // This code is published under the MIT License. using System; using System.Diagnostics; namespace SharpMath.Optimization.DualNumbers { /// <summary> /// This class represents a function value and its first and second partial derivatives at a given point. Several standard /// mathematical operations are defined. The class is immutable. /// </summary> [Serializable] [DebuggerStepThrough] [DebuggerDisplay("{DebuggerDisplay}")] public sealed class DualNumber { private static DualNumber zero; private double value; private int n; private double[] gradientArray, hessianArray; [NonSerialized] private Vector gradient; [NonSerialized] private Matrix hessian; static DualNumber() { // Used very often (e.g. in matrix initialization). zero = new DualNumber(0.0); } /// <summary> /// A new <see cref="DualNumber" /> with the specified value, and zero first and second partial derivatives. Use the /// implicit conversion operator from <see cref="double" /> instead of using this constructor directly. /// </summary> public DualNumber(double value) : this(value, null) { } /// <summary> /// A new <see cref="DualNumber" /> with the specified value and first partial derivatives, and zero second partial derivatives. /// </summary> public DualNumber(double value, Vector gradient) : this(value, gradient, null) { } /// <summary> /// A new <see cref="DualNumber" /> with the specified value and first and second partial derivatives. /// </summary> public DualNumber(double value, Vector gradient, Matrix hessian) { this.value = value; this.gradient = gradient; this.hessian = hessian; if (gradient != null) { n = gradient.Length; gradientArray = gradient.ToArray(); } if (hessian != null) { if (gradient == null) { throw new ArgumentException("The gradient must be specified if the Hessian is specified."); } if (hessian.Rows != n || hessian.Columns != n) { throw new ArgumentException("Inconsistent number of derivatives."); } // Since the Hessian is symmetric we only need to store the upper triangular part of it. Use a // one dimensional array until the matrix is requested (if ever). Doing it this way is almost // a factor of 10 faster than using naive matrix operations. hessianArray = new double[HessianSize(n)]; for (int i = 0, k = 0; i < n; i++) { for (int j = i; j < n; j++, k++) { if (hessian[i, j] != hessian[j, i] && !(double.IsNaN(hessian[i, j]) && double.IsNaN(hessian[j, i])) && !(double.IsPositiveInfinity(hessian[i, j]) && double.IsPositiveInfinity(hessian[j, i])) && !(double.IsNegativeInfinity(hessian[i, j]) && double.IsNegativeInfinity(hessian[j, i]))) { throw new ArgumentException("The Hessian must be symmetric."); } hessianArray[k] = hessian[i, j]; } } } } /// <summary> /// A new <see cref="DualNumber" /> with the specified value and first and second partial derivatives using /// the compact internal representation of the Hessian. /// </summary> public DualNumber(double value, double[] gradientArray, double[] hessianArray) { this.value = value; if (gradientArray != null) { n = gradientArray.Length; this.gradientArray = (double[])gradientArray.Clone(); } if (hessianArray != null) { if (gradientArray == null) { throw new ArgumentException("The gradient must be specified if the Hessian is specified."); } if (hessianArray.Length != HessianSize(n)) { throw new ArgumentException("Inconsistent number of derivatives."); } this.hessianArray = (double[])hessianArray.Clone(); } } /// <summary> /// Perform the unary operation h(x)=g(f(x)). Using the chain rule we're able to compute /// h(x), h'(x), and h''(x). The value and the first and second derivative of the outer /// function (the unary operation) must be specified. /// </summary> /// <param name="f">The inner function f.</param> /// <param name="g">g(f(x)).</param> /// <param name="g1">g'(f(x)).</param> /// <param name="g11">g''(f(x)).</param> public DualNumber(DualNumber f, double g, double g1, double g11) { value = g; if (f.gradientArray != null) { n = f.n; gradientArray = new double[n]; if (g1 != 0.0) { for (int i = 0; i < n; i++) { gradientArray[i] += g1 * f.gradientArray[i]; } } if (f.hessianArray != null || g11 != 0.0) { hessianArray = new double[HessianSize(n)]; if (g1 != 0.0 && f.hessianArray != null) { for (int i = 0, k = 0; i < n; i++) { for (int j = i; j < n; j++, k++) { hessianArray[k] += g1 * f.hessianArray[k]; } } } if (g11 != 0.0) { for (int i = 0, k = 0; i < n; i++) { for (int j = i; j < n; j++, k++) { hessianArray[k] += g11 * f.gradientArray[i] * f.gradientArray[j]; } } } } } } /// <summary> /// Perform the binary operation h(x)=g(f_1(x),f_2(x)). Using the chain rule we're able to compute /// h(x), h'(x), and h''(x). The value and the first and second partial derivatives of the outer /// function (the binary operation) must be specified. /// </summary> /// <param name="f1">The first inner function f_1 (left of the binary operator).</param> /// <param name="f2">The second inner function f_2 (right of the binary operator).</param> /// <param name="g">g(f_1(x),f_2(x)).</param> /// <param name="g1">The partial derivative $\frac{\partial g}{\partial x_1}(f_1(x),f_2(x))$.</param> /// <param name="g2">The partial derivative $\frac{\partial g}{\partial x_2}(f_1(x),f_2(x))$.</param> /// <param name="g11">The partial derivative $\frac{\partial^2g}{\partial x_1^2}(f_1(x),f_2(x))$.</param> /// <param name="g12">The partial derivative $\frac{\partial^2g}{\partial x_1\partial x_2}(f_1(x),f_2(x))$.</param> /// <param name="g22">The partial derivative $\frac{\partial^2g}{\partial x_2^2}(f_1(x),f_2(x))$.</param> public DualNumber(DualNumber f1, DualNumber f2, double g, double g1, double g2, double g11, double g12, double g22) { value = g; if (f1.gradientArray != null || f2.gradientArray != null) { if (f1.gradientArray != null && f2.gradientArray != null && f1.n != f2.n) { throw new ArgumentException("Inconsistent number of derivatives."); } // One of the counters may be zero if the corresponding DualNumber is a constant. n = Math.Max(f1.n, f2.n); gradientArray = new double[n]; if (g1 != 0.0 && f1.gradientArray != null) { for (int i = 0; i < n; i++) { gradientArray[i] += g1 * f1.gradientArray[i]; } } if (g2 != 0.0 && f2.gradientArray != null) { for (int i = 0; i < n; i++) { gradientArray[i] += g2 * f2.gradientArray[i]; } } if (f1.hessianArray != null || f2.hessianArray != null || g11 != 0.0 || g12 != 0.0 || g22 != 0.0) { hessianArray = new double[HessianSize(n)]; if (g1 != 0.0 && f1.hessianArray != null) { for (int i = 0, k = 0; i < n; i++) { for (int j = i; j < n; j++, k++) { hessianArray[k] += g1 * f1.hessianArray[k]; } } } if (g2 != 0.0 && f2.hessianArray != null) { for (int i = 0, k = 0; i < n; i++) { for (int j = i; j < n; j++, k++) { hessianArray[k] += g2 * f2.hessianArray[k]; } } } if (g11 != 0.0 && f1.gradientArray != null) { for (int i = 0, k = 0; i < n; i++) { for (int j = i; j < n; j++, k++) { hessianArray[k] += g11 * f1.gradientArray[i] * f1.gradientArray[j]; } } } if (g22 != 0.0 && f2.gradientArray != null) { for (int i = 0, k = 0; i < n; i++) { for (int j = i; j < n; j++, k++) { hessianArray[k] += g22 * f2.gradientArray[i] * f2.gradientArray[j]; } } } if (g12 != 0.0 && f1.gradientArray != null && f2.gradientArray != null) { for (int i = 0, k = 0; i < n; i++) { for (int j = i; j < n; j++, k++) { hessianArray[k] += g12 * (f1.gradientArray[i] * f2.gradientArray[j] + f2.gradientArray[i] * f1.gradientArray[j]); } } } } } } public override string ToString() { string s = string.Format("Value = {0}", value); if (gradientArray != null) { s += string.Format(", Gradient = {0}", Gradient); if (hessianArray != null) { s += string.Format(", Hessian = {0}", Hessian); } } return s; } public double[] ToGradientArray() { if (gradientArray == null) { return null; } return (double[])gradientArray.Clone(); } public double[] ToHessianArray() { if (hessianArray == null) { return null; } return (double[])hessianArray.Clone(); } /// <summary> /// Size of the linearized Hessian array given the size of the gradient. /// </summary> public static int HessianSize(int n) { if (n < 0) { throw new ArgumentOutOfRangeException(); } return n * (n + 1) / 2; } public static int HessianIndex(int n, int i, int j) { if (n < 0) { throw new ArgumentOutOfRangeException(); } if (i > j) { return HessianIndex(n, j, i); } // Now i <= j as required. if (i < 0 || j >= n) { throw new ArgumentOutOfRangeException(); } // This is the same as: // return HessianSize(n) - HessianSize(n - i) + j - i; return i * (1 - i) / 2 + i * n + j - i; } public static DualNumber Basis(double value, int n, int i) { return new DualNumber(value, Vector.Basis(n, i), Matrix.Zero(n, n)); } public static DualNumber Exp(DualNumber f) { double g = Math.Exp(f.value); double g1 = g; double g11 = g; return new DualNumber(f, g, g1, g11); } public static DualNumber Log(DualNumber f) { double g = Math.Log(f.value); double g1 = 1.0 / f.value; double g11 = -g1 / f.value; return new DualNumber(f, g, g1, g11); } public static DualNumber Sqr(DualNumber f) { return new DualNumber(f, f.value * f.value, 2.0 * f.value, 2.0); } public static DualNumber Sqrt(DualNumber f) { double g = Math.Sqrt(f.value); double g1 = 0.5 / g; double g11 = -0.5 * g1 / f.value; return new DualNumber(f, g, g1, g11); } public static DualNumber Pow(DualNumber f, double a) { double g = Math.Pow(f.value, a); double g1 = a * Math.Pow(f.value, a - 1.0); double g11 = a * (a - 1.0) * Math.Pow(f.value, a - 2.0); return new DualNumber(f, g, g1, g11); } public static DualNumber Pow(double a, DualNumber f) { double g = Math.Pow(a, f.value); double c = Math.Log(a); double g1 = c * g; double g11 = c * g1; return new DualNumber(f, g, g1, g11); } public static DualNumber Pow(DualNumber f1, DualNumber f2) { double g = Math.Pow(f1.value, f2.value); double c1 = Math.Pow(f1.value, f2.value - 1.0); double g1 = f2.value * c1; double g11 = f2.value * (f2.value - 1.0) * Math.Pow(f1.value, f2.value - 2.0); double c2 = Math.Log(f1.value); double g2 = c2 * g; double g22 = c2 * g2; double g12 = c1 * (1.0 + c2 * f2.value); return new DualNumber(f1, f2, g, g1, g2, g11, g12, g22); } public static DualNumber Cos(DualNumber f) { double g = Math.Cos(f.value); double g1 = -Math.Sin(f.value); double g11 = -g; return new DualNumber(f, g, g1, g11); } public static DualNumber Sin(DualNumber f) { double g = Math.Sin(f.value); double g1 = Math.Cos(f.value); double g11 = -g; return new DualNumber(f, g, g1, g11); } public static DualNumber Min(DualNumber f, DualNumber g) { // Like the step function. return f.Value < g.Value ? f : g; } public static DualNumber Max(DualNumber f, DualNumber g) { // Like the step function. return f.Value > g.Value ? f : g; } public static implicit operator DualNumber(double a) { if (a == 0.0) { return zero; } return new DualNumber(a); } public static DualNumber operator +(DualNumber f1, DualNumber f2) { return new DualNumber(f1, f2, f1.value + f2.value, 1.0, 1.0, 0.0, 0.0, 0.0); } public static DualNumber operator +(DualNumber f, double a) { return new DualNumber(f, f.value + a, 1.0, 0.0); } public static DualNumber operator +(double a, DualNumber f) { return new DualNumber(f, a + f.value, 1.0, 0.0); } public static DualNumber operator -(DualNumber f) { return new DualNumber(f, -f.value, -1.0, 0.0); } public static DualNumber operator -(DualNumber f1, DualNumber f2) { return new DualNumber(f1, f2, f1.value - f2.value, 1.0, -1.0, 0.0, 0.0, 0.0); } public static DualNumber operator -(DualNumber f, double a) { return new DualNumber(f, f.value - a, 1.0, 0.0); } public static DualNumber operator -(double a, DualNumber f) { return new DualNumber(f, a - f.value, -1.0, 0.0); } public static DualNumber operator *(DualNumber f1, DualNumber f2) { return new DualNumber(f1, f2, f1.value * f2.value, f2.value, f1.value, 0.0, 1.0, 0.0); } public static DualNumber operator *(DualNumber f, double a) { return new DualNumber(f, f.value * a, a, 0.0); } public static DualNumber operator *(double a, DualNumber f) { return new DualNumber(f, a * f.value, a, 0.0); } public static DualNumber operator /(DualNumber f1, DualNumber f2) { double g = f1.value / f2.value; double g1 = 1.0 / f2.value; double g2 = -g / f2.value; double g11 = 0.0; double g12 = -g1 / f2.value; double g22 = -2.0 * g2 / f2.value; return new DualNumber(f1, f2, g, g1, g2, g11, g12, g22); } public static DualNumber operator /(DualNumber f, double a) { return new DualNumber(f, f.value / a, 1.0 / a, 0.0); } public static DualNumber operator /(double a, DualNumber f) { double g = a / f.value; double g1 = -g / f.value; double g11 = -2.0 * g1 / f.value; return new DualNumber(f, g, g1, g11); } /// <summary> /// Number of variables. /// </summary> public int N { get { return n; } } /// <summary> /// The numerical value of the <see cref="DualNumber" />, i.e. the pure value without derivatives. /// </summary> public double Value { get { return value; } } /// <summary> /// A <see cref="Vector" /> representation of the gradient. /// </summary> public Vector Gradient { get { if (gradient == null && gradientArray != null) { gradient = new Vector(gradientArray); } return gradient; } } /// <summary> /// A <see cref="Matrix " /> representation of the Hessian. The Hessian is converted from the internal /// linearized representation as returned by <see cref="ToHessianArray" />. /// </summary> public Matrix Hessian { get { if (hessian == null && hessianArray != null) { double[,] a = new double[n, n]; for (int i = 0, k = 0; i < n; i++) { for (int j = i; j < n; j++, k++) { a[i, j] = a[j, i] = hessianArray[k]; } } hessian = new Matrix(a); } return hessian; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string DebuggerDisplay { get { return ToString(); } } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Tests.TestObjects; using Newtonsoft.Json.Utilities; #if !NETFX_CORE using NUnit.Framework; #else using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; #endif using Newtonsoft.Json.Schema; using System.IO; using Newtonsoft.Json.Linq; using System.Text; using Extensions = Newtonsoft.Json.Schema.Extensions; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Newtonsoft.Json.Tests.Schema { [TestFixture] public class JsonSchemaGeneratorTests : TestFixtureBase { [Test] public void Generate_GenericDictionary() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); JsonSchema schema = generator.Generate(typeof(Dictionary<string, List<string>>)); string json = schema.ToString(); Assert.AreEqual(@"{ ""type"": ""object"", ""additionalProperties"": { ""type"": [ ""array"", ""null"" ], ""items"": { ""type"": [ ""string"", ""null"" ] } } }", json); Dictionary<string, List<string>> value = new Dictionary<string, List<string>> { { "HasValue", new List<string>() { "first", "second", null } }, { "NoValue", null } }; string valueJson = JsonConvert.SerializeObject(value, Formatting.Indented); JObject o = JObject.Parse(valueJson); Assert.IsTrue(o.IsValid(schema)); } #if !(NETFX_CORE || PORTABLE || PORTABLE40) [Test] public void Generate_DefaultValueAttributeTestClass() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); JsonSchema schema = generator.Generate(typeof(DefaultValueAttributeTestClass)); string json = schema.ToString(); Assert.AreEqual(@"{ ""description"": ""DefaultValueAttributeTestClass description!"", ""type"": ""object"", ""additionalProperties"": false, ""properties"": { ""TestField1"": { ""required"": true, ""type"": ""integer"", ""default"": 21 }, ""TestProperty1"": { ""required"": true, ""type"": [ ""string"", ""null"" ], ""default"": ""TestProperty1Value"" } } }", json); } #endif [Test] public void Generate_Person() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); JsonSchema schema = generator.Generate(typeof(Person)); string json = schema.ToString(); Assert.AreEqual(@"{ ""id"": ""Person"", ""title"": ""Title!"", ""description"": ""JsonObjectAttribute description!"", ""type"": ""object"", ""properties"": { ""Name"": { ""required"": true, ""type"": [ ""string"", ""null"" ] }, ""BirthDate"": { ""required"": true, ""type"": ""string"" }, ""LastModified"": { ""required"": true, ""type"": ""string"" } } }", json); } [Test] public void Generate_UserNullable() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); JsonSchema schema = generator.Generate(typeof(UserNullable)); string json = schema.ToString(); Assert.AreEqual(@"{ ""type"": ""object"", ""properties"": { ""Id"": { ""required"": true, ""type"": ""string"" }, ""FName"": { ""required"": true, ""type"": [ ""string"", ""null"" ] }, ""LName"": { ""required"": true, ""type"": [ ""string"", ""null"" ] }, ""RoleId"": { ""required"": true, ""type"": ""integer"" }, ""NullableRoleId"": { ""required"": true, ""type"": [ ""integer"", ""null"" ] }, ""NullRoleId"": { ""required"": true, ""type"": [ ""integer"", ""null"" ] }, ""Active"": { ""required"": true, ""type"": [ ""boolean"", ""null"" ] } } }", json); } [Test] public void Generate_RequiredMembersClass() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); JsonSchema schema = generator.Generate(typeof(RequiredMembersClass)); Assert.AreEqual(JsonSchemaType.String, schema.Properties["FirstName"].Type); Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Null, schema.Properties["MiddleName"].Type); Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Null, schema.Properties["LastName"].Type); Assert.AreEqual(JsonSchemaType.String, schema.Properties["BirthDate"].Type); } [Test] public void Generate_Store() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); JsonSchema schema = generator.Generate(typeof(Store)); Assert.AreEqual(11, schema.Properties.Count); JsonSchema productArraySchema = schema.Properties["product"]; JsonSchema productSchema = productArraySchema.Items[0]; Assert.AreEqual(4, productSchema.Properties.Count); } [Test] public void MissingSchemaIdHandlingTest() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); JsonSchema schema = generator.Generate(typeof(Store)); Assert.AreEqual(null, schema.Id); generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName; schema = generator.Generate(typeof(Store)); Assert.AreEqual(typeof(Store).FullName, schema.Id); generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseAssemblyQualifiedName; schema = generator.Generate(typeof(Store)); Assert.AreEqual(typeof(Store).AssemblyQualifiedName, schema.Id); } [Test] public void CircularReferenceError() { ExceptionAssert.Throws<Exception>(@"Unresolved circular reference for type 'Newtonsoft.Json.Tests.TestObjects.CircularReferenceClass'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.", () => { JsonSchemaGenerator generator = new JsonSchemaGenerator(); generator.Generate(typeof(CircularReferenceClass)); }); } [Test] public void CircularReferenceWithTypeNameId() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName; JsonSchema schema = generator.Generate(typeof(CircularReferenceClass), true); Assert.AreEqual(JsonSchemaType.String, schema.Properties["Name"].Type); Assert.AreEqual(typeof(CircularReferenceClass).FullName, schema.Id); Assert.AreEqual(JsonSchemaType.Object | JsonSchemaType.Null, schema.Properties["Child"].Type); Assert.AreEqual(schema, schema.Properties["Child"]); } [Test] public void CircularReferenceWithExplicitId() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); JsonSchema schema = generator.Generate(typeof(CircularReferenceWithIdClass)); Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Null, schema.Properties["Name"].Type); Assert.AreEqual("MyExplicitId", schema.Id); Assert.AreEqual(JsonSchemaType.Object | JsonSchemaType.Null, schema.Properties["Child"].Type); Assert.AreEqual(schema, schema.Properties["Child"]); } [Test] public void GenerateSchemaForType() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName; JsonSchema schema = generator.Generate(typeof(Type)); Assert.AreEqual(JsonSchemaType.String, schema.Type); string json = JsonConvert.SerializeObject(typeof(Version), Formatting.Indented); JValue v = new JValue(json); Assert.IsTrue(v.IsValid(schema)); } #if !(NETFX_CORE || PORTABLE || PORTABLE40) [Test] public void GenerateSchemaForISerializable() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName; JsonSchema schema = generator.Generate(typeof(Exception)); Assert.AreEqual(JsonSchemaType.Object, schema.Type); Assert.AreEqual(true, schema.AllowAdditionalProperties); Assert.AreEqual(null, schema.Properties); } #endif #if !(NETFX_CORE || PORTABLE || PORTABLE40) [Test] public void GenerateSchemaForDBNull() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName; JsonSchema schema = generator.Generate(typeof(DBNull)); Assert.AreEqual(JsonSchemaType.Null, schema.Type); } public class CustomDirectoryInfoMapper : DefaultContractResolver { public CustomDirectoryInfoMapper() : base(true) { } protected override JsonContract CreateContract(Type objectType) { if (objectType == typeof(DirectoryInfo)) return base.CreateObjectContract(objectType); return base.CreateContract(objectType); } protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization) { IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization); JsonPropertyCollection c = new JsonPropertyCollection(type); c.AddRange(properties.Where(m => m.PropertyName != "Root")); return c; } } [Test] public void GenerateSchemaForDirectoryInfo() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName; generator.ContractResolver = new CustomDirectoryInfoMapper { #if !(NETFX_CORE || PORTABLE) IgnoreSerializableAttribute = true #endif }; JsonSchema schema = generator.Generate(typeof(DirectoryInfo), true); string json = schema.ToString(); Assert.AreEqual(@"{ ""id"": ""System.IO.DirectoryInfo"", ""required"": true, ""type"": [ ""object"", ""null"" ], ""additionalProperties"": false, ""properties"": { ""Name"": { ""required"": true, ""type"": [ ""string"", ""null"" ] }, ""Parent"": { ""$ref"": ""System.IO.DirectoryInfo"" }, ""Exists"": { ""required"": true, ""type"": ""boolean"" }, ""FullName"": { ""required"": true, ""type"": [ ""string"", ""null"" ] }, ""Extension"": { ""required"": true, ""type"": [ ""string"", ""null"" ] }, ""CreationTime"": { ""required"": true, ""type"": ""string"" }, ""CreationTimeUtc"": { ""required"": true, ""type"": ""string"" }, ""LastAccessTime"": { ""required"": true, ""type"": ""string"" }, ""LastAccessTimeUtc"": { ""required"": true, ""type"": ""string"" }, ""LastWriteTime"": { ""required"": true, ""type"": ""string"" }, ""LastWriteTimeUtc"": { ""required"": true, ""type"": ""string"" }, ""Attributes"": { ""required"": true, ""type"": ""integer"" } } }", json); DirectoryInfo temp = new DirectoryInfo(@"c:\temp"); JTokenWriter jsonWriter = new JTokenWriter(); JsonSerializer serializer = new JsonSerializer(); serializer.Converters.Add(new IsoDateTimeConverter()); serializer.ContractResolver = new CustomDirectoryInfoMapper { #if !(NETFX_CORE || PORTABLE) IgnoreSerializableInterface = true #endif }; serializer.Serialize(jsonWriter, temp); List<string> errors = new List<string>(); jsonWriter.Token.Validate(schema, (sender, args) => errors.Add(args.Message)); Assert.AreEqual(0, errors.Count); } #endif [Test] public void GenerateSchemaCamelCase() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName; generator.ContractResolver = new CamelCasePropertyNamesContractResolver() { #if !(NETFX_CORE || PORTABLE || PORTABLE40) IgnoreSerializableAttribute = true #endif }; JsonSchema schema = generator.Generate(typeof(Version), true); string json = schema.ToString(); Assert.AreEqual(@"{ ""id"": ""System.Version"", ""type"": [ ""object"", ""null"" ], ""additionalProperties"": false, ""properties"": { ""major"": { ""required"": true, ""type"": ""integer"" }, ""minor"": { ""required"": true, ""type"": ""integer"" }, ""build"": { ""required"": true, ""type"": ""integer"" }, ""revision"": { ""required"": true, ""type"": ""integer"" }, ""majorRevision"": { ""required"": true, ""type"": ""integer"" }, ""minorRevision"": { ""required"": true, ""type"": ""integer"" } } }", json); } #if !(NETFX_CORE || PORTABLE || PORTABLE40) [Test] public void GenerateSchemaSerializable() { JsonSchemaGenerator generator = new JsonSchemaGenerator(); generator.ContractResolver = new DefaultContractResolver { IgnoreSerializableAttribute = false }; generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName; JsonSchema schema = generator.Generate(typeof(Version), true); string json = schema.ToString(); Assert.AreEqual(@"{ ""id"": ""System.Version"", ""type"": [ ""object"", ""null"" ], ""additionalProperties"": false, ""properties"": { ""_Major"": { ""required"": true, ""type"": ""integer"" }, ""_Minor"": { ""required"": true, ""type"": ""integer"" }, ""_Build"": { ""required"": true, ""type"": ""integer"" }, ""_Revision"": { ""required"": true, ""type"": ""integer"" } } }", json); JTokenWriter jsonWriter = new JTokenWriter(); JsonSerializer serializer = new JsonSerializer(); serializer.ContractResolver = new DefaultContractResolver { IgnoreSerializableAttribute = false }; serializer.Serialize(jsonWriter, new Version(1, 2, 3, 4)); List<string> errors = new List<string>(); jsonWriter.Token.Validate(schema, (sender, args) => errors.Add(args.Message)); Assert.AreEqual(0, errors.Count); Assert.AreEqual(@"{ ""_Major"": 1, ""_Minor"": 2, ""_Build"": 3, ""_Revision"": 4 }", jsonWriter.Token.ToString()); Version version = jsonWriter.Token.ToObject<Version>(serializer); Assert.AreEqual(1, version.Major); Assert.AreEqual(2, version.Minor); Assert.AreEqual(3, version.Build); Assert.AreEqual(4, version.Revision); } #endif public enum SortTypeFlag { No = 0, Asc = 1, Desc = -1 } public class X { public SortTypeFlag x; } [Test] public void GenerateSchemaWithNegativeEnum() { JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator(); JsonSchema schema = jsonSchemaGenerator.Generate(typeof(X)); string json = schema.ToString(); Assert.AreEqual(@"{ ""type"": ""object"", ""properties"": { ""x"": { ""required"": true, ""type"": ""integer"", ""enum"": [ 0, 1, -1 ] } } }", json); } [Test] public void CircularCollectionReferences() { Type type = typeof(Workspace); JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator(); jsonSchemaGenerator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName; JsonSchema jsonSchema = jsonSchemaGenerator.Generate(type); // should succeed Assert.IsNotNull(jsonSchema); } [Test] public void CircularReferenceWithMixedRequires() { JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator(); jsonSchemaGenerator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName; JsonSchema jsonSchema = jsonSchemaGenerator.Generate(typeof(CircularReferenceClass)); string json = jsonSchema.ToString(); Assert.AreEqual(@"{ ""id"": ""Newtonsoft.Json.Tests.TestObjects.CircularReferenceClass"", ""type"": [ ""object"", ""null"" ], ""properties"": { ""Name"": { ""required"": true, ""type"": ""string"" }, ""Child"": { ""$ref"": ""Newtonsoft.Json.Tests.TestObjects.CircularReferenceClass"" } } }", json); } [Test] public void JsonPropertyWithHandlingValues() { JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator(); jsonSchemaGenerator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName; JsonSchema jsonSchema = jsonSchemaGenerator.Generate(typeof(JsonPropertyWithHandlingValues)); string json = jsonSchema.ToString(); Assert.AreEqual(@"{ ""id"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues"", ""required"": true, ""type"": [ ""object"", ""null"" ], ""properties"": { ""DefaultValueHandlingIgnoreProperty"": { ""type"": [ ""string"", ""null"" ], ""default"": ""Default!"" }, ""DefaultValueHandlingIncludeProperty"": { ""required"": true, ""type"": [ ""string"", ""null"" ], ""default"": ""Default!"" }, ""DefaultValueHandlingPopulateProperty"": { ""required"": true, ""type"": [ ""string"", ""null"" ], ""default"": ""Default!"" }, ""DefaultValueHandlingIgnoreAndPopulateProperty"": { ""type"": [ ""string"", ""null"" ], ""default"": ""Default!"" }, ""NullValueHandlingIgnoreProperty"": { ""type"": [ ""string"", ""null"" ] }, ""NullValueHandlingIncludeProperty"": { ""required"": true, ""type"": [ ""string"", ""null"" ] }, ""ReferenceLoopHandlingErrorProperty"": { ""$ref"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues"" }, ""ReferenceLoopHandlingIgnoreProperty"": { ""$ref"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues"" }, ""ReferenceLoopHandlingSerializeProperty"": { ""$ref"": ""Newtonsoft.Json.Tests.TestObjects.JsonPropertyWithHandlingValues"" } } }", json); } [Test] public void GenerateForNullableInt32() { JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator(); JsonSchema jsonSchema = jsonSchemaGenerator.Generate(typeof(NullableInt32TestClass)); string json = jsonSchema.ToString(); Assert.AreEqual(@"{ ""type"": ""object"", ""properties"": { ""Value"": { ""required"": true, ""type"": [ ""integer"", ""null"" ] } } }", json); } [JsonConverter(typeof(StringEnumConverter))] public enum SortTypeFlagAsString { No = 0, Asc = 1, Desc = -1 } public class Y { public SortTypeFlagAsString y; } [Test] [Ignore] public void GenerateSchemaWithStringEnum() { JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator(); JsonSchema schema = jsonSchemaGenerator.Generate(typeof(Y)); string json = schema.ToString(); // NOTE: This fails because the enum is serialized as an integer and not a string. // NOTE: There should exist a way to serialize the enum as lowercase strings. Assert.AreEqual(@"{ ""type"": ""object"", ""properties"": { ""y"": { ""required"": true, ""type"": ""string"", ""enum"": [ ""no"", ""asc"", ""desc"" ] } } }", json); } } public class NullableInt32TestClass { public int? Value { get; set; } } public class DMDSLBase { public String Comment; } public class Workspace : DMDSLBase { public ControlFlowItemCollection Jobs = new ControlFlowItemCollection(); } public class ControlFlowItemBase : DMDSLBase { public String Name; } public class ControlFlowItem : ControlFlowItemBase //A Job { public TaskCollection Tasks = new TaskCollection(); public ContainerCollection Containers = new ContainerCollection(); } public class ControlFlowItemCollection : List<ControlFlowItem> { } public class Task : ControlFlowItemBase { public DataFlowTaskCollection DataFlowTasks = new DataFlowTaskCollection(); public BulkInsertTaskCollection BulkInsertTask = new BulkInsertTaskCollection(); } public class TaskCollection : List<Task> { } public class Container : ControlFlowItemBase { public ControlFlowItemCollection ContainerJobs = new ControlFlowItemCollection(); } public class ContainerCollection : List<Container> { } public class DataFlowTask_DSL : ControlFlowItemBase { } public class DataFlowTaskCollection : List<DataFlowTask_DSL> { } public class SequenceContainer_DSL : Container { } public class BulkInsertTaskCollection : List<BulkInsertTask_DSL> { } public class BulkInsertTask_DSL { } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Net; using Microsoft.Protocols.TestTools.StackSdk.Security.Sspi; using Microsoft.Protocols.TestTools.StackSdk.Transport; namespace Microsoft.Protocols.TestTools.StackSdk.Networking.Rpce { /// <summary> /// RpceServerTransport provides transport layer /// and support for upper layer protocol to comunicate. /// </summary> public class RpceServerTransport : IDisposable { // RPC INTERFACE UUID, VERS_MAJOR, VERS_MINOR private struct RpcIf { internal RpcIf(Guid ifId, ushort ifMajorVer, ushort ifMinorVer) { this.id = ifId; this.majorVer = ifMajorVer; this.minorVer = ifMinorVer; } internal Guid id; internal ushort majorVer; internal ushort minorVer; } // callback func to check interface is expected. private delegate bool RpcIfMatchFunc(RpcIf rpcIf); #region Field members //A instance of RPCE server private RpceServer rpceServer; //The list of interface to automatically accept bind private List<RpcIf> registeredInterfaceList; #endregion #region ctor /// <summary> /// Initialize RPCE server transport /// </summary> public RpceServerTransport() { this.rpceServer = new RpceServer(); this.registeredInterfaceList = new List<RpcIf>(); } #endregion /// <summary> /// A read-only collection for servercontexts in the RPCE server. /// </summary> public ReadOnlyCollection<RpceServerContext> ServerContexts { get { return this.rpceServer.ServerContexts; } } #region start and stop /// <summary> /// Register an interface and turn on automatic accept bind request. /// </summary> /// <param name="ifId"> /// If_id to accept the bind. Null to accept all interface regardless the if_id. /// </param> /// <param name="ifMajorVer"> /// If_major_ver to accept the bind. Null to accept all interface regardless the if_major_ver. /// </param> /// <param name="ifMinorVer"> /// If_minor_ver to accept the bind. Null to accept all interface regardless the if_minor_ver. /// </param> public void RegisterInterface( Guid ifId, ushort ifMajorVer, ushort ifMinorVer) { RpcIf rpcIf = new RpcIf(ifId, ifMajorVer, ifMinorVer); this.registeredInterfaceList.Add(rpcIf); } /// <summary> /// Unregister an interface. If last interface is removed, turn off automatic accept bind request. /// </summary> /// <param name="ifId"> /// If_id to accept the bind. Null to accept all interface regardless the if_id. /// </param> /// <param name="ifMajorVer"> /// If_major_ver to accept the bind. Null to accept all interface regardless the if_major_ver. /// </param> /// <param name="ifMinorVer"> /// If_minor_ver to accept the bind. Null to accept all interface regardless the if_minor_ver. /// </param> public void UnregisterInterface( Guid ifId, ushort ifMajorVer, ushort ifMinorVer) { for (int i = 0; i < this.registeredInterfaceList.Count; i++) { RpcIf rpcIf = this.registeredInterfaceList[i]; if (rpcIf.id == ifId && rpcIf.majorVer == ifMajorVer && rpcIf.minorVer == ifMinorVer) { this.registeredInterfaceList.RemoveAt(i); break; } } } /// <summary> /// Set callback to create a ServerSecurityContext. /// </summary> /// <param name="securityContextCreator">A callback to create ServerSecurityContext.</param> public void SetSecurityContextCreator(RpceSecurityContextCreatingEventHandler securityContextCreator) { this.rpceServer.SetSecurityContextCreator(securityContextCreator); } /// <summary> /// Start to listen a TCP port. /// </summary> /// <param name="port">The TCP port to listen.</param> public virtual RpceServerContext StartTcp(ushort port) { return this.rpceServer.StartTcp(port); } /// <summary> /// Stop Tcp server. /// </summary> /// <param name="port">The TCP port listened.</param> public virtual void StopTcp(ushort port) { this.rpceServer.StopTcp(port); } /// <summary> /// Start to listen on a named pipe. /// </summary> /// <param name="namedPipe">The name of named pipe to listen.</param> /// <param name="credential">Credential to be used by underlayer SMB/SMB2 transport.</param> /// <param name="ipAddress">server's ipAddress</param> public virtual RpceServerContext StartNamedPipe(string namedPipe, AccountCredential credential, IPAddress ipAddress) { return this.rpceServer.StartNamedPipe(namedPipe, credential, ipAddress); } /// <summary> /// Stop named pipe server. /// </summary> /// <param name="namedPipe">The name of the named pipe listened on</param> public virtual void StopNamedPipe(string namedPipe) { this.rpceServer.StopNamedPipe(namedPipe); } /// <summary> /// Stop all servers. /// </summary> public virtual void StopAll() { this.rpceServer.StopAll(); } #endregion /// <summary> /// Expect to receive a call. /// </summary> /// <param name="timeout">Timeout of expecting a call.</param> /// <param name="sessionContext">Session Context of the received call.</param> /// <param name="opnum">Operation number of the method invoked.</param> /// <returns>Received a byte array of the request stub from a client.</returns> /// <exception cref="InvalidOperationException"> /// Thrown when receive error from server. /// </exception> public virtual byte[] ExpectCall( TimeSpan timeout, out RpceServerSessionContext sessionContext, out ushort opnum) { sessionContext = null; RpcePdu receivedPdu = ReceiveAndReassemblePdu(timeout, ref sessionContext); RpceCoRequestPdu requestPdu = receivedPdu as RpceCoRequestPdu; if (requestPdu == null) { throw new InvalidOperationException("Expect request_pdu, but received others."); } opnum = requestPdu.opnum; byte[] stub = requestPdu.stub; if (stub == null) { stub = new byte[0]; } return stub; } /// <summary> /// Send a Response to client. /// </summary> /// <param name="sessionContext">Context of the RPCE session.</param> /// <param name="responseStub">A byte array of the response stub send to client.</param> /// <exception cref="ArgumentNullException">Thrown when responseStub is null.</exception> public virtual void SendResponse( RpceServerSessionContext sessionContext, byte[] responseStub) { if (responseStub == null) { throw new ArgumentNullException("responseStub"); } RpceCoResponsePdu responsePdu = this.rpceServer.CreateCoResponsePdu(sessionContext, responseStub); FragmentAndSendPdu(sessionContext, responsePdu); } /// <summary> /// Send a Fault to client. /// </summary> /// <param name="sessionContext">Context of the RPCE session.</param> /// <param name="statusCode">Status code.</param> public virtual void SendFault(RpceServerSessionContext sessionContext, uint statusCode) { RpceCoFaultPdu faultPdu = this.rpceServer.CreateCoFaultPdu(sessionContext, null, statusCode); FragmentAndSendPdu(sessionContext, faultPdu); } #region Bind / Disconnect /// <summary> /// Calling this method to be notified when a new RPC connection is coming. /// Users, who don't care about the coming of a new connection, just call ExpectCall directly. /// </summary> /// <param name="ifId"> /// If_id to accept the bind. Null to accept all interface regardless the if_id. /// </param> /// <param name="ifMajorVer"> /// If_major_ver to accept the bind. Null to accept all interface regardless the if_major_ver. /// </param> /// <param name="ifMinorVer"> /// If_minor_ver to accept the bind. Null to accept all interface regardless the if_minor_ver. /// </param> /// <param name="timeout">Timeout of expecting a connection.</param> /// <param name="sessionContext">The sessionContext of binded connection.</param> /// <exception cref="InvalidOperationException"> /// Thrown when receive error from server. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown when securityProvider is null and auth_level is not NONE /// </exception> /// <exception cref="SspiException"> /// Thrown when accept client token failed /// </exception> public virtual void ExpectBind( Guid? ifId, ushort? ifMajorVer, ushort? ifMinorVer, TimeSpan timeout, out RpceServerSessionContext sessionContext) { if (this.registeredInterfaceList.Count > 0) { throw new InvalidOperationException("Auto accept bind was turned on, ExpectBind is not allowed."); } DateTime t0 = DateTime.Now; sessionContext = rpceServer.ExpectConnect(timeout); RpcIfMatchFunc matchFunc = delegate(RpcIf rpcIf) { return !((ifId != null && rpcIf.id != ifId.Value) || (ifMajorVer != null && rpcIf.majorVer != ifMajorVer.Value) || (ifMinorVer != null && rpcIf.minorVer != ifMinorVer.Value)); }; while (!InternalExpectBind(matchFunc, timeout - (DateTime.Now - t0), ref sessionContext)) { if ((DateTime.Now - t0) >= timeout) { throw new TimeoutException(); } } } /// <summary> /// Expect to disconnect from the specific client. /// </summary> /// <param name="timeout">Timeout of expecting to disconnect with client.</param> /// <param name="sessionContext">The sessionContext of expecting to disconnect.</param> public virtual void ExpectDisconnect( TimeSpan timeout, out RpceServerSessionContext sessionContext) { if (this.registeredInterfaceList.Count > 0) { throw new InvalidOperationException("Auto accept bind was turned on, ExpectBind is not allowed."); } sessionContext = null; this.rpceServer.ExpectDisconnect(timeout, ref sessionContext); } /// <summary> /// Disconnect with a client. /// </summary> /// <param name="sessionContext">Context of the RPCE session</param> public virtual void Disconnect(RpceServerSessionContext sessionContext) { this.rpceServer.Disconnect(sessionContext); } #endregion #region private method /// <summary> /// Calling this method to be notified when a new RPC connection is coming. /// </summary> /// <param name="ifMatchFunc">Matching function.</param> /// <param name="timeout">Timeout of expecting a connection.</param> /// <param name="sessionContext">The sessionContext of binded connection.</param> /// <returns>If bind succeeded, return true; otherwise, false.</returns> private bool InternalExpectBind( RpcIfMatchFunc ifMatchFunc, TimeSpan timeout, ref RpceServerSessionContext sessionContext) { RpcePdu receivedPdu = ReceiveAndReassemblePdu(timeout, ref sessionContext); RpceCoBindPdu bindPdu = receivedPdu as RpceCoBindPdu; if (bindPdu == null) { throw new InvalidOperationException("Expect bind_pdu, but received others."); } RpcIf rpcIf = new RpcIf(sessionContext.InterfaceId, sessionContext.InterfaceMajorVersion, sessionContext.InterfaceMinorVersion); if (!ifMatchFunc(rpcIf)) { // Interface doesn't match, response BindNak RpceCoBindNakPdu bindNakPdu = rpceServer.CreateCoBindNakPdu(sessionContext, p_reject_reason_t.REASON_NOT_SPECIFIED, null); FragmentAndSendPdu(sessionContext, bindNakPdu); return false; } RpceCoBindAckPdu bindAckPdu = rpceServer.CreateCoBindAckPdu(sessionContext); FragmentAndSendPdu(sessionContext, bindAckPdu); while (sessionContext.SecurityContext != null && sessionContext.SecurityContextNeedContinueProcessing) { receivedPdu = ReceiveAndReassemblePdu(timeout, ref sessionContext); RpceCoAlterContextPdu alterContextPdu = receivedPdu as RpceCoAlterContextPdu; RpceCoAuth3Pdu auth3Pdu = receivedPdu as RpceCoAuth3Pdu; if (alterContextPdu != null) { RpceCoAlterContextRespPdu alterContextRespPdu = rpceServer.CreateCoAlterContextRespPdu(sessionContext); FragmentAndSendPdu(sessionContext, alterContextRespPdu); } else if (auth3Pdu != null) { //Do nothing } } return true; } /// <summary> /// Receive and reassemble PDU. /// </summary> /// <param name="timeout">Timeout of receiving PDU</param> /// <param name="sessionContext">Context of the RPCE session</param> /// <returns>Received PDU</returns> private RpcePdu ReceiveAndReassemblePdu( TimeSpan timeout, ref RpceServerSessionContext sessionContext) { RpcePdu receivedPdu; bool expectAny = sessionContext == null; WaitForEvent: if (expectAny) { sessionContext = null; } EventType eventType = rpceServer.ExpectEvent(timeout, ref sessionContext, out receivedPdu); if (this.registeredInterfaceList.Count > 0) { // auto accept connect/bind/disconnect if (eventType == EventType.Connected) { RpcIfMatchFunc matchFunc = delegate(RpcIf rpcIf) { for (int i = 0; i < this.registeredInterfaceList.Count; i++) { if (this.registeredInterfaceList[i].Equals(rpcIf)) { return true; } } return false; }; InternalExpectBind(matchFunc, timeout, ref sessionContext); goto WaitForEvent; } else if (eventType == EventType.Disconnected) { goto WaitForEvent; } else { // it is a PDU. } } else if (eventType != EventType.ReceivedPacket) { throw new InvalidOperationException( string.Format("Unexpected event ({0}) received.", eventType)); } RpceCoPdu receivedCoPdu = receivedPdu as RpceCoPdu; if (receivedCoPdu == null) { return receivedPdu; } List<RpceCoPdu> pduList = new List<RpceCoPdu>(); pduList.Add(receivedCoPdu); while ((receivedCoPdu.pfc_flags & RpceCoPfcFlags.PFC_LAST_FRAG) == 0) { receivedPdu = rpceServer.ExpectPdu(timeout, ref sessionContext); receivedCoPdu = receivedPdu as RpceCoPdu; if (receivedCoPdu == null) { throw new InvalidOperationException("CL PDU received inside a connection."); } pduList.Add(receivedCoPdu); } return RpceUtility.ReassemblePdu(sessionContext, pduList.ToArray()); } /// <summary> /// Fragment and send PDU. /// </summary> /// <param name="sessionContext">Context of the RPCE session</param> /// <param name="pdu">PDU to Fragment and send.</param> private void FragmentAndSendPdu( RpceServerSessionContext sessionContext, RpceCoPdu pdu) { if (pdu.PTYPE == RpcePacketType.Bind || pdu.PTYPE == RpcePacketType.BindAck || pdu.PTYPE == RpcePacketType.AlterContext || pdu.PTYPE == RpcePacketType.AlterContextResp || pdu.PTYPE == RpcePacketType.Auth3) { pdu.InitializeAuthenticationToken(); pdu.SetLength(); foreach (RpceCoPdu fragPdu in RpceUtility.FragmentPdu(sessionContext, pdu)) { rpceServer.SendPdu(sessionContext, fragPdu); } } else { foreach (RpceCoPdu fragPdu in RpceUtility.FragmentPdu(sessionContext, pdu)) { fragPdu.InitializeAuthenticationToken(); rpceServer.SendPdu(sessionContext, fragPdu); } } } #endregion #region IDisposable Members /// <summary> /// Dispose method. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Dispose method. /// </summary> /// <param name="disposing"> /// True to release both managed and unmanaged resources.<para/> /// False to release unmanaged resources only. /// </param> protected virtual void Dispose(bool disposing) { if (disposing) { // Release managed resources. this.rpceServer.Dispose(); } } /// <summary> /// finalizer /// </summary> ~RpceServerTransport() { Dispose(false); } #endregion } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Apis.PolicyTroubleshooter.v1 { /// <summary>The PolicyTroubleshooter Service.</summary> public class PolicyTroubleshooterService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public PolicyTroubleshooterService() : this(new Google.Apis.Services.BaseClientService.Initializer()) { } /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public PolicyTroubleshooterService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { Iam = new IamResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features => new string[0]; /// <summary>Gets the service name.</summary> public override string Name => "policytroubleshooter"; /// <summary>Gets the service base URI.</summary> public override string BaseUri => #if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45 BaseUriOverride ?? "https://policytroubleshooter.googleapis.com/"; #else "https://policytroubleshooter.googleapis.com/"; #endif /// <summary>Gets the service base path.</summary> public override string BasePath => ""; #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri => "https://policytroubleshooter.googleapis.com/batch"; /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath => "batch"; #endif /// <summary>Available OAuth 2.0 scopes for use with the Policy Troubleshooter API.</summary> public class Scope { /// <summary> /// See, edit, configure, and delete your Google Cloud data and see the email address for your Google /// Account. /// </summary> public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; } /// <summary>Available OAuth 2.0 scope constants for use with the Policy Troubleshooter API.</summary> public static class ScopeConstants { /// <summary> /// See, edit, configure, and delete your Google Cloud data and see the email address for your Google /// Account. /// </summary> public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; } /// <summary>Gets the Iam resource.</summary> public virtual IamResource Iam { get; } } /// <summary>A base abstract class for PolicyTroubleshooter requests.</summary> public abstract class PolicyTroubleshooterBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { /// <summary>Constructs a new PolicyTroubleshooterBaseServiceRequest instance.</summary> protected PolicyTroubleshooterBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<XgafvEnum> Xgafv { get; set; } /// <summary>V1 error format.</summary> public enum XgafvEnum { /// <summary>v1 error format</summary> [Google.Apis.Util.StringValueAttribute("1")] Value1 = 0, /// <summary>v2 error format</summary> [Google.Apis.Util.StringValueAttribute("2")] Value2 = 1, } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json = 0, /// <summary>Media download with context-dependent Content-Type</summary> [Google.Apis.Util.StringValueAttribute("media")] Media = 1, /// <summary>Responses with Content-Type of application/x-protobuf</summary> [Google.Apis.Util.StringValueAttribute("proto")] Proto = 2, } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary> /// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required /// unless you provide an OAuth 2.0 token. /// </summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary> /// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a /// user, but should not exceed 40 characters. /// </summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes PolicyTroubleshooter parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "iam" collection of methods.</summary> public class IamResource { private const string Resource = "iam"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public IamResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary> /// Checks whether a principal has a specific permission for a specific resource, and explains why the principal /// does or does not have that permission. /// </summary> /// <param name="body">The body of the request.</param> public virtual TroubleshootRequest Troubleshoot(Google.Apis.PolicyTroubleshooter.v1.Data.GoogleCloudPolicytroubleshooterV1TroubleshootIamPolicyRequest body) { return new TroubleshootRequest(service, body); } /// <summary> /// Checks whether a principal has a specific permission for a specific resource, and explains why the principal /// does or does not have that permission. /// </summary> public class TroubleshootRequest : PolicyTroubleshooterBaseServiceRequest<Google.Apis.PolicyTroubleshooter.v1.Data.GoogleCloudPolicytroubleshooterV1TroubleshootIamPolicyResponse> { /// <summary>Constructs a new Troubleshoot request.</summary> public TroubleshootRequest(Google.Apis.Services.IClientService service, Google.Apis.PolicyTroubleshooter.v1.Data.GoogleCloudPolicytroubleshooterV1TroubleshootIamPolicyRequest body) : base(service) { Body = body; InitParameters(); } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.PolicyTroubleshooter.v1.Data.GoogleCloudPolicytroubleshooterV1TroubleshootIamPolicyRequest Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "troubleshoot"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/iam:troubleshoot"; /// <summary>Initializes Troubleshoot parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } } } namespace Google.Apis.PolicyTroubleshooter.v1.Data { /// <summary>Information about the principal, resource, and permission to check.</summary> public class GoogleCloudPolicytroubleshooterV1AccessTuple : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Required. The full resource name that identifies the resource. For example, /// `//compute.googleapis.com/projects/my-project/zones/us-central1-a/instances/my-instance`. For examples of /// full resource names for Google Cloud services, see /// https://cloud.google.com/iam/help/troubleshooter/full-resource-names. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("fullResourceName")] public virtual string FullResourceName { get; set; } /// <summary> /// Required. The IAM permission to check for the specified principal and resource. For a complete list of IAM /// permissions, see https://cloud.google.com/iam/help/permissions/reference. For a complete list of predefined /// IAM roles and the permissions in each role, see https://cloud.google.com/iam/help/roles/reference. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("permission")] public virtual string Permission { get; set; } /// <summary> /// Required. The principal whose access you want to check, in the form of the email address that represents /// that principal. For example, `alice@example.com` or `my-service-account@my-project.iam.gserviceaccount.com`. /// The principal must be a Google Account or a service account. Other types of principals are not supported. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("principal")] public virtual string Principal { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Details about how a binding in a policy affects a principal's ability to use a permission.</summary> public class GoogleCloudPolicytroubleshooterV1BindingExplanation : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Required. Indicates whether _this binding_ provides the specified permission to the specified principal for /// the specified resource. This field does _not_ indicate whether the principal actually has the permission for /// the resource. There might be another binding that overrides this binding. To determine whether the principal /// actually has the permission, use the `access` field in the TroubleshootIamPolicyResponse. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("access")] public virtual string Access { get; set; } /// <summary> /// A condition expression that prevents this binding from granting access unless the expression evaluates to /// `true`. To learn about IAM Conditions, see http://cloud.google.com/iam/help/conditions/overview. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("condition")] public virtual GoogleTypeExpr Condition { get; set; } /// <summary> /// Indicates whether each principal in the binding includes the principal specified in the request, either /// directly or indirectly. Each key identifies a principal in the binding, and each value indicates whether the /// principal in the binding includes the principal in the request. For example, suppose that a binding includes /// the following principals: * `user:alice@example.com` * `group:product-eng@example.com` You want to /// troubleshoot access for `user:bob@example.com`. This user is a principal of the group /// `group:product-eng@example.com`. For the first principal in the binding, the key is /// `user:alice@example.com`, and the `membership` field in the value is set to `MEMBERSHIP_NOT_INCLUDED`. For /// the second principal in the binding, the key is `group:product-eng@example.com`, and the `membership` field /// in the value is set to `MEMBERSHIP_INCLUDED`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("memberships")] public virtual System.Collections.Generic.IDictionary<string, GoogleCloudPolicytroubleshooterV1BindingExplanationAnnotatedMembership> Memberships { get; set; } /// <summary>The relevance of this binding to the overall determination for the entire policy.</summary> [Newtonsoft.Json.JsonPropertyAttribute("relevance")] public virtual string Relevance { get; set; } /// <summary> /// The role that this binding grants. For example, `roles/compute.serviceAgent`. For a complete list of /// predefined IAM roles, as well as the permissions in each role, see /// https://cloud.google.com/iam/help/roles/reference. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("role")] public virtual string Role { get; set; } /// <summary>Indicates whether the role granted by this binding contains the specified permission.</summary> [Newtonsoft.Json.JsonPropertyAttribute("rolePermission")] public virtual string RolePermission { get; set; } /// <summary> /// The relevance of the permission's existence, or nonexistence, in the role to the overall determination for /// the entire policy. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("rolePermissionRelevance")] public virtual string RolePermissionRelevance { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Details about whether the binding includes the principal.</summary> public class GoogleCloudPolicytroubleshooterV1BindingExplanationAnnotatedMembership : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Indicates whether the binding includes the principal.</summary> [Newtonsoft.Json.JsonPropertyAttribute("membership")] public virtual string Membership { get; set; } /// <summary>The relevance of the principal's status to the overall determination for the binding.</summary> [Newtonsoft.Json.JsonPropertyAttribute("relevance")] public virtual string Relevance { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Details about how a specific IAM Policy contributed to the access check.</summary> public class GoogleCloudPolicytroubleshooterV1ExplainedPolicy : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Indicates whether _this policy_ provides the specified permission to the specified principal for the /// specified resource. This field does _not_ indicate whether the principal actually has the permission for the /// resource. There might be another policy that overrides this policy. To determine whether the principal /// actually has the permission, use the `access` field in the TroubleshootIamPolicyResponse. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("access")] public virtual string Access { get; set; } /// <summary> /// Details about how each binding in the policy affects the principal's ability, or inability, to use the /// permission for the resource. If the sender of the request does not have access to the policy, this field is /// omitted. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("bindingExplanations")] public virtual System.Collections.Generic.IList<GoogleCloudPolicytroubleshooterV1BindingExplanation> BindingExplanations { get; set; } /// <summary> /// The full resource name that identifies the resource. For example, /// `//compute.googleapis.com/projects/my-project/zones/us-central1-a/instances/my-instance`. If the sender of /// the request does not have access to the policy, this field is omitted. For examples of full resource names /// for Google Cloud services, see https://cloud.google.com/iam/help/troubleshooter/full-resource-names. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("fullResourceName")] public virtual string FullResourceName { get; set; } /// <summary> /// The IAM policy attached to the resource. If the sender of the request does not have access to the policy, /// this field is empty. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("policy")] public virtual GoogleIamV1Policy Policy { get; set; } /// <summary> /// The relevance of this policy to the overall determination in the TroubleshootIamPolicyResponse. If the /// sender of the request does not have access to the policy, this field is omitted. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("relevance")] public virtual string Relevance { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Request for TroubleshootIamPolicy.</summary> public class GoogleCloudPolicytroubleshooterV1TroubleshootIamPolicyRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The information to use for checking whether a principal has a permission for a resource.</summary> [Newtonsoft.Json.JsonPropertyAttribute("accessTuple")] public virtual GoogleCloudPolicytroubleshooterV1AccessTuple AccessTuple { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Response for TroubleshootIamPolicy.</summary> public class GoogleCloudPolicytroubleshooterV1TroubleshootIamPolicyResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Indicates whether the principal has the specified permission for the specified resource, based on evaluating /// all of the applicable IAM policies. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("access")] public virtual string Access { get; set; } /// <summary> /// List of IAM policies that were evaluated to check the principal's permissions, with annotations to indicate /// how each policy contributed to the final result. The list of policies can include the policy for the /// resource itself. It can also include policies that are inherited from higher levels of the resource /// hierarchy, including the organization, the folder, and the project. To learn more about the resource /// hierarchy, see https://cloud.google.com/iam/help/resource-hierarchy. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("explainedPolicies")] public virtual System.Collections.Generic.IList<GoogleCloudPolicytroubleshooterV1ExplainedPolicy> ExplainedPolicies { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// Specifies the audit configuration for a service. The configuration determines which permission types are logged, /// and what identities, if any, are exempted from logging. An AuditConfig must have one or more AuditLogConfigs. If /// there are AuditConfigs for both `allServices` and a specific service, the union of the two AuditConfigs is used /// for that service: the log_types specified in each AuditConfig are enabled, and the exempted_members in each /// AuditLogConfig are exempted. Example Policy with multiple AuditConfigs: { "audit_configs": [ { "service": /// "allServices", "audit_log_configs": [ { "log_type": "DATA_READ", "exempted_members": [ "user:jose@example.com" ] /// }, { "log_type": "DATA_WRITE" }, { "log_type": "ADMIN_READ" } ] }, { "service": "sampleservice.googleapis.com", /// "audit_log_configs": [ { "log_type": "DATA_READ" }, { "log_type": "DATA_WRITE", "exempted_members": [ /// "user:aliya@example.com" ] } ] } ] } For sampleservice, this policy enables DATA_READ, DATA_WRITE and ADMIN_READ /// logging. It also exempts jose@example.com from DATA_READ logging, and aliya@example.com from DATA_WRITE logging. /// </summary> public class GoogleIamV1AuditConfig : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The configuration for logging of each type of permission.</summary> [Newtonsoft.Json.JsonPropertyAttribute("auditLogConfigs")] public virtual System.Collections.Generic.IList<GoogleIamV1AuditLogConfig> AuditLogConfigs { get; set; } /// <summary> /// Specifies a service that will be enabled for audit logging. For example, `storage.googleapis.com`, /// `cloudsql.googleapis.com`. `allServices` is a special value that covers all services. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("service")] public virtual string Service { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// Provides the configuration for logging a type of permissions. Example: { "audit_log_configs": [ { "log_type": /// "DATA_READ", "exempted_members": [ "user:jose@example.com" ] }, { "log_type": "DATA_WRITE" } ] } This enables /// 'DATA_READ' and 'DATA_WRITE' logging, while exempting jose@example.com from DATA_READ logging. /// </summary> public class GoogleIamV1AuditLogConfig : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Specifies the identities that do not cause logging for this type of permission. Follows the same format of /// Binding.members. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("exemptedMembers")] public virtual System.Collections.Generic.IList<string> ExemptedMembers { get; set; } /// <summary>The log type that this config enables.</summary> [Newtonsoft.Json.JsonPropertyAttribute("logType")] public virtual string LogType { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Associates `members` with a `role`.</summary> public class GoogleIamV1Binding : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// The condition that is associated with this binding. If the condition evaluates to `true`, then this binding /// applies to the current request. If the condition evaluates to `false`, then this binding does not apply to /// the current request. However, a different role binding might grant the same role to one or more of the /// members in this binding. To learn which resources support conditions in their IAM policies, see the [IAM /// documentation](https://cloud.google.com/iam/help/conditions/resource-policies). /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("condition")] public virtual GoogleTypeExpr Condition { get; set; } /// <summary> /// Specifies the identities requesting access for a Cloud Platform resource. `members` can have the following /// values: * `allUsers`: A special identifier that represents anyone who is on the internet; with or without a /// Google account. * `allAuthenticatedUsers`: A special identifier that represents anyone who is authenticated /// with a Google account or a service account. * `user:{emailid}`: An email address that represents a specific /// Google account. For example, `alice@example.com` . * `serviceAccount:{emailid}`: An email address that /// represents a service account. For example, `my-other-app@appspot.gserviceaccount.com`. * `group:{emailid}`: /// An email address that represents a Google group. For example, `admins@example.com`. * /// `deleted:user:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a user that /// has been recently deleted. For example, `alice@example.com?uid=123456789012345678901`. If the user is /// recovered, this value reverts to `user:{emailid}` and the recovered user retains the role in the binding. * /// `deleted:serviceAccount:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a /// service account that has been recently deleted. For example, /// `my-other-app@appspot.gserviceaccount.com?uid=123456789012345678901`. If the service account is undeleted, /// this value reverts to `serviceAccount:{emailid}` and the undeleted service account retains the role in the /// binding. * `deleted:group:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing /// a Google group that has been recently deleted. For example, `admins@example.com?uid=123456789012345678901`. /// If the group is recovered, this value reverts to `group:{emailid}` and the recovered group retains the role /// in the binding. * `domain:{domain}`: The G Suite domain (primary) that represents all the users of that /// domain. For example, `google.com` or `example.com`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("members")] public virtual System.Collections.Generic.IList<string> Members { get; set; } /// <summary> /// Role that is assigned to `members`. For example, `roles/viewer`, `roles/editor`, or `roles/owner`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("role")] public virtual string Role { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// An Identity and Access Management (IAM) policy, which specifies access controls for Google Cloud resources. A /// `Policy` is a collection of `bindings`. A `binding` binds one or more `members` to a single `role`. Members can /// be user accounts, service accounts, Google groups, and domains (such as G Suite). A `role` is a named list of /// permissions; each `role` can be an IAM predefined role or a user-created custom role. For some types of Google /// Cloud resources, a `binding` can also specify a `condition`, which is a logical expression that allows access to /// a resource only if the expression evaluates to `true`. A condition can add constraints based on attributes of /// the request, the resource, or both. To learn which resources support conditions in their IAM policies, see the /// [IAM documentation](https://cloud.google.com/iam/help/conditions/resource-policies). **JSON example:** { /// "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", /// "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, /// { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { /// "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time /// &amp;lt; timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 } **YAML example:** /// bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - /// serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - /// members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable /// access description: Does not grant access after Sep 2020 expression: request.time &amp;lt; /// timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3 For a description of IAM and its features, /// see the [IAM documentation](https://cloud.google.com/iam/docs/). /// </summary> public class GoogleIamV1Policy : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Specifies cloud audit logging configuration for this policy.</summary> [Newtonsoft.Json.JsonPropertyAttribute("auditConfigs")] public virtual System.Collections.Generic.IList<GoogleIamV1AuditConfig> AuditConfigs { get; set; } /// <summary> /// Associates a list of `members` to a `role`. Optionally, may specify a `condition` that determines how and /// when the `bindings` are applied. Each of the `bindings` must contain at least one member. The `bindings` in /// a `Policy` can refer to up to 1,500 members; up to 250 of these members can be Google groups. Each /// occurrence of a member counts towards these limits. For example, if the `bindings` grant 50 different roles /// to `user:alice@example.com`, and not to any other member, then you can add another 1,450 members to the /// `bindings` in the `Policy`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("bindings")] public virtual System.Collections.Generic.IList<GoogleIamV1Binding> Bindings { get; set; } /// <summary> /// `etag` is used for optimistic concurrency control as a way to help prevent simultaneous updates of a policy /// from overwriting each other. It is strongly suggested that systems make use of the `etag` in the /// read-modify-write cycle to perform policy updates in order to avoid race conditions: An `etag` is returned /// in the response to `getIamPolicy`, and systems are expected to put that etag in the request to /// `setIamPolicy` to ensure that their change will be applied to the same version of the policy. **Important:** /// If you use IAM Conditions, you must include the `etag` field whenever you call `setIamPolicy`. If you omit /// this field, then IAM allows you to overwrite a version `3` policy with a version `1` policy, and all of the /// conditions in the version `3` policy are lost. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("etag")] public virtual string ETag { get; set; } /// <summary> /// Specifies the format of the policy. Valid values are `0`, `1`, and `3`. Requests that specify an invalid /// value are rejected. Any operation that affects conditional role bindings must specify version `3`. This /// requirement applies to the following operations: * Getting a policy that includes a conditional role binding /// * Adding a conditional role binding to a policy * Changing a conditional role binding in a policy * Removing /// any role binding, with or without a condition, from a policy that includes conditions **Important:** If you /// use IAM Conditions, you must include the `etag` field whenever you call `setIamPolicy`. If you omit this /// field, then IAM allows you to overwrite a version `3` policy with a version `1` policy, and all of the /// conditions in the version `3` policy are lost. If a policy does not include any conditions, operations on /// that policy may specify any valid version or leave the field unset. To learn which resources support /// conditions in their IAM policies, see the [IAM /// documentation](https://cloud.google.com/iam/help/conditions/resource-policies). /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("version")] public virtual System.Nullable<int> Version { get; set; } } /// <summary> /// Represents a textual expression in the Common Expression Language (CEL) syntax. CEL is a C-like expression /// language. The syntax and semantics of CEL are documented at https://github.com/google/cel-spec. Example /// (Comparison): title: "Summary size limit" description: "Determines if a summary is less than 100 chars" /// expression: "document.summary.size() &amp;lt; 100" Example (Equality): title: "Requestor is owner" description: /// "Determines if requestor is the document owner" expression: "document.owner == request.auth.claims.email" /// Example (Logic): title: "Public documents" description: "Determine whether the document should be publicly /// visible" expression: "document.type != 'private' &amp;amp;&amp;amp; document.type != 'internal'" Example (Data /// Manipulation): title: "Notification string" description: "Create a notification string with a timestamp." /// expression: "'New message received at ' + string(document.create_time)" The exact variables and functions that /// may be referenced within an expression are determined by the service that evaluates it. See the service /// documentation for additional information. /// </summary> public class GoogleTypeExpr : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Optional. Description of the expression. This is a longer text which describes the expression, e.g. when /// hovered over it in a UI. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("description")] public virtual string Description { get; set; } /// <summary>Textual representation of an expression in Common Expression Language syntax.</summary> [Newtonsoft.Json.JsonPropertyAttribute("expression")] public virtual string Expression { get; set; } /// <summary> /// Optional. String indicating the location of the expression for error reporting, e.g. a file name and a /// position in the file. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("location")] public virtual string Location { get; set; } /// <summary> /// Optional. Title for the expression, i.e. a short string describing its purpose. This can be used e.g. in UIs /// which allow to enter the expression. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("title")] public virtual string Title { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using WebMatrix.WebData; using System.Security.Cryptography; using System.Configuration.Provider; using System.Web.Security; using System.IO; using System.Text; using System.Web.Configuration; using System.Web.Hosting; using System.Collections.Specialized; namespace Pablo.Gallery.Logic.Membership { public class GalleryMembershipProvider : ExtendedMembershipProvider { MembershipPasswordFormat passwordFormat; MachineKeySection machineKey; int maxInvalidPasswordAttempts; int minRequiredNonAlphanumericCharacters; int minRequiredPasswordLength; int passwordAttemptWindow; string passwordStrengthRegularExpression; bool enablePasswordReset; bool enablePasswordRetrieval; bool requiresQuestionAndAnswer; bool requiresUniqueEmail; int newPasswordLength; bool emailAsUserName; Models.GalleryContext Database() { return new Models.GalleryContext(); } public override void Initialize(string name, NameValueCollection config) { if (string.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "Gallery Membership Provider"); } base.Initialize(name, config); ApplicationName = GetConfigValue(config["applicationName"], HostingEnvironment.ApplicationVirtualPath); maxInvalidPasswordAttempts = Convert.ToInt32(GetConfigValue(config["maxInvalidPasswordAttempts"], "5")); passwordAttemptWindow = Convert.ToInt32(GetConfigValue(config["passwordAttemptWindow"], "10")); minRequiredNonAlphanumericCharacters = Convert.ToInt32(GetConfigValue(config["minRequiredNonAlphanumericCharacters"], "1")); minRequiredPasswordLength = Convert.ToInt32(GetConfigValue(config["minRequiredPasswordLength"], "7")); passwordStrengthRegularExpression = Convert.ToString(GetConfigValue(config["passwordStrengthRegularExpression"], "")); enablePasswordReset = Convert.ToBoolean(GetConfigValue(config["enablePasswordReset"], "true")); enablePasswordRetrieval = Convert.ToBoolean(GetConfigValue(config["enablePasswordRetrieval"], "true")); requiresQuestionAndAnswer = Convert.ToBoolean(GetConfigValue(config["requiresQuestionAndAnswer"], "false")); requiresUniqueEmail = Convert.ToBoolean(GetConfigValue(config["requiresUniqueEmail"], "true")); newPasswordLength = Convert.ToInt32(GetConfigValue(config["newPasswordLength"], "8")); emailAsUserName = Convert.ToBoolean(GetConfigValue(config["emailAsUserName"], "false")); var formatString = GetConfigValue(config["passwordFormat"], MembershipPasswordFormat.Hashed.ToString()); if (!Enum.TryParse<MembershipPasswordFormat>(formatString, out passwordFormat)) throw new ProviderException("Password format not supported."); var cfg = WebConfigurationManager.OpenWebConfiguration(HostingEnvironment.ApplicationVirtualPath); machineKey = (MachineKeySection)cfg.GetSection("system.web/machineKey"); if (machineKey.ValidationKey.Contains("AutoGenerate")) if (PasswordFormat != MembershipPasswordFormat.Clear) throw new ProviderException("Hashed or Encrypted passwords are not supported with auto-generated keys."); } string GetConfigValue(string configValue, string defaultValue) { return string.IsNullOrEmpty(configValue) ? defaultValue : configValue; } static string GenerateToken() { using (var generator = new RNGCryptoServiceProvider()) { var array = new byte[16]; generator.GetBytes(array); return HttpServerUtility.UrlTokenEncode(array); } } public override bool ConfirmAccount(string accountConfirmationToken) { using (var db = Database()) { var user = db.Users.FirstOrDefault(r => r.ConfirmationToken == accountConfirmationToken); if (user == null) return false; user.IsConfirmed = true; db.SaveChanges(); return true; } } public override bool ConfirmAccount(string userName, string accountConfirmationToken) { using (var db = Database()) { return db.Users.Any(r => r.UserName == userName && r.ConfirmationToken == accountConfirmationToken); } } public override string CreateAccount(string userName, string password, bool requireConfirmationToken) { return CreateUserAndAccount(userName, password, requireConfirmationToken, null); } public override string CreateUserAndAccount(string userName, string password, bool requireConfirmation, IDictionary<string, object> values) { using (var db = Database()) { var token = requireConfirmation ? GenerateToken() : null; var date = DateTime.UtcNow; var user = new Models.User { CreateDate = date, PasswordChangedDate = date, UserName = userName, Email = emailAsUserName ? userName : null, Password = EncodePassword(password), ConfirmationToken = token, IsConfirmed = !requireConfirmation }; if (values != null) { object val; if (values.TryGetValue("Alias", out val) && val is string) user.Alias = (string)val; if (!emailAsUserName && values.TryGetValue("Email", out val) && val is string) user.Email = (string)val; } db.Users.Add(user); db.SaveChanges(); return token; } } public override bool DeleteAccount(string userName) { using (var db = Database()) { var user = db.Users.FirstOrDefault(r => r.UserName == userName); if (user == null) return false; db.Users.Remove(user); db.SaveChanges(); return true; } } public override string GeneratePasswordResetToken(string userName, int tokenExpirationInMinutesFromNow) { using (var db = Database()) { var user = db.Users.FirstOrDefault(r => r.UserName == userName); if (user == null) throw new ProviderException("User not found"); var token = GenerateToken(); user.PasswordVerificationToken = token; user.PasswordVerificationExpiryDate = DateTime.UtcNow.AddMinutes(tokenExpirationInMinutesFromNow); db.SaveChanges(); return token; } } public override ICollection<OAuthAccountData> GetAccountsForUser(string userName) { using (var db = Database()) { var user = db.Users.FirstOrDefault(r => r.UserName == userName); if (user != null && user.OAuthMemberships != null) return user.OAuthMemberships.Select(r => new OAuthAccountData(r.Provider, r.ProviderUserId)).ToArray(); } return new OAuthAccountData[0]; } public override DateTime GetCreateDate(string userName) { using (var db = Database()) { var user = db.Users.FirstOrDefault(r => r.UserName == userName); return user.CreateDate ?? DateTime.MinValue; } } public override DateTime GetLastPasswordFailureDate(string userName) { using (var db = Database()) { var user = db.Users.FirstOrDefault(r => r.UserName == userName); return user.LastPasswordFailureDate ?? DateTime.MinValue; } } public override DateTime GetPasswordChangedDate(string userName) { using (var db = Database()) { var user = db.Users.FirstOrDefault(r => r.UserName == userName); return user.PasswordChangedDate ?? DateTime.MinValue; } } public override int GetPasswordFailuresSinceLastSuccess(string userName) { using (var db = Database()) { var user = db.Users.FirstOrDefault(r => r.UserName == userName); return user.PasswordFailuresSinceLastSuccess; } } public override int GetUserIdFromPasswordResetToken(string token) { using (var db = Database()) { var user = db.Users.FirstOrDefault(r => r.PasswordVerificationToken == token); return user.Id; } } public override bool IsConfirmed(string userName) { using (var db = Database()) { var user = db.Users.FirstOrDefault(r => r.UserName == userName); return user.IsConfirmed; } } public override bool ResetPasswordWithToken(string token, string newPassword) { using (var db = Database()) { var user = db.Users.FirstOrDefault(r => r.PasswordVerificationToken == token); if (user == null) return false; user.Password = EncodePassword(newPassword); user.PasswordChangedDate = DateTime.UtcNow; return true; } } public override string ApplicationName { get; set; } public override bool ChangePassword(string userName, string oldPassword, string newPassword) { using (var db = Database()) { var user = db.Users.FirstOrDefault(r => r.UserName == userName); if (user == null || !CheckPassword(oldPassword, user.Password)) return false; user.Password = EncodePassword(newPassword); user.PasswordChangedDate = DateTime.UtcNow; db.SaveChanges(); return true; } } public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer) { using (var db = Database()) { var user = db.Users.FirstOrDefault(r => r.UserName == username); if (user != null && CheckPassword(password, user.Password)) { user.PasswordQuestion = newPasswordQuestion; user.PasswordAnswer = EncodePassword(newPasswordAnswer); return true; } } return false; } public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) { using (var db = Database()) { var date = DateTime.UtcNow; var user = db.Users.FirstOrDefault(r => r.UserName == username || r.Email == email); if (user == null) { user = new Models.User { CreateDate = date, PasswordChangedDate = date, UserName = username, Email = emailAsUserName ? username : null, Password = EncodePassword(password), PasswordQuestion = passwordQuestion, PasswordAnswer = EncodePassword(passwordAnswer) }; db.SaveChanges(); status = MembershipCreateStatus.Success; return user.ToMembershipUser(Name, isApproved); } if (user.UserName == username) status = MembershipCreateStatus.DuplicateUserName; else if (user.Email == email) status = MembershipCreateStatus.DuplicateEmail; else status = MembershipCreateStatus.ProviderError; return null; } } public override bool DeleteUser(string username, bool deleteAllRelatedData) { using (var db = Database()) { var user = db.Users.FirstOrDefault(r => r.UserName == username); if (user == null) return false; db.Users.Remove(user); db.SaveChanges(); return true; } } public override bool EnablePasswordReset { get { return enablePasswordReset; } } public override bool EnablePasswordRetrieval { get { return enablePasswordRetrieval; } } public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords) { using (var db = Database()) { var result = new MembershipUserCollection(); var users = db.Users.Where(r => r.Email == emailToMatch); totalRecords = users.Count(); foreach (var user in users.Skip(pageIndex * pageSize).Take(pageSize)) { result.Add(user.ToMembershipUser(Name, true)); } return result; } } public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) { using (var db = Database()) { var result = new MembershipUserCollection(); var users = db.Users.Where(r => r.UserName == usernameToMatch); totalRecords = users.Count(); foreach (var user in users.Skip(pageIndex * pageSize).Take(pageSize)) { result.Add(user.ToMembershipUser(Name, true)); } return result; } } public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) { using (var db = Database()) { var result = new MembershipUserCollection(); var users = db.Users.Skip(pageIndex * pageSize).Take(pageSize); totalRecords = db.Users.Count(); foreach (var user in users) { result.Add(user.ToMembershipUser(Name, true)); } return result; } } public override int GetNumberOfUsersOnline() { return 0; } public override string GetPassword(string username, string answer) { throw new NotImplementedException(); } public override MembershipUser GetUser(string username, bool userIsOnline) { using (var db = Database()) { var user = db.Users.FirstOrDefault(r => r.UserName == username); if (user == null) return null; return user.ToMembershipUser(Name, true); } } public override int GetUserIdFromOAuth(string provider, string providerUserId) { using (var db = Database()) { var oauth = db.UserOAuthMemberships.FirstOrDefault(r => r.Provider == provider && r.ProviderUserId == providerUserId); if (oauth == null) return -1; return oauth.User.Id; } } public override void DeleteOAuthAccount(string provider, string providerUserId) { using (var db = Database()) { var oauth = db.UserOAuthMemberships.FirstOrDefault(r => r.Provider == provider && r.ProviderUserId == providerUserId); if (oauth != null) { db.UserOAuthMemberships.Remove(oauth); db.SaveChanges(); } } } public override void CreateOrUpdateOAuthAccount(string provider, string providerUserId, string userName) { using (var db = Database()) { var user = db.Users.FirstOrDefault(r => r.UserName == userName); if (user == null) throw new MembershipCreateUserException(MembershipCreateStatus.InvalidUserName); var oauth = db.UserOAuthMemberships.FirstOrDefault(r => r.Provider == provider && r.ProviderUserId == providerUserId); if (oauth != null) { oauth.User = user; } else { oauth = new Models.UserOAuthMembership { User = user, Provider = provider, ProviderUserId = providerUserId }; db.UserOAuthMemberships.Add(oauth); } db.SaveChanges(); } } public override string GetUserNameFromId(int userId) { using (var db = Database()) { var user = db.Users.FirstOrDefault(r => r.Id == userId); if (user != null) return user.UserName; } return null; } public override MembershipUser GetUser(object providerUserKey, bool userIsOnline) { throw new NotImplementedException(); } public override string GetUserNameByEmail(string email) { throw new NotImplementedException(); } public override int MaxInvalidPasswordAttempts { get { return maxInvalidPasswordAttempts; } } public override int MinRequiredNonAlphanumericCharacters { get { return minRequiredNonAlphanumericCharacters; } } public override int MinRequiredPasswordLength { get { return minRequiredPasswordLength; } } public override int PasswordAttemptWindow { get { return passwordAttemptWindow; } } public override MembershipPasswordFormat PasswordFormat { get { return passwordFormat; } } public override string PasswordStrengthRegularExpression { get { return passwordStrengthRegularExpression; } } public override bool RequiresQuestionAndAnswer { get { return requiresQuestionAndAnswer; } } public override bool RequiresUniqueEmail { get { return requiresUniqueEmail; } } public override string ResetPassword(string username, string answer) { using (var db = Database()) { var user = db.Users.FirstOrDefault(r => r.UserName == username && r.IsConfirmed); if (user == null) throw new MembershipPasswordException("The supplied user name is not found."); if (!CheckPassword(answer, user.PasswordAnswer)) throw new MembershipPasswordException("Incorrect password answer."); string newPassword = System.Web.Security.Membership.GeneratePassword(newPasswordLength, MinRequiredNonAlphanumericCharacters); user.LastLoginDate = DateTime.UtcNow; user.Password = EncodePassword(newPassword); db.SaveChanges(); return newPassword; } } public override bool UnlockUser(string userName) { throw new NotImplementedException(); } public override void UpdateUser(MembershipUser user) { throw new NotImplementedException(); } public override bool ValidateUser(string username, string password) { using (var db = Database()) { var user = db.Users.FirstOrDefault(r => r.UserName == username && r.IsConfirmed); if (user == null || !CheckPassword(password, user.Password)) return false; user.LastLoginDate = DateTime.UtcNow; db.SaveChanges(); return true; } } public override bool HasLocalAccount(int userId) { using (var db = Database()) { return db.Users.Any(r => r.Id == userId); } } string EncodePassword(string password) { string encodedPassword = password; switch (PasswordFormat) { case MembershipPasswordFormat.Clear: break; case MembershipPasswordFormat.Encrypted: encodedPassword = Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(password))); break; case MembershipPasswordFormat.Hashed: HMACSHA1 hash = new HMACSHA1(); hash.Key = HexToByte(machineKey.ValidationKey); encodedPassword = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password))); break; default: throw new ProviderException("Unsupported password format."); } return encodedPassword; } string UnEncodePassword(string encodedPassword) { string password = encodedPassword; switch (PasswordFormat) { case MembershipPasswordFormat.Clear: break; case MembershipPasswordFormat.Encrypted: password = Encoding.Unicode.GetString(DecryptPassword(Convert.FromBase64String(password))); break; case MembershipPasswordFormat.Hashed: throw new ProviderException("Cannot unencode a hashed password."); default: throw new ProviderException("Unsupported password format."); } return password; } byte[] HexToByte(string hexString) { var returnBytes = new byte[hexString.Length / 2]; for (int i = 0; i < returnBytes.Length; i++) returnBytes[i] = Convert.ToByte(hexString.Substring(i*2, 2), 16); return returnBytes; } bool CheckPassword(string password, string dbpassword) { string pass1 = password; string pass2 = dbpassword; switch (PasswordFormat) { case MembershipPasswordFormat.Encrypted: pass2 = UnEncodePassword(dbpassword); break; case MembershipPasswordFormat.Hashed: pass1 = EncodePassword(password); break; } return pass1 == pass2; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Globalization; using System.IO; using System.Web; using System.Xml; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Modules; using DotNetNuke.Modules.UserDefinedTable.Components; using DotNetNuke.Modules.UserDefinedTable.Interfaces; using DotNetNuke.Services.Exceptions; using DotNetNuke.Services.FileSystem; using DotNetNuke.Services.Search; using Microsoft.VisualBasic; using Globals = DotNetNuke.Common.Globals; namespace DotNetNuke.Modules.UserDefinedTable { public class BusinessController : ISearchable, IPortable, IPortable2 { public enum SettingsType { ModuleSettings, TabModuleSettings } static DataTable GetSettingsTable(int id, SettingsType type) { var modules = new ModuleController(); Hashtable settings = null; DataTable returnValue = null; switch (type) { case SettingsType.ModuleSettings: settings = modules.GetModuleSettings(id); returnValue = new DataTable(DataSetTableName.Settings); break; case SettingsType.TabModuleSettings: settings = modules.GetTabModuleSettings(id); returnValue = new DataTable(DataSetTableName.TabSettings); break; } var sortedSettings = new SortedList<string, string>(); if (settings != null) foreach (DictionaryEntry item in settings) { sortedSettings.Add(item.Key.ToString(), item.Value.ToString()); } var dc = new DataColumn(SettingsTableColumn.Setting, typeof (string)) {ColumnMapping = MappingType.Attribute}; if (returnValue != null) returnValue.Columns.Add(dc); dc = new DataColumn(SettingsTableColumn.Value, typeof (string)) {ColumnMapping = MappingType.Attribute}; if (returnValue != null) { returnValue.Columns.Add(dc); foreach (var key in sortedSettings.Keys) { var row = returnValue.NewRow(); row[SettingsTableColumn.Setting] = key; row[SettingsTableColumn.Value] = sortedSettings[key]; returnValue.Rows.Add(row); } return returnValue; } return null; } DataTable GetStylesheetTable(Components.Settings settings, int portalId) { var returnValue = new DataTable(DataSetTableName.Stylesheets); returnValue.Columns.Add(new DataColumn(StylesheetTableColumn.NameOfSetting, typeof (string))); returnValue.Columns.Add(new DataColumn(StylesheetTableColumn.LocalFilePath, typeof (string))); returnValue.Columns.Add(new DataColumn(StylesheetTableColumn.Stylesheet, typeof (string))); var renderMethod = string.Format("UDT_{0}", settings.RenderingMethod ); var listScript = renderMethod == SettingName.XslUserDefinedStyleSheet ? settings.ScriptByRenderingMethod( renderMethod ) : string.Empty; if (listScript.Length > 0) { var row = returnValue.NewRow(); row[StylesheetTableColumn.NameOfSetting] = SettingName.XslUserDefinedStyleSheet; row[StylesheetTableColumn.LocalFilePath] = listScript; row[StylesheetTableColumn.Stylesheet] = Utilities.ReadStringFromFile(listScript, portalId); returnValue.Rows.Add(row); } var trackingSkript = settings.TrackingScript; if (trackingSkript.Length > 0 && trackingSkript != "[AUTO]") { var row = returnValue.NewRow(); row[StylesheetTableColumn.NameOfSetting] = SettingName.TrackingScript; row[StylesheetTableColumn.LocalFilePath] = trackingSkript; row[StylesheetTableColumn.Stylesheet] = Utilities.ReadStringFromFile(trackingSkript, portalId); returnValue.Rows.Add(row); } return returnValue; } /// ----------------------------------------------------------------------------- /// <summary> /// Implements the search interface for DotNetNuke /// </summary> /// ----------------------------------------------------------------------------- public SearchItemInfoCollection GetSearchItems(ModuleInfo modInfo) { var searchItemCollection = new SearchItemInfoCollection(); var udtController = new UserDefinedTableController(modInfo); try { var dsUserDefinedRows = udtController.GetDataSet(withPreRenderedValues: false); //Get names of ChangedBy and ChangedAt columns var colnameChangedBy = udtController.ColumnNameByDataType(dsUserDefinedRows, DataTypeNames.UDT_DataType_ChangedBy); var colnameChangedAt = udtController.ColumnNameByDataType(dsUserDefinedRows, DataTypeNames.UDT_DataType_ChangedAt); var moduleController = new ModuleController(); var settings = moduleController.GetModuleSettings(modInfo.ModuleID); var includeInSearch = !(settings[SettingName.ExcludeFromSearch].AsBoolean()); if (includeInSearch) { foreach (DataRow row in dsUserDefinedRows.Tables[DataSetTableName.Data].Rows) { var changedDate = DateTime.Today; var changedByUserId = 0; if (colnameChangedAt != string.Empty && ! Information.IsDBNull(row[colnameChangedAt])) { changedDate = Convert.ToDateTime(row[colnameChangedAt]); } if (colnameChangedBy != string.Empty && ! Information.IsDBNull(row[colnameChangedBy])) { changedByUserId = ModuleSecurity.UserId(row[colnameChangedBy].ToString(), modInfo.PortalID); } var desc = string.Empty; foreach (DataRow col in dsUserDefinedRows.Tables[DataSetTableName.Fields].Rows) { var fieldType = col[FieldsTableColumn.Type].ToString(); var fieldTitle = col[FieldsTableColumn.Title].ToString(); var visible = Convert.ToBoolean(col[FieldsTableColumn.Visible]); if (visible && (fieldType.StartsWith("Text") || fieldType == DataTypeNames.UDT_DataType_String)) { desc += string.Format("{0} &bull; ", Convert.ToString(row[fieldTitle])); } } if (desc.EndsWith("<br/>")) { desc = desc.Substring(0, Convert.ToInt32(desc.Length - 5)); } var searchItem = new SearchItemInfo(modInfo.ModuleTitle, desc, changedByUserId, changedDate, modInfo.ModuleID, row[DataTableColumn.RowId].ToString(), desc); searchItemCollection.Add(searchItem); } } } catch (Exception ex) { Exceptions.LogException(ex); } return searchItemCollection; } /// ----------------------------------------------------------------------------- /// <summary> /// Implements the export interface for DotNetNuke /// </summary> /// ----------------------------------------------------------------------------- public string ExportModule(int moduleId) { return ExportModule(moduleId, Null.NullInteger); } /// <summary> /// Implements the enhanced export interface for DotNetNuke /// </summary> public string ExportModule(int moduleId, int tabId) { return ExportModule(moduleId, tabId, Null.NullInteger); } public string ExportModule(int moduleId, int tabId, int maxNumberOfItems) { var ds = ExportModuleDataSet(moduleId, tabId); if (maxNumberOfItems > Null.NullInteger) { //clear all but first row for (var i = ds.Tables[DataSetTableName.Data].Rows.Count - 1; i >= maxNumberOfItems; i--) { ds.Tables[DataSetTableName.Data].Rows.RemoveAt(i); } } //dataset to xml return ds.GetXml(); } public DataSet ExportModuleDataSet(int moduleId, int tabId) { DataSet ds; if (tabId == Null.NullInteger) { var udtController = new UserDefinedTableController(moduleId); ds = udtController.GetDataSet(false); ds.Tables.Add(GetSettingsTable(moduleId, SettingsType.ModuleSettings)); } else { var moduleInfo = new ModuleController().GetModule(moduleId, tabId); var udtController = new UserDefinedTableController(moduleInfo); ds = udtController.GetDataSet(false); ds.Tables.Add(GetSettingsTable(moduleId, SettingsType.ModuleSettings)); ds.Tables.Add(GetSettingsTable(moduleInfo.TabModuleID, SettingsType.TabModuleSettings)); ds.Tables.Add(GetStylesheetTable(udtController.Settings, moduleInfo.PortalID)); } return (ds); } /// ----------------------------------------------------------------------------- /// <summary> /// Implements the import interface for DotNetNuke /// </summary> /// ----------------------------------------------------------------------------- public void ImportModule(int moduleId, string content, string version, int userId) { ImportModule(moduleId, Null.NullInteger, content, version, userId, false); } /// <summary> /// Implements the enhanced Import Interface for DotNetNuke /// </summary> public void ImportModule(int moduleId, int tabId, string content, string version, int userId, bool isInstance) { // save script timeout var scriptTimeOut = HttpContext.Current.Server.ScriptTimeout; try { // temporarily set script timeout to large value ( this value is only applicable when application is not running in Debug mode ) HttpContext.Current.Server.ScriptTimeout = int.MaxValue; var udtController = new UserDefinedTableController(moduleId); using (var ds = new DataSet()) { var xmlNode = Globals.GetContent(content, string.Empty); ds.ReadXml(new XmlNodeReader(xmlNode)); var modules = new ModuleController(); var tabModuleId = Null.NullInteger; if (tabId != Null.NullInteger) { var moduleInfo = modules.GetModule(moduleId, tabId); tabModuleId = moduleInfo.TabModuleID; } if (tabModuleId != Null.NullInteger && ds.Tables[DataSetTableName.TabSettings] != null) { AddTabModuleSettings(modules, tabModuleId, ds); } if (! isInstance) { AddModuleSettings(moduleId, modules, ds); //Fields - first delete old Fields udtController.ResetModule(); AddFields(moduleId, ds); AddData(udtController, ds); } if (ds.Tables.Contains(DataSetTableName.Stylesheets)) { ImportStyleSheet(moduleId, isInstance, tabModuleId, modules, ds); } } } finally { // reset script timeout HttpContext.Current.Server.ScriptTimeout = scriptTimeOut; } } static void AddTabModuleSettings(ModuleController modules, int tabModuleId, DataSet ds) { foreach (DataRow row in ds.Tables[DataSetTableName.TabSettings].Rows) { modules.UpdateTabModuleSetting(tabModuleId, row[SettingsTableColumn.Setting].ToString(), row[SettingsTableColumn.Value].ToString()); } } static void AddModuleSettings(int moduleId, ModuleController modules, DataSet ds) { if (ds.Tables[DataSetTableName.Settings] != null) { foreach (DataRow row in ds.Tables[DataSetTableName.Settings].Rows) { modules.UpdateModuleSetting(moduleId, row[SettingsTableColumn.Setting].ToString(), row[SettingsTableColumn.Value].ToString()); } } } static void ImportStyleSheet(int moduleId, bool isInstance, int tabModuleId, ModuleController modules, DataSet ds) { var portalSettings = Globals.GetPortalSettings(); foreach (DataRow row in ds.Tables[DataSetTableName.Stylesheets].Rows) { var settingName = row[StylesheetTableColumn.NameOfSetting].ToString(); var localFilePath = row[StylesheetTableColumn.LocalFilePath].ToString(); var stylesheet = row[StylesheetTableColumn.Stylesheet].ToString(); //Check whether file exists if (File.Exists(((portalSettings.HomeDirectoryMapPath + localFilePath).Replace("/", "\\")))) { //nothing to do, settings points to existing stylesheet } else { var fileName = localFilePath.Substring( Convert.ToInt32( localFilePath.LastIndexOf("/", StringComparison.InvariantCultureIgnoreCase) + 1)); var folder = Utilities.GetFolder(portalSettings, Definition.XSLFolderName); Utilities.SaveScript(stylesheet, fileName, folder, false); if (tabModuleId != Null.NullInteger) { modules.UpdateTabModuleSetting(tabModuleId, settingName, string.Format("{0}/{1}", Definition.XSLFolderName, fileName)); } else { if (! isInstance) { modules.UpdateModuleSetting(moduleId, settingName, string.Format("{0}/{1}", Definition.XSLFolderName, fileName)); } } } } } static void AddData(UserDefinedTableController udtController, DataSet ds) { if (ds.Tables[DataSetTableName.Data] != null) { for (var rowNr = 0; rowNr <= ds.Tables[DataSetTableName.Data].Rows.Count - 1; rowNr++) { udtController.UpdateRow(ds, rowNr, isDataToImport: true); } } } static void AddFields(int moduleId, DataSet ds) { var fieldIndex = ds.Tables[DataSetTableName.Fields].Rows.Count; var fieldSettings = ds.Tables[DataSetTableName.FieldSettings]; foreach (DataRow row in ds.Tables[DataSetTableName.Fields].Rows) { var oldFieldId = row[FieldsTableColumn.Id].AsInt( ); var newFieldId= FieldController.AddField(moduleId, row[FieldsTableColumn.Title].ToString(), row.AsString(FieldsTableColumn.Order).AsInt(fieldIndex ), row.AsString((FieldsTableColumn.HelpText)), row.AsString(FieldsTableColumn.Required).AsBoolean(), row.AsString((FieldsTableColumn.Type)), row.AsString((FieldsTableColumn.Default)), row.AsString(FieldsTableColumn.Visible).AsBoolean(), row.AsString(FieldsTableColumn.ShowOnEdit).AsBoolean(true), row.AsString(FieldsTableColumn.Searchable).AsBoolean(), row.AsString(FieldsTableColumn.IsPrivate).AsBoolean(), row.AsString(FieldsTableColumn.MultipleValues).AsBoolean(), row.AsString((FieldsTableColumn.InputSettings)), row.AsString((FieldsTableColumn.OutputSettings)), row.AsString(FieldsTableColumn.NormalizeFlag).AsBoolean(), row.AsString((FieldsTableColumn.ValidationRule)), row.AsString((FieldsTableColumn.ValidationMessage)), row.AsString((FieldsTableColumn.EditStyle))); if (fieldSettings != null) { foreach (DataRowView setting in fieldSettings.WithFieldId(oldFieldId)) { FieldSettingsController.UpdateFieldSetting( (string) setting["SettingName"], (string) setting["SettingValue"], newFieldId); } } row[FieldsTableColumn.Id] = newFieldId; fieldIndex--; } } public bool ManagesModuleSettings { get { return true; } } public bool ManagesTabModuleSettings { get { return true; } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using NuGet; using Splat; using Squirrel; using Squirrel.Tests.TestHelpers; using Xunit; namespace Squirrel.Tests { public class FakeUrlDownloader : IFileDownloader { public Task<byte[]> DownloadUrl(string url) { return Task.FromResult(new byte[0]); } public async Task DownloadFile(string url, string targetFile, Action<int> progress) { } } public class ApplyReleasesTests : IEnableLogger { [Fact] public async Task CleanInstallRunsSquirrelAwareAppsWithInstallFlag() { string tempDir; string remotePkgDir; using (Utility.WithTempDirectory(out tempDir)) using (Utility.WithTempDirectory(out remotePkgDir)) { IntegrationTestHelper.CreateFakeInstalledApp("0.1.0", remotePkgDir); var pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir); ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES")); using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) { await fixture.FullInstall(); // NB: We execute the Squirrel-aware apps, so we need to give // them a minute to settle or else the using statement will // try to blow away a running process await Task.Delay(1000); Assert.False(File.Exists(Path.Combine(tempDir, "theApp", "app-0.1.0", "args2.txt"))); Assert.True(File.Exists(Path.Combine(tempDir, "theApp", "app-0.1.0", "args.txt"))); var text = File.ReadAllText(Path.Combine(tempDir, "theApp", "app-0.1.0", "args.txt"), Encoding.UTF8); Assert.Contains("firstrun", text); } } } [Fact] public async Task UpgradeRunsSquirrelAwareAppsWithUpgradeFlag() { string tempDir; string remotePkgDir; using (Utility.WithTempDirectory(out tempDir)) using (Utility.WithTempDirectory(out remotePkgDir)) { IntegrationTestHelper.CreateFakeInstalledApp("0.1.0", remotePkgDir); var pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir); ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES")); using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) { await fixture.FullInstall(); } await Task.Delay(1000); IntegrationTestHelper.CreateFakeInstalledApp("0.2.0", remotePkgDir); pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir); ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES")); using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) { await fixture.UpdateApp(); } await Task.Delay(1000); Assert.False(File.Exists(Path.Combine(tempDir, "theApp", "app-0.2.0", "args2.txt"))); Assert.True(File.Exists(Path.Combine(tempDir, "theApp", "app-0.2.0", "args.txt"))); var text = File.ReadAllText(Path.Combine(tempDir, "theApp", "app-0.2.0", "args.txt"), Encoding.UTF8); Assert.Contains("updated|0.2.0", text); } } [Fact] public async Task RunningUpgradeAppTwiceDoesntCrash() { string tempDir; string remotePkgDir; using (Utility.WithTempDirectory(out tempDir)) using (Utility.WithTempDirectory(out remotePkgDir)) { IntegrationTestHelper.CreateFakeInstalledApp("0.1.0", remotePkgDir); var pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir); ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES")); using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) { await fixture.FullInstall(); } await Task.Delay(1000); IntegrationTestHelper.CreateFakeInstalledApp("0.2.0", remotePkgDir); pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir); ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES")); using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) { await fixture.UpdateApp(); } await Task.Delay(1000); // NB: The 2nd time we won't have any updates to apply. We should just do nothing! using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) { await fixture.UpdateApp(); } await Task.Delay(1000); } } [Fact] public async Task FullUninstallRemovesAllVersions() { string tempDir; string remotePkgDir; using (Utility.WithTempDirectory(out tempDir)) using (Utility.WithTempDirectory(out remotePkgDir)) { IntegrationTestHelper.CreateFakeInstalledApp("0.1.0", remotePkgDir); var pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir); ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES")); using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) { await fixture.FullInstall(); } await Task.Delay(1000); IntegrationTestHelper.CreateFakeInstalledApp("0.2.0", remotePkgDir); pkgs = ReleaseEntry.BuildReleasesFile(remotePkgDir); ReleaseEntry.WriteReleaseFile(pkgs, Path.Combine(remotePkgDir, "RELEASES")); using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) { await fixture.UpdateApp(); } await Task.Delay(1000); using (var fixture = new UpdateManager(remotePkgDir, "theApp", tempDir)) { await fixture.FullUninstall(); } Assert.False(File.Exists(Path.Combine(tempDir, "theApp", "app-0.1.0", "args.txt"))); Assert.False(File.Exists(Path.Combine(tempDir, "theApp", "app-0.2.0", "args.txt"))); Assert.False(Directory.Exists(Path.Combine(tempDir, "theApp"))); } } [Fact] public void WhenNoNewReleasesAreAvailableTheListIsEmpty() { string tempDir; using (Utility.WithTempDirectory(out tempDir)) { var appDir = Directory.CreateDirectory(Path.Combine(tempDir, "theApp")); var packages = Path.Combine(appDir.FullName, "packages"); Directory.CreateDirectory(packages); var package = "Squirrel.Core.1.0.0.0-full.nupkg"; File.Copy(IntegrationTestHelper.GetPath("fixtures", package), Path.Combine(packages, package)); var aGivenPackage = Path.Combine(packages, package); var baseEntry = ReleaseEntry.GenerateFromFile(aGivenPackage); var updateInfo = UpdateInfo.Create(baseEntry, new[] { baseEntry }, "dontcare"); Assert.Empty(updateInfo.ReleasesToApply); } } [Fact] public void ThrowsWhenOnlyDeltaReleasesAreAvailable() { string tempDir; using (Utility.WithTempDirectory(out tempDir)) { var appDir = Directory.CreateDirectory(Path.Combine(tempDir, "theApp")); var packages = Path.Combine(appDir.FullName, "packages"); Directory.CreateDirectory(packages); var baseFile = "Squirrel.Core.1.0.0.0-full.nupkg"; File.Copy(IntegrationTestHelper.GetPath("fixtures", baseFile), Path.Combine(packages, baseFile)); var basePackage = Path.Combine(packages, baseFile); var baseEntry = ReleaseEntry.GenerateFromFile(basePackage); var deltaFile = "Squirrel.Core.1.1.0.0-delta.nupkg"; File.Copy(IntegrationTestHelper.GetPath("fixtures", deltaFile), Path.Combine(packages, deltaFile)); var deltaPackage = Path.Combine(packages, deltaFile); var deltaEntry = ReleaseEntry.GenerateFromFile(deltaPackage); Assert.Throws<Exception>( () => UpdateInfo.Create(baseEntry, new[] { deltaEntry }, "dontcare")); } } [Fact] public async Task ApplyReleasesWithOneReleaseFile() { string tempDir; using (Utility.WithTempDirectory(out tempDir)) { string appDir = Path.Combine(tempDir, "theApp"); string packagesDir = Path.Combine(appDir, "packages"); Directory.CreateDirectory(packagesDir); new[] { "Squirrel.Core.1.0.0.0-full.nupkg", "Squirrel.Core.1.1.0.0-full.nupkg", }.ForEach(x => File.Copy(IntegrationTestHelper.GetPath("fixtures", x), Path.Combine(packagesDir, x))); var fixture = new UpdateManager.ApplyReleasesImpl(appDir); var baseEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.0.0.0-full.nupkg")); var latestFullEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.1.0.0-full.nupkg")); var updateInfo = UpdateInfo.Create(baseEntry, new[] { latestFullEntry }, packagesDir); updateInfo.ReleasesToApply.Contains(latestFullEntry).ShouldBeTrue(); var progress = new List<int>(); await fixture.ApplyReleases(updateInfo, false, false, progress.Add); this.Log().Info("Progress: [{0}]", String.Join(",", progress)); progress .Aggregate(0, (acc, x) => { x.ShouldBeGreaterThan(acc); return x; }) .ShouldEqual(100); var filesToFind = new[] { new {Name = "NLog.dll", Version = new Version("2.0.0.0")}, new {Name = "NSync.Core.dll", Version = new Version("1.1.0.0")}, }; filesToFind.ForEach(x => { var path = Path.Combine(tempDir, "theApp", "app-1.1.0.0", x.Name); this.Log().Info("Looking for {0}", path); File.Exists(path).ShouldBeTrue(); var vi = FileVersionInfo.GetVersionInfo(path); var verInfo = new Version(vi.FileVersion ?? "1.0.0.0"); x.Version.ShouldEqual(verInfo); }); } } [Fact] public async Task ApplyReleaseWhichRemovesAFile() { string tempDir; using (Utility.WithTempDirectory(out tempDir)) { string appDir = Path.Combine(tempDir, "theApp"); string packagesDir = Path.Combine(appDir, "packages"); Directory.CreateDirectory(packagesDir); new[] { "Squirrel.Core.1.1.0.0-full.nupkg", "Squirrel.Core.1.2.0.0-full.nupkg", }.ForEach(x => File.Copy(IntegrationTestHelper.GetPath("fixtures", x), Path.Combine(packagesDir, x))); var fixture = new UpdateManager.ApplyReleasesImpl(appDir); var baseEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.1.0.0-full.nupkg")); var latestFullEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.2.0.0-full.nupkg")); var updateInfo = UpdateInfo.Create(baseEntry, new[] { latestFullEntry }, packagesDir); updateInfo.ReleasesToApply.Contains(latestFullEntry).ShouldBeTrue(); var progress = new List<int>(); await fixture.ApplyReleases(updateInfo, false, false, progress.Add); this.Log().Info("Progress: [{0}]", String.Join(",", progress)); progress .Aggregate(0, (acc, x) => { x.ShouldBeGreaterThan(acc); return x; }) .ShouldEqual(100); var rootDirectory = Path.Combine(tempDir, "theApp", "app-1.2.0.0"); new[] { new {Name = "NLog.dll", Version = new Version("2.0.0.0")}, new {Name = "NSync.Core.dll", Version = new Version("1.1.0.0")}, }.ForEach(x => { var path = Path.Combine(rootDirectory, x.Name); this.Log().Info("Looking for {0}", path); File.Exists(path).ShouldBeTrue(); }); var removedFile = Path.Combine("sub", "Ionic.Zip.dll"); var deployedPath = Path.Combine(rootDirectory, removedFile); File.Exists(deployedPath).ShouldBeFalse(); } } [Fact] public async Task ApplyReleaseWhichMovesAFileToADifferentDirectory() { string tempDir; using (Utility.WithTempDirectory(out tempDir)) { string appDir = Path.Combine(tempDir, "theApp"); string packagesDir = Path.Combine(appDir, "packages"); Directory.CreateDirectory(packagesDir); new[] { "Squirrel.Core.1.1.0.0-full.nupkg", "Squirrel.Core.1.3.0.0-full.nupkg", }.ForEach(x => File.Copy(IntegrationTestHelper.GetPath("fixtures", x), Path.Combine(packagesDir, x))); var fixture = new UpdateManager.ApplyReleasesImpl(appDir); var baseEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.1.0.0-full.nupkg")); var latestFullEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.3.0.0-full.nupkg")); var updateInfo = UpdateInfo.Create(baseEntry, new[] { latestFullEntry }, packagesDir); updateInfo.ReleasesToApply.Contains(latestFullEntry).ShouldBeTrue(); var progress = new List<int>(); await fixture.ApplyReleases(updateInfo, false, false, progress.Add); this.Log().Info("Progress: [{0}]", String.Join(",", progress)); progress .Aggregate(0, (acc, x) => { x.ShouldBeGreaterThan(acc); return x; }) .ShouldEqual(100); var rootDirectory = Path.Combine(tempDir, "theApp", "app-1.3.0.0"); new[] { new {Name = "NLog.dll", Version = new Version("2.0.0.0")}, new {Name = "NSync.Core.dll", Version = new Version("1.1.0.0")}, }.ForEach(x => { var path = Path.Combine(rootDirectory, x.Name); this.Log().Info("Looking for {0}", path); File.Exists(path).ShouldBeTrue(); }); var oldFile = Path.Combine(rootDirectory, "sub", "Ionic.Zip.dll"); File.Exists(oldFile).ShouldBeFalse(); var newFile = Path.Combine(rootDirectory, "other", "Ionic.Zip.dll"); File.Exists(newFile).ShouldBeTrue(); } } [Fact] public async Task ApplyReleasesWithDeltaReleases() { string tempDir; using (Utility.WithTempDirectory(out tempDir)) { string appDir = Path.Combine(tempDir, "theApp"); string packagesDir = Path.Combine(appDir, "packages"); Directory.CreateDirectory(packagesDir); new[] { "Squirrel.Core.1.0.0.0-full.nupkg", "Squirrel.Core.1.1.0.0-delta.nupkg", "Squirrel.Core.1.1.0.0-full.nupkg", }.ForEach(x => File.Copy(IntegrationTestHelper.GetPath("fixtures", x), Path.Combine(packagesDir, x))); var fixture = new UpdateManager.ApplyReleasesImpl(appDir); var baseEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.0.0.0-full.nupkg")); var deltaEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.1.0.0-delta.nupkg")); var latestFullEntry = ReleaseEntry.GenerateFromFile(Path.Combine(packagesDir, "Squirrel.Core.1.1.0.0-full.nupkg")); var updateInfo = UpdateInfo.Create(baseEntry, new[] { deltaEntry, latestFullEntry }, packagesDir); updateInfo.ReleasesToApply.Contains(deltaEntry).ShouldBeTrue(); var progress = new List<int>(); await fixture.ApplyReleases(updateInfo, false, false, progress.Add); this.Log().Info("Progress: [{0}]", String.Join(",", progress)); progress .Aggregate(0, (acc, x) => { x.ShouldBeGreaterThan(acc); return x; }) .ShouldEqual(100); var filesToFind = new[] { new {Name = "NLog.dll", Version = new Version("2.0.0.0")}, new {Name = "NSync.Core.dll", Version = new Version("1.1.0.0")}, }; filesToFind.ForEach(x => { var path = Path.Combine(tempDir, "theApp", "app-1.1.0.0", x.Name); this.Log().Info("Looking for {0}", path); File.Exists(path).ShouldBeTrue(); var vi = FileVersionInfo.GetVersionInfo(path); var verInfo = new Version(vi.FileVersion ?? "1.0.0.0"); x.Version.ShouldEqual(verInfo); }); } } [Fact] public async Task CreateFullPackagesFromDeltaSmokeTest() { string tempDir; using (Utility.WithTempDirectory(out tempDir)) { string appDir = Path.Combine(tempDir, "theApp"); string packagesDir = Path.Combine(appDir, "packages"); Directory.CreateDirectory(packagesDir); new[] { "Squirrel.Core.1.0.0.0-full.nupkg", "Squirrel.Core.1.1.0.0-delta.nupkg" }.ForEach(x => File.Copy(IntegrationTestHelper.GetPath("fixtures", x), Path.Combine(tempDir, "theApp", "packages", x))); var urlDownloader = new FakeUrlDownloader(); var fixture = new UpdateManager.ApplyReleasesImpl(appDir); var baseEntry = ReleaseEntry.GenerateFromFile(Path.Combine(tempDir, "theApp", "packages", "Squirrel.Core.1.0.0.0-full.nupkg")); var deltaEntry = ReleaseEntry.GenerateFromFile(Path.Combine(tempDir, "theApp", "packages", "Squirrel.Core.1.1.0.0-delta.nupkg")); var resultObs = (Task<ReleaseEntry>)fixture.GetType().GetMethod("createFullPackagesFromDeltas", BindingFlags.NonPublic | BindingFlags.Instance) .Invoke(fixture, new object[] { new[] {deltaEntry}, baseEntry }); var result = await resultObs; var zp = new ZipPackage(Path.Combine(tempDir, "theApp", "packages", result.Filename)); zp.Version.ToString().ShouldEqual("1.1.0.0"); } } [Fact] public async Task CreateShortcutsRoundTrip() { string remotePkgPath; string path; using (Utility.WithTempDirectory(out path)) { using (Utility.WithTempDirectory(out remotePkgPath)) using (var mgr = new UpdateManager(remotePkgPath, "theApp", path)) { IntegrationTestHelper.CreateFakeInstalledApp("1.0.0.1", remotePkgPath); await mgr.FullInstall(); } var fixture = new UpdateManager.ApplyReleasesImpl(Path.Combine(path, "theApp")); fixture.CreateShortcutsForExecutable("SquirrelAwareApp.exe", ShortcutLocation.Desktop | ShortcutLocation.StartMenu | ShortcutLocation.Startup | ShortcutLocation.AppRoot | ShortcutLocation.Taskbar, false, null, null); // NB: COM is Weird. Thread.Sleep(1000); fixture.RemoveShortcutsForExecutable("SquirrelAwareApp.exe", ShortcutLocation.Desktop | ShortcutLocation.StartMenu | ShortcutLocation.Startup | ShortcutLocation.AppRoot | ShortcutLocation.Taskbar); // NB: Squirrel-Aware first-run might still be running, slow // our roll before blowing away the temp path Thread.Sleep(1000); } } [Fact] public async Task GetShortcutsSmokeTest() { string remotePkgPath; string path; using (Utility.WithTempDirectory(out path)) { using (Utility.WithTempDirectory(out remotePkgPath)) using (var mgr = new UpdateManager(remotePkgPath, "theApp", path)) { IntegrationTestHelper.CreateFakeInstalledApp("1.0.0.1", remotePkgPath); await mgr.FullInstall(); } var fixture = new UpdateManager.ApplyReleasesImpl(Path.Combine(path, "theApp")); var result = fixture.GetShortcutsForExecutable("SquirrelAwareApp.exe", ShortcutLocation.Desktop | ShortcutLocation.StartMenu | ShortcutLocation.Startup, null); Assert.Equal(3, result.Keys.Count); // NB: Squirrel-Aware first-run might still be running, slow // our roll before blowing away the temp path Thread.Sleep(1000); } } } }
/* * 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 copyrightD * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Text; using OMV = OpenMetaverse; namespace OpenSim.Region.PhysicsModule.BulletS { public abstract class BSLinkset { // private static string LogHeader = "[BULLETSIM LINKSET]"; public enum LinksetImplementation { Constraint = 0, // linkset tied together with constraints Compound = 1, // linkset tied together as a compound object Manual = 2 // linkset tied together manually (code moves all the pieces) } // Create the correct type of linkset for this child public static BSLinkset Factory(BSScene physScene, BSPrimLinkable parent) { BSLinkset ret = null; switch (parent.LinksetType) { case LinksetImplementation.Constraint: ret = new BSLinksetConstraints(physScene, parent); break; case LinksetImplementation.Compound: ret = new BSLinksetCompound(physScene, parent); break; case LinksetImplementation.Manual: // ret = new BSLinksetManual(physScene, parent); break; default: ret = new BSLinksetCompound(physScene, parent); break; } if (ret == null) { physScene.Logger.ErrorFormat("[BULLETSIM LINKSET] Factory could not create linkset. Parent name={1}, ID={2}", parent.Name, parent.LocalID); } return ret; } public class BSLinkInfo { public BSPrimLinkable member; public BSLinkInfo(BSPrimLinkable pMember) { member = pMember; } public virtual void ResetLink() { } public virtual void SetLinkParameters(BSConstraint constrain) { } // Returns 'true' if physical property updates from the child should be reported to the simulator public virtual bool ShouldUpdateChildProperties() { return false; } } public LinksetImplementation LinksetImpl { get; protected set; } public BSPrimLinkable LinksetRoot { get; protected set; } protected BSScene m_physicsScene { get; private set; } static int m_nextLinksetID = 1; public int LinksetID { get; private set; } // The children under the root in this linkset. // protected HashSet<BSPrimLinkable> m_children; protected Dictionary<BSPrimLinkable, BSLinkInfo> m_children; // We lock the diddling of linkset classes to prevent any badness. // This locks the modification of the instances of this class. Changes // to the physical representation is done via the tainting mechenism. protected object m_linksetActivityLock = new Object(); // We keep the prim's mass in the linkset structure since it could be dependent on other prims public float LinksetMass { get; protected set; } public virtual bool LinksetIsColliding { get { return false; } } public OMV.Vector3 CenterOfMass { get { return ComputeLinksetCenterOfMass(); } } public OMV.Vector3 GeometricCenter { get { return ComputeLinksetGeometricCenter(); } } protected BSLinkset(BSScene scene, BSPrimLinkable parent) { // A simple linkset of one (no children) LinksetID = m_nextLinksetID++; // We create LOTS of linksets. if (m_nextLinksetID <= 0) m_nextLinksetID = 1; m_physicsScene = scene; LinksetRoot = parent; m_children = new Dictionary<BSPrimLinkable, BSLinkInfo>(); LinksetMass = parent.RawMass; Rebuilding = false; RebuildScheduled = false; parent.ClearDisplacement(); } // Link to a linkset where the child knows the parent. // Parent changing should not happen so do some sanity checking. // We return the parent's linkset so the child can track its membership. // Called at runtime. public BSLinkset AddMeToLinkset(BSPrimLinkable child) { lock (m_linksetActivityLock) { // Don't add the root to its own linkset if (!IsRoot(child)) AddChildToLinkset(child); LinksetMass = ComputeLinksetMass(); } return this; } // Remove a child from a linkset. // Returns a new linkset for the child which is a linkset of one (just the // orphened child). // Called at runtime. public BSLinkset RemoveMeFromLinkset(BSPrimLinkable child, bool inTaintTime) { lock (m_linksetActivityLock) { if (IsRoot(child)) { // Cannot remove the root from a linkset. return this; } RemoveChildFromLinkset(child, inTaintTime); LinksetMass = ComputeLinksetMass(); } // The child is down to a linkset of just itself return BSLinkset.Factory(m_physicsScene, child); } // Return 'true' if the passed object is the root object of this linkset public bool IsRoot(BSPrimLinkable requestor) { return (requestor.LocalID == LinksetRoot.LocalID); } public int NumberOfChildren { get { return m_children.Count; } } // Return 'true' if this linkset has any children (more than the root member) public bool HasAnyChildren { get { return (m_children.Count > 0); } } // Return 'true' if this child is in this linkset public bool HasChild(BSPrimLinkable child) { bool ret = false; lock (m_linksetActivityLock) { ret = m_children.ContainsKey(child); } return ret; } // Perform an action on each member of the linkset including root prim. // Depends on the action on whether this should be done at taint time. public delegate bool ForEachMemberAction(BSPrimLinkable obj); public virtual bool ForEachMember(ForEachMemberAction action) { bool ret = false; lock (m_linksetActivityLock) { action(LinksetRoot); foreach (BSPrimLinkable po in m_children.Keys) { if (action(po)) break; } } return ret; } public bool TryGetLinkInfo(BSPrimLinkable child, out BSLinkInfo foundInfo) { bool ret = false; BSLinkInfo found = null; lock (m_linksetActivityLock) { ret = m_children.TryGetValue(child, out found); } foundInfo = found; return ret; } // Perform an action on each member of the linkset including root prim. // Depends on the action on whether this should be done at taint time. public delegate bool ForEachLinkInfoAction(BSLinkInfo obj); public virtual bool ForEachLinkInfo(ForEachLinkInfoAction action) { bool ret = false; lock (m_linksetActivityLock) { foreach (BSLinkInfo po in m_children.Values) { if (action(po)) break; } } return ret; } // Check the type of the link and return 'true' if the link is flexible and the // updates from the child should be sent to the simulator so things change. public virtual bool ShouldReportPropertyUpdates(BSPrimLinkable child) { bool ret = false; BSLinkInfo linkInfo; if (m_children.TryGetValue(child, out linkInfo)) { ret = linkInfo.ShouldUpdateChildProperties(); } return ret; } // Called after a simulation step to post a collision with this object. // Return 'true' if linkset processed the collision. 'false' says the linkset didn't have // anything to add for the collision and it should be passed through normal processing. // Default processing for a linkset. public virtual bool HandleCollide(BSPhysObject collider, BSPhysObject collidee, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth) { bool ret = false; // prims in the same linkset cannot collide with each other BSPrimLinkable convCollidee = collidee as BSPrimLinkable; if (convCollidee != null && (LinksetID == convCollidee.Linkset.LinksetID)) { // By returning 'true', we tell the caller the collision has been 'handled' so it won't // do anything about this collision and thus, effectivily, ignoring the collision. ret = true; } else { // Not a collision between members of the linkset. Must be a real collision. // So the linkset root can know if there is a collision anywhere in the linkset. LinksetRoot.SomeCollisionSimulationStep = m_physicsScene.SimulationStep; } return ret; } // I am the root of a linkset and a new child is being added // Called while LinkActivity is locked. protected abstract void AddChildToLinkset(BSPrimLinkable child); // I am the root of a linkset and one of my children is being removed. // Safe to call even if the child is not really in my linkset. protected abstract void RemoveChildFromLinkset(BSPrimLinkable child, bool inTaintTime); // When physical properties are changed the linkset needs to recalculate // its internal properties. // May be called at runtime or taint-time. public virtual void Refresh(BSPrimLinkable requestor) { LinksetMass = ComputeLinksetMass(); } // Flag denoting the linkset is in the process of being rebuilt. // Used to know not the schedule a rebuild in the middle of a rebuild. // Because of potential update calls that could want to schedule another rebuild. protected bool Rebuilding { get; set; } // Flag saying a linkset rebuild has been scheduled. // This is turned on when the rebuild is requested and turned off when // the rebuild is complete. Used to limit modifications to the // linkset parameters while the linkset is in an intermediate state. // Protected by a "lock(m_linsetActivityLock)" on the BSLinkset object public bool RebuildScheduled { get; protected set; } // The object is going dynamic (physical). Do any setup necessary // for a dynamic linkset. // Only the state of the passed object can be modified. The rest of the linkset // has not yet been fully constructed. // Return 'true' if any properties updated on the passed object. // Called at taint-time! public abstract bool MakeDynamic(BSPrimLinkable child); public virtual bool AllPartsComplete { get { bool ret = true; this.ForEachMember((member) => { if ((!member.IsInitialized) || member.IsIncomplete || member.PrimAssetState == BSPhysObject.PrimAssetCondition.Waiting) { ret = false; return true; // exit loop } return false; // continue loop }); return ret; } } // The object is going static (non-physical). Do any setup necessary // for a static linkset. // Return 'true' if any properties updated on the passed object. // Called at taint-time! public abstract bool MakeStatic(BSPrimLinkable child); // Called when a parameter update comes from the physics engine for any object // of the linkset is received. // Passed flag is update came from physics engine (true) or the user (false). // Called at taint-time!! public abstract void UpdateProperties(UpdatedProperties whichUpdated, BSPrimLinkable physObject); // Routine used when rebuilding the body of the root of the linkset // Destroy all the constraints have have been made to root. // This is called when the root body is changing. // Returns 'true' of something was actually removed and would need restoring // Called at taint-time!! public abstract bool RemoveDependencies(BSPrimLinkable child); // ================================================================ // Some physical setting happen to all members of the linkset public virtual void SetPhysicalFriction(float friction) { ForEachMember((member) => { if (member.PhysBody.HasPhysicalBody) m_physicsScene.PE.SetFriction(member.PhysBody, friction); return false; // 'false' says to continue looping } ); } public virtual void SetPhysicalRestitution(float restitution) { ForEachMember((member) => { if (member.PhysBody.HasPhysicalBody) m_physicsScene.PE.SetRestitution(member.PhysBody, restitution); return false; // 'false' says to continue looping } ); } public virtual void SetPhysicalGravity(OMV.Vector3 gravity) { ForEachMember((member) => { if (member.PhysBody.HasPhysicalBody) m_physicsScene.PE.SetGravity(member.PhysBody, gravity); return false; // 'false' says to continue looping } ); } public virtual void ComputeAndSetLocalInertia(OMV.Vector3 inertiaFactor, float linksetMass) { ForEachMember((member) => { if (member.PhysBody.HasPhysicalBody) { OMV.Vector3 inertia = m_physicsScene.PE.CalculateLocalInertia(member.PhysShape.physShapeInfo, linksetMass); member.Inertia = inertia * inertiaFactor; m_physicsScene.PE.SetMassProps(member.PhysBody, linksetMass, member.Inertia); m_physicsScene.PE.UpdateInertiaTensor(member.PhysBody); DetailLog("{0},BSLinkset.ComputeAndSetLocalInertia,m.mass={1}, inertia={2}", member.LocalID, linksetMass, member.Inertia); } return false; // 'false' says to continue looping } ); } public virtual void SetPhysicalCollisionFlags(CollisionFlags collFlags) { ForEachMember((member) => { if (member.PhysBody.HasPhysicalBody) m_physicsScene.PE.SetCollisionFlags(member.PhysBody, collFlags); return false; // 'false' says to continue looping } ); } public virtual void AddToPhysicalCollisionFlags(CollisionFlags collFlags) { ForEachMember((member) => { if (member.PhysBody.HasPhysicalBody) m_physicsScene.PE.AddToCollisionFlags(member.PhysBody, collFlags); return false; // 'false' says to continue looping } ); } public virtual void RemoveFromPhysicalCollisionFlags(CollisionFlags collFlags) { ForEachMember((member) => { if (member.PhysBody.HasPhysicalBody) m_physicsScene.PE.RemoveFromCollisionFlags(member.PhysBody, collFlags); return false; // 'false' says to continue looping } ); } // ================================================================ protected virtual float ComputeLinksetMass() { float mass = LinksetRoot.RawMass; if (HasAnyChildren) { lock (m_linksetActivityLock) { foreach (BSPrimLinkable bp in m_children.Keys) { mass += bp.RawMass; } } } return mass; } // Computes linkset's center of mass in world coordinates. protected virtual OMV.Vector3 ComputeLinksetCenterOfMass() { OMV.Vector3 com; lock (m_linksetActivityLock) { com = LinksetRoot.Position * LinksetRoot.RawMass; float totalMass = LinksetRoot.RawMass; foreach (BSPrimLinkable bp in m_children.Keys) { com += bp.Position * bp.RawMass; totalMass += bp.RawMass; } if (totalMass != 0f) com /= totalMass; } return com; } protected virtual OMV.Vector3 ComputeLinksetGeometricCenter() { OMV.Vector3 com; lock (m_linksetActivityLock) { com = LinksetRoot.Position; foreach (BSPrimLinkable bp in m_children.Keys) { com += bp.Position; } com /= (m_children.Count + 1); } return com; } #region Extension public virtual object Extension(string pFunct, params object[] pParams) { return null; } #endregion // Extension // Invoke the detailed logger and output something if it's enabled. protected void DetailLog(string msg, params Object[] args) { if (m_physicsScene.PhysicsLogging.Enabled) m_physicsScene.DetailLog(msg, args); } } }
#region Imports... using DataAccess; using FCSAmerica.DifferenceMaker; using FCSAmerica.DifferenceMaker.Models; using log4net; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Web.UI.WebControls; #endregion partial class Admin_Reporting : System.Web.UI.Page { ILog _log = LogManager.GetLogger("Reporting"); #region Constants... private const int VW_REPORT_SELECTION = 0; #endregion #region Private Attributes... private static string _currentPayPeriod = string.Empty; #endregion #region Event Handlers... /// <summary> /// Initializes the web page. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param> override protected void OnInit(EventArgs e) { base.OnInit(e); lnkAwardsByEmployee.Click += this.lnkAwardsByEmployee_Click; lnkAybForTax.Click += this.lnkAybForTax_Click; ddlYearAyb.SelectedIndexChanged += this.ddlYearAyb_SelectedIndexChanged; } //ORIGINAL LINE: Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles this.Load override protected void OnLoad(EventArgs e) { base.OnLoad(e); if (!(Page.IsPostBack)) { if (UserUtil.IsCurrentUserAdmin()) { //Set so person can view all awards, and do record deletions Session["currentUser_EmpID"] = -1; //Only Admins can execute the tax report lnkAybForTax.Visible = true; } else { //If the person isn't in "AYBAdmins", get their user ID, so the report will only be on their subemployees GetCurrentUser(); //Hide the tax report link if the current user is not an Admin //lnkAybForTax.Visible = false; lnkAybForTax.Visible = false; } //Set the initial view this.mvAdmin.ActiveViewIndex = VW_REPORT_SELECTION; //Obtain the current pay period _currentPayPeriod = GetCurrentPayPeriod(); //Populate the year drop-down list with a set of valid years (based on what's in the database) PopulateYearsLists(); //Populate the pay period drop-down list based on the currently selected year PopulatePayPeriods(DateTime.Now.Year); Session["CurrentNodeValue"] = "0"; } } /// <summary> /// Generates the "Awards for Tax Purposes" report. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param> protected void btnGenerateTaxReport_Click(object sender, System.EventArgs e) { this.treeEmployees.Visible = false; if (this.ddlAybReportType.SelectedIndex == 0) { Session["fileName"] = "AYB25DollarAwards"; } else if (this.ddlAybReportType.SelectedIndex == 1) { Session["fileName"] = "AYBOtherDollarAwards"; } } /// <summary> /// Displays the "Awards by Employee" report criteria form. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param> protected void lnkAwardsByEmployee_Click(object sender, System.EventArgs e) { GetActiveEmployees(); if (this.treeEmployees.Nodes != null) { this.mvAdmin.ActiveViewIndex = 1; } } /// <summary> /// Displays the "Awards for Tax Purposes" report criteria form. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param> protected void lnkAybForTax_Click(object sender, System.EventArgs e) { this.mvAdmin.ActiveViewIndex = 2; } /// <summary> /// Reloads the pay period selection drop-down list when a different year is selected. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param> protected void ddlYearAyb_SelectedIndexChanged(object sender, System.EventArgs e) { PopulatePayPeriods(int.Parse(ddlYearAyb.SelectedValue)); } #endregion #region Private Methods... /// <summary> /// Populates the years lists based on the minimum and maximum years found in the payroll schedules /// stored within the database. /// </summary> private void PopulateYearsLists() { ddlYearAyb.Items.Clear(); for (int year = GetMinimumPayPeriodYear(); year <= DateTime.Now.Year; year++) { ddlYearAyb.Items.Add(new ListItem(year.ToString(), year.ToString())); if (year == DateTime.Now.Year) { ddlYearAyb.SelectedIndex = ddlYearAyb.Items.Count - 1; } } } /// <summary> /// Populates the list of active employees that report to the person currently logged in. /// </summary> private void GetActiveEmployees() { this.treeEmployees.Visible = true; //this.pnlGridButtons.Visible = false; DataSet dsEmployees = new DataSet(); var tvEmployees = this.treeEmployees; //Get the leader information for the root node of the tree var currentUserEmpID = SessionHelper.GetValue<int>(Session["currentUser_EmpID"]); var dtLeaders = GetLeaders(currentUserEmpID); var dtEmployees = GetEmployees(currentUserEmpID); dsEmployees.Tables.Add(dtLeaders); dsEmployees.Tables.Add(dtEmployees); //add relations to dataset to allow for hierarchical logic dsEmployees.Relations.Add("relEmployees", dsEmployees.Tables["dtLeaders"].Columns["Employee_ID"], dsEmployees.Tables["dtEmployees"].Columns["LeaderEmployee_ID"], false); dsEmployees.Relations.Add("relEmptoLeader", dsEmployees.Tables["dtEmployees"].Columns["Employee_ID"], dsEmployees.Tables["dtEmployees"].Columns["LeaderEmployee_ID"], false); TreeNode nodeLeader; TreeNode nodeEmployee = null; TreeNode nodeEmployee_level2 = null; TreeNode nodeEmployee_level3 = null; TreeNode nodeEmployee_level4 = null; foreach (DataRow rowLeader in dsEmployees.Tables["dtLeaders"].Rows) { //Leader nodeLeader = new TreeNode(); nodeLeader.Text = (string)rowLeader["Leader_Name"]; nodeLeader.Value = rowLeader["Employee_ID"].ToString(); tvEmployees.Nodes.Add(nodeLeader); foreach (DataRow rowemployee in rowLeader.GetChildRows("relEmployees")) { //Leader // -SubLeader nodeEmployee = new TreeNode(); nodeEmployee.Text = (string)rowemployee["NameDisplay"]; nodeEmployee.Value = rowemployee["Employee_ID"].ToString(); nodeLeader.ChildNodes.Add(nodeEmployee); foreach (DataRow rowemployee_level2 in rowemployee.GetChildRows("relEmpToLeader")) { //Leader // -SubLeader // -SubLeader nodeEmployee_level2 = new TreeNode(); nodeEmployee_level2.Text = (string)rowemployee_level2["NameDisplay"]; nodeEmployee_level2.Value = rowemployee_level2["Employee_ID"].ToString(); nodeEmployee.ChildNodes.Add(nodeEmployee_level2); foreach (DataRow rowEmployee_level3 in rowemployee_level2.GetChildRows("relEmpToLeader")) { //Leader // -SubLeader // -SubLeader // -Subleader nodeEmployee_level3 = new TreeNode(); nodeEmployee_level3.Text = (string)rowEmployee_level3["NameDisplay"]; nodeEmployee_level3.Value = rowEmployee_level3["Employee_ID"].ToString(); nodeEmployee_level2.ChildNodes.Add(nodeEmployee_level3); foreach (DataRow rowEmployee_level4 in rowEmployee_level3.GetChildRows("relEmpToLeader")) { //Leader // -SubLeader // -SubLeader // -SubLeader // -Lowest Level Employee nodeEmployee_level4 = new TreeNode(); nodeEmployee_level4.Text = (string)rowEmployee_level4["NameDisplay"]; nodeEmployee_level4.Value = rowEmployee_level4["Employee_ID"].ToString(); nodeEmployee_level3.ChildNodes.Add(nodeEmployee_level4); } } } } } //select first node of the tree automatically if (this.treeEmployees.Nodes.Count > 0) { this.treeEmployees.Nodes[0].Selected = true; } } private DataTable GetLeaders(int currentUserEmpId) { var tableName = "dtLeaders"; var result = GetEmptyTable<Leader_S_Result>(tableName); using (var client = new HttpClient()) { var url = "employee/leader/" + currentUserEmpId; client.BaseAddress = new Uri(ConfigurationManager.AppSettings["restUrl"]); var apiResponse = client.GetAsync(url).Result; if (apiResponse.StatusCode == HttpStatusCode.NotFound) { return result; } var data = apiResponse.Content.ReadAsAsync<DataTable>().Result; if (data.Rows.Count == 0) { return result; } FillTable(result, data); return result; } } private DataTable GetEmployees(int currentUserEmpId) { var tableName = "dtEmployees"; var result = GetEmptyTable<Employees_OfLeader_Result>(tableName); using (var client = new HttpClient()) { var url = "employee/leaderEmployee/" + currentUserEmpId; client.BaseAddress = new Uri(ConfigurationManager.AppSettings["restUrl"]); var apiResponse = client.GetAsync(url).Result; if (apiResponse.StatusCode == HttpStatusCode.NotFound) { return result; } var data = apiResponse.Content.ReadAsAsync<DataTable>().Result; if (data.Rows.Count == 0) { return result; } FillTable(result, data); return result; } } private DataTable GetEmptyTable<T>(string tableName) { var empty = new DataTable(); foreach (var prop in typeof(T).GetProperties()) { var propertyType = prop.PropertyType; if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) { propertyType = propertyType.GetGenericArguments()[0]; } empty.Columns.Add(prop.Name, propertyType); } empty.TableName = tableName; return empty; } private void FillTable(DataTable table, DataTable data) { table.BeginLoadData(); for (int i = 0; i < data.Rows.Count; i++) { table.LoadDataRow(data.Rows[i].ItemArray,true); } table.EndLoadData(); } /// <summary> /// Gets the currently logged in user's customer ID and stores it within a session variable. /// </summary> /// <remarks>The Employee ID for the currently logged in user is stored in a session variable /// called "currentUser_empID".</remarks> private void GetCurrentUser() { var loggedUserProvider = new LoggedUserProvider(); var loggedUser = loggedUserProvider.GetLoggedUserFromNetworkId(); var currentUserID = loggedUser.Employee_ID; Session["currentUser_empID"] = currentUserID; } /// <summary> /// Gets the current pay period. /// </summary> /// <returns>The current pay period in the format of "YYYY-NN" where: /// YYYY = Year /// NN = Pay period number. /// If no pay period is available for the current date, then an empty string is returned.</returns> private string GetCurrentPayPeriod() { object payPeriod = null; return String.Empty; } /// <summary> /// Populates the pay period selection drop-down list. /// </summary> /// <param name="year">The year in which to populate pay periods for.</param> private void PopulatePayPeriods(int year) { ddlPayPeriodAyb.Items.Clear(); var yearPaySchedules = new List<PaySchedule_OfYear_Result>(); using (var client = new HttpClient()) { var payScheduleUri = "report/payschedule/" + year; client.BaseAddress = new Uri(ConfigurationManager.AppSettings["restUrl"]); HttpResponseMessage responseMessage = client.GetAsync(payScheduleUri).Result; if (responseMessage.IsSuccessStatusCode) { yearPaySchedules = responseMessage.Content.ReadAsAsync<List<PaySchedule_OfYear_Result>>().Result; } foreach (var yearPaySchedule in yearPaySchedules) { var yearPay = yearPaySchedule.PayPeriodNumber_tx; if (yearPay != null) { string payPeriodNumber = yearPay.Split('-')[1].Trim(); string formattedPayPeriodSchedule = yearPaySchedule.PayrollDeadlineDate_dt.ToShortDateString(); ddlPayPeriodAyb.Items.Add(new ListItem(string.Format("{0} - {1}", payPeriodNumber, formattedPayPeriodSchedule), payPeriodNumber)); if (yearPaySchedule.PayPeriodNumber_tx == _currentPayPeriod) { ddlPayPeriodAyb.SelectedIndex = ddlPayPeriodAyb.Items.Count - 1; } } } } } /// <summary> /// Gets a list of payment period years from the database. /// </summary> /// <returns></returns> private int GetMinimumPayPeriodYear() { //Fills up the ddlAybYear with the min and max value of dropdown var minimumPayPeriodYears = new List<PaySchedule_MinMaxOfYear_Result>(); var minYear = 0; using (var client = new HttpClient()) { var requestUri = "report/minmaxpayschedule/"; client.BaseAddress = new Uri(ConfigurationManager.AppSettings["restUrl"]); HttpResponseMessage responseMessage = client.GetAsync(requestUri).Result; if (responseMessage.IsSuccessStatusCode) { minimumPayPeriodYears = responseMessage.Content.ReadAsAsync<List<PaySchedule_MinMaxOfYear_Result>>().Result; } foreach (var payPeriodYear in minimumPayPeriodYears) { minYear = payPeriodYear.MinPayScheduleYear.HasValue ? payPeriodYear.MinPayScheduleYear.Value : DateTime.Now.Year; } return minYear; } } #endregion protected void treeEmployees_SelectedNodeChanged(object sender, EventArgs e) { Session["CurrentNodeValue"] = (sender as TreeView).SelectedNode.Value; } }
// Copyright 2018 Esri. // // 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 ArcGISRuntime.Samples.Managers; using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Symbology; using Esri.ArcGISRuntime.UI; using Esri.ArcGISRuntime.UI.GeoAnalysis; using System; using Xamarin.Forms; using Colors = System.Drawing.Color; namespace ArcGISRuntime.Samples.LineOfSightGeoElement { [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Line of sight (geoelement)", category: "Analysis", description: "Show a line of sight between two moving objects.", instructions: "A line of sight will display between a point on the Empire State Building (observer) and a taxi (target).", tags: new[] { "3D", "line of sight", "visibility", "visibility analysis" })] [ArcGISRuntime.Samples.Shared.Attributes.OfflineData("3af5cfec0fd24dac8d88aea679027cb9")] public partial class LineOfSightGeoElement : ContentPage { // URL of the elevation service - provides elevation component of the scene private readonly Uri _elevationUri = new Uri("https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer"); // URL of the building service - provides builidng models private readonly Uri _buildingsUri = new Uri("https://tiles.arcgis.com/tiles/z2tnIkrLQ2BRzr6P/arcgis/rest/services/New_York_LoD2_3D_Buildings/SceneServer/layers/0"); // Starting point of the observation point private readonly MapPoint _observerPoint = new MapPoint(-73.984988, 40.748131, 20, SpatialReferences.Wgs84); // Graphic to represent the observation point private Graphic _observerGraphic; // Graphic to represent the observed target private Graphic _taxiGraphic; // Line of Sight Analysis private GeoElementLineOfSight _geoLine; // For taxi animation - four points in a loop private readonly MapPoint[] _points = { new MapPoint(-73.984513, 40.748469, SpatialReferences.Wgs84), new MapPoint(-73.985068, 40.747786, SpatialReferences.Wgs84), new MapPoint(-73.983452, 40.747091, SpatialReferences.Wgs84), new MapPoint(-73.982961, 40.747762, SpatialReferences.Wgs84) }; // For taxi animation - tracks animation state private int _pointIndex = 0; private int _frameIndex = 0; private readonly int _frameMax = 150; public LineOfSightGeoElement() { InitializeComponent(); // Create the UI, setup the control references and execute initialization Initialize(); } private async void Initialize() { // Create scene Scene myScene = new Scene(BasemapStyle.ArcGISImagery) { // Set initial viewpoint InitialViewpoint = new Viewpoint(_observerPoint, 1600) }; // Create the elevation source ElevationSource myElevationSource = new ArcGISTiledElevationSource(_elevationUri); // Add the elevation source to the scene myScene.BaseSurface.ElevationSources.Add(myElevationSource); // Create the building scene layer ArcGISSceneLayer mySceneLayer = new ArcGISSceneLayer(_buildingsUri); // Add the building layer to the scene myScene.OperationalLayers.Add(mySceneLayer); // Add the observer to the scene // Create a graphics overlay with relative surface placement; relative surface placement allows the Z position of the observation point to be adjusted GraphicsOverlay overlay = new GraphicsOverlay() { SceneProperties = new LayerSceneProperties(SurfacePlacement.Relative) }; // Create the symbol that will symbolize the observation point SimpleMarkerSceneSymbol symbol = new SimpleMarkerSceneSymbol(SimpleMarkerSceneSymbolStyle.Sphere, Colors.Red, 10, 10, 10, SceneSymbolAnchorPosition.Bottom); // Create the observation point graphic from the point and symbol _observerGraphic = new Graphic(_observerPoint, symbol); // Add the observer to the overlay overlay.Graphics.Add(_observerGraphic); // Add the overlay to the scene MySceneView.GraphicsOverlays.Add(overlay); try { // Add the taxi to the scene // Create the model symbol for the taxi ModelSceneSymbol taxiSymbol = await ModelSceneSymbol.CreateAsync(new Uri(GetModelUri())); // Set the anchor position for the mode; ensures that the model appears above the ground taxiSymbol.AnchorPosition = SceneSymbolAnchorPosition.Bottom; // Create the graphic from the taxi starting point and the symbol _taxiGraphic = new Graphic(_points[0], taxiSymbol); // Add the taxi graphic to the overlay overlay.Graphics.Add(_taxiGraphic); // Create GeoElement Line of sight analysis (taxi to building) // Create the analysis _geoLine = new GeoElementLineOfSight(_observerGraphic, _taxiGraphic) { // Apply an offset to the target. This helps avoid some false negatives TargetOffsetZ = 2 }; // Create the analysis overlay AnalysisOverlay myAnalysisOverlay = new AnalysisOverlay(); // Add the analysis to the overlay myAnalysisOverlay.Analyses.Add(_geoLine); // Add the analysis overlay to the scene MySceneView.AnalysisOverlays.Add(myAnalysisOverlay); // Create a timer; this will enable animating the taxi Device.StartTimer(new TimeSpan(0, 0, 0, 0, 60), () => { // Move the taxi every time the timer elapses AnimationTimer_Elapsed(this, null); // Keep the timer running return true; }); // Subscribe to TargetVisible events; allows for updating the UI and selecting the taxi when it is visible _geoLine.TargetVisibilityChanged += Geoline_TargetVisibilityChanged; // Add the scene to the view MySceneView.Scene = myScene; } catch (Exception e) { await Application.Current.MainPage.DisplayAlert("Error", e.ToString(), "OK"); } } private void AnimationTimer_Elapsed(object sender, EventArgs e) { // Note: the contents of this function are solely related to animating the taxi // Increment the frame counter _frameIndex++; // Reset the frame counter once one segment of the path has been travelled if (_frameIndex == _frameMax) { _frameIndex = 0; // Start navigating toward the next point _pointIndex++; // Restart if finished circuit if (_pointIndex == _points.Length) { _pointIndex = 0; } } // Get the point the taxi is travelling from MapPoint starting = _points[_pointIndex]; // Get the point the taxi is travelling to MapPoint ending = _points[(_pointIndex + 1) % _points.Length]; // Calculate the progress based on the current frame double progress = _frameIndex / (double)_frameMax; // Calculate the position of the taxi when it is {progress}% of the way through MapPoint intermediatePoint = InterpolatedPoint(starting, ending, progress); // Update the taxi geometry _taxiGraphic.Geometry = intermediatePoint; // Update the taxi rotation. GeodeticDistanceResult distance = GeometryEngine.DistanceGeodetic(starting, ending, LinearUnits.Meters, AngularUnits.Degrees, GeodeticCurveType.Geodesic); ((ModelSceneSymbol)_taxiGraphic.Symbol).Heading = distance.Azimuth1; } private MapPoint InterpolatedPoint(MapPoint firstPoint, MapPoint secondPoint, double progress) { // This function returns a MapPoint that is the result of travelling {progress}% of the way from {firstPoint} to {secondPoint} // Get the difference between the two points MapPoint difference = new MapPoint(secondPoint.X - firstPoint.X, secondPoint.Y - firstPoint.Y, secondPoint.Z - firstPoint.Z, SpatialReferences.Wgs84); // Scale the difference by the progress towards the destination MapPoint scaled = new MapPoint(difference.X * progress, difference.Y * progress, difference.Z * progress); // Add the scaled progress to the starting point return new MapPoint(firstPoint.X + scaled.X, firstPoint.Y + scaled.Y, firstPoint.Z + scaled.Z); } private void Geoline_TargetVisibilityChanged(object sender, EventArgs e) { // This is needed because Runtime delivers notifications from a different thread that doesn't have access to UI controls Device.BeginInvokeOnMainThread(UpdateUiAndSelection); } private void UpdateUiAndSelection() { switch (_geoLine.TargetVisibility) { case LineOfSightTargetVisibility.Obstructed: MyStatusLabel.Text = "Status: Obstructed"; _taxiGraphic.IsSelected = false; break; case LineOfSightTargetVisibility.Visible: MyStatusLabel.Text = "Status: Visible"; _taxiGraphic.IsSelected = true; break; default: case LineOfSightTargetVisibility.Unknown: MyStatusLabel.Text = "Status: Unknown"; _taxiGraphic.IsSelected = false; break; } } private static string GetModelUri() { // Returns the taxi model return DataManager.GetDataFolder("3af5cfec0fd24dac8d88aea679027cb9", "dolmus.3ds"); } private void MyHeightSlider_ValueChanged(object sender, EventArgs e) { // Update the height of the observer based on the slider value // Constrain the min and max to 20 and 150 units double minHeight = 20; double maxHeight = 150; // Scale the slider value; its default range is 0-10 double value = MyHeightSlider.Value; // Get the current point MapPoint oldPoint = (MapPoint)_observerGraphic.Geometry; // Create a new point with the same (x,y) but updated z MapPoint newPoint = new MapPoint(oldPoint.X, oldPoint.Y, (maxHeight - minHeight) * value + minHeight); // Apply the updated geometry to the observer point _observerGraphic.Geometry = newPoint; } } }
// 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.Runtime.Versioning; #if BIT64 using nint = System.Int64; using nuint = System.UInt64; #else using nint = System.Int32; using nuint = System.UInt32; #endif namespace System.Runtime.CompilerServices { // // Subsetted clone of System.Runtime.CompilerServices.Unsafe for internal runtime use. // Keep in sync with https://github.com/dotnet/corefx/tree/master/src/System.Runtime.CompilerServices.Unsafe. // /// <summary> /// Contains generic, low-level functionality for manipulating pointers. /// </summary> [CLSCompliant(false)] public static class Unsafe { /// <summary> /// Reads a value of type <typeparamref name="T"/> from the given location. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe T Read<T>(void* source) { return Unsafe.As<byte, T>(ref *(byte*)source); } /// <summary> /// Reads a value of type <typeparamref name="T"/> from the given location. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe T Read<T>(ref byte source) { return Unsafe.As<byte, T>(ref source); } /// <summary> /// Reads a value of type <typeparamref name="T"/> from the given location. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe T ReadUnaligned<T>(void* source) { return Unsafe.As<byte, T>(ref *(byte*)source); } /// <summary> /// Reads a value of type <typeparamref name="T"/> from the given location. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe T ReadUnaligned<T>(ref byte source) { return Unsafe.As<byte, T>(ref source); } /// <summary> /// Writes a value of type <typeparamref name="T"/> to the given location. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe void Write<T>(void* source, T value) { Unsafe.As<byte, T>(ref *(byte*)source) = value; } /// <summary> /// Writes a value of type <typeparamref name="T"/> to the given location. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe void Write<T>(ref byte source, T value) { Unsafe.As<byte, T>(ref source) = value; } /// <summary> /// Writes a value of type <typeparamref name="T"/> to the given location. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe void WriteUnaligned<T>(void* source, T value) { Unsafe.As<byte, T>(ref *(byte*)source) = value; } /// <summary> /// Writes a value of type <typeparamref name="T"/> to the given location. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe void WriteUnaligned<T>(ref byte source, T value) { Unsafe.As<byte, T>(ref source) = value; } /// <summary> /// Returns a pointer to the given by-ref parameter. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe void* AsPointer<T>(ref T source) { // This method is implemented by the toolchain throw new PlatformNotSupportedException(); // ldarg.0 // conv.u // ret } /// <summary> /// Returns the size of an object of the given type parameter. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int SizeOf<T>() { // This method is implemented by the toolchain throw new PlatformNotSupportedException(); // sizeof !!0 // ret } /// <summary> /// Casts the given object to the specified type, performs no dynamic type checking. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T As<T>(Object value) where T : class { // This method is implemented by the toolchain throw new PlatformNotSupportedException(); // ldarg.0 // ret } /// <summary> /// Reinterprets the given reference as a reference to a value of type <typeparamref name="TTo"/>. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref TTo As<TFrom, TTo>(ref TFrom source) { // This method is implemented by the toolchain throw new PlatformNotSupportedException(); // ldarg.0 // ret } [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static unsafe ref T AddByteOffset<T>(ref T source, nuint byteOffset) { return ref AddByteOffset(ref source, (IntPtr)(void*)byteOffset); } [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T AddByteOffset<T>(ref T source, IntPtr byteOffset) { // This method is implemented by the toolchain throw new PlatformNotSupportedException(); // ldarg.0 // ldarg.1 // add // ret } /// <summary> /// Adds an element offset to the given reference. /// </summary> [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T Add<T>(ref T source, int elementOffset) { return ref AddByteOffset(ref source, (IntPtr)(elementOffset * (nint)SizeOf<T>())); } /// <summary> /// Adds an element offset to the given pointer. /// </summary> [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe void* Add<T>(void* source, int elementOffset) { return (byte*)source + (elementOffset * (nint)SizeOf<T>()); } /// <summary> /// Determines whether the specified references point to the same location. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool AreSame<T>(ref T left, ref T right) { // This method is implemented by the toolchain throw new PlatformNotSupportedException(); // ldarg.0 // ldarg.1 // ceq // ret } /// <summary> /// Initializes a block of memory at the given location with a given initial value /// without assuming architecture dependent alignment of the address. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void InitBlockUnaligned(ref byte startAddress, byte value, uint byteCount) { for (uint i = 0; i < byteCount; i++) AddByteOffset(ref startAddress, i) = value; } } }
/* * LicenseManager.cs - Implementation of the * "System.ComponentModel.ComponentModel.LicenseManager" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.ComponentModel { #if CONFIG_COMPONENT_MODEL using System; using System.Collections; using System.Reflection; public sealed class LicenseManager { // Internal state. private static LicenseContext currentContext; private static Object contextLockedBy; private static Object ourLock; private static Hashtable providers; private static DefaultLicenseProvider defaultProvider; // Cannot instantiate this class. private LicenseManager() {} // Get or set the current license context. public static LicenseContext CurrentContext { get { lock(typeof(LicenseManager)) { if(currentContext == null) { currentContext = new LicenseContext(); } return currentContext; } } set { lock(typeof(LicenseManager)) { if(currentContext != null) { throw new InvalidOperationException (S._("Invalid_LicenseContextChange")); } currentContext = value; } } } // Get the usage mode for the current license context. public static LicenseUsageMode UsageMode { get { return CurrentContext.UsageMode; } } // Create an instance of an object, within a particular license context. public static Object CreateWithContext (Type type, LicenseContext creationContext) { return CreateWithContext(type, creationContext, new Object [0]); } public static Object CreateWithContext (Type type, LicenseContext creationContext, Object[] args) { lock(typeof(LicenseManager)) { // Temporarily switch to the new context during creation. LicenseContext savedContext = currentContext; currentContext = creationContext; try { // Make sure that we are the only context user. if(ourLock == null) { ourLock = new Object(); } LockContext(ourLock); try { try { return Activator.CreateInstance(type, args); } catch(TargetInvocationException e) { // Re-throw the inner exception, if present. if(e.InnerException != null) { throw e.InnerException; } else { throw; } } } finally { UnlockContext(ourLock); } } finally { currentContext = savedContext; } } } // Determine if a type has a valid license. public static bool IsLicensed(Type type) { return IsValid(type); } // Get the license provider for a specific type. private static LicenseProvider GetProvider(Type type) { Type providerType; LicenseProvider provider; Object[] attrs; lock(typeof(LicenseManager)) { // Get the cached license provider. if(providers == null) { providers = new Hashtable(); } provider = (providers[type] as LicenseProvider); if(provider != null) { return provider; } // Check the type's "LicenseProvider" attribute. attrs = type.GetCustomAttributes (typeof(LicenseProviderAttribute), true); if(attrs != null && attrs.Length > 0) { providerType = ((LicenseProviderAttribute)(attrs[0])) .LicenseProvider; if(providerType != null) { provider = (LicenseProvider) (Activator.CreateInstance(providerType)); providers[type] = provider; return provider; } } // No declared provider, so use the default provider. if(defaultProvider == null) { defaultProvider = new DefaultLicenseProvider(); } providers[type] = defaultProvider; return defaultProvider; } } // Perform license validation for a type. private static License PerformValidation(Type type, Object instance) { LicenseProvider provider = GetProvider(type); return provider.GetLicense (CurrentContext, type, instance, false); } // Determine if a valid license can be granted for a type. public static bool IsValid(Type type) { License license = PerformValidation(type, null); if(license != null) { license.Dispose(); return true; } else { return false; } } public static bool IsValid(Type type, Object instance, out License license) { license = PerformValidation(type, instance); return (license != null); } // Lock the license context associated with an object. public static void LockContext(Object contextUser) { lock(typeof(LicenseManager)) { if(contextLockedBy == null) { contextLockedBy = contextUser; } else { throw new InvalidOperationException (S._("Invalid_LicenseContextLocked")); } } } // Unlock the license context associated with an object. public static void UnlockContext(Object contextUser) { lock(typeof(LicenseManager)) { if(contextLockedBy == contextUser) { contextLockedBy = null; } else { throw new InvalidOperationException (S._("Invalid_LicenseContextNotLocked")); } } } // Validate a license for a type. public static void Validate(Type type) { if(!IsValid(type)) { throw new LicenseException(type); } } public static License Validate(Type type, Object instance) { License license; if(!IsValid(type, instance, out license)) { throw new LicenseException(type, instance); } return license; } // Default license provider for types that don't have their own. private sealed class DefaultLicenseProvider : LicenseProvider { // Get the license for a type. public override License GetLicense (LicenseContext context, Type type, Object instance, bool allowExceptions) { return new DefaultLicense(type.FullName); } }; // class DefaultLicenseProvider // The default license class. private sealed class DefaultLicense : License { // Internal state. private String key; // Constructor. public DefaultLicense(String key) { this.key = key; } // Get the license key. public override String LicenseKey { get { return key; } } // Dispose of this license. public override void Dispose() { // Nothing to do here. } }; // class DefaultLicense }; // class LicenseManager #endif // CONFIG_COMPONENT_MODEL }; // namespace System.ComponentModel
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 SysEspecialidad class. /// </summary> [Serializable] public partial class SysEspecialidadCollection : ActiveList<SysEspecialidad, SysEspecialidadCollection> { public SysEspecialidadCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>SysEspecialidadCollection</returns> public SysEspecialidadCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { SysEspecialidad o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the Sys_Especialidad table. /// </summary> [Serializable] public partial class SysEspecialidad : ActiveRecord<SysEspecialidad>, IActiveRecord { #region .ctors and Default Settings public SysEspecialidad() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public SysEspecialidad(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public SysEspecialidad(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public SysEspecialidad(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("Sys_Especialidad", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdEspecialidad = new TableSchema.TableColumn(schema); colvarIdEspecialidad.ColumnName = "idEspecialidad"; colvarIdEspecialidad.DataType = DbType.Int32; colvarIdEspecialidad.MaxLength = 0; colvarIdEspecialidad.AutoIncrement = true; colvarIdEspecialidad.IsNullable = false; colvarIdEspecialidad.IsPrimaryKey = true; colvarIdEspecialidad.IsForeignKey = false; colvarIdEspecialidad.IsReadOnly = false; colvarIdEspecialidad.DefaultSetting = @""; colvarIdEspecialidad.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdEspecialidad); TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema); colvarNombre.ColumnName = "nombre"; colvarNombre.DataType = DbType.String; colvarNombre.MaxLength = 50; colvarNombre.AutoIncrement = false; colvarNombre.IsNullable = false; colvarNombre.IsPrimaryKey = false; colvarNombre.IsForeignKey = false; colvarNombre.IsReadOnly = false; colvarNombre.DefaultSetting = @"('')"; colvarNombre.ForeignKeyTableName = ""; schema.Columns.Add(colvarNombre); TableSchema.TableColumn colvarCodigo = new TableSchema.TableColumn(schema); colvarCodigo.ColumnName = "codigo"; colvarCodigo.DataType = DbType.Int32; colvarCodigo.MaxLength = 0; colvarCodigo.AutoIncrement = false; colvarCodigo.IsNullable = false; colvarCodigo.IsPrimaryKey = false; colvarCodigo.IsForeignKey = false; colvarCodigo.IsReadOnly = false; colvarCodigo.DefaultSetting = @"((0))"; colvarCodigo.ForeignKeyTableName = ""; schema.Columns.Add(colvarCodigo); TableSchema.TableColumn colvarBackColor = new TableSchema.TableColumn(schema); colvarBackColor.ColumnName = "backColor"; colvarBackColor.DataType = DbType.String; colvarBackColor.MaxLength = 50; colvarBackColor.AutoIncrement = false; colvarBackColor.IsNullable = false; colvarBackColor.IsPrimaryKey = false; colvarBackColor.IsForeignKey = false; colvarBackColor.IsReadOnly = false; colvarBackColor.DefaultSetting = @"('')"; colvarBackColor.ForeignKeyTableName = ""; schema.Columns.Add(colvarBackColor); TableSchema.TableColumn colvarForeColor = new TableSchema.TableColumn(schema); colvarForeColor.ColumnName = "foreColor"; colvarForeColor.DataType = DbType.String; colvarForeColor.MaxLength = 50; colvarForeColor.AutoIncrement = false; colvarForeColor.IsNullable = false; colvarForeColor.IsPrimaryKey = false; colvarForeColor.IsForeignKey = false; colvarForeColor.IsReadOnly = false; colvarForeColor.DefaultSetting = @"('')"; colvarForeColor.ForeignKeyTableName = ""; schema.Columns.Add(colvarForeColor); TableSchema.TableColumn colvarCodigoNacion = new TableSchema.TableColumn(schema); colvarCodigoNacion.ColumnName = "codigoNacion"; colvarCodigoNacion.DataType = DbType.Int32; colvarCodigoNacion.MaxLength = 0; colvarCodigoNacion.AutoIncrement = false; colvarCodigoNacion.IsNullable = false; colvarCodigoNacion.IsPrimaryKey = false; colvarCodigoNacion.IsForeignKey = false; colvarCodigoNacion.IsReadOnly = false; colvarCodigoNacion.DefaultSetting = @"((0))"; colvarCodigoNacion.ForeignKeyTableName = ""; schema.Columns.Add(colvarCodigoNacion); TableSchema.TableColumn colvarUnidadOperativa = new TableSchema.TableColumn(schema); colvarUnidadOperativa.ColumnName = "unidadOperativa"; colvarUnidadOperativa.DataType = DbType.AnsiString; colvarUnidadOperativa.MaxLength = 5; colvarUnidadOperativa.AutoIncrement = false; colvarUnidadOperativa.IsNullable = true; colvarUnidadOperativa.IsPrimaryKey = false; colvarUnidadOperativa.IsForeignKey = false; colvarUnidadOperativa.IsReadOnly = false; colvarUnidadOperativa.DefaultSetting = @""; colvarUnidadOperativa.ForeignKeyTableName = ""; schema.Columns.Add(colvarUnidadOperativa); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("Sys_Especialidad",schema); } } #endregion #region Props [XmlAttribute("IdEspecialidad")] [Bindable(true)] public int IdEspecialidad { get { return GetColumnValue<int>(Columns.IdEspecialidad); } set { SetColumnValue(Columns.IdEspecialidad, value); } } [XmlAttribute("Nombre")] [Bindable(true)] public string Nombre { get { return GetColumnValue<string>(Columns.Nombre); } set { SetColumnValue(Columns.Nombre, value); } } [XmlAttribute("Codigo")] [Bindable(true)] public int Codigo { get { return GetColumnValue<int>(Columns.Codigo); } set { SetColumnValue(Columns.Codigo, value); } } [XmlAttribute("BackColor")] [Bindable(true)] public string BackColor { get { return GetColumnValue<string>(Columns.BackColor); } set { SetColumnValue(Columns.BackColor, value); } } [XmlAttribute("ForeColor")] [Bindable(true)] public string ForeColor { get { return GetColumnValue<string>(Columns.ForeColor); } set { SetColumnValue(Columns.ForeColor, value); } } [XmlAttribute("CodigoNacion")] [Bindable(true)] public int CodigoNacion { get { return GetColumnValue<int>(Columns.CodigoNacion); } set { SetColumnValue(Columns.CodigoNacion, value); } } [XmlAttribute("UnidadOperativa")] [Bindable(true)] public string UnidadOperativa { get { return GetColumnValue<string>(Columns.UnidadOperativa); } set { SetColumnValue(Columns.UnidadOperativa, value); } } #endregion #region PrimaryKey Methods protected override void SetPrimaryKey(object oValue) { base.SetPrimaryKey(oValue); SetPKValues(); } private DalSic.AprIntervencionProfesionalCollection colAprIntervencionProfesionalRecords; public DalSic.AprIntervencionProfesionalCollection AprIntervencionProfesionalRecords { get { if(colAprIntervencionProfesionalRecords == null) { colAprIntervencionProfesionalRecords = new DalSic.AprIntervencionProfesionalCollection().Where(AprIntervencionProfesional.Columns.IdEspecialidad, IdEspecialidad).Load(); colAprIntervencionProfesionalRecords.ListChanged += new ListChangedEventHandler(colAprIntervencionProfesionalRecords_ListChanged); } return colAprIntervencionProfesionalRecords; } set { colAprIntervencionProfesionalRecords = value; colAprIntervencionProfesionalRecords.ListChanged += new ListChangedEventHandler(colAprIntervencionProfesionalRecords_ListChanged); } } void colAprIntervencionProfesionalRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colAprIntervencionProfesionalRecords[e.NewIndex].IdEspecialidad = IdEspecialidad; } } private DalSic.SysRelEspecialidadEfectorCollection colSysRelEspecialidadEfectorRecords; public DalSic.SysRelEspecialidadEfectorCollection SysRelEspecialidadEfectorRecords { get { if(colSysRelEspecialidadEfectorRecords == null) { colSysRelEspecialidadEfectorRecords = new DalSic.SysRelEspecialidadEfectorCollection().Where(SysRelEspecialidadEfector.Columns.IdEspecialidad, IdEspecialidad).Load(); colSysRelEspecialidadEfectorRecords.ListChanged += new ListChangedEventHandler(colSysRelEspecialidadEfectorRecords_ListChanged); } return colSysRelEspecialidadEfectorRecords; } set { colSysRelEspecialidadEfectorRecords = value; colSysRelEspecialidadEfectorRecords.ListChanged += new ListChangedEventHandler(colSysRelEspecialidadEfectorRecords_ListChanged); } } void colSysRelEspecialidadEfectorRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colSysRelEspecialidadEfectorRecords[e.NewIndex].IdEspecialidad = IdEspecialidad; } } private DalSic.ConConsultumCollection colConConsulta; public DalSic.ConConsultumCollection ConConsulta { get { if(colConConsulta == null) { colConConsulta = new DalSic.ConConsultumCollection().Where(ConConsultum.Columns.IdEspecialidad, IdEspecialidad).Load(); colConConsulta.ListChanged += new ListChangedEventHandler(colConConsulta_ListChanged); } return colConConsulta; } set { colConConsulta = value; colConConsulta.ListChanged += new ListChangedEventHandler(colConConsulta_ListChanged); } } void colConConsulta_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colConConsulta[e.NewIndex].IdEspecialidad = IdEspecialidad; } } private DalSic.ConAgendaCollection colConAgendaRecords; public DalSic.ConAgendaCollection ConAgendaRecords { get { if(colConAgendaRecords == null) { colConAgendaRecords = new DalSic.ConAgendaCollection().Where(ConAgenda.Columns.IdEspecialidad, IdEspecialidad).Load(); colConAgendaRecords.ListChanged += new ListChangedEventHandler(colConAgendaRecords_ListChanged); } return colConAgendaRecords; } set { colConAgendaRecords = value; colConAgendaRecords.ListChanged += new ListChangedEventHandler(colConAgendaRecords_ListChanged); } } void colConAgendaRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colConAgendaRecords[e.NewIndex].IdEspecialidad = IdEspecialidad; } } private DalSic.ConAgendaProfesionalCollection colConAgendaProfesionalRecords; public DalSic.ConAgendaProfesionalCollection ConAgendaProfesionalRecords { get { if(colConAgendaProfesionalRecords == null) { colConAgendaProfesionalRecords = new DalSic.ConAgendaProfesionalCollection().Where(ConAgendaProfesional.Columns.IdEspecialidad, IdEspecialidad).Load(); colConAgendaProfesionalRecords.ListChanged += new ListChangedEventHandler(colConAgendaProfesionalRecords_ListChanged); } return colConAgendaProfesionalRecords; } set { colConAgendaProfesionalRecords = value; colConAgendaProfesionalRecords.ListChanged += new ListChangedEventHandler(colConAgendaProfesionalRecords_ListChanged); } } void colConAgendaProfesionalRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colConAgendaProfesionalRecords[e.NewIndex].IdEspecialidad = IdEspecialidad; } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varNombre,int varCodigo,string varBackColor,string varForeColor,int varCodigoNacion,string varUnidadOperativa) { SysEspecialidad item = new SysEspecialidad(); item.Nombre = varNombre; item.Codigo = varCodigo; item.BackColor = varBackColor; item.ForeColor = varForeColor; item.CodigoNacion = varCodigoNacion; item.UnidadOperativa = varUnidadOperativa; 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 varIdEspecialidad,string varNombre,int varCodigo,string varBackColor,string varForeColor,int varCodigoNacion,string varUnidadOperativa) { SysEspecialidad item = new SysEspecialidad(); item.IdEspecialidad = varIdEspecialidad; item.Nombre = varNombre; item.Codigo = varCodigo; item.BackColor = varBackColor; item.ForeColor = varForeColor; item.CodigoNacion = varCodigoNacion; item.UnidadOperativa = varUnidadOperativa; 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 IdEspecialidadColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn NombreColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn CodigoColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn BackColorColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn ForeColorColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn CodigoNacionColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn UnidadOperativaColumn { get { return Schema.Columns[6]; } } #endregion #region Columns Struct public struct Columns { public static string IdEspecialidad = @"idEspecialidad"; public static string Nombre = @"nombre"; public static string Codigo = @"codigo"; public static string BackColor = @"backColor"; public static string ForeColor = @"foreColor"; public static string CodigoNacion = @"codigoNacion"; public static string UnidadOperativa = @"unidadOperativa"; } #endregion #region Update PK Collections public void SetPKValues() { if (colAprIntervencionProfesionalRecords != null) { foreach (DalSic.AprIntervencionProfesional item in colAprIntervencionProfesionalRecords) { if (item.IdEspecialidad != IdEspecialidad) { item.IdEspecialidad = IdEspecialidad; } } } if (colSysRelEspecialidadEfectorRecords != null) { foreach (DalSic.SysRelEspecialidadEfector item in colSysRelEspecialidadEfectorRecords) { if (item.IdEspecialidad != IdEspecialidad) { item.IdEspecialidad = IdEspecialidad; } } } if (colConConsulta != null) { foreach (DalSic.ConConsultum item in colConConsulta) { if (item.IdEspecialidad != IdEspecialidad) { item.IdEspecialidad = IdEspecialidad; } } } if (colConAgendaRecords != null) { foreach (DalSic.ConAgenda item in colConAgendaRecords) { if (item.IdEspecialidad != IdEspecialidad) { item.IdEspecialidad = IdEspecialidad; } } } if (colConAgendaProfesionalRecords != null) { foreach (DalSic.ConAgendaProfesional item in colConAgendaProfesionalRecords) { if (item.IdEspecialidad != IdEspecialidad) { item.IdEspecialidad = IdEspecialidad; } } } } #endregion #region Deep Save public void DeepSave() { Save(); if (colAprIntervencionProfesionalRecords != null) { colAprIntervencionProfesionalRecords.SaveAll(); } if (colSysRelEspecialidadEfectorRecords != null) { colSysRelEspecialidadEfectorRecords.SaveAll(); } if (colConConsulta != null) { colConConsulta.SaveAll(); } if (colConAgendaRecords != null) { colConAgendaRecords.SaveAll(); } if (colConAgendaProfesionalRecords != null) { colConAgendaProfesionalRecords.SaveAll(); } } #endregion } }
using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.CallStack; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.CustomRuntimes; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.FunctionResolution; using Microsoft.VisualStudio.Debugger.Native; using Microsoft.VisualStudio.Debugger.Symbols; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; namespace nullc_debugger_component { namespace DkmDebugger { internal class NullcJitContextData { public ulong location = 0; public ulong dataStackBase = 0; public ulong dataStackTop = 0; public ulong callStackBase = 0; public ulong callStackTop = 0; } internal class NullcVmContextData { public ulong location = 0; public ulong dataStackBase = 0; public int dataStackCount = 0; public ulong codeBase = 0; public ulong callStackBase = 0; public int callStackCount = 0; } internal class NullcLocalProcessDataItem : DkmDataItem { public ulong moduleBytecodeLocation = 0; public ulong moduleBytecodeSize = 0; public byte[] moduleBytecodeRaw; public NullcBytecode bytecode; public NullcJitContextData jitContext = new NullcJitContextData(); public NullcVmContextData vmContext = new NullcVmContextData(); public ulong dataStackBase = 0; public NullcCallStack callStack = new NullcCallStack(); public List<string> activeDocumentPaths = new List<string>(); public void UpdateContextData(DkmProcess process) { jitContext.location = DebugHelpers.ReadPointerVariable(process, "nullcJitContextMainDataAddress").GetValueOrDefault(0); if (jitContext.location != 0) { jitContext.dataStackBase = DebugHelpers.ReadPointerVariable(process, jitContext.location + (ulong)DebugHelpers.GetPointerSize(process) * 0).GetValueOrDefault(0); jitContext.dataStackTop = DebugHelpers.ReadPointerVariable(process, jitContext.location + (ulong)DebugHelpers.GetPointerSize(process) * 1).GetValueOrDefault(0); jitContext.callStackBase = DebugHelpers.ReadPointerVariable(process, jitContext.location + (ulong)DebugHelpers.GetPointerSize(process) * 3).GetValueOrDefault(0); jitContext.callStackTop = DebugHelpers.ReadPointerVariable(process, jitContext.location + (ulong)DebugHelpers.GetPointerSize(process) * 4).GetValueOrDefault(0); } vmContext.location = DebugHelpers.ReadPointerVariable(process, "nullcVmContextMainDataAddress").GetValueOrDefault(0); if (vmContext.location != 0) { vmContext.dataStackBase = DebugHelpers.ReadPointerVariable(process, vmContext.location).GetValueOrDefault(0); vmContext.dataStackCount = DebugHelpers.ReadIntVariable(process, vmContext.location + (ulong)DebugHelpers.GetPointerSize(process)).GetValueOrDefault(0); vmContext.codeBase = DebugHelpers.ReadPointerVariable(process, vmContext.location + (ulong)DebugHelpers.GetPointerSize(process) + 8).GetValueOrDefault(0); vmContext.callStackBase = DebugHelpers.ReadPointerVariable(process, vmContext.location + (ulong)DebugHelpers.GetPointerSize(process) * 2 + 8).GetValueOrDefault(0); vmContext.callStackCount = DebugHelpers.ReadIntVariable(process, vmContext.location + (ulong)DebugHelpers.GetPointerSize(process) * 3 + 8).GetValueOrDefault(0); } } } internal class NullEvaluationDataItem : DkmDataItem { public ulong address; public NullcTypeInfo type; public string fullName; } internal class NullFrameLocalsDataItem : DkmDataItem { public NullcCallStackEntry activeEntry; } internal class NullResolvedDocumentDataItem : DkmDataItem { public NullcBytecode bytecode; public ulong moduleBase; public bool isVmModule; public int moduleIndex; } public class NullcLocalComponent : IDkmSymbolCompilerIdQuery, IDkmSymbolDocumentCollectionQuery, IDkmSymbolDocumentSpanQuery, IDkmSymbolQuery, IDkmSymbolFunctionResolver, IDkmLanguageFrameDecoder, IDkmModuleInstanceLoadNotification, IDkmLanguageExpressionEvaluator, IDkmLanguageInstructionDecoder, IDkmCustomMessageCallbackReceiver { DkmCompilerId IDkmSymbolCompilerIdQuery.GetCompilerId(DkmInstructionSymbol instruction, DkmInspectionSession inspectionSession) { if (instruction.Module.Name != "nullc.embedded.code") { return new DkmCompilerId(Guid.Empty, Guid.Empty); } return new DkmCompilerId(Guid.Empty, Guid.Empty); } DkmResolvedDocument[] IDkmSymbolDocumentCollectionQuery.FindDocuments(DkmModule module, DkmSourceFileId sourceFileId) { bool isVmModule = module.Name == "nullc.vm.code"; DkmModuleInstance nullcModuleInstance; if (isVmModule && DebugHelpers.checkVmModuleDocuments) { nullcModuleInstance = module.GetModuleInstances().OfType<DkmCustomModuleInstance>().FirstOrDefault(el => el.Module.CompilerId.VendorId == DebugHelpers.NullcCompilerGuid); } else { if (DebugHelpers.useNativeInterfaces) { nullcModuleInstance = module.GetModuleInstances().OfType<DkmNativeModuleInstance>().FirstOrDefault(el => el.Module.CompilerId.VendorId == DebugHelpers.NullcCompilerGuid); } else { nullcModuleInstance = module.GetModuleInstances().OfType<DkmCustomModuleInstance>().FirstOrDefault(el => el.Module.CompilerId.VendorId == DebugHelpers.NullcCompilerGuid); } } if (nullcModuleInstance == null) { return module.FindDocuments(sourceFileId); } var processData = DebugHelpers.GetOrCreateDataItem<NullcLocalProcessDataItem>(nullcModuleInstance.Process); if (processData.bytecode != null) { var processPath = nullcModuleInstance.Process.Path; var dataItem = new NullResolvedDocumentDataItem(); dataItem.bytecode = processData.bytecode; dataItem.moduleBase = nullcModuleInstance.BaseAddress; dataItem.isVmModule = isVmModule; DkmResolvedDocument[] MatchAgainstModule(string moduleName, int moduleIndex) { foreach (var importPath in processData.bytecode.importPaths) { var finalPath = importPath.Replace('/', '\\'); if (finalPath.Length == 0) { finalPath = $"{Path.GetDirectoryName(processPath)}\\"; } else if (!Path.IsPathRooted(finalPath)) { finalPath = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(processPath), finalPath)); } var modulePath = moduleName.Replace('/', '\\'); var combined = $"{finalPath}{modulePath}"; if (combined == sourceFileId.DocumentName) { dataItem.moduleIndex = moduleIndex; processData.activeDocumentPaths.Add(sourceFileId.DocumentName); return new DkmResolvedDocument[1] { DkmResolvedDocument.Create(module, sourceFileId.DocumentName, null, DkmDocumentMatchStrength.FullPath, DkmResolvedDocumentWarning.None, false, dataItem) }; } if (combined.ToLowerInvariant().EndsWith(sourceFileId.DocumentName.ToLowerInvariant())) { if (File.Exists(combined)) { dataItem.moduleIndex = moduleIndex; processData.activeDocumentPaths.Add(combined); return new DkmResolvedDocument[1] { DkmResolvedDocument.Create(module, sourceFileId.DocumentName, null, DkmDocumentMatchStrength.SubPath, DkmResolvedDocumentWarning.None, false, dataItem) }; } } } return null; } foreach (var nullcModule in processData.bytecode.modules) { int moduleIndex = processData.bytecode.modules.IndexOf(nullcModule); var result = MatchAgainstModule(nullcModule.name, moduleIndex); if (result != null) { return result; } } { var result = MatchAgainstModule(processData.bytecode.mainModuleName, -1); if (result != null) { return result; } } Debug.WriteLine($"Failed to find nullc document using '{sourceFileId.DocumentName}' name"); } return module.FindDocuments(sourceFileId); } DkmInstructionSymbol[] IDkmSymbolDocumentSpanQuery.FindSymbols(DkmResolvedDocument resolvedDocument, DkmTextSpan textSpan, string text, out DkmSourcePosition[] symbolLocation) { var documentData = DebugHelpers.GetOrCreateDataItem<NullResolvedDocumentDataItem>(resolvedDocument); if (documentData == null) { return resolvedDocument.FindSymbols(textSpan, text, out symbolLocation); } for (int line = textSpan.StartLine; line < textSpan.EndLine; line++) { int moduleSourceLocation = documentData.bytecode.GetModuleSourceLocation(documentData.moduleIndex); if (moduleSourceLocation == -1) { continue; } int instruction = documentData.bytecode.ConvertLineToInstruction(moduleSourceLocation, line - 1); if (instruction == 0) { continue; } var sourceFileId = DkmSourceFileId.Create(resolvedDocument.DocumentName, null, null, null); var resultSpan = new DkmTextSpan(line, line, 0, 0); symbolLocation = new DkmSourcePosition[1] { DkmSourcePosition.Create(sourceFileId, resultSpan) }; if (documentData.isVmModule) { return new DkmInstructionSymbol[1] { DkmCustomInstructionSymbol.Create(resolvedDocument.Module, DebugHelpers.NullcRuntimeGuid, null, (ulong)instruction, null) }; } else { ulong nativeInstruction = documentData.bytecode.ConvertInstructionToNativeAddress(instruction); Debug.Assert(nativeInstruction >= documentData.moduleBase); if (DebugHelpers.useNativeInterfaces) { return new DkmInstructionSymbol[1] { DkmNativeInstructionSymbol.Create(resolvedDocument.Module, (uint)(nativeInstruction - documentData.moduleBase)) }; } else { return new DkmInstructionSymbol[1] { DkmCustomInstructionSymbol.Create(resolvedDocument.Module, DebugHelpers.NullcRuntimeGuid, null, nativeInstruction, null) }; } } } return resolvedDocument.FindSymbols(textSpan, text, out symbolLocation); } string TryFindModuleFilePath(NullcLocalProcessDataItem processData, string processPath, string moduleName) { foreach (var importPath in processData.bytecode.importPaths) { var finalPath = importPath.Replace('/', '\\'); if (finalPath.Length == 0) { finalPath = $"{Path.GetDirectoryName(processPath)}\\"; } else if (!Path.IsPathRooted(finalPath)) { finalPath = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(processPath), finalPath)); } var modulePath = moduleName.Replace('/', '\\'); var combined = $"{finalPath}{modulePath}"; foreach (var activeDocumentPath in processData.activeDocumentPaths) { if (combined == activeDocumentPath) return combined; } if (File.Exists(combined)) { processData.activeDocumentPaths.Add(combined); return combined; } } return null; } DkmSourcePosition GetSourcePosition(NullcLocalProcessDataItem processData, string processPath, int nullcInstruction, out bool startOfLine) { int sourceLocation = processData.bytecode.GetInstructionSourceLocation(nullcInstruction); int moduleIndex = processData.bytecode.GetSourceLocationModuleIndex(sourceLocation); int column = 0; int line = processData.bytecode.GetSourceLocationLineAndColumn(sourceLocation, moduleIndex, out column); string moduleName = moduleIndex != -1 ? processData.bytecode.modules[moduleIndex].name : processData.bytecode.mainModuleName; string path = TryFindModuleFilePath(processData, processPath, moduleName); // Let Visual Studio find it using a partial name if (path == null) path = moduleName; startOfLine = true; return DkmSourcePosition.Create(DkmSourceFileId.Create(path, null, null, null), new DkmTextSpan(line, line, 0, 0)); } DkmSourcePosition IDkmSymbolQuery.GetSourcePosition(DkmInstructionSymbol instruction, DkmSourcePositionFlags flags, DkmInspectionSession inspectionSession, out bool startOfLine) { if (instruction.RuntimeType == DebugHelpers.NullcVmRuntimeGuid) { DkmCustomModuleInstance vmModuleInstance = instruction.Module.GetModuleInstances().OfType<DkmCustomModuleInstance>().FirstOrDefault(el => el.Module.CompilerId.VendorId == DebugHelpers.NullcCompilerGuid); if (vmModuleInstance == null) { return instruction.GetSourcePosition(flags, inspectionSession, out startOfLine); } var vmProcessData = DebugHelpers.GetOrCreateDataItem<NullcLocalProcessDataItem>(vmModuleInstance.Process); if (vmProcessData.bytecode != null) { var instructionSymbol = instruction as DkmCustomInstructionSymbol; int nullcInstruction = (int)instructionSymbol.Offset; if (nullcInstruction != 0) { return GetSourcePosition(vmProcessData, vmModuleInstance.Process.Path, nullcInstruction, out startOfLine); } } return instruction.GetSourcePosition(flags, inspectionSession, out startOfLine); } DkmModuleInstance nullcModuleInstance; if (DebugHelpers.useNativeInterfaces) { nullcModuleInstance = instruction.Module.GetModuleInstances().OfType<DkmNativeModuleInstance>().FirstOrDefault(el => el.Module.CompilerId.VendorId == DebugHelpers.NullcCompilerGuid); } else { nullcModuleInstance = instruction.Module.GetModuleInstances().OfType<DkmCustomModuleInstance>().FirstOrDefault(el => el.Module.CompilerId.VendorId == DebugHelpers.NullcCompilerGuid); } if (nullcModuleInstance == null) { return instruction.GetSourcePosition(flags, inspectionSession, out startOfLine); } var processData = DebugHelpers.GetOrCreateDataItem<NullcLocalProcessDataItem>(nullcModuleInstance.Process); if (processData.bytecode != null) { int nullcInstruction = 0; if (DebugHelpers.useNativeInterfaces) { var instructionSymbol = instruction as DkmNativeInstructionSymbol; if (instructionSymbol != null) { nullcInstruction = processData.bytecode.ConvertNativeAddressToInstruction(nullcModuleInstance.BaseAddress + instructionSymbol.RVA); } } else { var instructionSymbol = instruction as DkmCustomInstructionSymbol; if (instructionSymbol != null) { nullcInstruction = processData.bytecode.ConvertNativeAddressToInstruction(instructionSymbol.Offset); } } if (nullcInstruction != 0) { return GetSourcePosition(processData, nullcModuleInstance.Process.Path, nullcInstruction, out startOfLine); } } return instruction.GetSourcePosition(flags, inspectionSession, out startOfLine); } object IDkmSymbolQuery.GetSymbolInterface(DkmModule module, Guid interfaceID) { if (module.Name != "nullc.embedded.code") throw new NotImplementedException(); throw new NotImplementedException(); } string FormatFunction(NullcFuncInfo function, DkmVariableInfoFlags argumentFlags) { string result = $"{function.name}"; if (argumentFlags.HasFlag(DkmVariableInfoFlags.Types) || argumentFlags.HasFlag(DkmVariableInfoFlags.Names)) { result += "("; for (int i = 0; i < function.paramCount; i++) { var localInfo = function.arguments[i]; if (argumentFlags.HasFlag(DkmVariableInfoFlags.Types)) { if (i != 0) result += ", "; result += $"{localInfo.nullcType.name}"; if (argumentFlags.HasFlag(DkmVariableInfoFlags.Names)) result += $" {localInfo.name}"; } else if (argumentFlags.HasFlag(DkmVariableInfoFlags.Names)) { if (i != 0) result += ", "; result += $"{localInfo.name}"; } } result += ")"; } return result; } void IDkmLanguageFrameDecoder.GetFrameName(DkmInspectionContext inspectionContext, DkmWorkList workList, DkmStackWalkFrame frame, DkmVariableInfoFlags argumentFlags, DkmCompletionRoutine<DkmGetFrameNameAsyncResult> completionRoutine) { var process = frame.Process; var processData = DebugHelpers.GetOrCreateDataItem<NullcLocalProcessDataItem>(process); NullcFuncInfo function; if (inspectionContext.RuntimeInstance.Id.RuntimeType == DebugHelpers.NullcVmRuntimeGuid) function = processData.bytecode.GetFunctionAtAddress((int)(frame.InstructionAddress as DkmCustomInstructionAddress).Offset); else function = processData.bytecode.GetFunctionAtNativeAddress(frame.InstructionAddress.CPUInstructionPart.InstructionPointer); if (function != null) { completionRoutine(new DkmGetFrameNameAsyncResult(FormatFunction(function, argumentFlags))); return; } int nullcInstruction; if (inspectionContext.RuntimeInstance.Id.RuntimeType == DebugHelpers.NullcVmRuntimeGuid) nullcInstruction = (int)(frame.InstructionAddress as DkmCustomInstructionAddress).Offset; else nullcInstruction = processData.bytecode.ConvertNativeAddressToInstruction(frame.InstructionAddress.CPUInstructionPart.InstructionPointer); if (nullcInstruction != 0) { completionRoutine(new DkmGetFrameNameAsyncResult("nullcGlobal()")); return; } inspectionContext.GetFrameName(workList, frame, argumentFlags, completionRoutine); } void IDkmLanguageFrameDecoder.GetFrameReturnType(DkmInspectionContext inspectionContext, DkmWorkList workList, DkmStackWalkFrame frame, DkmCompletionRoutine<DkmGetFrameReturnTypeAsyncResult> completionRoutine) { // Not provided at the moment inspectionContext.GetFrameReturnType(workList, frame, completionRoutine); } string IDkmLanguageInstructionDecoder.GetMethodName(DkmLanguageInstructionAddress languageInstructionAddress, DkmVariableInfoFlags argumentFlags) { var processData = DebugHelpers.GetOrCreateDataItem<NullcLocalProcessDataItem>(languageInstructionAddress.Address.Process); NullcFuncInfo function; if (languageInstructionAddress.RuntimeInstance.Id.RuntimeType == DebugHelpers.NullcVmRuntimeGuid) function = processData.bytecode.GetFunctionAtAddress((int)(languageInstructionAddress.Address as DkmCustomInstructionAddress).Offset); else function = processData.bytecode.GetFunctionAtNativeAddress(languageInstructionAddress.Address.CPUInstructionPart.InstructionPointer); if (function != null) return FormatFunction(function, argumentFlags); int nullcInstruction; if (languageInstructionAddress.RuntimeInstance.Id.RuntimeType == DebugHelpers.NullcVmRuntimeGuid) nullcInstruction = (int)(languageInstructionAddress.Address as DkmCustomInstructionAddress).Offset; else nullcInstruction = processData.bytecode.ConvertNativeAddressToInstruction(languageInstructionAddress.Address.CPUInstructionPart.InstructionPointer); if (nullcInstruction != 0) { if (argumentFlags.HasFlag(DkmVariableInfoFlags.Types) || argumentFlags.HasFlag(DkmVariableInfoFlags.Names)) return "nullcGlobal()"; return "nullcGlobal"; } return languageInstructionAddress.GetMethodName(argumentFlags); } void UpdateModuleBytecode(DkmProcess process) { var processData = DebugHelpers.GetOrCreateDataItem<NullcLocalProcessDataItem>(process); processData.moduleBytecodeLocation = DebugHelpers.ReadPointerVariable(process, "nullcModuleBytecodeLocation").GetValueOrDefault(0); processData.moduleBytecodeSize = DebugHelpers.ReadPointerVariable(process, "nullcModuleBytecodeSize").GetValueOrDefault(0); if (processData.moduleBytecodeLocation != 0) { processData.moduleBytecodeRaw = new byte[processData.moduleBytecodeSize]; process.ReadMemory(processData.moduleBytecodeLocation, DkmReadMemoryFlags.None, processData.moduleBytecodeRaw); processData.bytecode = new NullcBytecode(); processData.bytecode.ReadFrom(processData.moduleBytecodeRaw, DebugHelpers.Is64Bit(process)); } } void IDkmModuleInstanceLoadNotification.OnModuleInstanceLoad(DkmModuleInstance moduleInstance, DkmWorkList workList, DkmEventDescriptorS eventDescriptor) { var process = moduleInstance.Process; var processData = DebugHelpers.GetOrCreateDataItem<NullcLocalProcessDataItem>(process); if (processData.moduleBytecodeLocation == 0) { UpdateModuleBytecode(process); } } DkmCustomMessage IDkmCustomMessageCallbackReceiver.SendHigher(DkmCustomMessage customMessage) { var processData = DebugHelpers.GetOrCreateDataItem<NullcLocalProcessDataItem>(customMessage.Process); if (customMessage.SourceId == DebugHelpers.NullcReloadSymbolsMessageGuid && customMessage.MessageCode == 1) { UpdateModuleBytecode(customMessage.Process); } return null; } string EvaluateValueAtAddress(DkmProcess process, NullcBytecode bytecode, NullcTypeInfo type, ulong address, out string editableValue, ref DkmEvaluationResultFlags flags, out DkmDataAddress dataAddress) { editableValue = null; dataAddress = null; if (type == null) return null; if (type.subCat == NullcTypeSubCategory.Pointer) { var value = DebugHelpers.ReadPointerVariable(process, address); if (value.HasValue) { flags |= DkmEvaluationResultFlags.Address | DkmEvaluationResultFlags.Expandable; editableValue = $"{value.Value}"; dataAddress = DkmDataAddress.Create(process.GetNativeRuntimeInstance(), value.Value, null); return $"0x{value.Value:x8}"; } return null; } if (type.subCat == NullcTypeSubCategory.Class) { if (type.typeCategory == NullcTypeCategory.Int) { var value = DebugHelpers.ReadIntVariable(process, address); if (value.HasValue) { for (int i = 0; i < type.nullcConstants.Count; i++) { var constant = type.nullcConstants[i]; if (constant.value == value.Value) { editableValue = $"{value.Value}"; return $"{constant.name} ({value.Value})"; } } editableValue = $"{value.Value}"; return $"({type.name}){value.Value}"; } return null; } flags |= DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly; return "{}"; } if (type.subCat == NullcTypeSubCategory.Array) { if (type.arrSize == -1) { var pointer = DebugHelpers.ReadPointerVariable(process, address); var length = DebugHelpers.ReadIntVariable(process, address + (ulong)DebugHelpers.GetPointerSize(process)); if (pointer.HasValue && length.HasValue) { flags |= DkmEvaluationResultFlags.IsBuiltInType | DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly; return $"0x{pointer.Value:x8} Size: {length.Value}"; } return null; } flags |= DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly; return $"Size: {type.arrSize}"; } if (type.subCat == NullcTypeSubCategory.Function) { var context = DebugHelpers.ReadPointerVariable(process, address); var id = DebugHelpers.ReadIntVariable(process, address + (ulong)DebugHelpers.GetPointerSize(process)); if (context.HasValue && id.HasValue) { var function = bytecode.functions[id.Value]; var returnType = function.nullcFunctionType.nullcMembers.First().nullcType; string result = ""; result += $"{returnType.name} {function.name}("; for (int i = 0; i < function.paramCount; i++) { var localInfo = function.arguments[i]; if (i != 0) result += ", "; result += $"{localInfo.nullcType.name} {localInfo.name}"; } result += ")"; flags |= DkmEvaluationResultFlags.ReadOnly; return result; } return null; } if (type.index == NullcTypeIndex.Bool) { var value = DebugHelpers.ReadByteVariable(process, address); if (value.HasValue) { if (value.Value != 0) { flags |= DkmEvaluationResultFlags.Boolean | DkmEvaluationResultFlags.BooleanTrue; editableValue = $"{value.Value}"; return "true"; } else { flags |= DkmEvaluationResultFlags.Boolean; editableValue = $"{value.Value}"; return "false"; } } return null; } if (type.index == NullcTypeIndex.TypeId) { var value = DebugHelpers.ReadIntVariable(process, address); if (value.HasValue) { flags |= DkmEvaluationResultFlags.IsBuiltInType; editableValue = $"{value.Value}"; return bytecode.types[value.Value].name; } return null; } switch (type.typeCategory) { case NullcTypeCategory.Char: { var value = DebugHelpers.ReadByteVariable(process, address); if (value.HasValue) { if (value > 0 && value <= 127) { flags |= DkmEvaluationResultFlags.IsBuiltInType; editableValue = $"{value.Value}"; return $"'{(char)value.Value}' ({value.Value:d})"; } else { flags |= DkmEvaluationResultFlags.IsBuiltInType; editableValue = $"{value.Value}"; return $"{value.Value:d}"; } } } break; case NullcTypeCategory.Short: { var value = DebugHelpers.ReadShortVariable(process, address); if (value.HasValue) { flags |= DkmEvaluationResultFlags.IsBuiltInType; editableValue = $"{value.Value}"; return $"{value.Value}"; } } break; case NullcTypeCategory.Int: { var value = DebugHelpers.ReadIntVariable(process, address); if (value.HasValue) { flags |= DkmEvaluationResultFlags.IsBuiltInType; editableValue = $"{value.Value}"; return $"{value.Value}"; } } break; case NullcTypeCategory.Long: { var value = DebugHelpers.ReadLongVariable(process, address); if (value.HasValue) { flags |= DkmEvaluationResultFlags.IsBuiltInType; editableValue = $"{value.Value}"; return $"{value.Value}"; } } break; case NullcTypeCategory.Float: { var value = DebugHelpers.ReadFloatVariable(process, address); if (value.HasValue) { flags |= DkmEvaluationResultFlags.IsBuiltInType; editableValue = $"{value.Value}"; return $"{value.Value}"; } } break; case NullcTypeCategory.Double: { var value = DebugHelpers.ReadDoubleVariable(process, address); if (value.HasValue) { flags |= DkmEvaluationResultFlags.IsBuiltInType; editableValue = $"{value.Value}"; return $"{value.Value}"; } } break; default: break; } return null; } void SetValueAtAddress(DkmProcess process, NullcBytecode bytecode, NullcTypeInfo type, ulong address, string value, out string error) { if (type.subCat == NullcTypeSubCategory.Pointer) { error = "Can't modify pointer value"; return; } if (type.subCat == NullcTypeSubCategory.Class) { if (type.typeCategory == NullcTypeCategory.Int) { if (!DebugHelpers.TryWriteVariable(process, address, int.Parse(value))) { error = "Failed to modify target process memory"; return; } error = null; return; } error = "Can't modify class value"; return; } if (type.subCat == NullcTypeSubCategory.Array) { error = "Can't modify array value"; return; } if (type.subCat == NullcTypeSubCategory.Function) { error = "Can't modify function value"; return; } if (type.index == NullcTypeIndex.Bool) { if (value == "true") { if (!DebugHelpers.TryWriteVariable(process, address, (byte)1)) { error = "Failed to modify target process memory"; return; } } else if (value == "false") { if (!DebugHelpers.TryWriteVariable(process, address, (byte)0)) { error = "Failed to modify target process memory"; return; } } else { if (!DebugHelpers.TryWriteVariable(process, address, (byte)(int.Parse(value) != 0 ? 1 : 0))) { error = "Failed to modify target process memory"; return; } } error = null; return; } switch (type.typeCategory) { case NullcTypeCategory.Char: if (!DebugHelpers.TryWriteVariable(process, address, byte.Parse(value))) { error = "Failed to modify target process memory"; return; } break; case NullcTypeCategory.Short: if (!DebugHelpers.TryWriteVariable(process, address, short.Parse(value))) { error = "Failed to modify target process memory"; return; } break; case NullcTypeCategory.Int: if (!DebugHelpers.TryWriteVariable(process, address, int.Parse(value))) { error = "Failed to modify target process memory"; return; } break; case NullcTypeCategory.Long: if (!DebugHelpers.TryWriteVariable(process, address, long.Parse(value))) { error = "Failed to modify target process memory"; return; } break; case NullcTypeCategory.Float: if (!DebugHelpers.TryWriteVariable(process, address, float.Parse(value))) { error = "Failed to modify target process memory"; return; } break; case NullcTypeCategory.Double: if (!DebugHelpers.TryWriteVariable(process, address, double.Parse(value))) { error = "Failed to modify target process memory"; return; } break; default: error = "Unknown value type"; return; } error = null; } DkmEvaluationResult EvaluateDataAtAddress(DkmInspectionContext inspectionContext, DkmStackWalkFrame stackFrame, string name, string fullName, NullcTypeInfo type, ulong address, DkmEvaluationResultFlags flags, DkmEvaluationResultAccessType access, DkmEvaluationResultStorageType storage) { var process = stackFrame.Process; var processData = DebugHelpers.GetOrCreateDataItem<NullcLocalProcessDataItem>(process); if (address == 0) return DkmFailedEvaluationResult.Create(inspectionContext, stackFrame, name, fullName, "Null pointer address", DkmEvaluationResultFlags.Invalid, null); string editableValue; DkmDataAddress dataAddress; string value = EvaluateValueAtAddress(process, processData.bytecode, type, address, out editableValue, ref flags, out dataAddress); if (value == null) return DkmFailedEvaluationResult.Create(inspectionContext, stackFrame, name, fullName, "Failed to read value", DkmEvaluationResultFlags.Invalid, null); DkmEvaluationResultCategory category = DkmEvaluationResultCategory.Data; DkmEvaluationResultTypeModifierFlags typeModifiers = DkmEvaluationResultTypeModifierFlags.None; NullEvaluationDataItem dataItem = new NullEvaluationDataItem(); dataItem.address = address; dataItem.type = type; dataItem.fullName = fullName; return DkmSuccessEvaluationResult.Create(inspectionContext, stackFrame, name, fullName, flags, value, editableValue, type.name, category, access, storage, typeModifiers, dataAddress, null, null, dataItem); } bool PrepareContext(DkmProcess process, Guid RuntimeInstanceId, out string error) { var processData = DebugHelpers.GetOrCreateDataItem<NullcLocalProcessDataItem>(process); if (processData.bytecode == null) { error = "Missing nullc bytecode"; return false; } processData.UpdateContextData(process); if (RuntimeInstanceId == DebugHelpers.NullcVmRuntimeGuid) { if (processData.vmContext.dataStackBase == 0) { error = "Missing nullc context"; return false; } processData.dataStackBase = processData.vmContext.dataStackBase; // VM call stack is currently not required in the debug component } else { if (processData.jitContext.dataStackBase == 0) { error = "Missing nullc context"; return false; } processData.dataStackBase = processData.jitContext.dataStackBase; processData.callStack.UpdateFrom(process, processData.jitContext.callStackBase, processData.jitContext.callStackTop, processData.bytecode); } error = null; return true; } NullcCallStackEntry GetStackFrameFunction(DkmProcess process, DkmStackWalkFrame stackFrame, out string error) { var processData = DebugHelpers.GetOrCreateDataItem<NullcLocalProcessDataItem>(process); NullcCallStackEntry activeEntry = null; if (stackFrame.Annotations != null) { NullcFuncInfo actualFunction; if (stackFrame.InstructionAddress.RuntimeInstance.Id.RuntimeType == DebugHelpers.NullcVmRuntimeGuid) actualFunction = processData.bytecode.GetFunctionAtAddress((int)(stackFrame.InstructionAddress as DkmCustomInstructionAddress).Offset); else actualFunction = processData.bytecode.GetFunctionAtNativeAddress(stackFrame.InstructionAddress.CPUInstructionPart.InstructionPointer); var dataBase = stackFrame.Annotations.FirstOrDefault((x) => x.Id == DebugHelpers.NullcCallStackDataBaseGuid); activeEntry = new NullcCallStackEntry(); activeEntry.function = actualFunction; activeEntry.dataOffset = (int)dataBase.Value; error = null; return activeEntry; } // Best-effort based fallback: find the first matching function if (activeEntry == null && stackFrame.InstructionAddress.RuntimeInstance.Id.RuntimeType != DebugHelpers.NullcVmRuntimeGuid) { var function = processData.bytecode.GetFunctionAtNativeAddress(stackFrame.InstructionAddress.CPUInstructionPart.InstructionPointer); activeEntry = processData.callStack.callStack.LastOrDefault((x) => x.function == function); } if (activeEntry == null) { error = "Failed to match nullc frame"; return null; } error = null; return activeEntry; } void IDkmLanguageExpressionEvaluator.EvaluateExpression(DkmInspectionContext inspectionContext, DkmWorkList workList, DkmLanguageExpression expression, DkmStackWalkFrame stackFrame, DkmCompletionRoutine<DkmEvaluateExpressionAsyncResult> completionRoutine) { var process = stackFrame.Process; if (!PrepareContext(process, inspectionContext.RuntimeInstance.Id.RuntimeType, out string error)) { completionRoutine(new DkmEvaluateExpressionAsyncResult(DkmFailedEvaluationResult.Create(inspectionContext, stackFrame, expression.Text, expression.Text, error, DkmEvaluationResultFlags.Invalid, null))); return; } NullcCallStackEntry activeEntry = GetStackFrameFunction(process, stackFrame, out error); if (activeEntry == null) { completionRoutine(new DkmEvaluateExpressionAsyncResult(DkmFailedEvaluationResult.Create(inspectionContext, stackFrame, expression.Text, expression.Text, error, DkmEvaluationResultFlags.Invalid, null))); return; } var processData = DebugHelpers.GetOrCreateDataItem<NullcLocalProcessDataItem>(process); string finalExpression = expression.Text; // Lets start by simple stand-alone variables // Since we don't handle composite expressions yet, we can at least clean-up access to class members (even if this can lead to a wrong result if member is shadowed) if (finalExpression.StartsWith("this.")) finalExpression = finalExpression.Substring(5); // TODO: DkmEvaluationResultCategory Method/Class // TODO: DkmEvaluationResultAccessType Internal // TODO: DkmEvaluationResultTypeModifierFlags Constant (enums, constants) // Check function locals and arguments // TODO: but which locals are still live at current point? if (activeEntry.function != null) { foreach (var el in activeEntry.function.locals) { if (el.name == finalExpression) { var address = processData.dataStackBase + (ulong)(activeEntry.dataOffset + el.offset); var result = EvaluateDataAtAddress(inspectionContext, stackFrame, el.name, el.name, el.nullcType, address, DkmEvaluationResultFlags.None, DkmEvaluationResultAccessType.None, DkmEvaluationResultStorageType.None); completionRoutine(new DkmEvaluateExpressionAsyncResult(result)); return; } } foreach (var el in activeEntry.function.arguments) { if (el.name == finalExpression) { var address = processData.dataStackBase + (ulong)(activeEntry.dataOffset + el.offset); var result = EvaluateDataAtAddress(inspectionContext, stackFrame, el.name, el.name, el.nullcType, address, DkmEvaluationResultFlags.None, DkmEvaluationResultAccessType.None, DkmEvaluationResultStorageType.None); completionRoutine(new DkmEvaluateExpressionAsyncResult(result)); return; } } if (activeEntry.function.nullcParentType != null) { var thisArgument = activeEntry.function.arguments.FirstOrDefault((x) => x.name == "this"); if (thisArgument != null) { var thisaddress = processData.dataStackBase + (ulong)(activeEntry.dataOffset + thisArgument.offset); var thisValue = DebugHelpers.ReadPointerVariable(process, thisaddress); if (thisValue.HasValue) { var classType = thisArgument.nullcType.nullcSubType; foreach (var el in classType.nullcMembers) { if (el.name == finalExpression) { var address = thisValue.Value + el.offset; var result = EvaluateDataAtAddress(inspectionContext, stackFrame, el.name, $"this.{el.name}", el.nullcType, address, DkmEvaluationResultFlags.None, DkmEvaluationResultAccessType.None, DkmEvaluationResultStorageType.None); completionRoutine(new DkmEvaluateExpressionAsyncResult(result)); } } } } } } // Check globals foreach (var el in processData.bytecode.variables) { if (el.name == finalExpression) { var address = processData.dataStackBase + (ulong)(el.offset); var result = EvaluateDataAtAddress(inspectionContext, stackFrame, el.name, el.name, el.nullcType, address, DkmEvaluationResultFlags.None, DkmEvaluationResultAccessType.Public, DkmEvaluationResultStorageType.Global); completionRoutine(new DkmEvaluateExpressionAsyncResult(result)); return; } } completionRoutine(new DkmEvaluateExpressionAsyncResult(DkmFailedEvaluationResult.Create(inspectionContext, stackFrame, expression.Text, expression.Text, "Failed to evaluate", DkmEvaluationResultFlags.Invalid, null))); } void IDkmLanguageExpressionEvaluator.GetChildren(DkmEvaluationResult result, DkmWorkList workList, int initialRequestSize, DkmInspectionContext inspectionContext, DkmCompletionRoutine<DkmGetChildrenAsyncResult> completionRoutine) { var evalData = result.GetDataItem<NullEvaluationDataItem>(); // Shouldn't happen if (evalData == null) { completionRoutine(new DkmGetChildrenAsyncResult(new DkmEvaluationResult[0], DkmEvaluationResultEnumContext.Create(0, result.StackFrame, inspectionContext, null))); return; } var process = result.StackFrame.Process; var bytecode = DebugHelpers.GetOrCreateDataItem<NullcLocalProcessDataItem>(process).bytecode; if (evalData.type.subCat == NullcTypeSubCategory.Pointer) { int finalInitialSize = initialRequestSize < 1 ? initialRequestSize : 1; DkmEvaluationResult[] initialResults = new DkmEvaluationResult[finalInitialSize]; var targetAddress = DebugHelpers.ReadPointerVariable(process, evalData.address); if (!targetAddress.HasValue) { completionRoutine(new DkmGetChildrenAsyncResult(new DkmEvaluationResult[0], DkmEvaluationResultEnumContext.Create(0, result.StackFrame, inspectionContext, null))); return; } var targetResult = EvaluateDataAtAddress(inspectionContext, result.StackFrame, "", $"*{result.FullName}", evalData.type.nullcSubType, targetAddress.Value, DkmEvaluationResultFlags.None, DkmEvaluationResultAccessType.Public, DkmEvaluationResultStorageType.None); if (initialRequestSize != 0) initialResults[0] = targetResult; // If pointer points to a class, inline class member display if (evalData.type.nullcSubType != null && evalData.type.nullcSubType.subCat == NullcTypeSubCategory.Class && targetAddress.HasValue && targetAddress.Value != 0 && (targetResult as DkmSuccessEvaluationResult) != null) { result = targetResult; var finalEvalData = new NullEvaluationDataItem(); finalEvalData.address = targetAddress.Value; finalEvalData.fullName = $"(*{result.FullName})"; finalEvalData.type = evalData.type.nullcSubType; evalData = finalEvalData; } else { var enumerator = DkmEvaluationResultEnumContext.Create(1, result.StackFrame, inspectionContext, evalData); completionRoutine(new DkmGetChildrenAsyncResult(initialResults, enumerator)); return; } } if (evalData.type.subCat == NullcTypeSubCategory.Class) { int actualSize = evalData.type.memberCount; bool isExtendable = evalData.type.typeFlags.HasFlag(NullcTypeFlags.IsExtendable); NullcTypeInfo classType = evalData.type; if (isExtendable) { int actualType = DebugHelpers.ReadIntVariable(inspectionContext.Thread.Process, evalData.address).GetValueOrDefault(0); if (actualType != 0 && actualType < bytecode.types.Count) { classType = bytecode.types[actualType]; actualSize = 1 + classType.memberCount; } } int finalInitialSize = initialRequestSize < actualSize ? initialRequestSize : actualSize; DkmEvaluationResult[] initialResults = new DkmEvaluationResult[finalInitialSize]; for (int i = 0; i < initialResults.Length; i++) { if (isExtendable && i == 0) { ulong address = evalData.address; var memberType = bytecode.types[(int)NullcTypeIndex.TypeId]; initialResults[i] = EvaluateDataAtAddress(inspectionContext, result.StackFrame, "typeid", $"{result.FullName}.typeid", memberType, address, DkmEvaluationResultFlags.None, DkmEvaluationResultAccessType.None, DkmEvaluationResultStorageType.None); } else { var memberIndex = isExtendable ? i - 1 : i; var member = classType.nullcMembers[memberIndex]; ulong address = evalData.address + member.offset; if (memberIndex < evalData.type.nullcMembers.Count) initialResults[i] = EvaluateDataAtAddress(inspectionContext, result.StackFrame, member.name, $"{result.FullName}.{member.name}", member.nullcType, address, DkmEvaluationResultFlags.None, DkmEvaluationResultAccessType.None, DkmEvaluationResultStorageType.None); else initialResults[i] = EvaluateDataAtAddress(inspectionContext, result.StackFrame, member.name, $"(({classType.name} ref){result.FullName}).{member.name}", member.nullcType, address, DkmEvaluationResultFlags.None, DkmEvaluationResultAccessType.None, DkmEvaluationResultStorageType.None); } } var finalEvalData = new NullEvaluationDataItem(); finalEvalData.address = evalData.address; finalEvalData.fullName = $"(({classType.name} ref){result.FullName})"; finalEvalData.type = classType; var enumerator = DkmEvaluationResultEnumContext.Create(actualSize, result.StackFrame, inspectionContext, finalEvalData); completionRoutine(new DkmGetChildrenAsyncResult(initialResults, enumerator)); return; } if (evalData.type.subCat == NullcTypeSubCategory.Array) { if (evalData.type.arrSize == -1) { ulong sizeAddress = evalData.address + (ulong)DebugHelpers.GetPointerSize(process); var dataAddress = DebugHelpers.ReadPointerVariable(process, evalData.address); var arrSize = DebugHelpers.ReadIntVariable(process, sizeAddress); if (dataAddress.HasValue && arrSize.HasValue) { int finalInitialSize = initialRequestSize < arrSize.Value + 1 ? initialRequestSize : arrSize.Value + 1; // Extra slot for array size DkmEvaluationResult[] initialResults = new DkmEvaluationResult[finalInitialSize]; if (finalInitialSize != 0) { var type = bytecode.types[(int)NullcTypeIndex.Int]; initialResults[0] = EvaluateDataAtAddress(inspectionContext, result.StackFrame, "size", $"{result.FullName}.size", type, sizeAddress, DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultAccessType.Internal, DkmEvaluationResultStorageType.None); } for (int i = 1; i < initialResults.Length; i++) { int index = i - 1; var type = evalData.type.nullcSubType; var elemAddress = dataAddress.Value + (ulong)(index * type.size); initialResults[i] = EvaluateDataAtAddress(inspectionContext, result.StackFrame, $"[{index}]", $"{result.FullName}[{index}]", type, elemAddress, DkmEvaluationResultFlags.None, DkmEvaluationResultAccessType.None, DkmEvaluationResultStorageType.None); } var enumerator = DkmEvaluationResultEnumContext.Create(arrSize.Value + 1, result.StackFrame, inspectionContext, evalData); completionRoutine(new DkmGetChildrenAsyncResult(initialResults, enumerator)); return; } } else { int finalInitialSize = initialRequestSize < evalData.type.arrSize ? initialRequestSize : evalData.type.arrSize; DkmEvaluationResult[] initialResults = new DkmEvaluationResult[finalInitialSize]; for (int i = 0; i < initialResults.Length; i++) { var type = evalData.type.nullcSubType; var elemAddress = evalData.address + (ulong)(i * type.size); initialResults[i] = EvaluateDataAtAddress(inspectionContext, result.StackFrame, $"[{i}]", $"{result.FullName}[{i}]", type, elemAddress, DkmEvaluationResultFlags.None, DkmEvaluationResultAccessType.None, DkmEvaluationResultStorageType.None); } var enumerator = DkmEvaluationResultEnumContext.Create(evalData.type.arrSize, result.StackFrame, inspectionContext, evalData); completionRoutine(new DkmGetChildrenAsyncResult(initialResults, enumerator)); return; } } // Shouldn't happen completionRoutine(new DkmGetChildrenAsyncResult(new DkmEvaluationResult[0], DkmEvaluationResultEnumContext.Create(0, result.StackFrame, inspectionContext, null))); } void IDkmLanguageExpressionEvaluator.GetFrameLocals(DkmInspectionContext inspectionContext, DkmWorkList workList, DkmStackWalkFrame stackFrame, DkmCompletionRoutine<DkmGetFrameLocalsAsyncResult> completionRoutine) { var process = stackFrame.Process; if (!PrepareContext(process, inspectionContext.RuntimeInstance.Id.RuntimeType, out string error)) { completionRoutine(new DkmGetFrameLocalsAsyncResult(DkmEvaluationResultEnumContext.Create(0, stackFrame, inspectionContext, null))); return; } NullcCallStackEntry activeEntry = GetStackFrameFunction(process, stackFrame, out error); if (activeEntry == null) { completionRoutine(new DkmGetFrameLocalsAsyncResult(DkmEvaluationResultEnumContext.Create(0, stackFrame, inspectionContext, null))); return; } var processData = DebugHelpers.GetOrCreateDataItem<NullcLocalProcessDataItem>(process); var frameLocalsData = new NullFrameLocalsDataItem(); frameLocalsData.activeEntry = activeEntry; if (activeEntry.function != null) { var count = activeEntry.function.arguments.Count + activeEntry.function.locals.Count; completionRoutine(new DkmGetFrameLocalsAsyncResult(DkmEvaluationResultEnumContext.Create(count, stackFrame, inspectionContext, frameLocalsData))); return; } completionRoutine(new DkmGetFrameLocalsAsyncResult(DkmEvaluationResultEnumContext.Create(processData.bytecode.variables.Count, stackFrame, inspectionContext, frameLocalsData))); } void IDkmLanguageExpressionEvaluator.GetFrameArguments(DkmInspectionContext inspectionContext, DkmWorkList workList, DkmStackWalkFrame stackFrame, DkmCompletionRoutine<DkmGetFrameArgumentsAsyncResult> completionRoutine) { var process = stackFrame.Process; if (!PrepareContext(process, inspectionContext.RuntimeInstance.Id.RuntimeType, out string error)) { completionRoutine(new DkmGetFrameArgumentsAsyncResult(new DkmEvaluationResult[0])); return; } NullcCallStackEntry activeEntry = GetStackFrameFunction(process, stackFrame, out error); if (activeEntry == null) { completionRoutine(new DkmGetFrameArgumentsAsyncResult(new DkmEvaluationResult[0])); return; } var processData = DebugHelpers.GetOrCreateDataItem<NullcLocalProcessDataItem>(process); var frameLocalsData = new NullFrameLocalsDataItem(); frameLocalsData.activeEntry = activeEntry; if (activeEntry.function != null) { var results = new DkmEvaluationResult[activeEntry.function.arguments.Count]; for (int i = 0; i < results.Length; i++) { var el = activeEntry.function.arguments[i]; var address = processData.dataStackBase + (ulong)(frameLocalsData.activeEntry.dataOffset + el.offset); results[i] = EvaluateDataAtAddress(inspectionContext, stackFrame, el.name, el.name, el.nullcType, address, DkmEvaluationResultFlags.None, DkmEvaluationResultAccessType.None, DkmEvaluationResultStorageType.None); } completionRoutine(new DkmGetFrameArgumentsAsyncResult(results)); return; } completionRoutine(new DkmGetFrameArgumentsAsyncResult(new DkmEvaluationResult[0])); } void IDkmLanguageExpressionEvaluator.GetItems(DkmEvaluationResultEnumContext enumContext, DkmWorkList workList, int startIndex, int count, DkmCompletionRoutine<DkmEvaluationEnumAsyncResult> completionRoutine) { var process = enumContext.StackFrame.Process; var processData = DebugHelpers.GetOrCreateDataItem<NullcLocalProcessDataItem>(process); var bytecode = processData.bytecode; var frameLocalsData = enumContext.GetDataItem<NullFrameLocalsDataItem>(); if (frameLocalsData != null) { var function = frameLocalsData.activeEntry.function; if (function != null) { // Visual Studio doesn't respect enumeration size for GetFrameLocals, so we need to limit it back var actualCount = function.arguments.Count + function.locals.Count; int finalCount = actualCount - startIndex; finalCount = finalCount < 0 ? 0 : (finalCount < count ? finalCount : count); var results = new DkmEvaluationResult[finalCount]; for (int i = startIndex; i < startIndex + finalCount; i++) { if (i < function.arguments.Count) { var el = function.arguments[i]; var address = processData.dataStackBase + (ulong)(frameLocalsData.activeEntry.dataOffset + el.offset); results[i - startIndex] = EvaluateDataAtAddress(enumContext.InspectionContext, enumContext.StackFrame, el.name, el.name, el.nullcType, address, DkmEvaluationResultFlags.None, DkmEvaluationResultAccessType.None, DkmEvaluationResultStorageType.None); } else { var el = function.locals[i - function.arguments.Count]; var address = processData.dataStackBase + (ulong)(frameLocalsData.activeEntry.dataOffset + el.offset); results[i - startIndex] = EvaluateDataAtAddress(enumContext.InspectionContext, enumContext.StackFrame, el.name, el.name, el.nullcType, address, DkmEvaluationResultFlags.None, DkmEvaluationResultAccessType.None, DkmEvaluationResultStorageType.None); } } completionRoutine(new DkmEvaluationEnumAsyncResult(results)); } else { // Visual Studio doesn't respect enumeration size for GetFrameLocals, so we need to limit it back var actualCount = bytecode.variables.Count; int finalCount = actualCount - startIndex; finalCount = finalCount < 0 ? 0 : (finalCount < count ? finalCount : count); var results = new DkmEvaluationResult[finalCount]; for (int i = startIndex; i < startIndex + finalCount; i++) { var el = bytecode.variables[i]; var address = processData.dataStackBase + (ulong)(frameLocalsData.activeEntry.dataOffset + el.offset); results[i - startIndex] = EvaluateDataAtAddress(enumContext.InspectionContext, enumContext.StackFrame, el.name, el.name, el.nullcType, address, DkmEvaluationResultFlags.None, DkmEvaluationResultAccessType.None, DkmEvaluationResultStorageType.Global); } completionRoutine(new DkmEvaluationEnumAsyncResult(results)); } return; } var evalData = enumContext.GetDataItem<NullEvaluationDataItem>(); // Shouldn't happen if (evalData == null) { completionRoutine(new DkmEvaluationEnumAsyncResult(new DkmEvaluationResult[0])); return; } if (evalData.type.subCat == NullcTypeSubCategory.Pointer) { if (startIndex != 0) { completionRoutine(new DkmEvaluationEnumAsyncResult()); return; } var results = new DkmEvaluationResult[1]; var targetAddress = DebugHelpers.ReadPointerVariable(process, evalData.address); if (!targetAddress.HasValue) { completionRoutine(new DkmEvaluationEnumAsyncResult(new DkmEvaluationResult[0])); return; } results[0] = EvaluateDataAtAddress(enumContext.InspectionContext, enumContext.StackFrame, "", $"*{evalData.fullName}", evalData.type.nullcSubType, targetAddress.Value, DkmEvaluationResultFlags.None, DkmEvaluationResultAccessType.Public, DkmEvaluationResultStorageType.None); completionRoutine(new DkmEvaluationEnumAsyncResult(results)); return; } if (evalData.type.subCat == NullcTypeSubCategory.Class) { bool isExtendable = evalData.type.typeFlags.HasFlag(NullcTypeFlags.IsExtendable); var results = new DkmEvaluationResult[count]; for (int i = startIndex; i < startIndex + count; i++) { if (isExtendable && i == 0) { ulong address = evalData.address; var memberType = bytecode.types[(int)NullcTypeIndex.TypeId]; results[i - startIndex] = EvaluateDataAtAddress(enumContext.InspectionContext, enumContext.StackFrame, "typeid", $"{evalData.fullName}.typeid", memberType, address, DkmEvaluationResultFlags.None, DkmEvaluationResultAccessType.None, DkmEvaluationResultStorageType.None); } else { var memberIndex = isExtendable ? i - 1 : i; var member = evalData.type.nullcMembers[i]; ulong address = evalData.address + member.offset; results[i - startIndex] = EvaluateDataAtAddress(enumContext.InspectionContext, enumContext.StackFrame, member.name, $"{evalData.fullName}.{member.name}", member.nullcType, address, DkmEvaluationResultFlags.None, DkmEvaluationResultAccessType.None, DkmEvaluationResultStorageType.None); } } completionRoutine(new DkmEvaluationEnumAsyncResult(results)); return; } if (evalData.type.subCat == NullcTypeSubCategory.Array) { if (evalData.type.arrSize == -1) { ulong sizeAddress = evalData.address + (ulong)DebugHelpers.GetPointerSize(process); var dataAddress = DebugHelpers.ReadPointerVariable(process, evalData.address); var arrSize = DebugHelpers.ReadIntVariable(process, sizeAddress); if (dataAddress.HasValue && arrSize.HasValue) { var results = new DkmEvaluationResult[count]; for (int i = startIndex; i < startIndex + count; i++) { if (i == 0) { var type = bytecode.types[(int)NullcTypeIndex.Int]; results[i - startIndex] = EvaluateDataAtAddress(enumContext.InspectionContext, enumContext.StackFrame, "size", $"{evalData.fullName}.size", type, sizeAddress, DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultAccessType.Internal, DkmEvaluationResultStorageType.None); } else { int index = i - 1; var type = evalData.type.nullcSubType; var elemAddress = dataAddress.Value + (ulong)(index * type.size); results[i - startIndex] = EvaluateDataAtAddress(enumContext.InspectionContext, enumContext.StackFrame, $"[{index}]", $"{evalData.fullName}[{index}]", type, elemAddress, DkmEvaluationResultFlags.None, DkmEvaluationResultAccessType.None, DkmEvaluationResultStorageType.None); } } completionRoutine(new DkmEvaluationEnumAsyncResult(results)); return; } } else { var results = new DkmEvaluationResult[count]; for (int i = startIndex; i < startIndex + count; i++) { var type = evalData.type.nullcSubType; var elemAddress = evalData.address + (ulong)(i * type.size); results[i - startIndex] = EvaluateDataAtAddress(enumContext.InspectionContext, enumContext.StackFrame, $"[{i}]", $"{evalData.fullName}[{i}]", type, elemAddress, DkmEvaluationResultFlags.None, DkmEvaluationResultAccessType.None, DkmEvaluationResultStorageType.None); } completionRoutine(new DkmEvaluationEnumAsyncResult(results)); return; } } completionRoutine(new DkmEvaluationEnumAsyncResult(new DkmEvaluationResult[0])); } void IDkmLanguageExpressionEvaluator.SetValueAsString(DkmEvaluationResult result, string value, int timeout, out string errorText) { var evalData = result.GetDataItem<NullEvaluationDataItem>(); // Shouldn't happen if (evalData == null) { errorText = "Missing evaluation data"; return; } var process = result.StackFrame.Process; var bytecode = DebugHelpers.GetOrCreateDataItem<NullcLocalProcessDataItem>(process).bytecode; try { SetValueAtAddress(process, bytecode, evalData.type, evalData.address, value, out errorText); } catch (Exception e) { errorText = e.Message; } } string IDkmLanguageExpressionEvaluator.GetUnderlyingString(DkmEvaluationResult result) { // RawString is not used at the moment return ""; } DkmInstructionSymbol[] IDkmSymbolFunctionResolver.Resolve(DkmSymbolFunctionResolutionRequest symbolFunctionResolutionRequest) { var processData = DebugHelpers.GetOrCreateDataItem<NullcLocalProcessDataItem>(symbolFunctionResolutionRequest.Process); var nullcCustomRuntime = symbolFunctionResolutionRequest.Process.GetRuntimeInstances().OfType<DkmCustomRuntimeInstance>().FirstOrDefault(el => el.Id.RuntimeType == DebugHelpers.NullcRuntimeGuid); var nullcNativeRuntime = DebugHelpers.useDefaultRuntimeInstance ? symbolFunctionResolutionRequest.Process.GetNativeRuntimeInstance() : symbolFunctionResolutionRequest.Process.GetRuntimeInstances().OfType<DkmNativeRuntimeInstance>().FirstOrDefault(el => el.Id.RuntimeType == DebugHelpers.NullcRuntimeGuid); if (DebugHelpers.useNativeInterfaces ? nullcNativeRuntime != null : nullcCustomRuntime != null) { DkmModuleInstance nullcModuleInstance; if (DebugHelpers.useNativeInterfaces) nullcModuleInstance = nullcNativeRuntime.GetModuleInstances().OfType<DkmNativeModuleInstance>().FirstOrDefault(el => el.Module != null && el.Module.CompilerId.VendorId == DebugHelpers.NullcCompilerGuid); else nullcModuleInstance = nullcCustomRuntime.GetModuleInstances().OfType<DkmCustomModuleInstance>().FirstOrDefault(el => el.Module != null && el.Module.CompilerId.VendorId == DebugHelpers.NullcCompilerGuid); if (nullcModuleInstance == null) return symbolFunctionResolutionRequest.Resolve(); foreach (var function in processData.bytecode.functions) { if (function.name == symbolFunctionResolutionRequest.FunctionName) { // External function if (function.regVmAddress == ~0u) return symbolFunctionResolutionRequest.Resolve(); ulong nativeInstruction = processData.bytecode.ConvertInstructionToNativeAddress((int)function.regVmAddress); return new DkmInstructionSymbol[1] { DkmNativeInstructionSymbol.Create(nullcModuleInstance.Module, (uint)(nativeInstruction - nullcModuleInstance.BaseAddress)) }; } } } return symbolFunctionResolutionRequest.Resolve(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Data; using System.Text; using SubSonic.DataProviders; using SubSonic.Extensions; using System.Linq.Expressions; using SubSonic.Schema; using SubSonic.Repository; using System.Data.Common; using SubSonic.SqlGeneration.Schema; namespace Solution.DataAccess.DataModel { /// <summary> /// A class which represents the Holidays table in the HKHR Database. /// </summary> public partial class Holidays: IActiveRecord { #region Built-in testing static TestRepository<Holidays> _testRepo; static void SetTestRepo(){ _testRepo = _testRepo ?? new TestRepository<Holidays>(new Solution.DataAccess.DataModel.HKHRDB()); } public static void ResetTestRepo(){ _testRepo = null; SetTestRepo(); } public static void Setup(List<Holidays> testlist){ SetTestRepo(); foreach (var item in testlist) { _testRepo._items.Add(item); } } public static void Setup(Holidays item) { SetTestRepo(); _testRepo._items.Add(item); } public static void Setup(int testItems) { SetTestRepo(); for(int i=0;i<testItems;i++){ Holidays item=new Holidays(); _testRepo._items.Add(item); } } public bool TestMode = false; #endregion IRepository<Holidays> _repo; ITable tbl; bool _isNew; public bool IsNew(){ return _isNew; } public void SetIsLoaded(bool isLoaded){ _isLoaded=isLoaded; if(isLoaded) OnLoaded(); } public void SetIsNew(bool isNew){ _isNew=isNew; } bool _isLoaded; public bool IsLoaded(){ return _isLoaded; } List<IColumn> _dirtyColumns; public bool IsDirty(){ return _dirtyColumns.Count>0; } public List<IColumn> GetDirtyColumns (){ return _dirtyColumns; } Solution.DataAccess.DataModel.HKHRDB _db; public Holidays(string connectionString, string providerName) { _db=new Solution.DataAccess.DataModel.HKHRDB(connectionString, providerName); Init(); } void Init(){ TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase); _dirtyColumns=new List<IColumn>(); if(TestMode){ Holidays.SetTestRepo(); _repo=_testRepo; }else{ _repo = new SubSonicRepository<Holidays>(_db); } tbl=_repo.GetTable(); SetIsNew(true); OnCreated(); } public Holidays(){ _db=new Solution.DataAccess.DataModel.HKHRDB(); Init(); } public void ORMapping(IDataRecord dataRecord) { IReadRecord readRecord = SqlReadRecord.GetIReadRecord(); readRecord.DataRecord = dataRecord; Id = readRecord.get_int("Id",null); hd_code = readRecord.get_string("hd_code",null); hd_name = readRecord.get_string("hd_name",null); hd_date = readRecord.get_datetime("hd_date",null); hd_end = readRecord.get_datetime("hd_end",null); begin_time = readRecord.get_datetime("begin_time",null); end_time = readRecord.get_datetime("end_time",null); hd_rate = readRecord.get_decimal("hd_rate",null); hd_type = readRecord.get_string("hd_type",null); hd_kind = readRecord.get_int("hd_kind",null); depart_id = readRecord.get_string("depart_id",null); alway_use = readRecord.get_short("alway_use",null); sub_depart = readRecord.get_short("sub_depart",null); need_write = readRecord.get_short("need_write",null); have_hrs = readRecord.get_short("have_hrs",null); memo = readRecord.get_string("memo",null); } partial void OnCreated(); partial void OnLoaded(); partial void OnSaved(); partial void OnChanged(); public IList<IColumn> Columns{ get{ return tbl.Columns; } } public Holidays(Expression<Func<Holidays, bool>> expression):this() { SetIsLoaded(_repo.Load(this,expression)); } internal static IRepository<Holidays> GetRepo(string connectionString, string providerName){ Solution.DataAccess.DataModel.HKHRDB db; if(String.IsNullOrEmpty(connectionString)){ db=new Solution.DataAccess.DataModel.HKHRDB(); }else{ db=new Solution.DataAccess.DataModel.HKHRDB(connectionString, providerName); } IRepository<Holidays> _repo; if(db.TestMode){ Holidays.SetTestRepo(); _repo=_testRepo; }else{ _repo = new SubSonicRepository<Holidays>(db); } return _repo; } internal static IRepository<Holidays> GetRepo(){ return GetRepo("",""); } public static Holidays SingleOrDefault(Expression<Func<Holidays, bool>> expression) { var repo = GetRepo(); var results=repo.Find(expression); Holidays single=null; if(results.Count() > 0){ single=results.ToList()[0]; single.OnLoaded(); single.SetIsLoaded(true); single.SetIsNew(false); } return single; } public static Holidays SingleOrDefault(Expression<Func<Holidays, bool>> expression,string connectionString, string providerName) { var repo = GetRepo(connectionString,providerName); var results=repo.Find(expression); Holidays single=null; if(results.Count() > 0){ single=results.ToList()[0]; } return single; } public static bool Exists(Expression<Func<Holidays, bool>> expression,string connectionString, string providerName) { return All(connectionString,providerName).Any(expression); } public static bool Exists(Expression<Func<Holidays, bool>> expression) { return All().Any(expression); } public static IList<Holidays> Find(Expression<Func<Holidays, bool>> expression) { var repo = GetRepo(); return repo.Find(expression).ToList(); } public static IList<Holidays> Find(Expression<Func<Holidays, bool>> expression,string connectionString, string providerName) { var repo = GetRepo(connectionString,providerName); return repo.Find(expression).ToList(); } public static IQueryable<Holidays> All(string connectionString, string providerName) { return GetRepo(connectionString,providerName).GetAll(); } public static IQueryable<Holidays> All() { return GetRepo().GetAll(); } public static PagedList<Holidays> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) { return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize); } public static PagedList<Holidays> GetPaged(string sortBy, int pageIndex, int pageSize) { return GetRepo().GetPaged(sortBy, pageIndex, pageSize); } public static PagedList<Holidays> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) { return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize); } public static PagedList<Holidays> GetPaged(int pageIndex, int pageSize) { return GetRepo().GetPaged(pageIndex, pageSize); } public string KeyName() { return "Id"; } public object KeyValue() { return this.Id; } public void SetKeyValue(object value) { if (value != null && value!=DBNull.Value) { var settable = value.ChangeTypeTo<int>(); this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null); } } public override string ToString(){ var sb = new StringBuilder(); sb.Append("Id=" + Id + "; "); sb.Append("hd_code=" + hd_code + "; "); sb.Append("hd_name=" + hd_name + "; "); sb.Append("hd_date=" + hd_date + "; "); sb.Append("hd_end=" + hd_end + "; "); sb.Append("begin_time=" + begin_time + "; "); sb.Append("end_time=" + end_time + "; "); sb.Append("hd_rate=" + hd_rate + "; "); sb.Append("hd_type=" + hd_type + "; "); sb.Append("hd_kind=" + hd_kind + "; "); sb.Append("depart_id=" + depart_id + "; "); sb.Append("alway_use=" + alway_use + "; "); sb.Append("sub_depart=" + sub_depart + "; "); sb.Append("need_write=" + need_write + "; "); sb.Append("have_hrs=" + have_hrs + "; "); sb.Append("memo=" + memo + "; "); return sb.ToString(); } public override bool Equals(object obj){ if(obj.GetType()==typeof(Holidays)){ Holidays compare=(Holidays)obj; return compare.KeyValue()==this.KeyValue(); }else{ return base.Equals(obj); } } public override int GetHashCode() { return this.Id; } public string DescriptorValue() { return this.hd_code.ToString(); } public string DescriptorColumn() { return "hd_code"; } public static string GetKeyColumn() { return "Id"; } public static string GetDescriptorColumn() { return "hd_code"; } #region ' Foreign Keys ' #endregion int _Id; /// <summary> /// /// </summary> [SubSonicPrimaryKey] public int Id { get { return _Id; } set { if(_Id!=value || _isLoaded){ _Id=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } string _hd_code; /// <summary> /// /// </summary> public string hd_code { get { return _hd_code; } set { if(_hd_code!=value || _isLoaded){ _hd_code=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="hd_code"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } string _hd_name; /// <summary> /// /// </summary> public string hd_name { get { return _hd_name; } set { if(_hd_name!=value || _isLoaded){ _hd_name=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="hd_name"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime _hd_date; /// <summary> /// /// </summary> public DateTime hd_date { get { return _hd_date; } set { if(_hd_date!=value || _isLoaded){ _hd_date=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="hd_date"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _hd_end; /// <summary> /// /// </summary> public DateTime? hd_end { get { return _hd_end; } set { if(_hd_end!=value || _isLoaded){ _hd_end=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="hd_end"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _begin_time; /// <summary> /// /// </summary> public DateTime? begin_time { get { return _begin_time; } set { if(_begin_time!=value || _isLoaded){ _begin_time=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="begin_time"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _end_time; /// <summary> /// /// </summary> public DateTime? end_time { get { return _end_time; } set { if(_end_time!=value || _isLoaded){ _end_time=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="end_time"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } decimal? _hd_rate; /// <summary> /// /// </summary> public decimal? hd_rate { get { return _hd_rate; } set { if(_hd_rate!=value || _isLoaded){ _hd_rate=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="hd_rate"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } string _hd_type; /// <summary> /// /// </summary> public string hd_type { get { return _hd_type; } set { if(_hd_type!=value || _isLoaded){ _hd_type=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="hd_type"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } int? _hd_kind; /// <summary> /// /// </summary> public int? hd_kind { get { return _hd_kind; } set { if(_hd_kind!=value || _isLoaded){ _hd_kind=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="hd_kind"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } string _depart_id; /// <summary> /// /// </summary> public string depart_id { get { return _depart_id; } set { if(_depart_id!=value || _isLoaded){ _depart_id=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="depart_id"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short _alway_use; /// <summary> /// /// </summary> public short alway_use { get { return _alway_use; } set { if(_alway_use!=value || _isLoaded){ _alway_use=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="alway_use"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short _sub_depart; /// <summary> /// /// </summary> public short sub_depart { get { return _sub_depart; } set { if(_sub_depart!=value || _isLoaded){ _sub_depart=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="sub_depart"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _need_write; /// <summary> /// /// </summary> public short? need_write { get { return _need_write; } set { if(_need_write!=value || _isLoaded){ _need_write=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="need_write"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _have_hrs; /// <summary> /// /// </summary> public short? have_hrs { get { return _have_hrs; } set { if(_have_hrs!=value || _isLoaded){ _have_hrs=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="have_hrs"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } string _memo; /// <summary> /// /// </summary> public string memo { get { return _memo; } set { if(_memo!=value || _isLoaded){ _memo=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="memo"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } public DbCommand GetUpdateCommand() { if(TestMode) return _db.DataProvider.CreateCommand(); else return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand(); } public DbCommand GetInsertCommand() { if(TestMode) return _db.DataProvider.CreateCommand(); else return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand(); } public DbCommand GetDeleteCommand() { if(TestMode) return _db.DataProvider.CreateCommand(); else return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand(); } public void Update(){ Update(_db.DataProvider); } public void Update(IDataProvider provider){ if(this._dirtyColumns.Count>0){ _repo.Update(this,provider); _dirtyColumns.Clear(); } OnSaved(); } public void Add(){ Add(_db.DataProvider); } public void Add(IDataProvider provider){ var key=KeyValue(); if(key==null){ var newKey=_repo.Add(this,provider); this.SetKeyValue(newKey); }else{ _repo.Add(this,provider); } SetIsNew(false); OnSaved(); } public void Save() { Save(_db.DataProvider); } public void Save(IDataProvider provider) { if (_isNew) { Add(provider); } else { Update(provider); } } public void Delete(IDataProvider provider) { _repo.Delete(KeyValue()); } public void Delete() { Delete(_db.DataProvider); } public static void Delete(Expression<Func<Holidays, bool>> expression) { var repo = GetRepo(); repo.DeleteMany(expression); } public void Load(IDataReader rdr) { Load(rdr, true); } public void Load(IDataReader rdr, bool closeReader) { if (rdr.Read()) { try { rdr.Load(this); SetIsNew(false); SetIsLoaded(true); } catch { SetIsLoaded(false); throw; } }else{ SetIsLoaded(false); } if (closeReader) rdr.Dispose(); } } }
using System; using System.Xml; using System.Data; using System.Data.OleDb; namespace MyMeta { #if ENTERPRISE using System.Runtime.InteropServices; [ComVisible(false), ClassInterface(ClassInterfaceType.AutoDual)] #endif public class Index : Single, IIndex { public Index() { } internal void AddColumn(string physicalColumnName) { if(null == _columns) { _columns = (Columns)this.dbRoot.ClassFactory.CreateColumns(); _columns.dbRoot = this.dbRoot; _columns.Index = this; } Column column = this.Indexes.Table.Columns[physicalColumnName] as Column; _columns.AddColumn(column); } #region Objects public ITable Table { get { return this.Indexes.Table; } } #endregion #region Collections virtual public IPropertyCollection GlobalProperties { get { Database db = this.Indexes.Table.Tables.Database as Database; if(null == db._indexProperties) { db._indexProperties = new PropertyCollection(); db._indexProperties.Parent = this; string xPath = this.GlobalUserDataXPath; XmlNode xmlNode = this.dbRoot.UserData.SelectSingleNode(xPath, null); if(xmlNode == null) { XmlNode parentNode = db.CreateGlobalXmlNode(); xmlNode = parentNode.OwnerDocument.CreateNode(XmlNodeType.Element, "Index", null); parentNode.AppendChild(xmlNode); } db._indexProperties.LoadAllGlobal(xmlNode); } return db._indexProperties; } } virtual public IPropertyCollection AllProperties { get { if(null == _allProperties) { _allProperties = new PropertyCollectionAll(); _allProperties.Load(this.Properties, this.GlobalProperties); } return _allProperties; } } internal PropertyCollectionAll _allProperties = null; #endregion #region Properties #if ENTERPRISE [DispId(0)] #endif override public string Alias { get { XmlNode node = null; if(this.GetXmlNode(out node, false)) { string niceName = null; if(this.GetUserData(node, "n", out niceName)) { if(string.Empty != niceName) return niceName; } } // There was no nice name return this.Name; } set { XmlNode node = null; if(this.GetXmlNode(out node, true)) { this.SetUserData(node, "n", value); } } } override public string Name { get { return this.GetString(Indexes.f_IndexName); } } virtual public string Schema { get { return this.GetString(Indexes.f_IndexSchema); } } virtual public System.Boolean Unique { get { return this.GetBool(Indexes.f_Unique); } } virtual public System.Boolean Clustered { get { return this.GetBool(Indexes.f_Clustered); } } virtual public string Type { get { System.Int32 i = this.GetInt32(Indexes.f_Type); switch(i) { case 1: return "BTREE"; case 2: return "HASH"; case 3: return "CONTENT"; case 4: return "OTHER"; default: return "OTHER"; } } } virtual public System.Int32 FillFactor { get { return this.GetInt32(Indexes.f_FillFactor); } } virtual public System.Int32 InitialSize { get { return this.GetInt32(Indexes.f_InitializeSize); } } virtual public System.Boolean SortBookmarks { get { return this.GetBool(Indexes.f_SortBookmarks); } } virtual public System.Boolean AutoUpdate { get { return this.GetBool(Indexes.f_AutoUpdate); } } virtual public string NullCollation { get { System.Int32 i = this.GetInt32(Indexes.f_NullCollation); switch(i) { case 1: return "END"; case 2: return "HIGH"; case 4: return "LOW"; case 8: return "START"; default: return "UNKNOWN"; } } } virtual public string Collation { get { System.Int32 i = this.GetInt16(Indexes.f_Collation); switch(i) { case 1: return "ASCENDING"; case 2: return "DECENDING"; default: return "UNKNOWN"; } } } virtual public Decimal Cardinality { get { return this.GetDecimal(Indexes.f_Cardinality); } } virtual public System.Int32 Pages { get { return this.GetInt32(Indexes.f_Pages); } } virtual public string FilterCondition { get { return this.GetString(Indexes.f_FilterCondition); } } virtual public System.Boolean Integrated { get { return this.GetBool(Indexes.f_Integrated); } } #endregion #region XML User Data #if ENTERPRISE [ComVisible(false)] #endif override public string UserDataXPath { get { return Indexes.UserDataXPath + @"/Index[@p='" + this.Name + "']"; } } #if ENTERPRISE [ComVisible(false)] #endif override public string GlobalUserDataXPath { get { return this.Indexes.Table.Tables.Database.GlobalUserDataXPath + "/Index"; } } #if ENTERPRISE [ComVisible(false)] #endif override internal bool GetXmlNode(out XmlNode node, bool forceCreate) { node = null; bool success = false; if(null == _xmlNode) { // Get the parent node XmlNode parentNode = null; if(this.Indexes.GetXmlNode(out parentNode, forceCreate)) { // See if our user data already exists string xPath = @"./Index[@p='" + this.Name + "']"; if(!GetUserData(xPath, parentNode, out _xmlNode) && forceCreate) { // Create it, and try again this.CreateUserMetaData(parentNode); GetUserData(xPath, parentNode, out _xmlNode); } } } if(null != _xmlNode) { node = _xmlNode; success = true; } return success; } #if ENTERPRISE [ComVisible(false)] #endif override public void CreateUserMetaData(XmlNode parentNode) { XmlNode myNode = parentNode.OwnerDocument.CreateNode(XmlNodeType.Element, "Index", null); parentNode.AppendChild(myNode); XmlAttribute attr; attr = parentNode.OwnerDocument.CreateAttribute("p"); attr.Value = this.Name; myNode.Attributes.Append(attr); attr = parentNode.OwnerDocument.CreateAttribute("n"); attr.Value = ""; myNode.Attributes.Append(attr); } #endregion #region INameValueCollection Members public string ItemName { get { return this.Name; } } public string ItemValue { get { return this.Name; } } #endregion virtual public IColumns Columns { get { return _columns; } } private Columns _columns = null; internal Indexes Indexes = null; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.TrafficManager { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; public partial class TrafficManagerManagementClient : ServiceClient<TrafficManagerManagementClient>, ITrafficManagerManagementClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets subscription credentials which uniquely identify Microsoft Azure /// subscription. The subscription ID forms part of the URI for every service /// call. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// Client Api Version. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IEndpointsOperations. /// </summary> public virtual IEndpointsOperations Endpoints { get; private set; } /// <summary> /// Gets the IProfilesOperations. /// </summary> public virtual IProfilesOperations Profiles { get; private set; } /// <summary> /// Gets the IGeographicHierarchiesOperations. /// </summary> public virtual IGeographicHierarchiesOperations GeographicHierarchies { get; private set; } /// <summary> /// Initializes a new instance of the TrafficManagerManagementClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected TrafficManagerManagementClient(params DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the TrafficManagerManagementClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected TrafficManagerManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the TrafficManagerManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected TrafficManagerManagementClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the TrafficManagerManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected TrafficManagerManagementClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the TrafficManagerManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public TrafficManagerManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the TrafficManagerManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public TrafficManagerManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the TrafficManagerManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public TrafficManagerManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the TrafficManagerManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public TrafficManagerManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { Endpoints = new EndpointsOperations(this); Profiles = new ProfilesOperations(this); GeographicHierarchies = new GeographicHierarchiesOperations(this); BaseUri = new System.Uri("https://management.azure.com"); ApiVersion = "2017-05-01"; AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Threading.Tasks; using AddressBook; using Foundation; using Mitten.Mobile.Application.AddressBook; namespace Mitten.Mobile.iOS.Application.AddressBook { /// <summary> /// Provides access to the iOS address book. /// </summary> public class iOSAddressBook : IAddressBook { private static class Constants { public static readonly DateTime ReferenceDate = new DateTime(2001, 1, 1, 0, 0, 0, DateTimeKind.Utc); public const string ExternalContactSource = "iOS"; public const string LabelTrimStart = "_$!<"; public const string LabelTrimEnd = ">!$_"; } private ABAddressBook addressBook; /// <summary> /// Gets the current authorization permissions for the address book. /// </summary> /// <returns>The current permission.</returns> public AddressBookPermission GetPermission() { ABAuthorizationStatus status = this.GetAuthorizationStatus(); if (status == ABAuthorizationStatus.Authorized) { return AddressBookPermission.Authorized; } if (status == ABAuthorizationStatus.Denied) { return AddressBookPermission.Denied; } if (status == ABAuthorizationStatus.NotDetermined) { return AddressBookPermission.NotDetermined; } if (status == ABAuthorizationStatus.Restricted) { return AddressBookPermission.Restricted; } throw new InvalidOperationException("Unexpected ABAuthorizationStatus (" + status + ")."); } /// <summary> /// Requests access to the device's address book. /// </summary> /// <returns>True if access was granted, otherwise false.</returns> public Task<bool> RequestAccess() { TaskCompletionSource<bool> taskCompletionSource = new TaskCompletionSource<bool>(); this.GetAddressBook().RequestAccess((result, error) => taskCompletionSource.SetResult(result)); return taskCompletionSource.Task; } /// <summary> /// Gets a list of all contacts from the device's address book. /// </summary> /// <returns>A list of contacts from address book.</returns> public Task<IEnumerable<AddressBookEntry>> GetAllContactsFromAddressBook() { return Task.Factory.StartNew( () => this.GetAddressBook() .GetPeople() .Where(item => item.Type == ABRecordType.Person) .Select(this.ConvertFromAddressBook)); } private AddressBookEntry ConvertFromAddressBook(ABPerson from) { AddressBookEntry entry = new AddressBookEntry(); entry.ExternalContactId = from.Id.ToString(); entry.ExternalContactSource = Constants.ExternalContactSource; entry.IsCompany = this.IsCompany(from); entry.FirstName = from.FirstName; entry.LastName = from.LastName; entry.CompanyName = from.Organization; entry.ExternalModificationDate = this.ToDateTime(from.ModificationDate); if (from.HasImage) { NSData imageData = from.GetImage(ABPersonImageFormat.OriginalSize); byte[] image = new byte[imageData.Length]; Marshal.Copy(imageData.Bytes, image, 0, Convert.ToInt32(imageData.Length)); entry.Image = image; } List<KeyValuePair<string, Address>> addresses = new List<KeyValuePair<string, Address>>(); foreach (ABMultiValueEntry<PersonAddress> address in from.GetAllAddresses()) { Address newAddress = new Address(); newAddress.Street = address.Value.Street; newAddress.City = address.Value.City; newAddress.Province = address.Value.State; newAddress.PostalCode = address.Value.Zip; newAddress.Country = address.Value.Country; addresses.Add(new KeyValuePair<string, Address>(this.NormalizeLabel(address.Label), newAddress)); } entry.Addresses = addresses; List<KeyValuePair<string, string>> emailAddresses = new List<KeyValuePair<string, string>>(); foreach (ABMultiValueEntry<string> emailAddress in from.GetEmails()) { emailAddresses.Add(new KeyValuePair<string, string>(this.NormalizeLabel(emailAddress.Label), emailAddress.Value)); } entry.EmailAddresses = emailAddresses; List<KeyValuePair<string, string>> phoneNumbers = new List<KeyValuePair<string, string>>(); foreach (ABMultiValueEntry<string> phoneNumber in from.GetPhones()) { phoneNumbers.Add(new KeyValuePair<string, string>(this.NormalizeLabel(phoneNumber.Label), phoneNumber.Value)); } entry.PhoneNumbers = phoneNumbers; return entry; } private bool IsCompany(ABPerson person) { if (person.PersonKind == ABPersonKind.Organization) { return true; } if (!string.IsNullOrWhiteSpace(person.Organization)) { return string.IsNullOrWhiteSpace(person.FirstName) && string.IsNullOrWhiteSpace(person.LastName); } return false; } private ABAddressBook GetAddressBook() { if (this.addressBook == null) { NSError error; this.addressBook = ABAddressBook.Create(out error); if (addressBook == null) { throw new InvalidOperationException("Failed to create an AddressBook with error (" + error + ")."); } } return this.addressBook; } private ABAuthorizationStatus GetAuthorizationStatus() { return ABAddressBook.GetAuthorizationStatus(); } private string NormalizeLabel(string label) { if (!string.IsNullOrWhiteSpace(label)) { return label .TrimStart(Constants.LabelTrimStart.ToCharArray()) .TrimEnd(Constants.LabelTrimEnd.ToCharArray()) .ToLowerInvariant(); } return label; } private DateTime ToDateTime(NSDate nsDate) { return Constants.ReferenceDate.AddSeconds(nsDate.SecondsSinceReferenceDate); } } }
// // Copyright (C) Microsoft. All rights reserved. // using System.Text; using System.Collections; using System.Management.Automation; using System.Globalization; using System.Management.Automation.Runspaces; namespace Microsoft.PowerShell.Commands { /// <summary> /// Implementing type for WSManConfigurationOption /// </summary> public class WSManConfigurationOption : PSTransportOption { private const string Token = " {0}='{1}'"; private const string QuotasToken = "<Quotas {0} />"; internal const string AttribOutputBufferingMode = "OutputBufferingMode"; internal static System.Management.Automation.Runspaces.OutputBufferingMode? DefaultOutputBufferingMode = System.Management.Automation.Runspaces.OutputBufferingMode.Block; private System.Management.Automation.Runspaces.OutputBufferingMode? _outputBufferingMode = null; private const string AttribProcessIdleTimeout = "ProcessIdleTimeoutSec"; internal static readonly int? DefaultProcessIdleTimeout_ForPSRemoting = 0; // in seconds internal static readonly int? DefaultProcessIdleTimeout_ForWorkflow = 1209600; // in seconds private int? _processIdleTimeoutSec = null; internal const string AttribMaxIdleTimeout = "MaxIdleTimeoutms"; internal static readonly int? DefaultMaxIdleTimeout = int.MaxValue; private int? _maxIdleTimeoutSec = null; internal const string AttribIdleTimeout = "IdleTimeoutms"; internal static readonly int? DefaultIdleTimeout = 7200; // 2 hours in seconds private int? _idleTimeoutSec = null; private const string AttribMaxConcurrentUsers = "MaxConcurrentUsers"; internal static readonly int? DefaultMaxConcurrentUsers = int.MaxValue; private int? _maxConcurrentUsers = null; private const string AttribMaxProcessesPerSession = "MaxProcessesPerShell"; internal static readonly int? DefaultMaxProcessesPerSession = int.MaxValue; private int? _maxProcessesPerSession = null; private const string AttribMaxMemoryPerSessionMB = "MaxMemoryPerShellMB"; internal static readonly int? DefaultMaxMemoryPerSessionMB = int.MaxValue; private int? _maxMemoryPerSessionMB = null; private const string AttribMaxSessions = "MaxShells"; internal static readonly int? DefaultMaxSessions = int.MaxValue; private int? _maxSessions = null; private const string AttribMaxSessionsPerUser = "MaxShellsPerUser"; internal static readonly int? DefaultMaxSessionsPerUser = int.MaxValue; private int? _maxSessionsPerUser = null; private const string AttribMaxConcurrentCommandsPerSession = "MaxConcurrentCommandsPerShell"; internal static readonly int? DefaultMaxConcurrentCommandsPerSession = int.MaxValue; private int? _maxConcurrentCommandsPerSession = null; /// <summary> /// Constructor that instantiates with default values /// </summary> internal WSManConfigurationOption() { } /// <summary> /// LoadFromDefaults /// </summary> /// <param name="sessionType"></param> /// <param name="keepAssigned"></param> protected internal override void LoadFromDefaults(PSSessionType sessionType, bool keepAssigned) { if (!keepAssigned || !_outputBufferingMode.HasValue) { _outputBufferingMode = DefaultOutputBufferingMode; } if (!keepAssigned || !_processIdleTimeoutSec.HasValue) { _processIdleTimeoutSec = sessionType == PSSessionType.Workflow ? DefaultProcessIdleTimeout_ForWorkflow : DefaultProcessIdleTimeout_ForPSRemoting; } if (!keepAssigned || !_maxIdleTimeoutSec.HasValue) { _maxIdleTimeoutSec = DefaultMaxIdleTimeout; } if (!keepAssigned || !_idleTimeoutSec.HasValue) { _idleTimeoutSec = DefaultIdleTimeout; } if (!keepAssigned || !_maxConcurrentUsers.HasValue) { _maxConcurrentUsers = DefaultMaxConcurrentUsers; } if (!keepAssigned || !_maxProcessesPerSession.HasValue) { _maxProcessesPerSession = DefaultMaxProcessesPerSession; } if (!keepAssigned || !_maxMemoryPerSessionMB.HasValue) { _maxMemoryPerSessionMB = DefaultMaxMemoryPerSessionMB; } if (!keepAssigned || !_maxSessions.HasValue) { _maxSessions = DefaultMaxSessions; } if (!keepAssigned || !_maxSessionsPerUser.HasValue) { _maxSessionsPerUser = DefaultMaxSessionsPerUser; } if (!keepAssigned || !_maxConcurrentCommandsPerSession.HasValue) { _maxConcurrentCommandsPerSession = DefaultMaxConcurrentCommandsPerSession; } } /// <summary> /// ProcessIdleTimeout in Seconds /// </summary> public int? ProcessIdleTimeoutSec { get { return _processIdleTimeoutSec; } internal set { _processIdleTimeoutSec = value; } } /// <summary> /// MaxIdleTimeout in Seconds /// </summary> public int? MaxIdleTimeoutSec { get { return _maxIdleTimeoutSec; } internal set { _maxIdleTimeoutSec = value; } } /// <summary> /// MaxSessions /// </summary> public int? MaxSessions { get { return _maxSessions; } internal set { _maxSessions = value; } } /// <summary> /// MaxConcurrentCommandsPerSession /// </summary> public int? MaxConcurrentCommandsPerSession { get { return _maxConcurrentCommandsPerSession; } internal set { _maxConcurrentCommandsPerSession = value; } } /// <summary> /// MaxSessionsPerUser /// </summary> public int? MaxSessionsPerUser { get { return _maxSessionsPerUser; } internal set { _maxSessionsPerUser = value; } } /// <summary> /// MaxMemoryPerSessionMB /// </summary> public int? MaxMemoryPerSessionMB { get { return _maxMemoryPerSessionMB; } internal set { _maxMemoryPerSessionMB = value; } } /// <summary> /// MaxProcessesPerSession /// </summary> public int? MaxProcessesPerSession { get { return _maxProcessesPerSession; } internal set { _maxProcessesPerSession = value; } } /// <summary> /// MaxConcurrentUsers /// </summary> public int? MaxConcurrentUsers { get { return _maxConcurrentUsers; } internal set { _maxConcurrentUsers = value; } } /// <summary> /// IdleTimeout in Seconds /// </summary> public int? IdleTimeoutSec { get { return _idleTimeoutSec; } internal set { _idleTimeoutSec = value; } } /// <summary> /// OutputBufferingMode /// </summary> public System.Management.Automation.Runspaces.OutputBufferingMode? OutputBufferingMode { get { return _outputBufferingMode; } internal set { _outputBufferingMode = value; } } internal override Hashtable ConstructQuotasAsHashtable() { Hashtable quotas = new Hashtable(); if (_idleTimeoutSec.HasValue) { quotas[AttribIdleTimeout] = (1000 * _idleTimeoutSec.Value).ToString(CultureInfo.InvariantCulture); } if (_maxConcurrentUsers.HasValue) { quotas[AttribMaxConcurrentUsers] = _maxConcurrentUsers.Value.ToString(CultureInfo.InvariantCulture); } if (_maxProcessesPerSession.HasValue) { quotas[AttribMaxProcessesPerSession] = _maxProcessesPerSession.Value.ToString(CultureInfo.InvariantCulture); } if (_maxMemoryPerSessionMB.HasValue) { quotas[AttribMaxMemoryPerSessionMB] = _maxMemoryPerSessionMB.Value.ToString(CultureInfo.InvariantCulture); } if (_maxSessionsPerUser.HasValue) { quotas[AttribMaxSessionsPerUser] = _maxSessionsPerUser.Value.ToString(CultureInfo.InvariantCulture); } if (_maxConcurrentCommandsPerSession.HasValue) { quotas[AttribMaxConcurrentCommandsPerSession] = _maxConcurrentCommandsPerSession.Value.ToString(CultureInfo.InvariantCulture); } if (_maxSessions.HasValue) { quotas[AttribMaxSessions] = _maxSessions.Value.ToString(CultureInfo.InvariantCulture); } if (_maxIdleTimeoutSec.HasValue) { quotas[AttribMaxIdleTimeout] = (1000 * _maxIdleTimeoutSec.Value).ToString(CultureInfo.InvariantCulture); } return quotas; } /// <summary> /// ConstructQuotas /// </summary> /// <returns></returns> internal override string ConstructQuotas() { StringBuilder sb = new StringBuilder(); if (_idleTimeoutSec.HasValue) { sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribIdleTimeout, 1000 * _idleTimeoutSec)); } if (_maxConcurrentUsers.HasValue) { sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxConcurrentUsers, _maxConcurrentUsers)); } if (_maxProcessesPerSession.HasValue) { sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxProcessesPerSession, _maxProcessesPerSession)); } if (_maxMemoryPerSessionMB.HasValue) { sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxMemoryPerSessionMB, _maxMemoryPerSessionMB)); } if (_maxSessionsPerUser.HasValue) { sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxSessionsPerUser, _maxSessionsPerUser)); } if (_maxConcurrentCommandsPerSession.HasValue) { sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxConcurrentCommandsPerSession, _maxConcurrentCommandsPerSession)); } if (_maxSessions.HasValue) { sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxSessions, _maxSessions)); } if (_maxIdleTimeoutSec.HasValue) { // Special case max int value for unbounded default. sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribMaxIdleTimeout, (_maxIdleTimeoutSec == int.MaxValue) ? _maxIdleTimeoutSec : (1000 * _maxIdleTimeoutSec))); } return sb.Length > 0 ? string.Format(CultureInfo.InvariantCulture, QuotasToken, sb.ToString()) : string.Empty; } /// <summary> /// ConstructOptionsXmlAttributes /// </summary> /// <returns></returns> internal override string ConstructOptionsAsXmlAttributes() { StringBuilder sb = new StringBuilder(); if (_outputBufferingMode.HasValue) { sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribOutputBufferingMode, _outputBufferingMode.ToString())); } if (_processIdleTimeoutSec.HasValue) { sb.Append(string.Format(CultureInfo.InvariantCulture, Token, AttribProcessIdleTimeout, _processIdleTimeoutSec)); } return sb.ToString(); } /// <summary> /// ConstructOptionsXmlAttributes /// </summary> /// <returns></returns> internal override Hashtable ConstructOptionsAsHashtable() { Hashtable table = new Hashtable(); if (_outputBufferingMode.HasValue) { table[AttribOutputBufferingMode] = _outputBufferingMode.ToString(); } if (_processIdleTimeoutSec.HasValue) { table[AttribProcessIdleTimeout] = _processIdleTimeoutSec; } return table; } } /// <summary> /// Command to create an object for WSManConfigurationOption /// </summary> [Cmdlet(VerbsCommon.New, "PSTransportOption", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=210608", RemotingCapability = RemotingCapability.None)] [OutputType(typeof(WSManConfigurationOption))] public sealed class NewPSTransportOptionCommand : PSCmdlet { private WSManConfigurationOption _option = new WSManConfigurationOption(); /// <summary> /// MaxIdleTimeoutSec /// </summary> [Parameter(ValueFromPipelineByPropertyName = true), ValidateRange(60, 2147483)] public int? MaxIdleTimeoutSec { get { return _option.MaxIdleTimeoutSec; } set { _option.MaxIdleTimeoutSec = value; } } /// <summary> /// ProcessIdleTimeoutSec /// </summary> [Parameter(ValueFromPipelineByPropertyName = true), ValidateRange(0, 1209600)] public int? ProcessIdleTimeoutSec { get { return _option.ProcessIdleTimeoutSec; } set { _option.ProcessIdleTimeoutSec = value; } } /// <summary> /// MaxSessions /// </summary> [Parameter(ValueFromPipelineByPropertyName = true), ValidateRange(1, int.MaxValue)] public int? MaxSessions { get { return _option.MaxSessions; } set { _option.MaxSessions = value; } } /// <summary> /// MaxConcurrentCommandsPerSession /// </summary> [Parameter(ValueFromPipelineByPropertyName = true), ValidateRange(1, int.MaxValue)] public int? MaxConcurrentCommandsPerSession { get { return _option.MaxConcurrentCommandsPerSession; } set { _option.MaxConcurrentCommandsPerSession = value; } } /// <summary> /// MaxSessionsPerUser /// </summary> [Parameter(ValueFromPipelineByPropertyName = true), ValidateRange(1, int.MaxValue)] public int? MaxSessionsPerUser { get { return _option.MaxSessionsPerUser; } set { _option.MaxSessionsPerUser = value; } } /// <summary> /// MaxMemoryPerSessionMB /// </summary> [Parameter(ValueFromPipelineByPropertyName = true), ValidateRange(5, int.MaxValue)] public int? MaxMemoryPerSessionMB { get { return _option.MaxMemoryPerSessionMB; } set { _option.MaxMemoryPerSessionMB = value; } } /// <summary> /// MaxProcessesPerSession /// </summary> [Parameter(ValueFromPipelineByPropertyName = true), ValidateRange(1, int.MaxValue)] public int? MaxProcessesPerSession { get { return _option.MaxProcessesPerSession; } set { _option.MaxProcessesPerSession = value; } } /// <summary> /// MaxConcurrentUsers /// </summary> [Parameter(ValueFromPipelineByPropertyName = true), ValidateRange(1, 100)] public int? MaxConcurrentUsers { get { return _option.MaxConcurrentUsers; } set { _option.MaxConcurrentUsers = value; } } /// <summary> /// IdleTimeoutMs /// </summary> [Parameter(ValueFromPipelineByPropertyName = true), ValidateRange(60, 2147483)] public int? IdleTimeoutSec { get { return _option.IdleTimeoutSec; } set { _option.IdleTimeoutSec = value; } } /// <summary> /// OutputBufferingMode /// </summary> [Parameter(ValueFromPipelineByPropertyName = true)] public System.Management.Automation.Runspaces.OutputBufferingMode? OutputBufferingMode { get { return _option.OutputBufferingMode; } set { _option.OutputBufferingMode = value; } } /// <summary> /// Overriding the base method /// </summary> protected override void ProcessRecord() { this.WriteObject(_option); } } }
// 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.Net.Test.Common; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Net.Sockets.Tests { // Code taken from https://msdn.microsoft.com/en-us/library/system.net.sockets.socketasynceventargs.aspx // Implements the connection logic for the socket server. // After accepting a connection, all data read from the client // is sent back to the client. The read and echo back to the client pattern // is continued until the client disconnects. public class SocketTestServerAsync : SocketTestServer { private const int OpsToPreAlloc = 2; // Read, write (don't alloc buffer space for accepts). private VerboseTestLogging _log; private int _maxNumConnections; // The maximum number of connections the sample is designed to handle simultaneously. private int _receiveBufferSize; // Buffer size to use for each socket I/O operation. private BufferManager _bufferManager; // Represents a large reusable set of buffers for all socket operations. private Socket _listenSocket; // The socket used to listen for incoming connection requests. private SocketAsyncEventArgsPool _readWritePool; // Pool of reusable SocketAsyncEventArgs objects for write, read and accept socket operations. private int _totalBytesRead; // Counter of the total # bytes received by the server. private int _numConnectedSockets; // The total number of clients connected to the server. private Semaphore _maxNumberAcceptedClientsSemaphore; private int _acceptRetryCount = 10; private ProtocolType _protocolType; private object _listenSocketLock = new object(); protected sealed override int Port { get { return ((IPEndPoint)_listenSocket.LocalEndPoint).Port; } } public SocketTestServerAsync(int numConnections, int receiveBufferSize, EndPoint localEndPoint, ProtocolType protocolType = ProtocolType.Tcp) { _log = VerboseTestLogging.GetInstance(); _totalBytesRead = 0; _numConnectedSockets = 0; _maxNumConnections = numConnections; _receiveBufferSize = receiveBufferSize; // Allocate buffers such that the maximum number of sockets can have one outstanding read and // write posted to the socket simultaneously. _bufferManager = new BufferManager(receiveBufferSize * numConnections * OpsToPreAlloc, receiveBufferSize); _readWritePool = new SocketAsyncEventArgsPool(numConnections); _maxNumberAcceptedClientsSemaphore = new Semaphore(numConnections, numConnections); _protocolType = protocolType; Init(); Start(localEndPoint); } protected override void Dispose(bool disposing) { _log.WriteLine(this.GetHashCode() + " Dispose (_numConnectedSockets={0})", _numConnectedSockets); if (disposing && (_listenSocket != null)) { lock (_listenSocketLock) { if (_listenSocket != null) { _listenSocket.Dispose(); _listenSocket = null; } } } } // Initializes the server by preallocating reusable buffers and // context objects. These objects do not need to be preallocated // or reused, but it is done this way to illustrate how the API can // easily be used to create reusable objects to increase server performance. // private void Init() { // Allocates one large byte buffer which all I/O operations use a piece of. This guards // against memory fragmentation. _bufferManager.InitBuffer(); // Pre-allocate pool of SocketAsyncEventArgs objects. SocketAsyncEventArgs readWriteEventArg; for (int i = 0; i < _maxNumConnections; i++) { // Pre-allocate a set of reusable SocketAsyncEventArgs. readWriteEventArg = new SocketAsyncEventArgs(); readWriteEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(IO_Completed); readWriteEventArg.UserToken = new AsyncUserToken(); // Assign a byte buffer from the buffer pool to the SocketAsyncEventArg object. _bufferManager.SetBuffer(readWriteEventArg); // Add SocketAsyncEventArg to the pool. _readWritePool.Push(readWriteEventArg); } } // Starts the server such that it is listening for // incoming connection requests. // // <param name="localEndPoint">The endpoint which the server will listen // for connection requests on</param> private void Start(EndPoint localEndPoint) { // Create the socket which listens for incoming connections. _listenSocket = new Socket(localEndPoint.AddressFamily, SocketType.Stream, _protocolType); _listenSocket.Bind(localEndPoint); // Start the server with a listen backlog of 100 connections. _listenSocket.Listen(100); // Post accepts on the listening socket. StartAccept(null); } // Begins an operation to accept a connection request from the client // // <param name="acceptEventArg">The context object to use when issuing // the accept operation on the server's listening socket</param> private void StartAccept(SocketAsyncEventArgs acceptEventArg) { if (acceptEventArg == null) { acceptEventArg = new SocketAsyncEventArgs(); acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(AcceptEventArg_Completed); } else { // Socket must be cleared since the context object is being reused. acceptEventArg.AcceptSocket = null; } _log.WriteLine(this.GetHashCode() + " StartAccept(_numConnectedSockets={0})", _numConnectedSockets); Assert.True(_maxNumberAcceptedClientsSemaphore.WaitOne(Configuration.PassingTestTimeout), "Timeout waiting for client connection."); if (_listenSocket == null) { return; } bool willRaiseEvent = false; lock (_listenSocketLock) { if (_listenSocket != null) { willRaiseEvent = _listenSocket.AcceptAsync(acceptEventArg); } else { return; } } if (!willRaiseEvent) { ProcessAccept(acceptEventArg); } } // This method is the callback method associated with Socket.AcceptAsync // operations and is invoked when an accept operation is complete. private void AcceptEventArg_Completed(object sender, SocketAsyncEventArgs e) { ProcessAccept(e); } private void ProcessAccept(SocketAsyncEventArgs e) { if (e.SocketError != SocketError.Success) { _log.WriteLine(this.GetHashCode() + " ProcessAccept(_numConnectedSockets={0}): {1}", _numConnectedSockets, e.SocketError); // If possible, retry the accept after a short wait. if (e.SocketError == SocketError.OperationAborted || e.SocketError == SocketError.Interrupted) { return; } if (Interlocked.Decrement(ref _acceptRetryCount) <= 0) { Assert.True(false, "accept retry limit exceeded."); return; } Task.Delay(500).Wait(); } else { Interlocked.Increment(ref _numConnectedSockets); _log.WriteLine(this.GetHashCode() + " ProcessAccept(_numConnectedSockets={0})", _numConnectedSockets); // Get the socket for the accepted client connection and put it into the ReadEventArg object user token. SocketAsyncEventArgs readEventArgs = _readWritePool.Pop(); ((AsyncUserToken)readEventArgs.UserToken).Socket = e.AcceptSocket; // As soon as the client is connected, post a receive to the connection. bool willRaiseEvent = e.AcceptSocket.ReceiveAsync(readEventArgs); if (!willRaiseEvent) { _log.WriteLine(this.GetHashCode() + " ProcessAccept -> ProcessReceive"); ProcessReceive(readEventArgs); } } // Accept the next connection request. StartAccept(e); } // This method is called whenever a receive or send operation is completed on a socket. // // <param name="e">SocketAsyncEventArg associated with the completed receive operation</param> private void IO_Completed(object sender, SocketAsyncEventArgs e) { // determine which type of operation just completed and call the associated handler switch (e.LastOperation) { case SocketAsyncOperation.Receive: ProcessReceive(e); break; case SocketAsyncOperation.Send: ProcessSend(e); break; default: throw new ArgumentException("The last operation completed on the socket was not a receive or send"); } } // This method is invoked when an asynchronous receive operation completes. // If the remote host closed the connection, then the socket is closed. // If data was received then the data is echoed back to the client. private void ProcessReceive(SocketAsyncEventArgs e) { _log.WriteLine( this.GetHashCode() + " ProcessReceive(bytesTransferred={0}, SocketError={1}, _numConnectedSockets={2})", e.BytesTransferred, e.SocketError, _numConnectedSockets); // Check if the remote host closed the connection. AsyncUserToken token = (AsyncUserToken)e.UserToken; if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success) { // Increment the count of the total bytes receive by the server. Interlocked.Add(ref _totalBytesRead, e.BytesTransferred); _log.WriteLine(this.GetHashCode() + " The server has read a total of {0} bytes", _totalBytesRead); // Echo the data received back to the client. e.SetBuffer(e.Offset, e.BytesTransferred); bool willRaiseEvent = token.Socket.SendAsync(e); if (!willRaiseEvent) { ProcessSend(e); } } else { CloseClientSocket(e); } } // This method is invoked when an asynchronous send operation completes. // The method issues another receive on the socket to read any additional // data sent from the client. // // <param name="e"></param> private void ProcessSend(SocketAsyncEventArgs e) { _log.WriteLine( this.GetHashCode() + " ProcessSend(SocketError={0}, _numConnectedSockets={1})", e.SocketError, _numConnectedSockets); if (e.SocketError == SocketError.Success) { // Done echoing data back to the client. AsyncUserToken token = (AsyncUserToken)e.UserToken; // Read the next block of data send from the client. bool willRaiseEvent = token.Socket.ReceiveAsync(e); if (!willRaiseEvent) { _log.WriteLine(this.GetHashCode() + " ProcessSend -> ProcessReceive"); ProcessReceive(e); } } else { _log.WriteLine(this.GetHashCode() + " ProcessSend -> CloseClientSocket"); CloseClientSocket(e); } } private void CloseClientSocket(SocketAsyncEventArgs e) { AsyncUserToken token = e.UserToken as AsyncUserToken; _log.WriteLine( this.GetHashCode() + " CloseClientSocket(_numConnectedSockets={0}, SocketError={1})", _numConnectedSockets, e.SocketError); // Close the socket associated with the client. try { token.Socket.Shutdown(SocketShutdown.Send); } catch (Exception ex) { // Throws if client process has already closed. _log.WriteLine( this.GetHashCode() + " CloseClientSocket Exception:{0}", ex); } token.Socket.Dispose(); // Decrement the counter keeping track of the total number of clients connected to the server. Interlocked.Decrement(ref _numConnectedSockets); _maxNumberAcceptedClientsSemaphore.Release(); _log.WriteLine( this.GetHashCode() + " CloseClientSocket(_numConnectedSockets={0})", _numConnectedSockets); // Free the SocketAsyncEventArg so they can be reused by another client. _readWritePool.Push(e); } } internal class AsyncUserToken { public Socket Socket { get; set; } } // Represents a collection of reusable SocketAsyncEventArgs objects. internal class SocketAsyncEventArgsPool { private Stack<SocketAsyncEventArgs> _pool; // Initializes the object pool to the specified size. // // The "capacity" parameter is the maximum number of // SocketAsyncEventArgs objects the pool can hold. public SocketAsyncEventArgsPool(int capacity) { _pool = new Stack<SocketAsyncEventArgs>(capacity); } // Add a SocketAsyncEventArg instance to the pool. // // The "item" parameter is the SocketAsyncEventArgs instance // to add to the pool. public void Push(SocketAsyncEventArgs item) { if (item == null) { throw new ArgumentNullException("Items added to a SocketAsyncEventArgsPool cannot be null"); } lock (_pool) { _pool.Push(item); } } // Removes a SocketAsyncEventArgs instance from the pool // and returns the object removed from the pool. public SocketAsyncEventArgs Pop() { lock (_pool) { return _pool.Pop(); } } // The number of SocketAsyncEventArgs instances in the pool. public int Count { get { return _pool.Count; } } } // This class creates a single large buffer which can be divided up // and assigned to SocketAsyncEventArgs objects for use with each // socket I/O operation. // // This enables buffers to be easily reused and guards against // fragmenting heap memory. // // The operations exposed on the BufferManager class are not thread safe. internal class BufferManager { private readonly int _numBytes; // The total number of bytes controlled by the buffer pool. private readonly Stack<int> _freeIndexPool; private readonly int _bufferSize; private byte[] _buffer; // The underlying byte array maintained by the Buffer Manager. private int _currentIndex; public BufferManager(int totalBytes, int bufferSize) { _numBytes = totalBytes; _currentIndex = 0; _bufferSize = bufferSize; _freeIndexPool = new Stack<int>(); } // Allocates buffer space used by the buffer pool. public void InitBuffer() { // Create one big large buffer and divide that // out to each SocketAsyncEventArg object. _buffer = new byte[_numBytes]; } // Assigns a buffer from the buffer pool to the // specified SocketAsyncEventArgs object. // // <returns>true if the buffer was successfully set, else false</returns> public bool SetBuffer(SocketAsyncEventArgs args) { if (_freeIndexPool.Count > 0) { args.SetBuffer(_buffer, _freeIndexPool.Pop(), _bufferSize); } else { if ((_numBytes - _bufferSize) < _currentIndex) { return false; } args.SetBuffer(_buffer, _currentIndex, _bufferSize); _currentIndex += _bufferSize; } return true; } // Removes the buffer from a SocketAsyncEventArg object. // This frees the buffer back to the buffer pool. public void FreeBuffer(SocketAsyncEventArgs args) { _freeIndexPool.Push(args.Offset); args.SetBuffer(null, 0, 0); } } }
using System; using System.Collections.Generic; using System.Linq; using Machine.Fakes.Internal; namespace Machine.Fakes.Sdk { /// <summary> /// Shortcut for <see cref="SpecificationController{TSubject}"/> which /// supplies the type of the fake engine to be used via a generic type parameter. /// </summary> /// <typeparam name="TSubject"> /// The subject for the specification. This is the type that is created by the /// specification for you. /// </typeparam> /// <typeparam name="TFakeEngine"> /// Specifies the type of the fake engine which will be used. /// </typeparam> public class SpecificationController<TSubject, TFakeEngine> : SpecificationController<TSubject> where TSubject : class where TFakeEngine : IFakeEngine, new() { /// <summary> /// Creates a new instance of the <see cref="SpecificationController{TSubject, TFakeEngine}"/> class. /// </summary> public SpecificationController() : base(new TFakeEngine()) { } } /// <summary> /// Controller that implements all the core capabilities of Machine.Fakes. /// This includes filling a subject with fakes and providing all the handy helper methods /// for interacting with fakes in a specification. /// </summary> /// <typeparam name="TSubject"> /// The subject for the specification. This is the type that is created by the /// specification for you. /// </typeparam> public class SpecificationController<TSubject> : IFakeAccessor, IDisposable where TSubject : class { private readonly BehaviorConfigController _behaviorConfigController = new BehaviorConfigController(); private readonly AutoFakeContainer _container; private TSubject _specificationSubject; /// <summary> /// Creates a new instance of the <see cref="SpecificationController{TSubject}"/> class. /// </summary> /// <param name="fakeEngine"> /// Specifies the <see cref="IFakeEngine"/> that is used for creating specifications. /// </param> public SpecificationController(IFakeEngine fakeEngine) { Guard.AgainstArgumentNull(fakeEngine, "fakeEngine"); _container = new AutoFakeContainer(fakeEngine); FakeEngineGateway.EngineIs(fakeEngine); } /// <summary> /// Gives access to the subject under specification. On first access /// the spec tries to create an instance of the subject type by itself. /// Override this behavior by manually setting a subject instance. /// </summary> public TSubject Subject { get { return _specificationSubject ?? (_specificationSubject = _container.CreateSubject<TSubject>()); } set { _specificationSubject = value; } } /// <summary> /// Applies the configuration embedded in the registar to the underlying container. /// </summary> /// <param name="registrar"> /// Specifies the registrar. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when the supplied registrar is <c>null</c>. /// </exception> public void Configure(Registrar registrar) { Guard.AgainstArgumentNull(registrar, "registar"); registrar.Apply(_container.Register); } /// <summary> /// Configures the specification to execute a behavior config before the action on the subject /// is executed (<see cref="Because"/>). /// </summary> /// <typeparam name="TBehaviorConfig">Specifies the type of the config to be executed.</typeparam> /// <returns>The behavior config instance.</returns> /// <remarks> /// The class specified by <typeparamref name="TBehaviorConfig"/> /// needs to have private fields assigned with either <see cref="OnEstablish"/> /// or <see cref="OnCleanup"/> delegates. /// </remarks> public TBehaviorConfig With<TBehaviorConfig>() where TBehaviorConfig : new () { var behaviorConfig = new TBehaviorConfig(); With(behaviorConfig); return behaviorConfig; } /// <summary> /// Configures the specification to execute the behavior config specified /// by <paramref name = "behaviorConfig" /> before the action on the sut is executed (<see cref = "Because" />). /// </summary> /// <param name = "behaviorConfig"> /// Specifies the behavior config to be executed. /// </param> /// <remarks> /// The object specified by <see paramref="behaviorConfig"/> /// needs to have private fields assigned with either <see cref="OnEstablish"/> /// or <see cref="OnCleanup"/> delegates. /// </remarks> public void With(object behaviorConfig) { _behaviorConfigController.Establish(behaviorConfig, this); } /// <summary> /// Creates a fake of the type specified by <typeparamref name = "TInterfaceType" /> without a default constructor. /// </summary> /// <typeparam name = "TInterfaceType">The type to create a fake for.</typeparam> /// <param name="args"> /// No default constructor arguments /// </param> /// <returns> /// An newly created fake implementing <typeparamref name = "TInterfaceType" />. /// </returns> public TInterfaceType An<TInterfaceType>(params object[] args) where TInterfaceType : class { return (TInterfaceType)An(typeof(TInterfaceType), args); } /// <summary> /// Creates a fake of the type specified by <paramref name="interfaceType"/> without default constructor. /// </summary> /// The type to create a fake for. /// <param name="interfaceType"> /// Specifies the type of item to fake. /// </param> /// <param name="args"> /// Specifies the constructor parameters if the class is a concrete class without default constructor /// </param> /// <returns> /// An newly created fake implementing <paramref name="interfaceType"/>. /// </returns> public object An(Type interfaceType, params object[] args) { return _container.CreateFake(interfaceType, args); } /// <summary> /// Creates a fake of the type specified by <typeparamref name = "TInterfaceType" />. /// This method reuses existing instances. If an instance of <typeparamref name = "TInterfaceType" /> /// was already requested it's returned here. (You can say this is kind of a singleton behavior) /// Besides that, you can obtain a reference to automatically injected fakes with this /// method. /// </summary> /// <typeparam name = "TInterfaceType">The type to create a fake for. (Should be an interface or an abstract class)</typeparam> /// <returns> /// An instance implementing <typeparamref name="TInterfaceType" />. /// </returns> public TInterfaceType The<TInterfaceType>() where TInterfaceType : class { return _container.Get<TInterfaceType>(); } /// <summary> /// Creates a list containing 3 fake instances of the type specified /// via <typeparamref name = "TInterfaceType" />. /// </summary> /// <typeparam name = "TInterfaceType">Specifies the item type of the list. This should be an interface or an abstract class.</typeparam> /// <returns>An <see cref = "IList{T}" />.</returns> public IList<TInterfaceType> Some<TInterfaceType>() where TInterfaceType : class { return Some<TInterfaceType>(3); } /// <summary> /// Creates a list of fakes. /// </summary> /// <typeparam name="TInterfaceType"> /// Specifies the item type of the list. This should be an interface or an abstract class. /// </typeparam> /// <param name="amount"> /// Specifies the amount of fakes that have to be created and inserted into the list. /// </param> /// <returns> /// An <see cref="IList{TInterfaceType}"/>. /// </returns> public IList<TInterfaceType> Some<TInterfaceType>(int amount) where TInterfaceType : class { if (amount < 0) throw new ArgumentOutOfRangeException("amount"); return Enumerable.Range(0, amount) .Select(x => (TInterfaceType)_container.CreateFake(typeof(TInterfaceType))) .ToList(); } /// <summary> /// Performs cleanup. Exuecutes the Cleanup functionality of all configured behavior configs. /// </summary> public void Dispose() { _behaviorConfigController.CleanUp(Subject); } /// <summary> /// Ensures that the subject has been created. This will trigger the lazy loading in case creation hasn't happened /// before. /// </summary> public void EnsureSubjectCreated() { // ReSharper disable ReturnValueOfPureMethodIsNotUsed Subject.ToString(); // ReSharper restore ReturnValueOfPureMethodIsNotUsed } } }
#region License /* The MIT License Copyright (c) 2008 Sky Morey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using System.Collections.Generic; using System.Text; using System.Globalization; namespace System.Web.UI { /// <summary> /// ClientScript /// </summary> public static class ClientScript { /// <summary> /// EmptyFunction /// </summary> public static string EmptyFunction = "function(){}"; /// <summary> /// EmptyObject /// </summary> public static string EmptyObject = "{}"; /// <summary> /// EmptyArray /// </summary> public static string EmptyArray = "[]"; #region Encode /// <summary> /// Encodes the array. /// </summary> /// <param name="array">The array.</param> /// <returns></returns> public static string EncodeArray(string[] array) { return (array != null ? "[" + string.Join(",", array) + "]" : "null"); } /// <summary> /// Encodes the bool. /// </summary> /// <param name="value">if set to <c>true</c> [value].</param> /// <returns></returns> public static string EncodeBool(bool value) { return (value ? "true" : "false"); } /// <summary> /// Encodes the date time. /// </summary> /// <param name="value">The value.</param> /// <returns></returns> public static string EncodeDateTime(DateTime value) { return value.ToString(); } /// <summary> /// Encodes the decimal. /// </summary> /// <param name="value">The value.</param> /// <returns></returns> public static string EncodeDecimal(decimal value) { return value.ToString(); } /// <summary> /// Encodes the expression. /// </summary> /// <param name="value">The value.</param> /// <returns></returns> public static string EncodeExpression(string value) { return value; } /// <summary> /// Encodes the function. /// </summary> /// <param name="value">The value.</param> /// <returns></returns> public static string EncodeFunction(string value) { return value; } /// <summary> /// Encodes the dictionary. /// </summary> /// <param name="value">The value.</param> /// <returns></returns> public static string EncodeDictionary(IDictionary<string, string> value) { return EncodeDictionary(value, false); } public static string EncodeDictionary(IDictionary<string, string> value, bool includeNewLine) { if (value == null) return "null"; if (value.Count == 0) return "{}"; var b = new StringBuilder("{"); if (includeNewLine) { foreach (string key in value.Keys) b.AppendLine(key + ": " + value[key] + ","); b.Length -= 3; } else { foreach (string key in value.Keys) b.Append(key + ": " + value[key] + ", "); b.Length -= 2; } b.Append("}"); return b.ToString(); } public static string EncodeDictionary(IDictionary<string, object> value) { return EncodeDictionary(value, false); } public static string EncodeDictionary(IDictionary<string, object> value, bool includeNewLine) { if (value == null) return "null"; if (value.Count == 0) return "{}"; var b = new StringBuilder("{"); if (includeNewLine) { foreach (string key in value.Keys) b.AppendLine(key + ": " + value[key] + ", "); b.Length -= 4; } else { foreach (string key in value.Keys) b.Append(key + ": " + value[key] + ", "); b.Length -= 2; } b.Append("}"); return b.ToString(); } /// <summary> /// Encodes the int32. /// </summary> /// <param name="value">The value.</param> /// <returns></returns> public static string EncodeInt32(int value) { return value.ToString(); } /// <summary> /// Encodes the reg exp. /// </summary> /// <param name="value">The value.</param> /// <returns></returns> public static string EncodeRegExp(string value) { if (string.IsNullOrEmpty(value)) throw new ArgumentNullException("value"); return value; } /// <summary> /// Encodes the text. /// </summary> /// <param name="value">The value.</param> /// <returns></returns> public static string EncodeText(string value) { if (value == null) return "null"; else if (value.Length == 0) return "''"; else { var b = new StringBuilder("'", value.Length); InternalEscapeText(InternalEscapeTextType.Text, b, value); b.Append("'"); return b.ToString(); } } /// <summary> /// Encodes the partial text. /// </summary> /// <param name="value">The value.</param> /// <returns></returns> public static string EncodePartialText(string value) { if (string.IsNullOrEmpty(value)) return string.Empty; var b = new StringBuilder(value.Length); InternalEscapeText(InternalEscapeTextType.Text, b, value); return b.ToString(); } /// <summary> /// InternalEscapeTextType /// </summary> private enum InternalEscapeTextType { Text, } private static void InternalEscapeText(InternalEscapeTextType textType, StringBuilder b, string value) { foreach (char c in value) { int code = (int)c; switch (c) { case '\b': b.Append("\\right"); break; case '\f': b.Append("\\f"); break; case '\n': b.Append("\\n"); break; case '\r': b.Append("\\r"); break; case '\t': b.Append("\\t"); break; case '\\': case '\'': b.Append("\\" + c); break; default: if ((code >= 32) && (code < 128)) b.Append(c); else b.AppendFormat(CultureInfo.InvariantCulture.NumberFormat, "\\u{0:X4}", code); break; } } } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Security; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp.Presentation; using Microsoft.CodeAnalysis.Editor.UnitTests.Classification; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp { public abstract class AbstractSignatureHelpProviderTests<TWorkspaceFixture> : TestBase, IClassFixture<TWorkspaceFixture> where TWorkspaceFixture : TestWorkspaceFixture, new() { protected TWorkspaceFixture workspaceFixture; internal abstract ISignatureHelpProvider CreateSignatureHelpProvider(); protected AbstractSignatureHelpProviderTests(TWorkspaceFixture workspaceFixture) { this.workspaceFixture = workspaceFixture; } public override void Dispose() { this.workspaceFixture.CloseTextView(); base.Dispose(); } /// <summary> /// Verifies that sighelp comes up at the indicated location in markup ($$), with the indicated span [| ... |]. /// </summary> /// <param name="markup">Input markup with $$ denoting the cursor position, and [| ... |] /// denoting the expected sighelp span</param> /// <param name="expectedOrderedItemsOrNull">The exact expected sighelp items list. If null, this part of the test is ignored.</param> /// <param name="usePreviousCharAsTrigger">If true, uses the last character before $$ to trigger sighelp. /// If false, invokes sighelp explicitly at the cursor location.</param> /// <param name="sourceCodeKind">The sourcecodekind to run this test on. If null, runs on both regular and script sources.</param> protected virtual void Test( string markup, IEnumerable<SignatureHelpTestItem> expectedOrderedItemsOrNull = null, bool usePreviousCharAsTrigger = false, SourceCodeKind? sourceCodeKind = null, bool experimental = false) { if (sourceCodeKind.HasValue) { TestSignatureHelpWorker(markup, sourceCodeKind.Value, experimental, expectedOrderedItemsOrNull, usePreviousCharAsTrigger); } else { TestSignatureHelpWorker(markup, SourceCodeKind.Regular, experimental, expectedOrderedItemsOrNull, usePreviousCharAsTrigger); TestSignatureHelpWorker(markup, SourceCodeKind.Script, experimental, expectedOrderedItemsOrNull, usePreviousCharAsTrigger); } } private void TestSignatureHelpWorker( string markupWithPositionAndOptSpan, SourceCodeKind sourceCodeKind, bool experimental, IEnumerable<SignatureHelpTestItem> expectedOrderedItemsOrNull = null, bool usePreviousCharAsTrigger = false) { markupWithPositionAndOptSpan = markupWithPositionAndOptSpan.NormalizeLineEndings(); string code; int cursorPosition; IList<TextSpan> textSpans; TextSpan? textSpan = null; MarkupTestFile.GetPositionAndSpans( markupWithPositionAndOptSpan, out code, out cursorPosition, out textSpans); if (textSpans.Any()) { textSpan = textSpans.First(); } var parseOptions = CreateExperimentalParseOptions(); // regular var document1 = workspaceFixture.UpdateDocument(code, sourceCodeKind); if (experimental) { document1 = document1.Project.WithParseOptions(parseOptions).GetDocument(document1.Id); } TestSignatureHelpWorkerShared(code, cursorPosition, sourceCodeKind, document1, textSpan, expectedOrderedItemsOrNull, usePreviousCharAsTrigger); // speculative semantic model if (CanUseSpeculativeSemanticModel(document1, cursorPosition)) { var document2 = workspaceFixture.UpdateDocument(code, sourceCodeKind, cleanBeforeUpdate: false); if (experimental) { document2 = document2.Project.WithParseOptions(parseOptions).GetDocument(document2.Id); } TestSignatureHelpWorkerShared(code, cursorPosition, sourceCodeKind, document2, textSpan, expectedOrderedItemsOrNull, usePreviousCharAsTrigger); } } protected abstract ParseOptions CreateExperimentalParseOptions(); private static bool CanUseSpeculativeSemanticModel(Document document, int position) { var service = document.Project.LanguageServices.GetService<ISyntaxFactsService>(); var node = document.GetSyntaxRootAsync().Result.FindToken(position).Parent; return !service.GetMemberBodySpanForSpeculativeBinding(node).IsEmpty; } protected virtual void VerifyTriggerCharacters(char[] expectedTriggerCharacters, char[] unexpectedTriggerCharacters, SourceCodeKind? sourceCodeKind = null) { if (sourceCodeKind.HasValue) { VerifyTriggerCharactersWorker(expectedTriggerCharacters, unexpectedTriggerCharacters, sourceCodeKind.Value); } else { VerifyTriggerCharactersWorker(expectedTriggerCharacters, unexpectedTriggerCharacters, SourceCodeKind.Regular); VerifyTriggerCharactersWorker(expectedTriggerCharacters, unexpectedTriggerCharacters, SourceCodeKind.Script); } } private void VerifyTriggerCharactersWorker(char[] expectedTriggerCharacters, char[] unexpectedTriggerCharacters, SourceCodeKind sourceCodeKind) { ISignatureHelpProvider signatureHelpProvider = CreateSignatureHelpProvider(); foreach (var expectedTriggerCharacter in expectedTriggerCharacters) { Assert.True(signatureHelpProvider.IsTriggerCharacter(expectedTriggerCharacter), "Expected '" + expectedTriggerCharacter + "' to be a trigger character"); } foreach (var unexpectedTriggerCharacter in unexpectedTriggerCharacters) { Assert.False(signatureHelpProvider.IsTriggerCharacter(unexpectedTriggerCharacter), "Expected '" + unexpectedTriggerCharacter + "' to NOT be a trigger character"); } } protected virtual void VerifyCurrentParameterName(string markup, string expectedParameterName, SourceCodeKind? sourceCodeKind = null) { if (sourceCodeKind.HasValue) { VerifyCurrentParameterNameWorker(markup, expectedParameterName, sourceCodeKind.Value); } else { VerifyCurrentParameterNameWorker(markup, expectedParameterName, SourceCodeKind.Regular); VerifyCurrentParameterNameWorker(markup, expectedParameterName, SourceCodeKind.Script); } } private static SignatureHelpState GetArgumentState(int cursorPosition, Document document, ISignatureHelpProvider signatureHelpProvider, SignatureHelpTriggerInfo triggerInfo) { var items = signatureHelpProvider.GetItemsAsync(document, cursorPosition, triggerInfo, CancellationToken.None).WaitAndGetResult(CancellationToken.None); return items == null ? null : new SignatureHelpState(items.ArgumentIndex, items.ArgumentCount, items.ArgumentName, null); } private void VerifyCurrentParameterNameWorker(string markup, string expectedParameterName, SourceCodeKind sourceCodeKind) { string code; int cursorPosition; MarkupTestFile.GetPosition(markup.NormalizeLineEndings(), out code, out cursorPosition); var document = workspaceFixture.UpdateDocument(code, sourceCodeKind); var signatureHelpProvider = CreateSignatureHelpProvider(); var triggerInfo = new SignatureHelpTriggerInfo(SignatureHelpTriggerReason.InvokeSignatureHelpCommand); var items = signatureHelpProvider.GetItemsAsync(document, cursorPosition, triggerInfo, CancellationToken.None).Result; Assert.Equal(expectedParameterName, GetArgumentState(cursorPosition, document, signatureHelpProvider, triggerInfo).ArgumentName); } private void CompareAndAssertCollectionsAndCurrentParameter( IEnumerable<SignatureHelpTestItem> expectedTestItems, SignatureHelpItems actualSignatureHelpItems, ISignatureHelpProvider signatureHelpProvider, Document document, int cursorPosition) { Assert.Equal(expectedTestItems.Count(), actualSignatureHelpItems.Items.Count()); for (int i = 0; i < expectedTestItems.Count(); i++) { CompareSigHelpItemsAndCurrentPosition( actualSignatureHelpItems, actualSignatureHelpItems.Items.ElementAt(i), expectedTestItems.ElementAt(i), signatureHelpProvider, document, cursorPosition, actualSignatureHelpItems.ApplicableSpan); } } private void CompareSigHelpItemsAndCurrentPosition( SignatureHelpItems items, SignatureHelpItem actualSignatureHelpItem, SignatureHelpTestItem expectedTestItem, ISignatureHelpProvider signatureHelpProvider, Document document, int cursorPosition, TextSpan applicableSpan) { int currentParameterIndex = -1; if (expectedTestItem.CurrentParameterIndex != null) { if (expectedTestItem.CurrentParameterIndex.Value >= 0 && expectedTestItem.CurrentParameterIndex.Value < actualSignatureHelpItem.Parameters.Length) { currentParameterIndex = expectedTestItem.CurrentParameterIndex.Value; } } var signature = new Signature(applicableToSpan: null, signatureHelpItem: actualSignatureHelpItem, selectedParameterIndex: currentParameterIndex); // We're a match if the signature matches... // We're now combining the signature and documentation to make classification work. if (!string.IsNullOrEmpty(expectedTestItem.MethodDocumentation)) { Assert.Equal(expectedTestItem.Signature + "\r\n" + expectedTestItem.MethodDocumentation, signature.Content); } else { Assert.Equal(expectedTestItem.Signature, signature.Content); } if (expectedTestItem.PrettyPrintedSignature != null) { Assert.Equal(expectedTestItem.PrettyPrintedSignature, signature.PrettyPrintedContent); } if (expectedTestItem.MethodDocumentation != null) { Assert.Equal(expectedTestItem.MethodDocumentation, actualSignatureHelpItem.DocumentationFactory(CancellationToken.None).GetFullText()); } if (expectedTestItem.ParameterDocumentation != null) { Assert.Equal(expectedTestItem.ParameterDocumentation, signature.CurrentParameter.Documentation); } if (expectedTestItem.CurrentParameterIndex != null) { Assert.Equal(expectedTestItem.CurrentParameterIndex, items.ArgumentIndex); } if (expectedTestItem.Description != null) { Assert.Equal(expectedTestItem.Description, ToString(actualSignatureHelpItem.DescriptionParts)); } } private string ToString(IEnumerable<SymbolDisplayPart> list) { return string.Concat(list.Select(i => i.ToString())); } protected void TestSignatureHelpInEditorBrowsableContexts( string markup, string referencedCode, IEnumerable<SignatureHelpTestItem> expectedOrderedItemsMetadataReference, IEnumerable<SignatureHelpTestItem> expectedOrderedItemsSameSolution, string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers = false) { if (expectedOrderedItemsMetadataReference == null || expectedOrderedItemsSameSolution == null) { AssertEx.Fail("Expected signature help items must be provided for EditorBrowsable tests. If there are no expected items, provide an empty IEnumerable rather than null."); } TestSignatureHelpWithMetadataReferenceHelper(markup, referencedCode, expectedOrderedItemsMetadataReference, sourceLanguage, referencedLanguage, hideAdvancedMembers); TestSignatureHelpWithProjectReferenceHelper(markup, referencedCode, expectedOrderedItemsSameSolution, sourceLanguage, referencedLanguage, hideAdvancedMembers); // Multi-language projects are not supported. if (sourceLanguage == referencedLanguage) { TestSignatureHelpInSameProjectHelper(markup, referencedCode, expectedOrderedItemsSameSolution, sourceLanguage, hideAdvancedMembers); } } public void TestSignatureHelpWithMetadataReferenceHelper(string sourceCode, string referencedCode, IEnumerable<SignatureHelpTestItem> expectedOrderedItems, string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document FilePath=""SourceDocument""> {1} </Document> <MetadataReferenceFromSource Language=""{2}"" CommonReferences=""true""> <Document FilePath=""ReferencedDocument""> {3} </Document> </MetadataReferenceFromSource> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode), referencedLanguage, SecurityElement.Escape(referencedCode)); VerifyItemWithReferenceWorker(xmlString, expectedOrderedItems, hideAdvancedMembers); } public void TestSignatureHelpWithProjectReferenceHelper(string sourceCode, string referencedCode, IEnumerable<SignatureHelpTestItem> expectedOrderedItems, string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <ProjectReference>ReferencedProject</ProjectReference> <Document FilePath=""SourceDocument""> {1} </Document> </Project> <Project Language=""{2}"" CommonReferences=""true"" AssemblyName=""ReferencedProject""> <Document FilePath=""ReferencedDocument""> {3} </Document> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode), referencedLanguage, SecurityElement.Escape(referencedCode)); VerifyItemWithReferenceWorker(xmlString, expectedOrderedItems, hideAdvancedMembers); } private void TestSignatureHelpInSameProjectHelper(string sourceCode, string referencedCode, IEnumerable<SignatureHelpTestItem> expectedOrderedItems, string sourceLanguage, bool hideAdvancedMembers) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document FilePath=""SourceDocument""> {1} </Document> <Document FilePath=""ReferencedDocument""> {2} </Document> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode), SecurityElement.Escape(referencedCode)); VerifyItemWithReferenceWorker(xmlString, expectedOrderedItems, hideAdvancedMembers); } protected void VerifyItemWithReferenceWorker(string xmlString, IEnumerable<SignatureHelpTestItem> expectedOrderedItems, bool hideAdvancedMembers) { using (var testWorkspace = TestWorkspaceFactory.CreateWorkspace(xmlString)) { var optionsService = testWorkspace.Services.GetService<IOptionService>(); var cursorPosition = testWorkspace.Documents.First(d => d.Name == "SourceDocument").CursorPosition.Value; var documentId = testWorkspace.Documents.First(d => d.Name == "SourceDocument").Id; var document = testWorkspace.CurrentSolution.GetDocument(documentId); var code = document.GetTextAsync().Result.ToString(); optionsService.SetOptions(optionsService.GetOptions().WithChangedOption(Microsoft.CodeAnalysis.Completion.CompletionOptions.HideAdvancedMembers, document.Project.Language, hideAdvancedMembers)); IList<TextSpan> textSpans = null; var selectedSpans = testWorkspace.Documents.First(d => d.Name == "SourceDocument").SelectedSpans; if (selectedSpans.Any()) { textSpans = selectedSpans; } TextSpan? textSpan = null; if (textSpans != null && textSpans.Any()) { textSpan = textSpans.First(); } TestSignatureHelpWorkerShared(code, cursorPosition, SourceCodeKind.Regular, document, textSpan, expectedOrderedItems); } } private void TestSignatureHelpWorkerShared( string code, int cursorPosition, SourceCodeKind sourceCodeKind, Document document, TextSpan? textSpan, IEnumerable<SignatureHelpTestItem> expectedOrderedItemsOrNull = null, bool usePreviousCharAsTrigger = false) { var signatureHelpProvider = CreateSignatureHelpProvider(); var triggerInfo = new SignatureHelpTriggerInfo(SignatureHelpTriggerReason.InvokeSignatureHelpCommand); if (usePreviousCharAsTrigger) { triggerInfo = new SignatureHelpTriggerInfo( SignatureHelpTriggerReason.TypeCharCommand, code.ElementAt(cursorPosition - 1)); if (!signatureHelpProvider.IsTriggerCharacter(triggerInfo.TriggerCharacter.Value)) { return; } } var items = signatureHelpProvider.GetItemsAsync(document, cursorPosition, triggerInfo, CancellationToken.None).Result; // If we're expecting 0 items, then there's no need to compare them if ((expectedOrderedItemsOrNull == null || !expectedOrderedItemsOrNull.Any()) && items == null) { return; } AssertEx.NotNull(items, "Signature help provider returned null for items. Did you forget $$ in the test or is the test otherwise malformed, e.g. quotes not escaped?"); // Verify the span if (textSpan != null) { Assert.Equal(textSpan, items.ApplicableSpan); } if (expectedOrderedItemsOrNull != null) { CompareAndAssertCollectionsAndCurrentParameter(expectedOrderedItemsOrNull, items, signatureHelpProvider, document, cursorPosition); } } protected void TestSignatureHelpWithMscorlib45( string markup, IEnumerable<SignatureHelpTestItem> expectedOrderedItems, string sourceLanguage) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferencesNet45=""true""> <Document FilePath=""SourceDocument""> {1} </Document> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(markup)); using (var testWorkspace = TestWorkspaceFactory.CreateWorkspace(xmlString)) { var cursorPosition = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").CursorPosition.Value; var documentId = testWorkspace.Documents.Where(d => d.Name == "SourceDocument").Single().Id; var document = testWorkspace.CurrentSolution.GetDocument(documentId); var code = document.GetTextAsync().Result.ToString(); IList<TextSpan> textSpans = null; var selectedSpans = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").SelectedSpans; if (selectedSpans.Any()) { textSpans = selectedSpans; } TextSpan? textSpan = null; if (textSpans != null && textSpans.Any()) { textSpan = textSpans.First(); } TestSignatureHelpWorkerShared(code, cursorPosition, SourceCodeKind.Regular, document, textSpan, expectedOrderedItems); } } } }
// Copyright 2018 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 gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpcgcp = Google.Api.Gax.Grpc.Gcp; using gcbcv = Google.Cloud.Bigtable.Common.V2; using pb = Google.Protobuf; using pbwkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using sys = System; using sc = System.Collections; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using linq = System.Linq; using st = System.Threading; using stt = System.Threading.Tasks; using Google.Api.Gax; namespace Google.Cloud.Bigtable.V2 { /// <summary> /// Bigtable client wrapper, for convenient use. /// </summary> public partial class BigtableClient { /// <summary>Streams back the contents of all requested rows in key order, optionally applying the same Reader filter to each.</summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// If the <see cref="ReadRowsRequest.AppProfileId"/> has not been specified, it will be initialized from the value stored in the client. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The server stream. /// </returns> public virtual ReadRowsStream ReadRows( ReadRowsRequest request, gaxgrpc::CallSettings callSettings = null) { throw new sys::NotImplementedException(); } /// <summary> /// Returns a sample of row keys in the table. The returned row keys will /// delimit contiguous sections of the table of approximately equal size, /// which can be used to break up the data for distributed tasks like /// mapreduces. /// </summary> /// <param name="tableName"> /// The unique name of the table from which to sample row keys. /// Values are of the form /// `projects/&lt;project&gt;/instances/&lt;instance&gt;/tables/&lt;table&gt;`. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The server stream. /// </returns> public virtual BigtableServiceApiClient.SampleRowKeysStream SampleRowKeys( gcbcv::TableName tableName, gaxgrpc::CallSettings callSettings = null) => SampleRowKeys( new SampleRowKeysRequest { TableNameAsTableName = gax::GaxPreconditions.CheckNotNull(tableName, nameof(tableName)), }, callSettings); /// <summary> /// Returns a sample of row keys in the table. The returned row keys will /// delimit contiguous sections of the table of approximately equal size, /// which can be used to break up the data for distributed tasks like /// mapreduces. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// If the <see cref="SampleRowKeysRequest.AppProfileId"/> has not been specified, it will be initialized from the value stored in the client. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The server stream. /// </returns> public virtual BigtableServiceApiClient.SampleRowKeysStream SampleRowKeys( SampleRowKeysRequest request, gaxgrpc::CallSettings callSettings = null) { throw new sys::NotImplementedException(); } /// <summary> /// Mutates a row atomically. Cells already present in the row are left /// unchanged unless explicitly changed by `mutation`. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// If the <see cref="MutateRowRequest.AppProfileId"/> has not been specified, it will be initialized from the value stored in the client. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual stt::Task<MutateRowResponse> MutateRowAsync( MutateRowRequest request, gaxgrpc::CallSettings callSettings = null) { throw new sys::NotImplementedException(); } /// <summary> /// Mutates a row atomically. Cells already present in the row are left /// unchanged unless explicitly changed by `mutation`. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// If the <see cref="MutateRowRequest.AppProfileId"/> has not been specified, it will be initialized from the value stored in the client. /// </param> /// <param name="cancellationToken"> /// A <see cref="st::CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual stt::Task<MutateRowResponse> MutateRowAsync( MutateRowRequest request, st::CancellationToken cancellationToken) => MutateRowAsync( request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Mutates a row atomically. Cells already present in the row are left /// unchanged unless explicitly changed by `mutation`. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// If the <see cref="MutateRowRequest.AppProfileId"/> has not been specified, it will be initialized from the value stored in the client. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual MutateRowResponse MutateRow( MutateRowRequest request, gaxgrpc::CallSettings callSettings = null) { throw new sys::NotImplementedException(); } /// <summary> /// Mutates multiple rows in a batch. Each individual row is mutated /// atomically as in MutateRow, but the entire batch is not executed /// atomically. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// If the <see cref="MutateRowsRequest.AppProfileId"/> has not been specified, it will be initialized from the value stored in the client. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns>The RPC response.</returns> public virtual MutateRowsResponse MutateRows( MutateRowsRequest request, gaxgrpc::CallSettings callSettings = null) { throw new sys::NotImplementedException(); } /// <summary> /// Mutates multiple rows in a batch. Each individual row is mutated /// atomically as in MutateRow, but the entire batch is not executed /// atomically. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// If the <see cref="MutateRowsRequest.AppProfileId"/> has not been specified, it will be initialized from the value stored in the client. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns>The RPC response.</returns> public virtual stt::Task<MutateRowsResponse> MutateRowsAsync( MutateRowsRequest request, gaxgrpc::CallSettings callSettings = null) { throw new sys::NotImplementedException(); } /// <summary> /// Mutates multiple rows in a batch. Each individual row is mutated /// atomically as in MutateRow, but the entire batch is not executed /// atomically. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// If the <see cref="MutateRowsRequest.AppProfileId"/> has not been specified, it will be initialized from the value stored in the client. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>The RPC response.</returns> public virtual stt::Task<MutateRowsResponse> MutateRowsAsync( MutateRowsRequest request, st::CancellationToken cancellationToken) => MutateRowsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Mutates a row atomically based on the output of a predicate Reader filter. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// If the <see cref="CheckAndMutateRowRequest.AppProfileId"/> has not been specified, it will be initialized from the value stored in the client. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual stt::Task<CheckAndMutateRowResponse> CheckAndMutateRowAsync( CheckAndMutateRowRequest request, gaxgrpc::CallSettings callSettings = null) { throw new sys::NotImplementedException(); } /// <summary> /// Mutates a row atomically based on the output of a predicate Reader filter. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// If the <see cref="CheckAndMutateRowRequest.AppProfileId"/> has not been specified, it will be initialized from the value stored in the client. /// </param> /// <param name="cancellationToken"> /// A <see cref="st::CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual stt::Task<CheckAndMutateRowResponse> CheckAndMutateRowAsync( CheckAndMutateRowRequest request, st::CancellationToken cancellationToken) => CheckAndMutateRowAsync( request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Mutates a row atomically based on the output of a predicate Reader filter. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// If the <see cref="CheckAndMutateRowRequest.AppProfileId"/> has not been specified, it will be initialized from the value stored in the client. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual CheckAndMutateRowResponse CheckAndMutateRow( CheckAndMutateRowRequest request, gaxgrpc::CallSettings callSettings = null) { throw new sys::NotImplementedException(); } /// <summary> /// Modifies a row atomically on the server. The method reads the latest /// existing timestamp and value from the specified columns and writes a new /// entry based on pre-defined read/modify/write rules. The new value for the /// timestamp is the greater of the existing timestamp or the current server /// time. The method returns the new contents of all modified cells. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// If the <see cref="ReadModifyWriteRowRequest.AppProfileId"/> has not been specified, it will be initialized from the value stored in the client. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual stt::Task<ReadModifyWriteRowResponse> ReadModifyWriteRowAsync( ReadModifyWriteRowRequest request, gaxgrpc::CallSettings callSettings = null) { throw new sys::NotImplementedException(); } /// <summary> /// Modifies a row atomically on the server. The method reads the latest /// existing timestamp and value from the specified columns and writes a new /// entry based on pre-defined read/modify/write rules. The new value for the /// timestamp is the greater of the existing timestamp or the current server /// time. The method returns the new contents of all modified cells. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// If the <see cref="ReadModifyWriteRowRequest.AppProfileId"/> has not been specified, it will be initialized from the value stored in the client. /// </param> /// <param name="cancellationToken"> /// A <see cref="st::CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual stt::Task<ReadModifyWriteRowResponse> ReadModifyWriteRowAsync( ReadModifyWriteRowRequest request, st::CancellationToken cancellationToken) => ReadModifyWriteRowAsync( request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Modifies a row atomically on the server. The method reads the latest /// existing timestamp and value from the specified columns and writes a new /// entry based on pre-defined read/modify/write rules. The new value for the /// timestamp is the greater of the existing timestamp or the current server /// time. The method returns the new contents of all modified cells. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// If the <see cref="ReadModifyWriteRowRequest.AppProfileId"/> has not been specified, it will be initialized from the value stored in the client. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual ReadModifyWriteRowResponse ReadModifyWriteRow( ReadModifyWriteRowRequest request, gaxgrpc::CallSettings callSettings = null) { throw new sys::NotImplementedException(); } } /// <summary> /// Bigtable client wrapper, for convenient use. /// </summary> public sealed partial class BigtableClientImpl : BigtableClient { /// <inheritdoc/> public override ReadRowsStream ReadRows( ReadRowsRequest request, gaxgrpc::CallSettings callSettings = null) => ReadRowsImpl(request, callSettings); /// <inheritdoc/> public override BigtableServiceApiClient.SampleRowKeysStream SampleRowKeys( SampleRowKeysRequest request, gaxgrpc::CallSettings callSettings = null) => _client.SampleRowKeys(request, callSettings); /// <inheritdoc/> public override stt::Task<MutateRowResponse> MutateRowAsync( MutateRowRequest request, gaxgrpc::CallSettings callSettings = null) => _client.MutateRowAsync(request, callSettings); /// <inheritdoc/> public override MutateRowResponse MutateRow( MutateRowRequest request, gaxgrpc::CallSettings callSettings = null) => _client.MutateRow(request, callSettings); /// <inheritdoc/> public override MutateRowsResponse MutateRows( MutateRowsRequest request, gaxgrpc::CallSettings callSettings = null) => stt::Task.Run(() => MutateRowsAsync(request, callSettings)).ResultWithUnwrappedExceptions(); /// <inheritdoc/> public override stt::Task<MutateRowsResponse> MutateRowsAsync( MutateRowsRequest request, gaxgrpc::CallSettings callSettings = null) => MutateRowsImpl(request, callSettings); /// <inheritdoc/> public override stt::Task<CheckAndMutateRowResponse> CheckAndMutateRowAsync( CheckAndMutateRowRequest request, gaxgrpc::CallSettings callSettings = null) => _client.CheckAndMutateRowAsync(request, callSettings); /// <inheritdoc/> public override CheckAndMutateRowResponse CheckAndMutateRow( CheckAndMutateRowRequest request, gaxgrpc::CallSettings callSettings = null) => _client.CheckAndMutateRow(request, callSettings); /// <inheritdoc/> public override stt::Task<ReadModifyWriteRowResponse> ReadModifyWriteRowAsync( ReadModifyWriteRowRequest request, gaxgrpc::CallSettings callSettings = null) => _client.ReadModifyWriteRowAsync(request, callSettings); /// <inheritdoc/> public override ReadModifyWriteRowResponse ReadModifyWriteRow( ReadModifyWriteRowRequest request, gaxgrpc::CallSettings callSettings = null) => _client.ReadModifyWriteRow(request, callSettings); } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WebsitePanel.Portal.SkinControls { public partial class UserSpaceBreadcrumb { /// <summary> /// repUsersPath control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Repeater repUsersPath; /// <summary> /// spanSpace control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlGenericControl spanSpace; /// <summary> /// imgSep control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Image imgSep; /// <summary> /// Image1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Image Image1; /// <summary> /// lnkSpace control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.HyperLink lnkSpace; /// <summary> /// imgSep2 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Image imgSep2; /// <summary> /// lnkCurrentPage control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.HyperLink lnkCurrentPage; /// <summary> /// spanOrgn control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlGenericControl spanOrgn; /// <summary> /// imgSep3 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Image imgSep3; /// <summary> /// lnkOrgn control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.HyperLink lnkOrgn; /// <summary> /// imgSep4 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Image imgSep4; /// <summary> /// lnkOrgCurPage control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.HyperLink lnkOrgCurPage; /// <summary> /// SpaceOrgs control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.SkinControls.SpaceOrganizationsSelector SpaceOrgs; /// <summary> /// CurrentNode control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlGenericControl CurrentNode; /// <summary> /// pnlViewUser control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel pnlViewUser; /// <summary> /// lblUsername control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblUsername; /// <summary> /// updatePanelUsers control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.UpdatePanel updatePanelUsers; /// <summary> /// pnlViewSpace control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel pnlViewSpace; /// <summary> /// lblUserAccountName control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblUserAccountName; /// <summary> /// cmdSpaceName control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.LinkButton cmdSpaceName; /// <summary> /// lblSpaceDescription control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblSpaceDescription; /// <summary> /// pnlEditSpace control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel pnlEditSpace; /// <summary> /// txtName control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtName; /// <summary> /// cmdSave control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.LinkButton cmdSave; /// <summary> /// cmdCancel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.LinkButton cmdCancel; /// <summary> /// valRequireName control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.RequiredFieldValidator valRequireName; } }
/* 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 java.lang; using java.io; using java.nio.charset; using java.util; using org.junit; using stab.query; using cnatural.helpers; namespace stab.reflection.test { public class TypeSystemTest { private String bin = System.getProperty("user.dir") + "/tests/tests.jar"; [Test] public void testObjectMethods() { var typeSystem = new Library(new String[] {}); var typeInfo = typeSystem.getType("java/lang/Object"); var names = Query.asIterable(new String[] { "<init>", "equals", "getClass", "hashCode", "notify", "notifyAll", "toString", "wait", "wait", "wait" }); Assert.assertTrue(typeInfo.Methods.where(p => p.IsPublic).select(p => p.Name).orderBy(p => p).sequenceEqual(names)); } [Test] public void testBaseTypes() { var typeSystem = new Library(new String[] {}); var stringType = typeSystem.getType("java/lang/String"); var types = Query.asIterable(new TypeInfo[] { typeSystem.getType("java/lang/Object"), typeSystem.getType("java/io/Serializable"), typeSystem.getType("java/lang/CharSequence"), typeSystem.getGenericType(typeSystem.getType("java/lang/Comparable"), Collections.singletonList(stringType)) }); var publicBaseTypes = stringType.getBaseTypes().where(p => p.IsPublic); Assert.assertTrue(publicBaseTypes.union(types).sequenceEqual(publicBaseTypes)); Assert.assertFalse(publicBaseTypes.except(types).any()); } [Test] public void testSimpleClass() { doTest("SimpleClass"); } [Test] public void testGenericClass() { doTest("GenericClass"); } [Test] public void testConstructedGenericClass() { var typeSystem = new Library(new String[] { bin }); var typeInfo = typeSystem.getType("stab/bytecode/test/classes/GenericClass"); var args = new ArrayList<TypeInfo>(); args.add(typeSystem.getType("java/lang/String")); doTest("ConstructedGenericClass", typeSystem.getGenericType(typeInfo, args)); } [Test] public void testSimpleMethod() { doTest("SimpleMethod"); } [Test] public void testGenericMethod() { doTest("GenericMethod"); } [Test] public void testNestedClass() { doTest("NestedClass"); } [Test] public void testSimpleField() { doTest("SimpleField"); } [Test] public void testStaticInitializer() { doTest("StaticInitializer"); } [Test] public void testAnnotation() { doTest("Annotation"); } private void doTest(String test) { var typeSystem = new Library(new String[] { bin }); var typeInfo = typeSystem.getType("stab/bytecode/test/classes/" + test); doTest(test, typeInfo); } private void doTest(String test, TypeInfo typeInfo) { String result = typeToString(typeInfo, ""); var userDir = System.getProperty("user.dir"); var generatedPath = PathHelper.combine(userDir, "Tests/resources/TypeSystemTest/generated"); var generatedDir = new File(generatedPath); if (!generatedDir.exists()) { generatedDir.mkdir(); } var fileWriter = new FileWriter(PathHelper.combine(generatedPath, test + ".txt")); fileWriter.write(result); fileWriter.close(); var expectedPath = PathHelper.combine(userDir, "Tests/resources/TypeSystemTest/expected"); var expectedFile = new File(PathHelper.combine(expectedPath, test + ".txt")); Assert.assertTrue("Expected file not found: " + expectedFile, expectedFile.exists()); var fileReader = new InputStreamReader(new FileInputStream((expectedFile)), Charset.forName("UTF-8")); var reference = readToEnd(fileReader); var genReader = new BufferedReader(new StringReader(result)); var refReader = new BufferedReader(new StringReader(reference)); for (;;) { var genLine = genReader.readLine(); var refLine = refReader.readLine(); if (genLine == null && refLine == null) { break; } Assert.assertEquals(refLine, genLine); } } private String typeToString(TypeInfo typeInfo, String indent) { var sb = new StringBuilder(); sb.append(indent).append("// ").append(typeInfo.Descriptor).append(" / ").append(typeInfo.Signature).append("\n"); annotations(typeInfo.Annotations, indent, sb); sb.append(indent); if (typeInfo.IsPublic) { sb.append("public "); } if (typeInfo.IsInterface) { sb.append("interface "); } else { sb.append("class "); } typeName(typeInfo, sb); sb.append(" "); if (typeInfo.BaseType != null) { sb.append(": "); typeName(typeInfo.BaseType, sb); sb.append(" "); } var comma = typeInfo.BaseType != null; if (typeInfo.Interfaces.any()) { if (comma) { sb.append(", "); } else { comma = true; } var first = true; foreach (var t in typeInfo.Interfaces) { if (first) { first = false; } else { sb.append(", "); } typeName(t, sb); } sb.append(" "); } foreach (var t in typeInfo.GenericArguments) { if (t.IsGenericParameter) { if (t.GenericParameterBounds.any()) { sb.append("\n").append(indent).append(" ").append("where "); typeName(t, sb); sb.append(": "); bool first = true; foreach (var bound in t.GenericParameterBounds) { if (first) { first = false; } else { sb.append(", "); } typeName(bound, sb); } sb.append(" "); } } } sb.append("{\n"); foreach (var t in typeInfo.NestedTypes) { sb.append(typeToString(t, indent + " ")); } foreach (var f in typeInfo.Fields) { sb.append(indent).append(" // ").append(f.Descriptor).append(" / ").append(f.Signature).append("\n"); sb.append(indent).append(" "); if (f.IsPublic) { sb.append("public "); } if (f.IsProtected) { sb.append("protected "); } if (f.IsPrivate) { sb.append("private "); } if (f.IsFinal) { sb.append("final "); } if (f.IsStatic) { sb.append("static "); } if (f.IsEnum) { sb.append("enum "); } if (f.IsSynthetic) { sb.append("synthetic "); } if (f.IsTransient) { sb.append("transient "); } if (f.IsVolatile) { sb.append("volatile "); } typeName(f.Type, sb); sb.append(" ").append(f.Name).append(";\n"); } foreach (var meth in typeInfo.Methods) { sb.append(indent).append(" // ").append(meth.Descriptor).append(" / ").append(meth.Signature).append("\n"); sb.append(indent).append(" "); if (meth.IsPublic) { sb.append("public "); } if (meth.IsFinal) { sb.append("final "); } if (meth.IsStatic) { sb.append("static "); } typeName(meth.ReturnType, sb); sb.append(" ").append(meth.Name); if (meth.GenericArguments.any()) { sb.append("<"); var first = true; foreach (var t in meth.GenericArguments) { if (first) { first = false; } else { sb.append(", "); } typeName(t, sb); } sb.append(">"); } sb.append("("); var first = true; foreach (var p in meth.Parameters) { if (first) { first = false; } else { sb.append(", "); } typeName(p.Type, sb); sb.append(" "); sb.append(p.Name); } sb.append(")").append(" {\n").append(indent).append(" ").append("}\n"); } sb.append(indent).append("}\n"); return sb.toString(); } private void annotations(Iterable<AnnotationValue> annotations, String indent, StringBuilder sb) { foreach (var a in annotations) { sb.append(indent).append("["); annotation(a, indent, sb); sb.append("]\n"); } } private void annotation(AnnotationValue a, String indent, StringBuilder sb) { sb.append(a.Type.FullName); if (a.ArgumentNames.any()) { sb.append("("); var first = true; foreach (var argName in a.ArgumentNames) { var arg = a.getArgument(argName); if (first) { first = false; } else { sb.append(", "); } sb.append(arg.Name).append(" = "); switch (arg.AnnotationArgumentKind) { case Annotation: annotation((AnnotationValue)arg, indent, sb); break; case Boolean: sb.append(arg.Value); break; default: throw new RuntimeException("Unhandled annotation argument kind: " + arg.getAnnotationArgumentKind()); } } sb.append(")"); } } private void typeName(TypeInfo typeInfo, StringBuilder sb) { sb.append(typeInfo.FullName); if (typeInfo.GenericArguments.any()) { sb.append("<"); var first = true; foreach (var t in typeInfo.GenericArguments) { if (first) { first = false; } else { sb.append(", "); } typeName(t, sb); } sb.append(">"); } } private String readToEnd(Reader reader) { var sb = new StringBuilder(); var buff = new char[1024]; int read; while ((read = reader.read(buff)) != -1) { sb.append(buff, 0, read); } return sb.toString(); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management.Sql; using Microsoft.Azure.Management.Sql.Models; namespace Microsoft.Azure.Management.Sql { /// <summary> /// The Windows Azure SQL Database management API provides a RESTful set of /// web services that interact with Windows Azure SQL Database services to /// manage your databases. The API enables users to create, retrieve, /// update, and delete databases and servers. /// </summary> public static partial class DataMaskingOperationsExtensions { /// <summary> /// Creates or updates an Azure SQL Database data masking policy /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IDataMaskingOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database for which the data /// masking rule applies. /// </param> /// <param name='parameters'> /// Required. The required parameters for createing or updating a /// firewall rule. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse CreateOrUpdatePolicy(this IDataMaskingOperations operations, string resourceGroupName, string serverName, string databaseName, DataMaskingPolicyCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IDataMaskingOperations)s).CreateOrUpdatePolicyAsync(resourceGroupName, serverName, databaseName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates or updates an Azure SQL Database data masking policy /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IDataMaskingOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database for which the data /// masking rule applies. /// </param> /// <param name='parameters'> /// Required. The required parameters for createing or updating a /// firewall rule. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> CreateOrUpdatePolicyAsync(this IDataMaskingOperations operations, string resourceGroupName, string serverName, string databaseName, DataMaskingPolicyCreateOrUpdateParameters parameters) { return operations.CreateOrUpdatePolicyAsync(resourceGroupName, serverName, databaseName, parameters, CancellationToken.None); } /// <summary> /// Creates or updates an Azure SQL Database Server Firewall rule. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IDataMaskingOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database for which the data /// masking rule applies. /// </param> /// <param name='dataMaskingRule'> /// Required. The name of the Azure SQL Database data masking rule. /// </param> /// <param name='parameters'> /// Required. The required parameters for createing or updating a data /// masking rule. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse CreateOrUpdateRule(this IDataMaskingOperations operations, string resourceGroupName, string serverName, string databaseName, string dataMaskingRule, DataMaskingRuleCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IDataMaskingOperations)s).CreateOrUpdateRuleAsync(resourceGroupName, serverName, databaseName, dataMaskingRule, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates or updates an Azure SQL Database Server Firewall rule. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IDataMaskingOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database for which the data /// masking rule applies. /// </param> /// <param name='dataMaskingRule'> /// Required. The name of the Azure SQL Database data masking rule. /// </param> /// <param name='parameters'> /// Required. The required parameters for createing or updating a data /// masking rule. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> CreateOrUpdateRuleAsync(this IDataMaskingOperations operations, string resourceGroupName, string serverName, string databaseName, string dataMaskingRule, DataMaskingRuleCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateRuleAsync(resourceGroupName, serverName, databaseName, dataMaskingRule, parameters, CancellationToken.None); } /// <summary> /// Deletes an Azure SQL Server data masking rule. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IDataMaskingOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database for which the data /// masking rule applies. /// </param> /// <param name='dataMaskingRule'> /// Required. The name of the Azure SQL Database data masking rule. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this IDataMaskingOperations operations, string resourceGroupName, string serverName, string databaseName, string dataMaskingRule) { return Task.Factory.StartNew((object s) => { return ((IDataMaskingOperations)s).DeleteAsync(resourceGroupName, serverName, databaseName, dataMaskingRule); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes an Azure SQL Server data masking rule. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IDataMaskingOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database for which the data /// masking rule applies. /// </param> /// <param name='dataMaskingRule'> /// Required. The name of the Azure SQL Database data masking rule. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this IDataMaskingOperations operations, string resourceGroupName, string serverName, string databaseName, string dataMaskingRule) { return operations.DeleteAsync(resourceGroupName, serverName, databaseName, dataMaskingRule, CancellationToken.None); } /// <summary> /// Returns an Azure SQL Database data masking policy. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IDataMaskingOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database for which the data /// masking policy applies. /// </param> /// <returns> /// Represents the response to a data masking policy get request. /// </returns> public static DataMaskingPolicyGetResponse GetPolicy(this IDataMaskingOperations operations, string resourceGroupName, string serverName, string databaseName) { return Task.Factory.StartNew((object s) => { return ((IDataMaskingOperations)s).GetPolicyAsync(resourceGroupName, serverName, databaseName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns an Azure SQL Database data masking policy. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IDataMaskingOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database for which the data /// masking policy applies. /// </param> /// <returns> /// Represents the response to a data masking policy get request. /// </returns> public static Task<DataMaskingPolicyGetResponse> GetPolicyAsync(this IDataMaskingOperations operations, string resourceGroupName, string serverName, string databaseName) { return operations.GetPolicyAsync(resourceGroupName, serverName, databaseName, CancellationToken.None); } /// <summary> /// Returns an Azure SQL Database data masking rule. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IDataMaskingOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database for which the data /// masking rule applies. /// </param> /// <param name='dataMaskingRule'> /// Required. The name of the Azure SQL Database data masking rule. /// </param> /// <returns> /// Represents the response to a data masking rule get request. /// </returns> public static DataMaskingRuleGetResponse GetRule(this IDataMaskingOperations operations, string resourceGroupName, string serverName, string databaseName, string dataMaskingRule) { return Task.Factory.StartNew((object s) => { return ((IDataMaskingOperations)s).GetRuleAsync(resourceGroupName, serverName, databaseName, dataMaskingRule); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns an Azure SQL Database data masking rule. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IDataMaskingOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database for which the data /// masking rule applies. /// </param> /// <param name='dataMaskingRule'> /// Required. The name of the Azure SQL Database data masking rule. /// </param> /// <returns> /// Represents the response to a data masking rule get request. /// </returns> public static Task<DataMaskingRuleGetResponse> GetRuleAsync(this IDataMaskingOperations operations, string resourceGroupName, string serverName, string databaseName, string dataMaskingRule) { return operations.GetRuleAsync(resourceGroupName, serverName, databaseName, dataMaskingRule, CancellationToken.None); } /// <summary> /// Returns a list of Azure SQL Database data masking rules. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IDataMaskingOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database for which the data /// masking rules applies. /// </param> /// <returns> /// Represents the response to a List data masking rules request. /// </returns> public static DataMaskingRuleListResponse List(this IDataMaskingOperations operations, string resourceGroupName, string serverName, string databaseName) { return Task.Factory.StartNew((object s) => { return ((IDataMaskingOperations)s).ListAsync(resourceGroupName, serverName, databaseName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns a list of Azure SQL Database data masking rules. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IDataMaskingOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database for which the data /// masking rules applies. /// </param> /// <returns> /// Represents the response to a List data masking rules request. /// </returns> public static Task<DataMaskingRuleListResponse> ListAsync(this IDataMaskingOperations operations, string resourceGroupName, string serverName, string databaseName) { return operations.ListAsync(resourceGroupName, serverName, databaseName, CancellationToken.None); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Text; namespace Microsoft.Protocols.TestTools.StackSdk.Messages.Marshaling { /// <summary> /// The Scanner State /// </summary> public enum ScannerState { /// <summary> /// Scan by Space /// </summary> Space, /// <summary> /// Scan by Number /// </summary> Number, /// <summary> /// Scan by Identifier /// </summary> Identifier, /// <summary> /// Scan by Operator /// </summary> Operator, } /// <summary> /// The Expression Lexer /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] public class ExpressionLexer { private IEnumerator<IToken> tokens; private IToken token; /// <summary> /// Constructor /// </summary> /// <param name="expression">The expression</param> public ExpressionLexer(string expression) { if (expression == null) { throw new ArgumentNullException("expression"); } this.tokens = Tokenize(expression); } /// <summary> /// Get the next token /// </summary> /// <returns>The next token</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] public IToken GetNextToken() { if (tokens.MoveNext()) { token = tokens.Current; if (token.Type == TokenType.Invalid) { throw new ExpressionEvaluatorException( string.Format(CultureInfo.InvariantCulture, "invalid token '{0}'", token.Text.Substring(0))); } return token; } else return new Token(TokenType.EndOfFile, String.Empty); } /// <summary> /// Tokenize the input expression /// </summary> /// <param name="expression">The input expression</param> /// <returns>Tokens</returns> protected IEnumerator<IToken> Tokenize(string expression) { int pos = 0; int n = expression.Length; StringBuilder currentToken = new StringBuilder(); ScannerState state = ScannerState.Space; while (pos < n) { char nextCh = expression[pos++]; switch (state) { case ScannerState.Space: if (IsWhitespace(nextCh)) continue; if (IsIdentifier(nextCh, true)) { currentToken.Append(nextCh); state = ScannerState.Identifier; continue; } if (IsNumber(nextCh, true)) { currentToken.Append(nextCh); state = ScannerState.Number; continue; } if (IsOperator(nextCh)) { currentToken.Append(nextCh); state = ScannerState.Operator; continue; } if (IsSeparator(nextCh)) { yield return MakeSeparatorToken(nextCh.ToString()); continue; } yield return MakeInvalidToken("#" + nextCh); continue; case ScannerState.Identifier: if (IsIdentifier(nextCh, false)) { currentToken.Append(nextCh); continue; } else { yield return MakeIdentifierToken(currentToken.ToString()); currentToken = new StringBuilder(); pos--; state = ScannerState.Space; continue; } case ScannerState.Number: if (IsNumber(nextCh, false)) { currentToken.Append(nextCh); continue; } else { yield return MakeNumberToken(currentToken.ToString()); currentToken = new StringBuilder(); pos--; state = ScannerState.Space; continue; } case ScannerState.Operator: if (IsOperator(nextCh) && IsSupportedOperator(currentToken.ToString() + nextCh)) { currentToken.Append(nextCh); continue; } else { yield return MakeOperatorToken(currentToken.ToString()); currentToken = new StringBuilder(); pos--; state = ScannerState.Space; continue; } } } if (state != ScannerState.Space) yield return MakeTokenFromState(currentToken.ToString(), state); } /// <summary> /// Check if the input char is an identifier /// </summary> /// <param name="ch">The input char</param> /// <param name="start">Whether the char is at the beginning of an expression</param> /// <returns>True if the input char is an identifier</returns> protected static bool IsIdentifier(char ch, bool start) { return (start ? Char.IsLetter(ch) : Char.IsLetterOrDigit(ch)) || ch == '@' || ch == '_'; } /// <summary> /// Check if the input char is a number /// </summary> /// <param name="ch">The input char</param> /// <param name="start">Whether the char is at the beginning of an expression</param> /// <returns>True if the input char is a number</returns> protected static bool IsNumber(char ch, bool start) { return Char.IsDigit(ch) || !start && (ch == 'x' || ch == 'X' || ch >= 'a' && ch <= 'f' || ch >= 'A' && ch <= 'F'); } /// <summary> /// Check if the input char is a white space /// </summary> /// <param name="ch">The input char</param> /// <returns>True if the input char is a white space</returns> protected static bool IsWhitespace(char ch) { return Char.IsWhiteSpace(ch); } /// <summary> /// Check if the input char is an operator /// </summary> /// <param name="ch">The input char</param> /// <returns>True if the input char is an operator</returns> protected static bool IsOperator(char ch) { string opchs = "?:&|^=!><+-*/%*~"; return opchs.IndexOf(ch) >= 0; } /// <summary> /// Check if the input char is a separator /// </summary> /// <param name="ch">The input char</param> /// <returns>True if the input char is a separator</returns> protected static bool IsSeparator(char ch) { return ch == '(' || ch == ')' || ch == ','; } private static string[] supportedOperators = { "+", "-", "*", "/", "%", "~", "!", "<<", ">>", ">", "<", ">=", "<=", "==", "!=", "&&", "||", "&", "|", "^", "?", ":", }; /// <summary> /// Check if the input operator is supported /// </summary> /// <param name="op">The input operator (in string format)</param> /// <returns>True if the input operator is supported</returns> protected static bool IsSupportedOperator(string op) { foreach (string supportedOp in supportedOperators) { if (supportedOp == op) { return true; } } return false; } /// <summary> /// Make token for the input operator /// </summary> /// <param name="op">The input operator (in string format)</param> /// <returns>The token made based on the input operator</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] protected static IToken MakeOperatorToken(string op) { switch (op) { case "+": return new Token(TokenType.Plus, op); case "-": return new Token(TokenType.Minus, op); case "*": return new Token(TokenType.Multiply, op); case "/": return new Token(TokenType.Divide, op); case "%": return new Token(TokenType.Multiply, op); case "~": return new Token(TokenType.BitNot, op); case "!": return new Token(TokenType.Not, op); case "<<": return new Token(TokenType.ShiftLeft, op); case ">>": return new Token(TokenType.ShiftRight, op); case ">": return new Token(TokenType.Greater, op); case "<": return new Token(TokenType.Lesser, op); case ">=": return new Token(TokenType.GreaterOrEqual, op); case "<=": return new Token(TokenType.LesserOrEqual, op); case "==": return new Token(TokenType.Equal, op); case "!=": return new Token(TokenType.NotEqual, op); case "&&": return new Token(TokenType.And, op); case "||": return new Token(TokenType.Or, op); case "&": return new Token(TokenType.BitAnd, op); case "|": return new Token(TokenType.BitOr, op); case "^": return new Token(TokenType.BitXor, op); case "?": return new Token(TokenType.Conditional, op); case ":": return new Token(TokenType.Colon, op); default: throw new ExpressionEvaluatorException( string.Format(CultureInfo.InvariantCulture, "unknown operator : {0}", op)); } } /// <summary> /// Make token for the input number /// </summary> /// <param name="number">The input number (in string format)</param> /// <returns>The token made based on the input number</returns> protected static IToken MakeNumberToken(string number) { return new Token(TokenType.Integer, number); } /// <summary> /// Make token for the input identifier /// </summary> /// <param name="identifier">The input identifier (in string format)</param> /// <returns>The token made based on the input identifier</returns> protected static IToken MakeIdentifierToken(string identifier) { return new Token(TokenType.String, identifier); } /// <summary> /// Make token for the input separator /// </summary> /// <param name="separator">The input separator (in string format)</param> /// <returns>The token made based on the input separator</returns> protected static IToken MakeSeparatorToken(string separator) { return new Token(TokenType.Separator, separator); } /// <summary> /// Make invalid token for the input string /// </summary> /// <param name="invalid">The input string</param> /// <returns>The token made based on the input string</returns> protected static IToken MakeInvalidToken(string invalid) { return new Token(TokenType.Invalid, invalid); } /// <summary> /// Make token from token string and scanner state /// </summary> /// <param name="token">The input token string</param> /// <param name="state">The scanner state</param> /// <returns>The token made based on the scanner state</returns> protected static IToken MakeTokenFromState(string token, ScannerState state) { switch (state) { case ScannerState.Identifier: return MakeIdentifierToken(token); case ScannerState.Number: return MakeNumberToken(token); case ScannerState.Operator: return MakeOperatorToken(token); default: throw new ExpressionEvaluatorException( string.Format(CultureInfo.InvariantCulture, "unknown token '{0}'", token)); } } } }
// 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.Composition.Diagnostics; using System.ComponentModel.Composition.Hosting; using System.ComponentModel.Composition.Primitives; using System.ComponentModel.Composition.ReflectionModel; using System.Linq; using System.Reflection; using System.Threading; using Microsoft.Internal; namespace System.ComponentModel.Composition.AttributedModel { internal class AttributedPartCreationInfo : IReflectionPartCreationInfo { private readonly Type _type; private readonly bool _ignoreConstructorImports = false; private readonly ICompositionElement _origin; private PartCreationPolicyAttribute _partCreationPolicy = null; private ConstructorInfo _constructor; private IEnumerable<ExportDefinition> _exports; private IEnumerable<ImportDefinition> _imports; private HashSet<string> _contractNamesOnNonInterfaces; public AttributedPartCreationInfo(Type type, PartCreationPolicyAttribute partCreationPolicy, bool ignoreConstructorImports, ICompositionElement origin) { if (type == null) { throw new ArgumentNullException(nameof(type)); } _type = type; _ignoreConstructorImports = ignoreConstructorImports; _partCreationPolicy = partCreationPolicy; _origin = origin; } public Type GetPartType() { return _type; } public Lazy<Type> GetLazyPartType() { return new Lazy<Type>(GetPartType, LazyThreadSafetyMode.PublicationOnly); } public ConstructorInfo GetConstructor() { if (_constructor == null && !_ignoreConstructorImports) { _constructor = SelectPartConstructor(_type); } return _constructor; } public IDictionary<string, object> GetMetadata() { return _type.GetPartMetadataForType(CreationPolicy); } public IEnumerable<ExportDefinition> GetExports() { DiscoverExportsAndImports(); return _exports; } public IEnumerable<ImportDefinition> GetImports() { DiscoverExportsAndImports(); return _imports; } public bool IsDisposalRequired { get { return typeof(IDisposable).IsAssignableFrom(GetPartType()); } } public bool IsIdentityComparison { get { return true; } } public bool IsPartDiscoverable() { // The part should not be marked with the "NonDiscoverable" if (_type.IsAttributeDefined<PartNotDiscoverableAttribute>()) { CompositionTrace.DefinitionMarkedWithPartNotDiscoverableAttribute(_type); return false; } // The part should have exports if (!HasExports()) { CompositionTrace.DefinitionContainsNoExports(_type); return false; } // If the part is generic, all exports should have the same number of generic parameters // (otherwise we have no way to specialize the part based on an export) if (!AllExportsHaveMatchingArity()) { // The function has already reported all violations via tracing return false; } return true; } private bool HasExports() { return GetExportMembers(_type).Any() || GetInheritedExports(_type).Any(); } private bool AllExportsHaveMatchingArity() { bool isArityMatched = true; if (_type.ContainsGenericParameters) { int partGenericArity = _type.GetPureGenericArity(); // each member should have the same arity foreach (MemberInfo member in GetExportMembers(_type).Concat(GetInheritedExports(_type))) { if (member.MemberType == MemberTypes.Method) { // open generics are unsupported on methods if (((MethodInfo)member).ContainsGenericParameters) { isArityMatched = false; CompositionTrace.DefinitionMismatchedExportArity(_type, member); continue; } } if (member.GetDefaultTypeFromMember().GetPureGenericArity() != partGenericArity) { isArityMatched = false; CompositionTrace.DefinitionMismatchedExportArity(_type, member); } } } return isArityMatched; } string ICompositionElement.DisplayName { get { return GetDisplayName(); } } ICompositionElement ICompositionElement.Origin { get { return _origin; } } public override string ToString() { return GetDisplayName(); } private string GetDisplayName() { return GetPartType().GetDisplayName(); } private CreationPolicy CreationPolicy { get { if (_partCreationPolicy == null) { _partCreationPolicy = _type.GetFirstAttribute<PartCreationPolicyAttribute>() ?? PartCreationPolicyAttribute.Default; } return _partCreationPolicy.CreationPolicy; } } private static ConstructorInfo SelectPartConstructor(Type type) { if (type == null) { throw new ArgumentNullException(nameof(type)); } if (type.IsAbstract) { return null; } // Only deal with non-static constructors BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; ConstructorInfo[] constructors = type.GetConstructors(flags); // Should likely only happen for static or abstract types if (constructors.Length == 0) { return null; } // Optimize single default constructor. if (constructors.Length == 1 && constructors[0].GetParameters().Length == 0) { return constructors[0]; } // Select the marked constructor if there is exactly one marked ConstructorInfo importingConstructor = null; ConstructorInfo defaultConstructor = null; foreach (ConstructorInfo constructor in constructors) { // an importing constructor found if (constructor.IsAttributeDefined<ImportingConstructorAttribute>()) { if (importingConstructor != null) { // more that one importing constructor - return null ot error out on creation return null; } else { importingConstructor = constructor; } } // otherwise if we havent seen the default constructor yet, check if this one is it else if (defaultConstructor == null) { if (constructor.GetParameters().Length == 0) { defaultConstructor = constructor; } } } return importingConstructor ?? defaultConstructor; } private void DiscoverExportsAndImports() { // NOTE : in most cases both of these will be null or not null at the same time // the only situation when that is not the case is when there was a failure during the previous discovery // and one of them ended up not being set. In that case we will force the discovery again so that the same exception is thrown. if ((_exports != null) && (_imports != null)) { return; } _exports = GetExportDefinitions(); _imports = GetImportDefinitions(); } private IEnumerable<ExportDefinition> GetExportDefinitions() { List<ExportDefinition> exports = new List<ExportDefinition>(); _contractNamesOnNonInterfaces = new HashSet<string>(); // GetExportMembers should only contain the type itself along with the members declared on it, // it should not contain any base types, members on base types or interfaces on the type. foreach (MemberInfo member in GetExportMembers(_type)) { foreach (ExportAttribute exportAttribute in member.GetAttributes<ExportAttribute>()) { AttributedExportDefinition attributedExportDefinition = CreateExportDefinition(member, exportAttribute); if (exportAttribute.GetType() == CompositionServices.InheritedExportAttributeType) { // Any InheritedExports on the type itself are contributed during this pass // and we need to do the book keeping for those. if (!_contractNamesOnNonInterfaces.Contains(attributedExportDefinition.ContractName)) { exports.Add(new ReflectionMemberExportDefinition(member.ToLazyMember(), attributedExportDefinition, this)); _contractNamesOnNonInterfaces.Add(attributedExportDefinition.ContractName); } } else { exports.Add(new ReflectionMemberExportDefinition(member.ToLazyMember(), attributedExportDefinition, this)); } } } // GetInheritedExports should only contain InheritedExports on base types or interfaces. // The order of types returned here is important because it is used as a // priority list of which InhertedExport to choose if multiple exists with // the same contract name. Therefore ensure that we always return the types // in the hiearchy from most derived to the lowest base type, followed // by all the interfaces that this type implements. foreach (Type type in GetInheritedExports(_type)) { foreach (InheritedExportAttribute exportAttribute in type.GetAttributes<InheritedExportAttribute>()) { AttributedExportDefinition attributedExportDefinition = CreateExportDefinition(type, exportAttribute); if (!_contractNamesOnNonInterfaces.Contains(attributedExportDefinition.ContractName)) { exports.Add(new ReflectionMemberExportDefinition(type.ToLazyMember(), attributedExportDefinition, this)); if (!type.IsInterface) { _contractNamesOnNonInterfaces.Add(attributedExportDefinition.ContractName); } } } } _contractNamesOnNonInterfaces = null; // No need to hold this state around any longer return exports; } private AttributedExportDefinition CreateExportDefinition(MemberInfo member, ExportAttribute exportAttribute) { string contractName = null; Type typeIdentityType = null; member.GetContractInfoFromExport(exportAttribute, out typeIdentityType, out contractName); return new AttributedExportDefinition(this, member, exportAttribute, typeIdentityType, contractName); } private IEnumerable<MemberInfo> GetExportMembers(Type type) { BindingFlags flags = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; // If the type is abstract only find local static exports if (type.IsAbstract) { flags &= ~BindingFlags.Instance; } else if (IsExport(type)) { yield return type; } // Walk the fields foreach (FieldInfo member in type.GetFields(flags)) { if (IsExport(member)) { yield return member; } } // Walk the properties foreach (PropertyInfo member in type.GetProperties(flags)) { if (IsExport(member)) { yield return member; } } // Walk the methods foreach (MethodInfo member in type.GetMethods(flags)) { if (IsExport(member)) { yield return member; } } } private IEnumerable<Type> GetInheritedExports(Type type) { // If the type is abstract we aren't interested in type level exports if (type.IsAbstract) { yield break; } // The order of types returned here is important because it is used as a // priority list of which InhertedExport to choose if multiple exists with // the same contract name. Therefore ensure that we always return the types // in the hiearchy from most derived to the lowest base type, followed // by all the interfaces that this type implements. Type currentType = type.BaseType; if (currentType == null) { yield break; } // Stopping at object instead of null to help with performance. It is a noticable performance // gain (~5%) if we don't have to try and pull the attributes we know don't exist on object. // We also need the null check in case we're passed a type that doesn't live in the runtime context. while (currentType != null && currentType.UnderlyingSystemType != CompositionServices.ObjectType) { if (IsInheritedExport(currentType)) { yield return currentType; } currentType = currentType.BaseType; } foreach (Type iface in type.GetInterfaces()) { if (IsInheritedExport(iface)) { yield return iface; } } } private static bool IsExport(ICustomAttributeProvider attributeProvider) { return attributeProvider.IsAttributeDefined<ExportAttribute>(false); } private static bool IsInheritedExport(ICustomAttributeProvider attributedProvider) { return attributedProvider.IsAttributeDefined<InheritedExportAttribute>(false); } private IEnumerable<ImportDefinition> GetImportDefinitions() { List<ImportDefinition> imports = new List<ImportDefinition>(); foreach (MemberInfo member in GetImportMembers(_type)) { ReflectionMemberImportDefinition importDefinition = AttributedModelDiscovery.CreateMemberImportDefinition(member, this); imports.Add(importDefinition); } ConstructorInfo constructor = GetConstructor(); if (constructor != null) { foreach (ParameterInfo parameter in constructor.GetParameters()) { ReflectionParameterImportDefinition importDefinition = AttributedModelDiscovery.CreateParameterImportDefinition(parameter, this); imports.Add(importDefinition); } } return imports; } private IEnumerable<MemberInfo> GetImportMembers(Type type) { if (type.IsAbstract) { yield break; } foreach (MemberInfo member in GetDeclaredOnlyImportMembers(type)) { yield return member; } // Walk up the type chain until you hit object. if (type.BaseType != null) { Type baseType = type.BaseType; // Stopping at object instead of null to help with performance. It is a noticable performance // gain (~5%) if we don't have to try and pull the attributes we know don't exist on object. // We also need the null check in case we're passed a type that doesn't live in the runtime context. while (baseType != null && baseType.UnderlyingSystemType != CompositionServices.ObjectType) { foreach (MemberInfo member in GetDeclaredOnlyImportMembers(baseType)) { yield return member; } baseType = baseType.BaseType; } } } private IEnumerable<MemberInfo> GetDeclaredOnlyImportMembers(Type type) { BindingFlags flags = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; // Walk the fields foreach (FieldInfo member in type.GetFields(flags)) { if (IsImport(member)) { yield return member; } } // Walk the properties foreach (PropertyInfo member in type.GetProperties(flags)) { if (IsImport(member)) { yield return member; } } } private static bool IsImport(ICustomAttributeProvider attributeProvider) { return attributeProvider.IsAttributeDefined<IAttributedImport>(false); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices; namespace SuperPMICollection { public class SpmiException : Exception { public SpmiException() : base() { } public SpmiException(string message) : base(message) { } public SpmiException(string message, Exception innerException) : base(message, innerException) { } } internal class Global { // Arguments to the program. These should not be touched by Initialize(), as they are set earlier than that. internal static bool SkipCleanup = false; // Should we skip all cleanup? That is, should we keep all temporary files? Useful for debugging. // Computed values based on the environment and platform. internal static bool IsWindows { get; private set; } internal static bool IsOSX { get; private set; } internal static bool IsLinux { get; private set; } internal static string CoreRoot { get; private set; } internal static string StandaloneJitName { get; private set; } internal static string CollectorShimName { get; private set; } internal static string SuperPmiToolName { get; private set; } internal static string McsToolName { get; private set; } internal static string JitPath { get; private set; } // Path to the standalone JIT internal static string SuperPmiPath { get; private set; } // Path to superpmi.exe internal static string McsPath { get; private set; } // Path to mcs.exe // Initialize the global state. Don't use a class constructor, because we might throw exceptions // that we want to catch. public static void Initialize() { string core_root_raw = System.Environment.GetEnvironmentVariable("CORE_ROOT"); if (String.IsNullOrEmpty(core_root_raw)) { throw new SpmiException("Environment variable CORE_ROOT is not set"); } try { CoreRoot = System.IO.Path.GetFullPath(core_root_raw); } catch (Exception ex) { throw new SpmiException("Illegal CORE_ROOT environment variable (" + core_root_raw + "), exception: " + ex.Message); } IsWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); IsOSX = RuntimeInformation.IsOSPlatform(OSPlatform.OSX); IsLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); if (IsWindows) { StandaloneJitName = "clrjit.dll"; CollectorShimName = "superpmi-shim-collector.dll"; SuperPmiToolName = "superpmi.exe"; McsToolName = "mcs.exe"; } else if (IsLinux) { StandaloneJitName = "libclrjit.so"; CollectorShimName = "libsuperpmi-shim-collector.so"; SuperPmiToolName = "superpmi"; McsToolName = "mcs"; } else if (IsOSX) { StandaloneJitName = "libclrjit.dylib"; CollectorShimName = "libsuperpmi-shim-collector.dylib"; SuperPmiToolName = "superpmi"; McsToolName = "mcs"; } else { throw new SpmiException("Unknown platform"); } JitPath = Path.Combine(CoreRoot, StandaloneJitName); SuperPmiPath = Path.Combine(CoreRoot, SuperPmiToolName); McsPath = Path.Combine(CoreRoot, McsToolName); } } internal class SuperPMICollectionClass { private static string s_tempDir = null; // Temporary directory where we will put the MC files, MCH files, MCL files, and TOC. private static string s_baseFailMclFile = null; // Pathname for a temporary .MCL file used for noticing superpmi replay failures against base MCH. private static string s_finalFailMclFile = null; // Pathname for a temporary .MCL file used for noticing superpmi replay failures against final MCH. private static string s_baseMchFile = null; // The base .MCH file path private static string s_cleanMchFile = null; // The clean .MCH file path private static string s_finalMchFile = null; // The clean thin unique .MCH file path private static string s_tocFile = null; // The .TOC file path for the clean thin unique .MCH file private static string s_errors = ""; // Collect non-fatal file delete errors to display at the end of the collection process. private static bool s_saveFinalMchFile = false; // Should we save the final MCH file, or delete it? private static void SafeFileDelete(string filePath) { try { File.Delete(filePath); } catch(Exception ex) { string err = string.Format("Error deleting file \"{0}\": {1}", filePath, ex.Message); s_errors += err + System.Environment.NewLine; Console.Error.WriteLine(err); } } private static void CreateTempDirectory(string tempPath) { if (tempPath == null) { tempPath = Path.GetTempPath(); } s_tempDir = Path.Combine(tempPath, Path.GetRandomFileName() + "SPMI"); if (Directory.Exists(s_tempDir)) { throw new SpmiException("temporary directory already exists: " + s_tempDir); } DirectoryInfo di = Directory.CreateDirectory(s_tempDir); } private static void ChooseFilePaths(string outputMchPath) { s_baseFailMclFile = Path.Combine(s_tempDir, "basefail.mcl"); s_finalFailMclFile = Path.Combine(s_tempDir, "finalfail.mcl"); s_baseMchFile = Path.Combine(s_tempDir, "base.mch"); s_cleanMchFile = Path.Combine(s_tempDir, "clean.mch"); if (outputMchPath == null) { s_saveFinalMchFile = false; s_finalMchFile = Path.Combine(s_tempDir, "final.mch"); s_tocFile = Path.Combine(s_tempDir, "final.mch.mct"); } else { s_saveFinalMchFile = true; s_finalMchFile = Path.GetFullPath(outputMchPath); s_tocFile = s_finalMchFile + ".mct"; } } private static int RunProgram(string program, string arguments) { // If the program is a script, move the program name into the arguments, and run it // under the appropriate shell. if (Global.IsWindows) { if ((program.LastIndexOf(".bat") != -1) || (program.LastIndexOf(".cmd") != -1)) { string programArgumentSep = String.IsNullOrEmpty(arguments) ? "" : " "; arguments = "/c " + program + programArgumentSep + arguments; program = Environment.GetEnvironmentVariable("ComSpec"); // path to CMD.exe } } else { if (program.LastIndexOf(".sh") != -1) { string programArgumentSep = String.IsNullOrEmpty(arguments) ? "" : " "; arguments = "bash " + program + programArgumentSep + arguments; program = "/usr/bin/env"; } } Console.WriteLine("Running: " + program + " " + arguments); Process p = Process.Start(program, arguments); p.WaitForExit(); return p.ExitCode; } // Run a single test from the coreclr test binary drop. // This works even if given a test path in Windows file system format (e.g., // "c:\foo\bar\runit.cmd") when run on Unix. It converts to Unix path format and replaces // the ".cmd" with ".sh" before attempting to run the script. private static void RunTest(string testName) { string testDir; if (Global.IsWindows) { int lastIndex = testName.LastIndexOf("\\"); if (lastIndex == -1) { throw new SpmiException("test path doesn't have any directory separators? " + testName); } testDir = testName.Substring(0, lastIndex); } else { // Just in case we've been given a test name in Windows format, convert it to Unix format here. testName = testName.Replace("\\", "/"); testName = testName.Replace(".cmd", ".sh"); testName = testName.Replace(".bat", ".sh"); // The way tests are run on Linux, we might need to do some setup. In particular, // if the test scripts are copied from Windows, we need to convert line endings // to Unix line endings, and make the script executable. We can always do this // more than once. This same transformation is done in runtest.sh. // Review: RunProgram doesn't seem to work if the program isn't a full path. RunProgram("/usr/bin/perl", @"-pi -e 's/\r\n|\n|\r/\n/g' " + "\"" + testName + "\""); RunProgram("/bin/chmod", "+x \"" + testName + "\""); // Now, figure out how to run the test. int lastIndex = testName.LastIndexOf("/"); if (lastIndex == -1) { throw new SpmiException("test path doesn't have any directory separators? " + testName); } testDir = testName.Substring(0, lastIndex); } // Run the script in the same directory where the test lives. string originalDir = Directory.GetCurrentDirectory(); Directory.SetCurrentDirectory(testDir); try { RunProgram(testName, ""); } finally { // Restore the original current directory from before the test run. Directory.SetCurrentDirectory(originalDir); } } private static string[] GetSpmiTestFullPaths() { var spmiTestFullPaths = new List<string>(); using (var resourceStream = typeof(SuperPMICollectionClass).GetTypeInfo().Assembly.GetManifestResourceStream("SpmiTestNames")) using (var streamReader = new StreamReader(resourceStream)) { string currentDirectory = Directory.GetCurrentDirectory(); string spmiTestName; while ((spmiTestName = streamReader.ReadLine()) != null) { string spmiTestFullPath = Path.Combine(currentDirectory, spmiTestName, Path.ChangeExtension(spmiTestName, ".cmd")); spmiTestFullPaths.Add(spmiTestFullPath); } } return spmiTestFullPaths.ToArray(); } // Run all the programs from the CoreCLR test binary drop we wish to run while collecting MC files. private static void RunTestProgramsWhileCollecting() { // Run the tests foreach (string spmiTestPath in GetSpmiTestFullPaths()) { try { RunTest(spmiTestPath); } catch (SpmiException ex) { // Ignore failures running the test. We don't really care if they pass or not // as long as they generate some .MC files. Plus, I'm not sure how confident // we can be in getting a correct error code. Console.Error.WriteLine("WARNING: test failed (ignoring): " + ex.Message); } } } // Run all the programs we wish to run while collecting MC files. private static void RunProgramsWhileCollecting(string runProgramPath, string runProgramArguments) { if (runProgramPath == null) { // No program was given to use for collection, so use our default set. RunTestProgramsWhileCollecting(); } else { RunProgram(runProgramPath, runProgramArguments); } } // Collect MC files: // a. Set environment variables // b. Run tests // c. Un-set environment variables // d. Check that something was generated private static void CollectMCFiles(string runProgramPath, string runProgramArguments) { // Set environment variables. Console.WriteLine("Setting environment variables:"); Console.WriteLine(" SuperPMIShimLogPath=" + s_tempDir); Console.WriteLine(" SuperPMIShimPath=" + Global.JitPath); Console.WriteLine(" COMPlus_AltJit=*"); Console.WriteLine(" COMPlus_AltJitName=" + Global.CollectorShimName); Environment.SetEnvironmentVariable("SuperPMIShimLogPath", s_tempDir); Environment.SetEnvironmentVariable("SuperPMIShimPath", Global.JitPath); Environment.SetEnvironmentVariable("COMPlus_AltJit", "*"); Environment.SetEnvironmentVariable("COMPlus_AltJitName", Global.CollectorShimName); RunProgramsWhileCollecting(runProgramPath, runProgramArguments); // Un-set environment variables Environment.SetEnvironmentVariable("SuperPMIShimLogPath", ""); Environment.SetEnvironmentVariable("SuperPMIShimPath", ""); Environment.SetEnvironmentVariable("COMPlus_AltJit", ""); Environment.SetEnvironmentVariable("COMPlus_AltJitName", ""); // Did any .mc files get generated? string[] mcFiles = Directory.GetFiles(s_tempDir, "*.mc"); if (mcFiles.Length == 0) { throw new SpmiException("no .mc files generated"); } } // Merge MC files: // mcs -merge <s_baseMchFile> <s_tempDir>\*.mc -recursive private static void MergeMCFiles() { string pattern = Path.Combine(s_tempDir, "*.mc"); RunProgram(Global.McsPath, "-merge " + s_baseMchFile + " " + pattern + " -recursive"); if (!File.Exists(s_baseMchFile)) { throw new SpmiException("file missing: " + s_baseMchFile); } if (!Global.SkipCleanup) { // All the individual MC files are no longer necessary, now that we've merged them into the base.mch. Delete them. string[] mcFiles = Directory.GetFiles(s_tempDir, "*.mc"); foreach (string mcFile in mcFiles) { SafeFileDelete(mcFile); } } } // Create clean MCH file: // <superPmiPath> -p -f <s_baseFailMclFile> <s_baseMchFile> <jitPath> // if <s_baseFailMclFile> is non-empty: // <mcl> -strip <s_baseFailMclFile> <s_baseMchFile> <s_cleanMchFile> // else: // s_cleanMchFile = s_baseMchFile // no need to copy; just change string names (and null out s_baseMchFile so we don't try to delete twice) // del <s_baseFailMclFile> private static void CreateCleanMCHFile() { RunProgram(Global.SuperPmiPath, "-p -f " + s_baseFailMclFile + " " + s_baseMchFile + " " + Global.JitPath); if (File.Exists(s_baseFailMclFile) && !String.IsNullOrEmpty(File.ReadAllText(s_baseFailMclFile))) { RunProgram(Global.McsPath, "-strip " + s_baseMchFile + " " + s_cleanMchFile); } else { // Instead of stripping the file, just set s_cleanMchFile = s_baseMchFile and // null out s_baseMchFile so we don't try to delete the same file twice. // Note that we never use s_baseMchFile after this function is called. s_cleanMchFile = s_baseMchFile; s_baseMchFile = null; } if (!File.Exists(s_cleanMchFile)) { throw new SpmiException("file missing: " + s_cleanMchFile); } if (!Global.SkipCleanup) { if (File.Exists(s_baseFailMclFile)) { SafeFileDelete(s_baseFailMclFile); s_baseFailMclFile = null; } // The base file is no longer used (unless there was no cleaning done, in which case // s_baseMchFile has been null-ed and s_cleanMchFile points at the base file). if ((s_baseMchFile != null) && File.Exists(s_baseMchFile)) { SafeFileDelete(s_baseMchFile); s_baseMchFile = null; } } } // Create a thin unique MCH: // <mcl> -removeDup -thin <s_cleanMchFile> <s_finalMchFile> private static void CreateThinUniqueMCH() { RunProgram(Global.McsPath, "-removeDup -thin " + s_cleanMchFile + " " + s_finalMchFile); if (!File.Exists(s_finalMchFile)) { throw new SpmiException("file missing: " + s_finalMchFile); } if (!Global.SkipCleanup) { // The clean file is no longer used; delete it. if ((s_cleanMchFile != null) && File.Exists(s_cleanMchFile)) { SafeFileDelete(s_cleanMchFile); s_cleanMchFile = null; } } } // Create a TOC file: // <mcl> -toc <s_finalMchFile> // // check that .mct file was created private static void CreateTOC() { RunProgram(Global.McsPath, "-toc " + s_finalMchFile); if (!File.Exists(s_tocFile)) { throw new SpmiException("file missing: " + s_tocFile); } } // Verify the resulting MCH file is error-free when running superpmi against it with the same JIT used for collection. // <superPmiPath> -p -f <s_finalFailMclFile> <s_finalMchFile> <jitPath> // if <s_finalFailMclFile> is non-empty: // // error! private static void VerifyFinalMCH() { RunProgram(Global.SuperPmiPath, "-p -f " + s_finalFailMclFile + " " + s_finalMchFile + " " + Global.JitPath); if (!File.Exists(s_finalFailMclFile) || !String.IsNullOrEmpty(File.ReadAllText(s_finalFailMclFile))) { throw new SpmiException("replay of final file is not error free"); } if (!Global.SkipCleanup) { if (File.Exists(s_finalFailMclFile)) { SafeFileDelete(s_finalFailMclFile); s_finalFailMclFile = null; } } } // Cleanup. If we get here due to a failure of some kind, we want to do full cleanup. If we get here as part // of normal shutdown processing, we want to keep the s_finalMchFile and s_tocFile if s_saveFinalMchFile == true. // del <s_baseMchFile> // del <s_cleanMchFile> // del <s_finalMchFile> // del <s_tocFile> // rmdir <s_tempDir> private static void Cleanup() { if (Global.SkipCleanup) return; try { if ((s_baseFailMclFile != null) && File.Exists(s_baseFailMclFile)) { SafeFileDelete(s_baseFailMclFile); s_baseFailMclFile = null; } if ((s_baseMchFile != null) && File.Exists(s_baseMchFile)) { SafeFileDelete(s_baseMchFile); s_baseMchFile = null; } if ((s_cleanMchFile != null) && File.Exists(s_cleanMchFile)) { SafeFileDelete(s_cleanMchFile); s_cleanMchFile = null; } if (!s_saveFinalMchFile) { // Note that if we fail to create the TOC, but we already // successfully created the MCH file, and the user wants to // keep the final result, then we will still keep the final // MCH file. We'll also keep it if the verify pass fails. if ((s_finalMchFile != null) && File.Exists(s_finalMchFile)) { SafeFileDelete(s_finalMchFile); } if ((s_tocFile != null) && File.Exists(s_tocFile)) { SafeFileDelete(s_tocFile); } } if ((s_finalFailMclFile != null) && File.Exists(s_finalFailMclFile)) { SafeFileDelete(s_finalFailMclFile); s_finalFailMclFile = null; } if ((s_tempDir != null) && Directory.Exists(s_tempDir)) { Directory.Delete(s_tempDir, /* delete recursively */ true); } } catch (Exception ex) { Console.Error.WriteLine("ERROR during cleanup: " + ex.Message); } } public static int Collect(string outputMchPath, string runProgramPath, string runProgramArguments, string tempPath) { // Do a basic SuperPMI collect and validation: // 1. Collect MC files by running a set of sample apps. // 2. Merge the MC files into a single MCH using "mcs -merge *.mc -recursive". // 3. Create a clean MCH by running superpmi over the MCH, and using "mcs -strip" to filter // out any failures (if any). // 4. Create a thin unique MCH by using "mcs -removeDup -thin". // 5. Create a TOC using "mcs -toc". // 6. Verify the resulting MCH file is error-free when running superpmi against it with the // same JIT used for collection. // // MCH files are big. If we don't need them anymore, clean them up right away to avoid // running out of disk space in disk constrained situations. string thisTask = "SuperPMI collection and playback"; Console.WriteLine(thisTask + " - BEGIN"); int result = 101; // assume error (!= 100) try { CreateTempDirectory(tempPath); ChooseFilePaths(outputMchPath); CollectMCFiles(runProgramPath, runProgramArguments); MergeMCFiles(); CreateCleanMCHFile(); CreateThinUniqueMCH(); CreateTOC(); VerifyFinalMCH(); // Success! result = 100; } catch (SpmiException ex) { Console.Error.WriteLine("ERROR: " + ex.Message); result = 101; } catch (Exception ex) { Console.Error.WriteLine("ERROR: unknown exception running collection: " + ex.Message); result = 101; } finally { Cleanup(); } // Re-display the file delete errors, if any, in case they got lost in the output so far. if (!String.IsNullOrEmpty(s_errors)) { Console.Error.WriteLine("Non-fatal errors occurred during processing:"); Console.Error.Write(s_errors); } if (result == 100) { Console.WriteLine(thisTask + " - SUCCESS"); } else { Console.WriteLine(thisTask + " - FAILED"); } return result; } } internal class Program { private static void Usage() { // Unfortunately, under CoreCLR, this just gets is the path to CoreRun.exe: // string thisProgram = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName; string thisProgram = "superpmicollect"; Console.WriteLine("Usage: {0} [arguments]", thisProgram); Console.WriteLine(" where [arguments] is zero or more of:"); Console.WriteLine(" -? | -help : Display this help text."); Console.WriteLine(" -mch <file> : Specify the name of the generated clean/thin/unique MCH file."); Console.WriteLine(" The MCH file is retained (by default, the final MCH file is deleted)."); Console.WriteLine(" -run <program> [arguments...] : This program (or script) is invoked to run any number"); Console.WriteLine(" of programs during MC collection. All arguments after"); Console.WriteLine(" <program> are passed to <program> as its arguments."); Console.WriteLine(" Thus, -run must be the last argument."); Console.WriteLine(" -skipCleanup : Do not delete any intermediate files created during processing."); Console.WriteLine(" -temp <dir> : A newly created, randomly-named, subdirectory of this"); Console.WriteLine(" directory will be used to store all temporary files."); Console.WriteLine(" By default, the user temporary directory is used"); Console.WriteLine(" (%TEMP% on Windows, /tmp on Unix)."); Console.WriteLine(" Since SuperPMI collections generate a lot of data, this option"); Console.WriteLine(" is useful if the normal temporary directory doesn't have enough space."); Console.WriteLine(""); Console.WriteLine("This program performs a collection of SuperPMI data. With no arguments, a hard-coded list of"); Console.WriteLine("programs are run during collection. With the -run argument, the user species which apps are run."); Console.WriteLine(""); Console.WriteLine("If -mch is not given, all generated files are deleted, and the result is simply the exit code"); Console.WriteLine("indicating whether the collection succeeded. This is useful as a test."); Console.WriteLine(""); Console.WriteLine("If the COMPlus_AltJit variable is already set, it is assumed SuperPMI collection is already happening,"); Console.WriteLine("and the program exits with success."); Console.WriteLine(""); Console.WriteLine("On success, the return code is 100."); } private static int Main(string[] args) { string outputMchPath = null; string runProgramPath = null; string runProgramArguments = null; string tempPath = null; // Parse arguments if (args.Length > 0) { for (int i = 0; i < args.Length; i++) { switch (args[i]) { default: Usage(); return 101; case "-?": Usage(); return 101; case "-help": Usage(); return 101; case "-skipCleanup": Global.SkipCleanup = true; break; case "-mch": i++; if (i >= args.Length) { Console.Error.WriteLine("Error: missing argument to -mch"); Usage(); return 101; } outputMchPath = args[i]; if (!outputMchPath.EndsWith(".mch")) { // We need the resulting file to end with ".mch". If the user didn't specify this, then simply add it. // Thus, if the user specifies "-mch foo", we'll generate foo.mch (and TOC file foo.mch.mct). outputMchPath += ".mch"; } outputMchPath = Path.GetFullPath(outputMchPath); break; case "-run": i++; if (i >= args.Length) { Console.Error.WriteLine("Error: missing argument to -run"); Usage(); return 101; } runProgramPath = Path.GetFullPath(args[i]); if (!File.Exists(runProgramPath)) { Console.Error.WriteLine("Error: couldn't find program {0}", runProgramPath); return 101; } // The rest of the arguments, if any, are passed as arguments to the run program. i++; if (i < args.Length) { string[] runArgumentsArray = new string[args.Length - i]; for (int j = 0; i < args.Length; i++, j++) { runArgumentsArray[j] = args[i]; } runProgramArguments = string.Join(" ", runArgumentsArray); } break; case "-temp": i++; if (i >= args.Length) { Console.Error.WriteLine("Error: missing argument to -temp"); Usage(); return 101; } tempPath = args[i]; break; } } } // Done with argument parsing. string altjitvar = System.Environment.GetEnvironmentVariable("COMPlus_AltJit"); if (!String.IsNullOrEmpty(altjitvar)) { // Someone already has the COMPlus_AltJit variable set. We don't want to override // that. Perhaps someone is already doing a SuperPMI collection and invokes this // program as part of a full test path in which this program exists. Console.WriteLine("COMPlus_AltJit already exists: skipping SuperPMI collection and returning success"); return 100; } int result; try { Global.Initialize(); result = SuperPMICollectionClass.Collect(outputMchPath, runProgramPath, runProgramArguments, tempPath); } catch (SpmiException ex) { Console.Error.WriteLine("ERROR: " + ex.Message); result = 101; } catch (Exception ex) { Console.Error.WriteLine("ERROR: unknown exception running collection: " + ex.Message); result = 101; } return result; } } }
using System; using SimpleCompiler.Shared; namespace SimpleCompiler.VirtualMachine { public class Stack { const string ERROR_STACK_EMPTY = "Empty stack"; const string ERROR_STACK_FULL = "Full stack"; const string ERROR_STACK_FUNCTIONS_FULL = "Full functions call stack"; const string ERROR_STACK_INVALID_TYPE = "Invalid type"; const int MAX_STACK = 1024; const int MAX_STACK_FUNCTIONS = 512; public class InfoStackFunctions { public int numberVars; public int offsetVars; public int offsetStack; public int instruction; public Function functions; }; private int stackPos; private DataType.DataTypeEnum[] dataTypes = new DataType.DataTypeEnum[MAX_STACK + 1]; private object[] values = new object[MAX_STACK + 1]; private int stackFunctionsPos; private InfoStackFunctions[] stackFunctions = new InfoStackFunctions[MAX_STACK_FUNCTIONS]; private int numberOfVars; private int offsetVars; private int offsetStack; public Stack() { this.stackPos = -1; this.offsetStack = -1; this.offsetVars = 0; this.numberOfVars = 0; this.stackFunctionsPos = 0; for (int i = 0; i < MAX_STACK_FUNCTIONS; i++) stackFunctions[i] = new InfoStackFunctions(); } public void Clear() { this.offsetStack = -1; this.offsetVars = 0; this.numberOfVars = 0; this.stackFunctionsPos = 0; for (int i = 0; i < MAX_STACK_FUNCTIONS; i++) stackFunctions[i].functions = null; while(this.stackPos >= 0) Pop(); } private void ThrowRuntimeErrorIf(bool condition, string description) { if (condition) throw new RuntimeError(description); } public void PushInt(int val) { ThrowRuntimeErrorIf(this.stackPos == MAX_STACK, ERROR_STACK_FULL); this.stackPos++; this.dataTypes[this.stackPos] = DataType.DataTypeEnum.TYPE_INT; this.values[this.stackPos] = val; } public void PushFloat(float val) { ThrowRuntimeErrorIf(this.stackPos == MAX_STACK, ERROR_STACK_FULL); this.stackPos++; this.dataTypes[this.stackPos] = DataType.DataTypeEnum.TYPE_FLOAT; this.values[this.stackPos] = val; } public void PushString(string val) { ThrowRuntimeErrorIf(this.stackPos == MAX_STACK, ERROR_STACK_FULL); this.stackPos++; this.dataTypes[this.stackPos] = DataType.DataTypeEnum.TYPE_STRING; this.values[this.stackPos] = val; } public void Pop() { ThrowRuntimeErrorIf(this.stackPos == this.offsetStack, ERROR_STACK_EMPTY); this.stackPos--; } public int PopInt() { ThrowRuntimeErrorIf(this.stackPos == this.offsetStack, ERROR_STACK_EMPTY); ThrowRuntimeErrorIf(this.dataTypes[this.stackPos] != DataType.DataTypeEnum.TYPE_INT, ERROR_STACK_INVALID_TYPE); return((int) this.values[this.stackPos--]); } public float PopFloat() { ThrowRuntimeErrorIf(this.stackPos == this.offsetStack, ERROR_STACK_EMPTY); ThrowRuntimeErrorIf(this.dataTypes[this.stackPos] != DataType.DataTypeEnum.TYPE_FLOAT, ERROR_STACK_INVALID_TYPE); return((float) this.values[this.stackPos--]); } public string PopString() { ThrowRuntimeErrorIf(this.stackPos == this.offsetStack, ERROR_STACK_EMPTY); ThrowRuntimeErrorIf(this.dataTypes[this.stackPos] != DataType.DataTypeEnum.TYPE_STRING, ERROR_STACK_INVALID_TYPE); return (string) this.values[this.stackPos--]; } public void Duplicate() { ThrowRuntimeErrorIf(this.stackPos == this.offsetStack, ERROR_STACK_EMPTY); ThrowRuntimeErrorIf(this.stackPos == MAX_STACK, ERROR_STACK_FULL); this.dataTypes[this.stackPos + 1] = this.dataTypes[this.stackPos]; this.values[this.stackPos + 1] = this.values[this.stackPos]; this.stackPos++; } public int GetNumberOfElementsInStack() { return (this.stackPos - this.offsetStack); } public DataType.DataTypeEnum GetLastElementDataType() { ThrowRuntimeErrorIf(this.stackPos == this.offsetStack, ERROR_STACK_EMPTY); return(this.dataTypes[this.stackPos]); } public void PushFunctionCall(int parameters, int vars, Function function, int instruction) { ThrowRuntimeErrorIf(this.stackPos - parameters + vars >= MAX_STACK, ERROR_STACK_FULL); ThrowRuntimeErrorIf(this.stackFunctionsPos + 1 == MAX_STACK_FUNCTIONS, ERROR_STACK_FUNCTIONS_FULL); this.stackFunctionsPos++; InfoStackFunctions infoStack = this.stackFunctions[this.stackFunctionsPos]; infoStack.numberVars = this.numberOfVars; infoStack.offsetStack = this.offsetStack; infoStack.offsetVars = this.offsetVars; infoStack.instruction = instruction; infoStack.functions = function; this.offsetVars = this.stackPos + 1 - parameters; this.offsetStack = this.offsetVars + vars - 1; this.numberOfVars = vars; this.stackPos = this.offsetStack; } public void IncrementInt() { ThrowRuntimeErrorIf(this.stackPos == this.offsetStack, ERROR_STACK_EMPTY); ThrowRuntimeErrorIf(this.dataTypes[this.stackPos] != DataType.DataTypeEnum.TYPE_INT, ERROR_STACK_INVALID_TYPE); int v = (int) this.values[this.stackPos]; v++; this.values[this.stackPos] = v; } public void DecrementInt() { ThrowRuntimeErrorIf(this.stackPos == this.offsetStack, ERROR_STACK_EMPTY); ThrowRuntimeErrorIf(this.dataTypes[this.stackPos] != DataType.DataTypeEnum.TYPE_INT, ERROR_STACK_INVALID_TYPE); int v = (int) this.values[this.stackPos]; v--; this.values[this.stackPos] = v; } public InfoStackFunctions GetLastFunctionCall() { return(this.stackFunctions[this.stackFunctionsPos]); } public void PopFunctionCall() { while(this.stackPos >= this.offsetVars) this.values[this.stackPos--] = null; InfoStackFunctions infoStack = this.stackFunctions[this.stackFunctionsPos]; this.numberOfVars = infoStack.numberVars; this.offsetVars = infoStack.offsetVars; this.offsetStack = infoStack.offsetStack; this.stackFunctionsPos--; } public int GetNumberOfElementsInFunctionCallStack() { return(this.stackFunctionsPos); } public DataType.DataTypeEnum GetVarDataType(int n) { //Chequeo no necesario porque chequeo todos los indices en CDefinicionObjeto::PrvValidarFuncion //ThrowErrorEjecucionSi(n >= this.cantVars, "Numero de variable invalido"); return(this.dataTypes[n + this.offsetVars]); } public void SetVarInt(int n, int val) { //Chequeo no necesario porque chequeo todos los indices en CDefinicionObjeto::PrvValidarFuncion //ThrowErrorEjecucionSi(n >= this.cantVars, "Numero de variable invalido"); n += this.offsetVars; this.dataTypes[n] = DataType.DataTypeEnum.TYPE_INT; this.values[n] = val; } public void SetVarFloat(int n, float val) { //Chequeo no necesario porque chequeo todos los indices en CDefinicionObjeto::PrvValidarFuncion //ThrowErrorEjecucionSi(n >= this.cantVars, "Numero de variable invalido"); n += this.offsetVars; this.dataTypes[n] = DataType.DataTypeEnum.TYPE_FLOAT; this.values[n] = val; } public void SetVarString(int n, string val) { //Chequeo no necesario porque chequeo todos los indices en CDefinicionObjeto::PrvValidarFuncion //ThrowErrorEjecucionSi(n >= this.cantVars, "Numero de variable invalido"); n += this.offsetVars; this.dataTypes[n] = DataType.DataTypeEnum.TYPE_STRING; this.values[n] = val; } public int GetVarInt(int n) { //Chequeo no necesario porque chequeo todos los indices en CDefinicionObjeto::PrvValidarFuncion //ThrowErrorEjecucionSi(n >= this.cantVars, "Numero de variable invalido"); n += this.offsetVars; ThrowRuntimeErrorIf(this.dataTypes[n] != DataType.DataTypeEnum.TYPE_INT, "Tipo de variable incorrecto"); return (int) this.values[n]; } public float GetVarFloat(int n) { //Chequeo no necesario porque chequeo todos los indices en CDefinicionObjeto::PrvValidarFuncion //ThrowErrorEjecucionSi(n >= this.cantVars, "Numero de variable invalido"); n += this.offsetVars; ThrowRuntimeErrorIf(this.dataTypes[n] != DataType.DataTypeEnum.TYPE_FLOAT, "Tipo de variable incorrecto"); return (float) this.values[n]; } public string GetVarString(int n) { //Chequeo no necesario porque chequeo todos los indices en CDefinicionObjeto::PrvValidarFuncion //ThrowErrorEjecucionSi(n >= this.cantVars, "Numero de variable invalido"); n += this.offsetVars; ThrowRuntimeErrorIf(this.dataTypes[n] != DataType.DataTypeEnum.TYPE_STRING, "Tipo de variable incorrecto"); ThrowRuntimeErrorIf(this.values[n] == null, "El valor almacenado en la variable es NULL, no puede obtenerse este valor"); return (string) this.values[n]; } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Management.Automation.Language; using System.Text; namespace System.Management.Automation { internal class MergedCommandParameterMetadata { /// <summary> /// Replaces any existing metadata in this object with the metadata specified. /// /// Note that this method should NOT be called after a MergedCommandParameterMetadata /// instance is made read only by calling MakeReadOnly(). This is because MakeReadOnly() /// will turn 'bindableParameters', 'aliasedParameters' and 'parameterSetMap' into /// ReadOnlyDictionary and ReadOnlyCollection. /// </summary> /// <param name="metadata"> /// The metadata to replace in this object. /// </param> /// <returns> /// A list of the merged parameter metadata that was added. /// </returns> internal List<MergedCompiledCommandParameter> ReplaceMetadata(MergedCommandParameterMetadata metadata) { var result = new List<MergedCompiledCommandParameter>(); // Replace bindable parameters _bindableParameters.Clear(); foreach (KeyValuePair<string, MergedCompiledCommandParameter> entry in metadata.BindableParameters) { _bindableParameters.Add(entry.Key, entry.Value); result.Add(entry.Value); } _aliasedParameters.Clear(); foreach (KeyValuePair<string, MergedCompiledCommandParameter> entry in metadata.AliasedParameters) { _aliasedParameters.Add(entry.Key, entry.Value); } // Replace additional meta info _defaultParameterSetName = metadata._defaultParameterSetName; _nextAvailableParameterSetIndex = metadata._nextAvailableParameterSetIndex; _parameterSetMap.Clear(); var parameterSetMapInList = (List<string>)_parameterSetMap; parameterSetMapInList.AddRange(metadata._parameterSetMap); Diagnostics.Assert(ParameterSetCount == _nextAvailableParameterSetIndex, "After replacement with the metadata of the new parameters, ParameterSetCount should be equal to nextAvailableParameterSetIndex"); return result; } /// <summary> /// Merges the specified metadata with the other metadata already defined /// in this object. /// </summary> /// <param name="parameterMetadata"> /// The compiled metadata for the type to be merged. /// </param> /// <param name="binderAssociation"> /// The type of binder that the CommandProcessor will use to bind /// the parameters for <paramref name="parameterMetadata"/> /// </param> /// <returns> /// A collection of the merged parameter metadata that was added. /// </returns> /// <exception cref="MetadataException"> /// If a parameter name or alias described in the <paramref name="parameterMetadata"/> already /// exists. /// </exception> internal Collection<MergedCompiledCommandParameter> AddMetadataForBinder( InternalParameterMetadata parameterMetadata, ParameterBinderAssociation binderAssociation) { if (parameterMetadata == null) { throw PSTraceSource.NewArgumentNullException(nameof(parameterMetadata)); } Collection<MergedCompiledCommandParameter> result = new Collection<MergedCompiledCommandParameter>(); // Merge in the bindable parameters foreach (KeyValuePair<string, CompiledCommandParameter> bindableParameter in parameterMetadata.BindableParameters) { if (_bindableParameters.ContainsKey(bindableParameter.Key)) { MetadataException exception = new MetadataException( "ParameterNameAlreadyExistsForCommand", null, Metadata.ParameterNameAlreadyExistsForCommand, bindableParameter.Key); throw exception; } // NTRAID#Windows Out Of Band Releases-926371-2005/12/27-JonN if (_aliasedParameters.ContainsKey(bindableParameter.Key)) { MetadataException exception = new MetadataException( "ParameterNameConflictsWithAlias", null, Metadata.ParameterNameConflictsWithAlias, bindableParameter.Key, RetrieveParameterNameForAlias(bindableParameter.Key, _aliasedParameters)); throw exception; } MergedCompiledCommandParameter mergedParameter = new MergedCompiledCommandParameter(bindableParameter.Value, binderAssociation); _bindableParameters.Add(bindableParameter.Key, mergedParameter); result.Add(mergedParameter); // Merge in the aliases foreach (string aliasName in bindableParameter.Value.Aliases) { if (_aliasedParameters.ContainsKey(aliasName)) { MetadataException exception = new MetadataException( "AliasParameterNameAlreadyExistsForCommand", null, Metadata.AliasParameterNameAlreadyExistsForCommand, aliasName); throw exception; } // NTRAID#Windows Out Of Band Releases-926371-2005/12/27-JonN if (_bindableParameters.ContainsKey(aliasName)) { MetadataException exception = new MetadataException( "ParameterNameConflictsWithAlias", null, Metadata.ParameterNameConflictsWithAlias, RetrieveParameterNameForAlias(aliasName, _bindableParameters), bindableParameter.Value.Name); throw exception; } _aliasedParameters.Add(aliasName, mergedParameter); } } return result; } /// <summary> /// The next available parameter set bit. This number increments but the parameter /// set bit is really 1 shifted left this number of times. This number also acts /// as the index for the parameter set map. /// </summary> private uint _nextAvailableParameterSetIndex; /// <summary> /// Gets the number of parameter sets that were declared for the command. /// </summary> internal int ParameterSetCount { get { return _parameterSetMap.Count; } } /// <summary> /// Gets a bit-field representing all valid parameter sets. /// </summary> internal uint AllParameterSetFlags { get { return (1u << ParameterSetCount) - 1; } } /// <summary> /// This is the parameter set map. The index is the number of times 1 gets shifted /// left to specify the bit field marker for the parameter set. /// The value is the parameter set name. /// New parameter sets are added at the nextAvailableParameterSetIndex. /// </summary> private IList<string> _parameterSetMap = new List<string>(); /// <summary> /// The name of the default parameter set. /// </summary> private string _defaultParameterSetName; /// <summary> /// Adds the parameter set name to the parameter set map and returns the /// index. If the parameter set name was already in the map, the index to /// the existing parameter set name is returned. /// </summary> /// <param name="parameterSetName"> /// The name of the parameter set to add. /// </param> /// <returns> /// The index of the parameter set name. If the name didn't already exist the /// name gets added and the new index is returned. If the name already exists /// the index of the existing name is returned. /// </returns> /// <remarks> /// The nextAvailableParameterSetIndex is incremented if the parameter set name /// is added. /// </remarks> /// <exception cref="ParsingMetadataException"> /// If more than uint.MaxValue parameter-sets are defined for the command. /// </exception> private int AddParameterSetToMap(string parameterSetName) { int index = -1; if (!string.IsNullOrEmpty(parameterSetName)) { index = _parameterSetMap.IndexOf(parameterSetName); // A parameter set name should only be added once if (index == -1) { if (_nextAvailableParameterSetIndex == uint.MaxValue) { // Don't let the parameter set index overflow ParsingMetadataException parsingException = new ParsingMetadataException( "ParsingTooManyParameterSets", null, Metadata.ParsingTooManyParameterSets); throw parsingException; } _parameterSetMap.Add(parameterSetName); index = _parameterSetMap.IndexOf(parameterSetName); Diagnostics.Assert( index == _nextAvailableParameterSetIndex, "AddParameterSetToMap should always add the parameter set name to the map at the nextAvailableParameterSetIndex"); _nextAvailableParameterSetIndex++; } } return index; } /// <summary> /// Loops through all the parameters and retrieves the parameter set names. In the process /// it generates a mapping of parameter set names to the bits in the bit-field and sets /// the parameter set flags for the parameter. /// </summary> /// <param name="defaultParameterSetName"> /// The default parameter set name. /// </param> /// <returns> /// The bit flag for the default parameter set. /// </returns> /// <exception cref="ParsingMetadataException"> /// If more than uint.MaxValue parameter-sets are defined for the command. /// </exception> internal uint GenerateParameterSetMappingFromMetadata(string defaultParameterSetName) { // First clear the parameter set map _parameterSetMap.Clear(); _nextAvailableParameterSetIndex = 0; uint defaultParameterSetFlag = 0; if (!string.IsNullOrEmpty(defaultParameterSetName)) { _defaultParameterSetName = defaultParameterSetName; // Add the default parameter set to the parameter set map int index = AddParameterSetToMap(defaultParameterSetName); defaultParameterSetFlag = (uint)1 << index; } // Loop through all the parameters and then each parameter set for each parameter foreach (MergedCompiledCommandParameter parameter in BindableParameters.Values) { // For each parameter we need to generate a bit-field for the parameter sets // that the parameter is a part of. uint parameterSetBitField = 0; foreach (var keyValuePair in parameter.Parameter.ParameterSetData) { var parameterSetName = keyValuePair.Key; var parameterSetData = keyValuePair.Value; if (string.Equals(parameterSetName, ParameterAttribute.AllParameterSets, StringComparison.OrdinalIgnoreCase)) { // Don't add the parameter set name but assign the bit field zero and then mark the bool parameterSetData.ParameterSetFlag = 0; parameterSetData.IsInAllSets = true; parameter.Parameter.IsInAllSets = true; } else { // Add the parameter set name and/or get the index in the map int index = AddParameterSetToMap(parameterSetName); Diagnostics.Assert( index >= 0, "AddParameterSetToMap should always be able to add the parameter set name, if not it should throw"); // Calculate the bit for this parameter set uint parameterSetBit = (uint)1 << index; // Add the bit to the bit-field parameterSetBitField |= parameterSetBit; // Add the bit to the parameter set specific data parameterSetData.ParameterSetFlag = parameterSetBit; } } // Set the bit field in the parameter parameter.Parameter.ParameterSetFlags = parameterSetBitField; } return defaultParameterSetFlag; } /// <summary> /// Gets the parameter set name for the specified parameter set. /// </summary> /// <param name="parameterSet"> /// The parameter set to get the name for. /// </param> /// <returns> /// The name of the specified parameter set. /// </returns> internal string GetParameterSetName(uint parameterSet) { string result = _defaultParameterSetName; if (string.IsNullOrEmpty(result)) { result = ParameterAttribute.AllParameterSets; } if (parameterSet != uint.MaxValue && parameterSet != 0) { // Count the number of right shifts it takes to hit the parameter set // This is the index into the parameter set map. int index = 0; while (((parameterSet >> index) & 0x1) == 0) { ++index; } // Now check to see if there are any remaining sets passed this bit. // If so return string.Empty if (((parameterSet >> (index + 1)) & 0x1) == 0) { // Ensure that the bit found was within the map, if not return an empty string if (index < _parameterSetMap.Count) { result = _parameterSetMap[index]; } else { result = string.Empty; } } else { result = string.Empty; } } return result; } /// <summary> /// Helper function to retrieve the name of the parameter /// which defined an alias. /// </summary> /// <param name="key"></param> /// <param name="dict"></param> /// <returns></returns> private static string RetrieveParameterNameForAlias( string key, IDictionary<string, MergedCompiledCommandParameter> dict) { MergedCompiledCommandParameter mergedParam = dict[key]; if (mergedParam != null) { CompiledCommandParameter compiledParam = mergedParam.Parameter; if (compiledParam != null) { if (!string.IsNullOrEmpty(compiledParam.Name)) return compiledParam.Name; } } return string.Empty; } /// <summary> /// Gets the parameters by matching its name. /// </summary> /// <param name="name"> /// The name of the parameter. /// </param> /// <param name="throwOnParameterNotFound"> /// If true and a matching parameter is not found, an exception will be /// throw. If false and a matching parameter is not found, null is returned. /// </param> /// <param name="tryExactMatching"> /// If true we do exact matching, otherwise we do not. /// </param> /// <param name="invocationInfo"> /// The invocation information about the code being run. /// </param> /// <returns> /// The a collection of the metadata associated with the parameters that /// match the specified name. If no matches were found, an empty collection /// is returned. /// </returns> /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// </exception> internal MergedCompiledCommandParameter GetMatchingParameter( string name, bool throwOnParameterNotFound, bool tryExactMatching, InvocationInfo invocationInfo) { if (string.IsNullOrEmpty(name)) { throw PSTraceSource.NewArgumentException(nameof(name)); } Collection<MergedCompiledCommandParameter> matchingParameters = new Collection<MergedCompiledCommandParameter>(); // Skip the leading '-' if present if (name.Length > 0 && CharExtensions.IsDash(name[0])) { name = name.Substring(1); } // First try to match the bindable parameters foreach (string parameterName in _bindableParameters.Keys) { if (CultureInfo.InvariantCulture.CompareInfo.IsPrefix(parameterName, name, CompareOptions.IgnoreCase)) { // If it is an exact match then only return the exact match // as the result if (tryExactMatching && string.Equals(parameterName, name, StringComparison.OrdinalIgnoreCase)) { return _bindableParameters[parameterName]; } else { matchingParameters.Add(_bindableParameters[parameterName]); } } } // Now check the aliases foreach (string parameterName in _aliasedParameters.Keys) { if (CultureInfo.InvariantCulture.CompareInfo.IsPrefix(parameterName, name, CompareOptions.IgnoreCase)) { // If it is an exact match then only return the exact match // as the result if (tryExactMatching && string.Equals(parameterName, name, StringComparison.OrdinalIgnoreCase)) { return _aliasedParameters[parameterName]; } else { if (!matchingParameters.Contains(_aliasedParameters[parameterName])) { matchingParameters.Add(_aliasedParameters[parameterName]); } } } } if (matchingParameters.Count > 1) { // Prefer parameters in the cmdlet over common parameters Collection<MergedCompiledCommandParameter> filteredParameters = new Collection<MergedCompiledCommandParameter>(); foreach (MergedCompiledCommandParameter matchingParameter in matchingParameters) { if ((matchingParameter.BinderAssociation == ParameterBinderAssociation.DeclaredFormalParameters) || (matchingParameter.BinderAssociation == ParameterBinderAssociation.DynamicParameters)) { filteredParameters.Add(matchingParameter); } } if (tryExactMatching && filteredParameters.Count == 1) { matchingParameters = filteredParameters; } else { StringBuilder possibleMatches = new StringBuilder(); foreach (MergedCompiledCommandParameter matchingParameter in matchingParameters) { possibleMatches.Append(" -"); possibleMatches.Append(matchingParameter.Parameter.Name); } ParameterBindingException exception = new ParameterBindingException( ErrorCategory.InvalidArgument, invocationInfo, null, name, null, null, ParameterBinderStrings.AmbiguousParameter, "AmbiguousParameter", possibleMatches); throw exception; } } else if (matchingParameters.Count == 0) { if (throwOnParameterNotFound) { ParameterBindingException exception = new ParameterBindingException( ErrorCategory.InvalidArgument, invocationInfo, null, name, null, null, ParameterBinderStrings.NamedParameterNotFound, "NamedParameterNotFound"); throw exception; } } MergedCompiledCommandParameter result = null; if (matchingParameters.Count > 0) { result = matchingParameters[0]; } return result; } /// <summary> /// Gets a collection of all the parameters that are allowed in the parameter set. /// </summary> /// <param name="parameterSetFlag"> /// The bit representing the parameter set from which the parameters should be retrieved. /// </param> /// <returns> /// A collection of all the parameters in the specified parameter set. /// </returns> internal Collection<MergedCompiledCommandParameter> GetParametersInParameterSet(uint parameterSetFlag) { Collection<MergedCompiledCommandParameter> result = new Collection<MergedCompiledCommandParameter>(); foreach (MergedCompiledCommandParameter parameter in BindableParameters.Values) { if ((parameterSetFlag & parameter.Parameter.ParameterSetFlags) != 0 || parameter.Parameter.IsInAllSets) { result.Add(parameter); } } return result; } /// <summary> /// Gets a dictionary of the compiled parameter metadata for this Type. /// The dictionary keys are the names of the parameters and /// the values are the compiled parameter metadata. /// </summary> internal IDictionary<string, MergedCompiledCommandParameter> BindableParameters { get { return _bindableParameters; } } private IDictionary<string, MergedCompiledCommandParameter> _bindableParameters = new Dictionary<string, MergedCompiledCommandParameter>(StringComparer.OrdinalIgnoreCase); /// <summary> /// Gets a dictionary of the parameters that have been aliased to other names. The key is /// the alias name and the value is the MergedCompiledCommandParameter metadata. /// </summary> internal IDictionary<string, MergedCompiledCommandParameter> AliasedParameters { get { return _aliasedParameters; } } private IDictionary<string, MergedCompiledCommandParameter> _aliasedParameters = new Dictionary<string, MergedCompiledCommandParameter>(StringComparer.OrdinalIgnoreCase); internal void MakeReadOnly() { _bindableParameters = new ReadOnlyDictionary<string, MergedCompiledCommandParameter>(_bindableParameters); _aliasedParameters = new ReadOnlyDictionary<string, MergedCompiledCommandParameter>(_aliasedParameters); _parameterSetMap = new ReadOnlyCollection<string>(_parameterSetMap); } internal void ResetReadOnly() { _bindableParameters = new Dictionary<string, MergedCompiledCommandParameter>(_bindableParameters, StringComparer.OrdinalIgnoreCase); _aliasedParameters = new Dictionary<string, MergedCompiledCommandParameter>(_aliasedParameters, StringComparer.OrdinalIgnoreCase); } } /// <summary> /// Makes an association between a CompiledCommandParameter and the type /// of the parameter binder used to bind the parameter. /// </summary> internal class MergedCompiledCommandParameter { /// <summary> /// Constructs an association between the CompiledCommandParameter and the /// binder that should be used to bind it. /// </summary> /// <param name="parameter"> /// The metadata for a parameter. /// </param> /// <param name="binderAssociation"> /// The type of binder that should be used to bind the parameter. /// </param> internal MergedCompiledCommandParameter( CompiledCommandParameter parameter, ParameterBinderAssociation binderAssociation) { Diagnostics.Assert(parameter != null, "caller to verify parameter is not null"); this.Parameter = parameter; this.BinderAssociation = binderAssociation; } /// <summary> /// Gets the compiled command parameter for the association. /// </summary> internal CompiledCommandParameter Parameter { get; } /// <summary> /// Gets the type of binder that the compiled command parameter should be bound with. /// </summary> internal ParameterBinderAssociation BinderAssociation { get; } public override string ToString() { return Parameter.ToString(); } } /// <summary> /// This enum is used in the MergedCompiledCommandParameter class /// to associate a particular CompiledCommandParameter with the /// appropriate ParameterBinder. /// </summary> internal enum ParameterBinderAssociation { /// <summary> /// The parameter was declared as a formal parameter in the command type. /// </summary> DeclaredFormalParameters, /// <summary> /// The parameter was declared as a dynamic parameter for the command. /// </summary> DynamicParameters, /// <summary> /// The parameter is a common parameter found in the CommonParameters class. /// </summary> CommonParameters, /// <summary> /// The parameter is a ShouldProcess parameter found in the ShouldProcessParameters class. /// </summary> ShouldProcessParameters, /// <summary> /// The parameter is a transactions parameter found in the TransactionParameters class. /// </summary> TransactionParameters, /// <summary> /// The parameter is a Paging parameter found in the PagingParameters class. /// </summary> PagingParameters, } }
// // Util.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Text; using Xwt.Backends; using Xwt.Drawing; #if MONOMAC using nfloat = System.Single; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; using MonoMac.AppKit; using MonoMac.CoreGraphics; using MonoMac.CoreImage; using MonoMac.Foundation; using MonoMac.ObjCRuntime; #else using AppKit; using CoreGraphics; using CoreImage; using Foundation; using ObjCRuntime; #endif using RectangleF = System.Drawing.RectangleF; using SizeF = System.Drawing.SizeF; namespace Xwt.Mac { public static class Util { public static readonly string DeviceRGBString = NSColorSpace.DeviceRGB.ToString (); static CGColorSpace deviceRGB, pattern; public static CGColorSpace DeviceRGBColorSpace { get { if (deviceRGB == null) deviceRGB = CGColorSpace.CreateDeviceRGB (); return deviceRGB; } } public static CGColorSpace PatternColorSpace { get { if (pattern == null) pattern = CGColorSpace.CreatePattern (null); return pattern; } } public static double WidgetX (this NSView v) { return (double) v.Frame.X; } public static double WidgetY (this NSView v) { return (double) v.Frame.Y; } public static double WidgetWidth (this NSView v) { return (double) (v.Frame.Width); } public static double WidgetHeight (this NSView v) { return (double) (v.Frame.Height); } public static Rectangle WidgetBounds (this NSView v) { return new Rectangle (v.WidgetX(), v.WidgetY(), v.WidgetWidth(), v.WidgetHeight()); } public static void SetWidgetBounds (this NSView v, Rectangle rect) { nfloat y = (nfloat)rect.Y; if (v.Superview != null) y = v.Superview.Frame.Height - y - (float)rect.Height; v.Frame = new CGRect ((nfloat)rect.X, y, (nfloat)rect.Width, (nfloat)rect.Height); } public static Alignment ToAlignment (this NSTextAlignment align) { switch (align) { case NSTextAlignment.Center: return Alignment.Center; case NSTextAlignment.Right: return Alignment.End; default: return Alignment.Start; } } public static NSTextAlignment ToNSTextAlignment (this Alignment align) { switch (align) { case Alignment.Center: return NSTextAlignment.Center; case Alignment.End: return NSTextAlignment.Right; default: return NSTextAlignment.Left; } } public static NSColor ToNSColor (this Color col) { return NSColor.FromDeviceRgba ((float)col.Red, (float)col.Green, (float)col.Blue, (float)col.Alpha); } static readonly CGColorSpace DeviceRgbColorSpace = CGColorSpace.CreateDeviceRGB (); public static CGColor ToCGColor (this Color col) { return new CGColor (DeviceRgbColorSpace, new nfloat[] { (nfloat)col.Red, (nfloat)col.Green, (nfloat)col.Blue, (nfloat)col.Alpha }); } public static Color ToXwtColor (this NSColor col) { col = col.UsingColorSpace (DeviceRGBString); return new Color (col.RedComponent, col.GreenComponent, col.BlueComponent, col.AlphaComponent); } public static Color ToXwtColor (this CGColor col) { var cs = col.Components; return new Color (cs[0], cs[1], cs[2], col.Alpha); } public static Size ToXwtSize (this CGSize s) { return new Size (s.Width, s.Height); } public static CGRect ToCGRect (this Rectangle r) { return new CGRect ((nfloat)r.X, (nfloat)r.Y, (nfloat)r.Width, (nfloat)r.Height); } // /System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Headers/IconsCore.h public static int ToIconType (string id) { switch (id) { case StockIconId.Error: return 1937010544; // 'stop' case StockIconId.Warning: return 1667331444; // 'caut' case StockIconId.Information: return 1852798053; // 'note' case StockIconId.Question: return 1903519091; // 'ques' case StockIconId.Remove: return 1952736620; // 'tdel' } return 0; } /* To get the above int values, pass the four char code thru this: public static int C (string code) { return ((int)code[0]) << 24 | ((int)code[1]) << 16 | ((int)code[2]) << 8 | ((int)code[3]); } */ public static SizeF ToIconSize (IconSize size) { switch (size) { case IconSize.Small: return new SizeF (16f, 16f); case IconSize.Large: return new SizeF (64f, 64f); } return new SizeF (32f, 32f); } public static string ToUTI (this TransferDataType dt) { if (dt == TransferDataType.Uri) return NSPasteboard.NSUrlType; if (dt == TransferDataType.Text) return NSPasteboard.NSStringType; if (dt == TransferDataType.Rtf) return NSPasteboard.NSRtfType; if (dt == TransferDataType.Html) return NSPasteboard.NSHtmlType; if (dt == TransferDataType.Image) return NSPasteboard.NSTiffType; return dt.Id; } #if MONOMAC static Selector selCopyWithZone = new Selector ("copyWithZone:"); static DateTime lastCopyPoolDrain = DateTime.Now; static List<object> copyPool = new List<object> (); /// <summary> /// Implements the NSCopying protocol in a class. The class must implement ICopiableObject. /// The method ICopiableObject.CopyFrom will be called to make the copy of the object /// </summary> /// <typeparam name="T">Type for which to enable copying</typeparam> public static void MakeCopiable<T> () where T:ICopiableObject { Class c = new Class (typeof(T)); c.AddMethod (selCopyWithZone.Handle, new Func<IntPtr, IntPtr, IntPtr, IntPtr> (MakeCopy), "i@:@"); } static IntPtr MakeCopy (IntPtr sender, IntPtr sel, IntPtr zone) { var thisOb = (ICopiableObject) Runtime.GetNSObject (sender); // Makes a copy of the object by calling the default implementation of copyWithZone IntPtr copyHandle = Messaging.IntPtr_objc_msgSendSuper_IntPtr(((NSObject)thisOb).SuperHandle, selCopyWithZone.Handle, zone); var copyOb = (ICopiableObject) Runtime.GetNSObject (copyHandle); // Copy of managed data copyOb.CopyFrom (thisOb); // Copied objects are for internal use of the Cocoa framework. We need to keep a reference of the // managed object until the the framework doesn't need it anymore. if ((DateTime.Now - lastCopyPoolDrain).TotalSeconds > 2) DrainObjectCopyPool (); copyPool.Add (copyOb); return ((NSObject)copyOb).Handle; } public static void DrainObjectCopyPool () { // Objects in the pool have been created by Cocoa, so there should be no managed references // other than the ones we keep in the pool. An object can be removed from the pool if it // has only 1 reference left (the managed one) List<NSObject> markedForDelete = new List<NSObject> (); foreach (NSObject ob in copyPool) { var count = ob.RetainCount; if (count == 1) markedForDelete.Add (ob); } foreach (NSObject ob in markedForDelete) copyPool.Remove (ob); lastCopyPoolDrain = DateTime.Now; } #else public static void MakeCopiable<T> () where T:ICopiableObject { // Nothing to do for XamMac } public static void DrainObjectCopyPool () { // Nothing to do for XamMac } #endif public static NSBitmapImageFileType ToMacFileType (this ImageFileType type) { switch (type) { case ImageFileType.Png: return NSBitmapImageFileType.Png; case ImageFileType.Jpeg: return NSBitmapImageFileType.Jpeg; case ImageFileType.Bmp: return NSBitmapImageFileType.Bmp; default: throw new NotSupportedException (); } } public static NSImage ToNSImage (this ImageDescription idesc) { if (idesc.IsNull) return null; var img = (NSImage)idesc.Backend; if (img is CustomImage) img = ((CustomImage)img).Clone (); else { img = (NSImage)img.Copy (); } img.Size = new System.Drawing.SizeF ((float)idesc.Size.Width, (float)idesc.Size.Height); return img; } public static int ToUnderlineStyle (FontStyle style) { return 1; } static Selector applyFontTraits = new Selector ("applyFontTraits:range:"); public static NSAttributedString ToAttributedString (this FormattedText ft) { NSMutableAttributedString ns = new NSMutableAttributedString (ft.Text); ns.BeginEditing (); foreach (var att in ft.Attributes) { var r = new NSRange (att.StartIndex, att.Count); if (att is BackgroundTextAttribute) { var xa = (BackgroundTextAttribute)att; ns.AddAttribute (NSAttributedString.BackgroundColorAttributeName, xa.Color.ToNSColor (), r); } else if (att is ColorTextAttribute) { var xa = (ColorTextAttribute)att; ns.AddAttribute (NSAttributedString.ForegroundColorAttributeName, xa.Color.ToNSColor (), r); } else if (att is UnderlineTextAttribute) { var xa = (UnderlineTextAttribute)att; int style = xa.Underline ? 0x01 /*NSUnderlineStyleSingle*/ : 0; ns.AddAttribute (NSAttributedString.UnderlineStyleAttributeName, (NSNumber)style, r); } else if (att is FontStyleTextAttribute) { var xa = (FontStyleTextAttribute)att; if (xa.Style == FontStyle.Italic) { Messaging.void_objc_msgSend_int_NSRange (ns.Handle, applyFontTraits.Handle, (IntPtr)(long)NSFontTraitMask.Italic, r); } else if (xa.Style == FontStyle.Oblique) { ns.AddAttribute (NSAttributedString.ObliquenessAttributeName, (NSNumber)0.2f, r); } else { ns.AddAttribute (NSAttributedString.ObliquenessAttributeName, (NSNumber)0.0f, r); Messaging.void_objc_msgSend_int_NSRange (ns.Handle, applyFontTraits.Handle, (IntPtr)(long)NSFontTraitMask.Unitalic, r); } } else if (att is FontWeightTextAttribute) { var xa = (FontWeightTextAttribute)att; var trait = xa.Weight >= FontWeight.Bold ? NSFontTraitMask.Bold : NSFontTraitMask.Unbold; Messaging.void_objc_msgSend_int_NSRange (ns.Handle, applyFontTraits.Handle, (IntPtr)(long) trait, r); } else if (att is LinkTextAttribute) { var xa = (LinkTextAttribute)att; ns.AddAttribute (NSAttributedString.LinkAttributeName, new NSUrl (xa.Target.ToString ()), r); ns.AddAttribute (NSAttributedString.ForegroundColorAttributeName, NSColor.Blue, r); ns.AddAttribute (NSAttributedString.UnderlineStyleAttributeName, NSNumber.FromInt32 ((int)NSUnderlineStyle.Single), r); } else if (att is StrikethroughTextAttribute) { var xa = (StrikethroughTextAttribute)att; int style = xa.Strikethrough ? 0x01 /*NSUnderlineStyleSingle*/ : 0; ns.AddAttribute (NSAttributedString.StrikethroughStyleAttributeName, (NSNumber)style, r); } else if (att is FontTextAttribute) { var xa = (FontTextAttribute)att; var nf = ((FontData)Toolkit.GetBackend (xa.Font)).Font; ns.AddAttribute (NSAttributedString.FontAttributeName, nf, r); } } ns.EndEditing (); return ns; } /// <summary> /// Removes the mnemonics (underscore character) from a string. /// </summary> /// <returns>The string with the mnemonics unescaped.</returns> /// <param name="text">The string.</param> /// <remarks> /// Single underscores are removed. Double underscores are replaced with single underscores (unescaped). /// </remarks> public static string RemoveMnemonic(this string str) { if (str == null) return null; var newText = new StringBuilder (); for (int i = 0; i < str.Length; i++) { if (str [i] != '_') newText.Append (str [i]); else if (i < str.Length && str [i + 1] == '_') { newText.Append ('_'); i++; } } return newText.ToString (); } public static CheckBoxState ToXwtState (this NSCellStateValue state) { switch (state) { case NSCellStateValue.Mixed: return CheckBoxState.Mixed; case NSCellStateValue.On: return CheckBoxState.On; case NSCellStateValue.Off: return CheckBoxState.Off; default: throw new ArgumentOutOfRangeException (); } } public static NSCellStateValue ToMacState (this CheckBoxState state) { switch (state) { case CheckBoxState.Mixed: return NSCellStateValue.Mixed; case CheckBoxState.On: return NSCellStateValue.On; case CheckBoxState.Off: return NSCellStateValue.Off; default: throw new ArgumentOutOfRangeException (); } } public static ModifierKeys ToXwtValue (this NSEventModifierMask e) { ModifierKeys m = ModifierKeys.None; if (e.HasFlag (NSEventModifierMask.ControlKeyMask)) m |= ModifierKeys.Control; if (e.HasFlag (NSEventModifierMask.AlternateKeyMask)) m |= ModifierKeys.Alt; if (e.HasFlag (NSEventModifierMask.CommandKeyMask)) m |= ModifierKeys.Command; if (e.HasFlag (NSEventModifierMask.ShiftKeyMask)) m |= ModifierKeys.Shift; return m; } public static NSTableViewGridStyle ToMacValue (this GridLines value) { switch (value) { case GridLines.Both: return (NSTableViewGridStyle.SolidHorizontalLine | NSTableViewGridStyle.SolidVerticalLine); case GridLines.Horizontal: return NSTableViewGridStyle.SolidHorizontalLine; case GridLines.Vertical: return NSTableViewGridStyle.SolidVerticalLine; case GridLines.None: return NSTableViewGridStyle.None; } throw new InvalidOperationException("Invalid GridLines value: " + value); } public static GridLines ToXwtValue (this NSTableViewGridStyle value) { if (value.HasFlag (NSTableViewGridStyle.SolidHorizontalLine)) { if (value.HasFlag (NSTableViewGridStyle.SolidVerticalLine)) return GridLines.Both; else return GridLines.Horizontal; } if (value.HasFlag (NSTableViewGridStyle.SolidVerticalLine)) return GridLines.Vertical; return GridLines.None; } public static void DrawWithColorTransform (this NSView view, Color? color, Action drawDelegate) { if (color.HasValue) { if (view.Frame.Size.Width <= 0 || view.Frame.Size.Height <= 0) return; // render view to image var image = new NSImage(view.Frame.Size); image.LockFocusFlipped(!view.IsFlipped); drawDelegate (); image.UnlockFocus(); // create Core image for transformation var rr = new CGRect(0, 0, view.Frame.Size.Width, view.Frame.Size.Height); var ciImage = CIImage.FromCGImage(image.AsCGImage (ref rr, NSGraphicsContext.CurrentContext, null)); // apply color matrix var transformColor = new CIColorMatrix(); transformColor.SetDefaults(); transformColor.Image = ciImage; transformColor.RVector = new CIVector(0, (float)color.Value.Red, 0); transformColor.GVector = new CIVector((float)color.Value.Green, 0, 0); transformColor.BVector = new CIVector(0, 0, (float)color.Value.Blue); ciImage = (CIImage)transformColor.ValueForKey(new NSString("outputImage")); var ciCtx = CIContext.FromContext(NSGraphicsContext.CurrentContext.GraphicsPort, null); ciCtx.DrawImage (ciImage, rr, rr); } else drawDelegate(); } } public interface ICopiableObject { void CopyFrom (object other); } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace Sandbox.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
/* * Copyright 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 directconnect-2012-10-25.normal.json service model. */ using System; using Amazon.Runtime; namespace Amazon.DirectConnect { /// <summary> /// Constants used for properties of type ConnectionState. /// </summary> public class ConnectionState : ConstantClass { /// <summary> /// Constant Available for ConnectionState /// </summary> public static readonly ConnectionState Available = new ConnectionState("available"); /// <summary> /// Constant Deleted for ConnectionState /// </summary> public static readonly ConnectionState Deleted = new ConnectionState("deleted"); /// <summary> /// Constant Deleting for ConnectionState /// </summary> public static readonly ConnectionState Deleting = new ConnectionState("deleting"); /// <summary> /// Constant Down for ConnectionState /// </summary> public static readonly ConnectionState Down = new ConnectionState("down"); /// <summary> /// Constant Ordering for ConnectionState /// </summary> public static readonly ConnectionState Ordering = new ConnectionState("ordering"); /// <summary> /// Constant Pending for ConnectionState /// </summary> public static readonly ConnectionState Pending = new ConnectionState("pending"); /// <summary> /// Constant Rejected for ConnectionState /// </summary> public static readonly ConnectionState Rejected = new ConnectionState("rejected"); /// <summary> /// Constant Requested for ConnectionState /// </summary> public static readonly ConnectionState Requested = new ConnectionState("requested"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public ConnectionState(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static ConnectionState FindValue(string value) { return FindValue<ConnectionState>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator ConnectionState(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type InterconnectState. /// </summary> public class InterconnectState : ConstantClass { /// <summary> /// Constant Available for InterconnectState /// </summary> public static readonly InterconnectState Available = new InterconnectState("available"); /// <summary> /// Constant Deleted for InterconnectState /// </summary> public static readonly InterconnectState Deleted = new InterconnectState("deleted"); /// <summary> /// Constant Deleting for InterconnectState /// </summary> public static readonly InterconnectState Deleting = new InterconnectState("deleting"); /// <summary> /// Constant Down for InterconnectState /// </summary> public static readonly InterconnectState Down = new InterconnectState("down"); /// <summary> /// Constant Pending for InterconnectState /// </summary> public static readonly InterconnectState Pending = new InterconnectState("pending"); /// <summary> /// Constant Requested for InterconnectState /// </summary> public static readonly InterconnectState Requested = new InterconnectState("requested"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public InterconnectState(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static InterconnectState FindValue(string value) { return FindValue<InterconnectState>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator InterconnectState(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type VirtualInterfaceState. /// </summary> public class VirtualInterfaceState : ConstantClass { /// <summary> /// Constant Available for VirtualInterfaceState /// </summary> public static readonly VirtualInterfaceState Available = new VirtualInterfaceState("available"); /// <summary> /// Constant Confirming for VirtualInterfaceState /// </summary> public static readonly VirtualInterfaceState Confirming = new VirtualInterfaceState("confirming"); /// <summary> /// Constant Deleted for VirtualInterfaceState /// </summary> public static readonly VirtualInterfaceState Deleted = new VirtualInterfaceState("deleted"); /// <summary> /// Constant Deleting for VirtualInterfaceState /// </summary> public static readonly VirtualInterfaceState Deleting = new VirtualInterfaceState("deleting"); /// <summary> /// Constant Pending for VirtualInterfaceState /// </summary> public static readonly VirtualInterfaceState Pending = new VirtualInterfaceState("pending"); /// <summary> /// Constant Rejected for VirtualInterfaceState /// </summary> public static readonly VirtualInterfaceState Rejected = new VirtualInterfaceState("rejected"); /// <summary> /// Constant Verifying for VirtualInterfaceState /// </summary> public static readonly VirtualInterfaceState Verifying = new VirtualInterfaceState("verifying"); /// <summary> /// This constant constructor does not need to be called if the constant /// you are attempting to use is already defined as a static instance of /// this class. /// This constructor should be used to construct constants that are not /// defined as statics, for instance if attempting to use a feature that is /// newer than the current version of the SDK. /// </summary> public VirtualInterfaceState(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static VirtualInterfaceState FindValue(string value) { return FindValue<VirtualInterfaceState>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator VirtualInterfaceState(string value) { return FindValue(value); } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Timers; using Nini.Config; using OpenMetaverse; using Aurora.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace Aurora.Modules.Combat { public class AuroraCombatModule : INonSharedRegionModule, ICombatModule { private readonly List<UUID> CombatAllowedAgents = new List<UUID>(); private readonly Dictionary<string, List<UUID>> Teams = new Dictionary<string, List<UUID>>(); public bool AllowTeamKilling; public bool AllowTeams; public float DamageToTeamKillers; public bool DisallowTeleportingForCombatants = true; public bool ForceRequireCombatPermission = true; public float MaximumDamageToInflict; private float MaximumHealth; public float RegenerateHealthSpeed; public bool SendTeamKillerInfo; public float TeamHitsBeforeSend; public bool m_HasLeftCombat; public Vector3 m_RespawnPosition; public int m_SecondsBeforeRespawn; private IConfig m_config; private bool m_enabled; public bool m_regenHealth; public IScene m_scene; public bool m_shouldRespawn; #region ICombatModule Members public void AddCombatPermission(UUID AgentID) { if (!CombatAllowedAgents.Contains(AgentID)) CombatAllowedAgents.Add(AgentID); } public bool CheckCombatPermission(UUID AgentID) { return CombatAllowedAgents.Contains(AgentID); } public List<UUID> GetTeammates(string Team) { lock (Teams) { List<UUID> Teammates = new List<UUID>(); if (Teams.ContainsKey(Team)) { Teams.TryGetValue(Team, out Teammates); } return Teammates; } } #endregion #region INonSharedRegionModule Members public string Name { get { return "AuroraCombatModule"; } } public Type ReplaceableInterface { get { return null; } } public void Initialise(IConfigSource source) { m_config = source.Configs["CombatModule"]; if (m_config != null) { m_enabled = m_config.GetBoolean("Enabled", true); MaximumHealth = m_config.GetFloat("MaximumHealth", 100); ForceRequireCombatPermission = m_config.GetBoolean("ForceRequireCombatPermission", ForceRequireCombatPermission); DisallowTeleportingForCombatants = m_config.GetBoolean("DisallowTeleportingForCombatants", DisallowTeleportingForCombatants); AllowTeamKilling = m_config.GetBoolean("AllowTeamKilling", true); AllowTeams = m_config.GetBoolean("AllowTeams", false); SendTeamKillerInfo = m_config.GetBoolean("SendTeamKillerInfo", false); TeamHitsBeforeSend = m_config.GetFloat("TeamHitsBeforeSend", 3); DamageToTeamKillers = m_config.GetFloat("DamageToTeamKillers", 100); MaximumHealth = m_config.GetFloat("MaximumHealth", 100); MaximumDamageToInflict = m_config.GetFloat("MaximumDamageToInflict", 100); m_RespawnPosition.X = m_config.GetFloat("RespawnPositionX", 128); m_RespawnPosition.Y = m_config.GetFloat("RespawnPositionY", 128); m_RespawnPosition.Z = m_config.GetFloat("RespawnPositionZ", 128); m_SecondsBeforeRespawn = m_config.GetInt("SecondsBeforeRespawn", 5); m_shouldRespawn = m_config.GetBoolean("ShouldRespawn", false); m_regenHealth = m_config.GetBoolean("RegenerateHealth", true); RegenerateHealthSpeed = m_config.GetFloat("RegenerateHealthSpeed", 0.0625f); } } public void Close() { } public void AddRegion(IScene scene) { if (m_enabled) { m_scene = scene; scene.RegisterModuleInterface<ICombatModule>(this); scene.EventManager.OnNewPresence += NewPresence; scene.EventManager.OnRemovePresence += EventManager_OnRemovePresence; scene.EventManager.OnAvatarEnteringNewParcel += AvatarEnteringParcel; scene.Permissions.OnAllowedOutgoingLocalTeleport += AllowedTeleports; scene.Permissions.OnAllowedOutgoingRemoteTeleport += AllowedTeleports; scene.EventManager.OnLandObjectAdded += OnLandObjectAdded; } } public void RemoveRegion(IScene scene) { if (m_enabled) { scene.EventManager.OnNewPresence -= NewPresence; scene.EventManager.OnRemovePresence -= EventManager_OnRemovePresence; scene.EventManager.OnAvatarEnteringNewParcel -= AvatarEnteringParcel; scene.Permissions.OnAllowedOutgoingLocalTeleport -= AllowedTeleports; scene.Permissions.OnAllowedOutgoingRemoteTeleport -= AllowedTeleports; scene.EventManager.OnLandObjectAdded -= OnLandObjectAdded; } } public void RegionLoaded(IScene scene) { } #endregion private bool AllowedTeleports(UUID userID, IScene scene, out string reason) { //Make sure that agents that are in combat cannot tp around. They CAN tp if they are out of combat however reason = ""; IScenePresence SP = null; if (scene.TryGetScenePresence(userID, out SP)) if (DisallowTeleportingForCombatants && SP.RequestModuleInterface<ICombatPresence>() != null && !SP.RequestModuleInterface<ICombatPresence>().HasLeftCombat && !SP.Invulnerable) return false; return true; } private void NewPresence(IScenePresence presence) { presence.RegisterModuleInterface<ICombatPresence>(new CombatPresence(this, presence, m_config)); } private void EventManager_OnRemovePresence(IScenePresence presence) { CombatPresence m = (CombatPresence) presence.RequestModuleInterface<ICombatPresence>(); if (m != null) { presence.UnregisterModuleInterface<ICombatPresence>(m); m.Close(); } } public void AddPlayerToTeam(string Team, UUID AgentID) { lock (Teams) { List<UUID> Teammates = new List<UUID>(); if (Teams.TryGetValue(Team, out Teammates)) Teams.Remove(Team); else Teammates = new List<UUID>(); Teammates.Add(AgentID); Teams.Add(Team, Teammates); } } public void RemovePlayerFromTeam(string Team, UUID AgentID) { lock (Teams) { List<UUID> Teammates = new List<UUID>(); if (Teams.TryGetValue(Team, out Teammates)) { Teams.Remove(Team); if (Teammates.Contains(AgentID)) Teammates.Remove(AgentID); Teams.Add(Team, Teammates); } } } private void OnLandObjectAdded(LandData newParcel) { //If a new land object is added or updated, we need to redo the check for the avatars invulnerability #if (!ISWIN) m_scene.ForEachScenePresence(delegate(IScenePresence sp) { AvatarEnteringParcel(sp, null); }); #else m_scene.ForEachScenePresence(sp => AvatarEnteringParcel(sp, null)); #endif } public void AddDamageToPrim(ISceneEntity entity) { } private void AvatarEnteringParcel(IScenePresence avatar, ILandObject oldParcel) { ILandObject obj = null; IParcelManagementModule parcelManagement = avatar.Scene.RequestModuleInterface<IParcelManagementModule>(); if (parcelManagement != null) { obj = parcelManagement.GetLandObject(avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y); } if (obj == null) return; try { if ((obj.LandData.Flags & (uint) ParcelFlags.AllowDamage) != 0) { ICombatPresence CP = avatar.RequestModuleInterface<ICombatPresence>(); CP.Health = MaximumHealth; avatar.Invulnerable = false; } else { avatar.Invulnerable = true; } } catch (Exception) { } } #region Nested type: CombatObject private class CombatObject //: ICombatPresence { private readonly float MaximumDamageToInflict; private readonly float MaximumHealth; private readonly AuroraCombatModule m_combatModule; private readonly ISceneEntity m_part; private string m_Team; private float m_health = 100f; public CombatObject(AuroraCombatModule module, ISceneEntity part, IConfig m_config) { m_part = part; m_combatModule = module; MaximumHealth = m_config.GetFloat("MaximumHealth", 100); MaximumDamageToInflict = m_config.GetFloat("MaximumDamageToInflict", 100); m_Team = "No Team"; m_part.RootChild.OnAddPhysics += AddPhysics; m_part.RootChild.OnRemovePhysics += RemovePhysics; } public string Team { get { return m_Team; } set { m_combatModule.RemovePlayerFromTeam(m_Team, m_part.UUID); m_Team = value; m_combatModule.AddPlayerToTeam(m_Team, m_part.UUID); } } public float Health { get { return m_health; } set { m_health = value; } } public bool HasLeftCombat { get { return false; } set { } } public void RemovePhysics() { if (m_part.RootChild.PhysActor != null) m_part.RootChild.PhysActor.OnCollisionUpdate -= PhysicsActor_OnCollisionUpdate; } public void AddPhysics() { if (m_part.RootChild.PhysActor != null) m_part.RootChild.PhysActor.OnCollisionUpdate += PhysicsActor_OnCollisionUpdate; } public void PhysicsActor_OnCollisionUpdate(EventArgs e) { /*if (HasLeftCombat) return; */ if (e == null) return; /*CollisionEventUpdate collisionData = (CollisionEventUpdate) e; Dictionary<uint, ContactPoint> coldata = collisionData.m_objCollisionList; UUID killerObj = UUID.Zero; foreach (uint localid in coldata.Keys) { ISceneChildEntity part = m_part.Scene.GetSceneObjectPart(localid); if (part != null && part.ParentEntity.Damage != -1.0f) { if (part.ParentEntity.Damage > MaximumDamageToInflict) part.ParentEntity.Damage = MaximumDamageToInflict; Health -= part.ParentEntity.Damage; if (Health <= 0.0f) killerObj = part.UUID; } else { float Z = Math.Abs(m_part.Velocity.Z); if (coldata[localid].PenetrationDepth >= 0.05f) Health -= coldata[localid].PenetrationDepth*Z; } //Regenerate health (this is approx 1 sec) if ((int) (Health + 0.0625) <= m_combatModule.MaximumHealth) Health += 0.0625f; if (Health > m_combatModule.MaximumHealth) Health = m_combatModule.MaximumHealth; } if (Health <= 0) { Die(killerObj); }*/ } public void LeaveCombat() { //NoOp } public void JoinCombat() { //NoOp } public List<UUID> GetTeammates() { return m_combatModule.GetTeammates(m_Team); } public void IncurDamage(uint localID, double damage, UUID OwnerID) { if (damage < 0) return; if (damage > MaximumDamageToInflict) damage = MaximumDamageToInflict; float health = Health; health -= (float) damage; if (health <= 0) Die(OwnerID); } public void IncurDamage(uint localID, double damage, string RegionName, Vector3 pos, Vector3 lookat, UUID OwnerID) { if (damage < 0) return; if (damage > MaximumDamageToInflict) damage = MaximumDamageToInflict; float health = Health; health -= (float) damage; if (health <= 0) Die(OwnerID); } public void IncurHealing(double healing, UUID OwnerID) { if (healing < 0) return; float health = Health; health += (float) healing; if (health >= MaximumHealth) health = MaximumHealth; } private void Die(UUID OwnerID) { foreach (IScriptModule m in m_part.Scene.RequestModuleInterfaces<IScriptModule>()) { m.PostObjectEvent(m_part.UUID, "dead_object", new object[] {OwnerID}); } } public void SetStat(string StatName, float statValue) { } } #endregion #region Nested type: CombatPresence private class CombatPresence : ICombatPresence { #region Declares private readonly Dictionary<UUID, float> TeamHits = new Dictionary<UUID, float>(); private readonly Timer m_healthtimer = new Timer(); private IScenePresence m_SP; private string m_Team = "No Team"; private AuroraCombatModule m_combatModule; private float m_health = 100f; //private Dictionary<string, float> GenericStats = new Dictionary<string, float>(); public float Health { get { return m_health; } set { if (value > m_health) IncurHealing(value - m_health); else IncurDamage(null, m_health - value); } } public bool HasLeftCombat { get { return m_combatModule.m_HasLeftCombat; } set { m_combatModule.m_HasLeftCombat = value; } } public string Team { get { return m_Team; } set { m_combatModule.RemovePlayerFromTeam(m_Team, m_SP.UUID); m_Team = value; m_combatModule.AddPlayerToTeam(m_Team, m_SP.UUID); } } #endregion #region Initialization/Close public CombatPresence(AuroraCombatModule module, IScenePresence SP, IConfig m_config) { m_SP = SP; m_combatModule = module; HasLeftCombat = false; m_Team = "No Team"; SP.OnAddPhysics += SP_OnAddPhysics; SP.OnRemovePhysics += SP_OnRemovePhysics; //Use this to fix the avatars health m_healthtimer.Interval = 1000; // 1 sec m_healthtimer.Elapsed += fixAvatarHealth_Elapsed; m_healthtimer.Start(); } public void Close() { m_healthtimer.Stop(); m_healthtimer.Close(); m_SP.OnAddPhysics -= SP_OnAddPhysics; m_SP.OnRemovePhysics -= SP_OnRemovePhysics; SP_OnRemovePhysics(); m_combatModule = null; m_SP = null; } #endregion #region Physics events public void SP_OnRemovePhysics() { if (m_SP.PhysicsActor != null) m_SP.PhysicsActor.OnCollisionUpdate -= PhysicsActor_OnCollisionUpdate; } public void SP_OnAddPhysics() { if (m_SP.PhysicsActor != null) m_SP.PhysicsActor.OnCollisionUpdate += PhysicsActor_OnCollisionUpdate; } public void PhysicsActor_OnCollisionUpdate(EventArgs e) { if (m_SP == null || m_SP.Scene == null || m_SP.Invulnerable || HasLeftCombat || e == null) return; CollisionEventUpdate collisionData = (CollisionEventUpdate) e; Dictionary<uint, ContactPoint> coldata = collisionData.m_objCollisionList; float starthealth = Health; IScenePresence killingAvatar = null; foreach (uint localid in coldata.Keys) { ISceneChildEntity part = m_SP.Scene.GetSceneObjectPart(localid); IScenePresence otherAvatar = null; if (part != null && part.ParentEntity.Damage > 0) { otherAvatar = m_SP.Scene.GetScenePresence(part.OwnerID); ICombatPresence OtherAvatarCP = otherAvatar == null ? null : otherAvatar.RequestModuleInterface<ICombatPresence>(); if (OtherAvatarCP != null && OtherAvatarCP.HasLeftCombat) // If the avatar is null, the person is not inworld, and not on a team //If they have left combat, do not let them cause any damage. continue; //Check max damage to inflict if (part.ParentEntity.Damage > m_combatModule.MaximumDamageToInflict) part.ParentEntity.Damage = m_combatModule.MaximumDamageToInflict; // If the avatar is null, the person is not inworld, and not on a team if (m_combatModule.AllowTeams && OtherAvatarCP != null && otherAvatar.UUID != m_SP.UUID && OtherAvatarCP.Team == Team) { float Hits = 0; if (!TeamHits.TryGetValue(otherAvatar.UUID, out Hits)) Hits = 0; Hits++; if (m_combatModule.SendTeamKillerInfo && Hits == m_combatModule.TeamHitsBeforeSend) { otherAvatar.ControllingClient.SendAlertMessage("You have shot too many teammates and " + m_combatModule.DamageToTeamKillers + " health has been taken from you!"); OtherAvatarCP.IncurDamage(null, m_combatModule.DamageToTeamKillers); Hits = 0; } TeamHits[otherAvatar.UUID] = Hits; if (m_combatModule.AllowTeamKilling) //Green light on team killing Health -= part.ParentEntity.Damage; } else //Object, hit em Health -= part.ParentEntity.Damage; } else { float Z = m_SP.Velocity.Length()/20; if (coldata[localid].PenetrationDepth >= 0.05f && m_SP.Velocity.Z < -5 && !m_SP.PhysicsActor.Flying) { Z = Math.Min(Z, 1.5f); float damage = Math.Min(coldata[localid].PenetrationDepth, 15f); Health -= damage*Z; } } if (Health > m_combatModule.MaximumHealth) Health = m_combatModule.MaximumHealth; if (Health <= 0 && killingAvatar == null) killingAvatar = otherAvatar; //MainConsole.Instance.Debug("[AVATAR]: Collision with localid: " + localid.ToString() + " at depth: " + coldata[localid].ToString()); } if (starthealth != Health) m_SP.ControllingClient.SendHealth(Health); if (Health <= 0) KillAvatar(killingAvatar, "You killed " + m_SP.Name, "You died!", true, true); } #endregion #region Kill Avatar public void KillAvatar(IScenePresence killingAvatar, string killingAvatarMessage, string deadAvatarMessage, bool TeleportAgent, bool showAgentMessages) { try { if (showAgentMessages) { if (deadAvatarMessage != "") m_SP.ControllingClient.SendAgentAlertMessage(deadAvatarMessage, true); //Send it as a blue box at the bottom of the screen rather than as a full popup if (killingAvatar != null && killingAvatarMessage != "") killingAvatar.ControllingClient.SendAlertMessage(killingAvatarMessage); } } catch (InvalidOperationException) { } Health = m_combatModule.MaximumHealth; if (TeleportAgent) { if (m_combatModule.m_shouldRespawn) { if (m_combatModule.m_SecondsBeforeRespawn != 0) { m_SP.AllowMovement = false; this.HasLeftCombat = true; Timer t = new Timer {Interval = m_combatModule.m_SecondsBeforeRespawn*1000, AutoReset = false}; //Use this to reenable movement and combat //Only once t.Elapsed += respawn_Elapsed; t.Start(); } m_SP.Teleport(m_combatModule.m_RespawnPosition); } else { IEntityTransferModule transferModule = m_SP.Scene.RequestModuleInterface<IEntityTransferModule>(); if (transferModule != null) if (!transferModule.TeleportHome(m_SP.UUID, m_SP.ControllingClient)) { if (m_SP.PhysicsActor != null) m_SP.PhysicsActor.Flying = true; m_SP.Teleport(new Vector3(m_SP.Scene.RegionInfo.RegionSizeX/2, m_SP.Scene.RegionInfo.RegionSizeY/2, 128)); } } } m_SP.Scene.AuroraEventManager.FireGenericEventHandler("OnAvatarDeath", m_SP); } #endregion #region Timer events private void fixAvatarHealth_Elapsed(object sender, ElapsedEventArgs e) { //Regenerate health a bit every second if (m_combatModule.m_regenHealth) { if ((Health + m_combatModule.RegenerateHealthSpeed) <= m_combatModule.MaximumHealth) { m_health += m_combatModule.RegenerateHealthSpeed; m_SP.ControllingClient.SendHealth(Health); } else if (Health != m_combatModule.MaximumHealth) { m_health = m_combatModule.MaximumHealth; m_SP.ControllingClient.SendHealth(Health); } } } private void respawn_Elapsed(object sender, ElapsedEventArgs e) { m_SP.AllowMovement = true; this.HasLeftCombat = false; } #endregion #region Combat functions public void LeaveCombat() { m_combatModule.RemovePlayerFromTeam(m_Team, m_SP.UUID); HasLeftCombat = true; } public void JoinCombat() { HasLeftCombat = false; m_combatModule.AddPlayerToTeam(m_Team, m_SP.UUID); } public List<UUID> GetTeammates() { return m_combatModule.GetTeammates(m_Team); } #endregion #region Incur* functions public void IncurDamage(IScenePresence killingAvatar, double damage) { InnerIncurDamage(killingAvatar, damage, true); } public void IncurDamage(IScenePresence killingAvatar, double damage, string RegionName, Vector3 pos, Vector3 lookat) { if (damage < 0) return; if (InnerIncurDamage(killingAvatar, damage, false)) { //They died, teleport them IEntityTransferModule entityTransfer = m_SP.Scene.RequestModuleInterface<IEntityTransferModule>(); if (entityTransfer != null) entityTransfer.RequestTeleportLocation(m_SP.ControllingClient, RegionName, pos, lookat, (uint) TeleportFlags.ViaHome); } } public void IncurHealing(double healing) { if (healing < 0) return; if (!this.HasLeftCombat || !m_combatModule.ForceRequireCombatPermission) { m_health += (float) healing; if (m_health >= m_combatModule.MaximumHealth) m_health = m_combatModule.MaximumHealth; m_SP.ControllingClient.SendHealth(m_health); } } private bool InnerIncurDamage(IScenePresence killingAvatar, double damage, bool teleport) { if (damage < 0) return false; if (!this.HasLeftCombat || !m_combatModule.ForceRequireCombatPermission) { if (damage > m_combatModule.MaximumDamageToInflict) damage = m_combatModule.MaximumDamageToInflict; m_health -= (float) damage; m_SP.ControllingClient.SendHealth(Health); if (Health <= 0) { KillAvatar(killingAvatar, "You killed " + m_SP.Name, "You died!", teleport, true); return true; } } return false; } #endregion #region Stat functions public void SetStat(string StatName, float statValue) { } #endregion } #endregion } }
using System.Globalization; using System.Text.RegularExpressions; namespace Anycmd.Xacml.Runtime.DataTypes { using Functions; using Interfaces; /// <summary> /// A class defining the DaytimeDuration data type. /// </summary> public class DaytimeDuration : IDataType { #region Private members /// <summary> /// The regular expression used to validate the day time duration as a string value. /// </summary> private const string PATTERN = @"[\-]?P([0-9]+D(T([0-9]+(H([0-9]+(M([0-9]+(\.[0-9]*)?S|\.[0-9]+S)?|(\.[0-9]*)?S)|(\.[0-9]*)?S)?|M([0-9](\.[0-9]*)?S|\.[0-9]+S)?|(\.[0-9]*)?S)|\.[0-9]+S))?|T([0-9]+(H([0-9]+(M([0-9]+(\.[0-9]*)?S|\.[0-9]+S)?|(\.[0-9]*)?S)|(\.[0-9]*)?S)?|M([0-9]+(\.[0-9]*)?S|\.[0-9]+S)?|(\.[0-9]*)?S)|\.[0-9]+S))"; /// <summary> /// The regular expression used to match the day time duration and extract some values. /// </summary> private const string PATTERN_MATCH = @"(?<n>[\-]?)P((?<d>(\d+|\.\d+|\d+\.\d+))D)?T((?<h>(\d+|\.\d+|\d+\.\d+))H)?((?<m>(\d+|\.\d+|\d+\.\d+))M)?((?<s>(\d+|\.\d+|\d+\.\d+))S)?"; /// <summary> /// The original value found in the document. /// </summary> private string _durationValue; /// <summary> /// The days of the duration. /// </summary> private int _days; /// <summary> /// The hours of the duration. /// </summary> private int _hours; /// <summary> /// The minutes of the duration. /// </summary> private int _minutes; /// <summary> /// The seconds of the duration. /// </summary> private int _seconds; /// <summary> /// Whether is a negative duration. /// </summary> private bool _negative; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> internal DaytimeDuration() { } /// <summary> /// Creates a new DaytimeDuration using the string value. /// </summary> /// <param name="value">The DaytimeDuration as a string.</param> public DaytimeDuration(string value) { _durationValue = value; Regex re = new Regex(PATTERN); Match m = re.Match(value); if (m.Success) { re = new Regex(PATTERN_MATCH); m = re.Match(value); if (m.Success) { _negative = (m.Groups["n"].Value == "-"); _days = int.Parse(m.Groups["d"].Value, CultureInfo.InvariantCulture); _hours = int.Parse(m.Groups["h"].Value, CultureInfo.InvariantCulture); _minutes = int.Parse(m.Groups["m"].Value, CultureInfo.InvariantCulture); _seconds = int.Parse(m.Groups["s"].Value, CultureInfo.InvariantCulture); } else { throw new EvaluationException(Properties.Resource.exc_bug); } } else { throw new EvaluationException(string.Format(Properties.Resource.exc_invalid_daytime_duration_value, value)); } } #endregion #region Public properties /// <summary> /// The days of the duration. /// </summary> public int Days { get { return _negative ? _days * -1 : _days; } } /// <summary> /// The hours of the duration. /// </summary> public int Hours { get { return _negative ? _hours * -1 : _hours; } } /// <summary> /// The minutes of the duration. /// </summary> public int Minutes { get { return _negative ? _minutes * -1 : _minutes; } } /// <summary> /// The seconds of the duration. /// </summary> public int Seconds { get { return _negative ? _seconds * -1 : _seconds; } } #endregion #region Public methods /// <summary> /// The HashCode method overloaded because of a compiler warning. The base class is called. /// </summary> /// <returns>The HashCode calculated at the base class.</returns> public override int GetHashCode() { return base.GetHashCode(); } /// <summary> /// Equals method overloaded to compare two values of the same data type. /// </summary> /// <param name="obj">The object to compare with.</param> /// <returns>true, if both values are equals, otherwise false.</returns> public override bool Equals(object obj) { DaytimeDuration compareTo = obj as DaytimeDuration; if (compareTo == null) { return base.Equals(obj); } return _days == compareTo._days && _hours == compareTo._hours && _minutes == compareTo._minutes && _seconds == compareTo._seconds && _negative == compareTo._negative; } #endregion #region IDataType Members /// <summary> /// Return the function that compares two values of this data type. /// </summary> /// <value>An IFunction instance.</value> public IFunction EqualFunction { get { return new DaytimeDurationEqual(); } } /// <summary> /// Return the function that verifies if a value is contained within a bag of values of this data type. /// </summary> /// <value>An IFunction instance.</value> public IFunction IsInFunction { get { return new DaytimeDurationIsIn(); } } /// <summary> /// Return the function that verifies if all the values in a bag are contained within another bag of values of this data type. /// </summary> /// <value>An IFunction instance.</value> public IFunction SubsetFunction { get { return new DaytimeDurationSubset(); } } /// <summary> /// The string representation of the data type constant. /// </summary> /// <value>A string with the Uri for the data type.</value> public string DataTypeName { get { return Consts.Schema1.InternalDataTypes.XQueryDaytimeDuration; } } /// <summary> /// Return an instance of an DaytimeDuration form the string specified. /// </summary> /// <param name="value">The string value to parse.</param> /// <param name="parNo">The parameter number being parsed.</param> /// <returns>An instance of the type.</returns> public object Parse(string value, int parNo) { return new DaytimeDuration(value); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.Serialization; namespace System.Collections.Generic { /// <summary> /// Used internally to control behavior of insertion into a <see cref="Dictionary{TKey, TValue}"/>. /// </summary> internal enum InsertionBehavior : byte { /// <summary> /// The default insertion behavior. /// </summary> None = 0, /// <summary> /// Specifies that an existing entry with the same key should be overwritten if encountered. /// </summary> OverwriteExisting = 1, /// <summary> /// Specifies that if an existing entry with the same key is encountered, an exception should be thrown. /// </summary> ThrowOnExisting = 2 } [DebuggerTypeProxy(typeof(IDictionaryDebugView<,>))] [DebuggerDisplay("Count = {Count}")] [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>, ISerializable, IDeserializationCallback where TKey : notnull { private struct Entry { // 0-based index of next entry in chain: -1 means end of chain // also encodes whether this entry _itself_ is part of the free list by changing sign and subtracting 3, // so -2 means end of free list, -3 means index 0 but on free list, -4 means index 1 but on free list, etc. public int next; public uint hashCode; public TKey key; // Key of entry public TValue value; // Value of entry } private int[]? _buckets; private Entry[]? _entries; private int _count; private int _freeList; private int _freeCount; private int _version; private IEqualityComparer<TKey>? _comparer; private KeyCollection? _keys; private ValueCollection? _values; private const int StartOfFreeList = -3; // constants for serialization private const string VersionName = "Version"; // Do not rename (binary serialization) private const string HashSizeName = "HashSize"; // Do not rename (binary serialization). Must save buckets.Length private const string KeyValuePairsName = "KeyValuePairs"; // Do not rename (binary serialization) private const string ComparerName = "Comparer"; // Do not rename (binary serialization) public Dictionary() : this(0, null) { } public Dictionary(int capacity) : this(capacity, null) { } public Dictionary(IEqualityComparer<TKey>? comparer) : this(0, comparer) { } public Dictionary(int capacity, IEqualityComparer<TKey>? comparer) { if (capacity < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity); if (capacity > 0) Initialize(capacity); if (comparer != EqualityComparer<TKey>.Default) { _comparer = comparer; } if (typeof(TKey) == typeof(string) && _comparer == null) { // To start, move off default comparer for string which is randomised _comparer = (IEqualityComparer<TKey>)NonRandomizedStringEqualityComparer.Default; } } public Dictionary(IDictionary<TKey, TValue> dictionary) : this(dictionary, null) { } public Dictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey>? comparer) : this(dictionary != null ? dictionary.Count : 0, comparer) { if (dictionary == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary); } // It is likely that the passed-in dictionary is Dictionary<TKey,TValue>. When this is the case, // avoid the enumerator allocation and overhead by looping through the entries array directly. // We only do this when dictionary is Dictionary<TKey,TValue> and not a subclass, to maintain // back-compat with subclasses that may have overridden the enumerator behavior. if (dictionary.GetType() == typeof(Dictionary<TKey, TValue>)) { Dictionary<TKey, TValue> d = (Dictionary<TKey, TValue>)dictionary; int count = d._count; Entry[]? entries = d._entries; for (int i = 0; i < count; i++) { if (entries![i].next >= -1) { Add(entries[i].key, entries[i].value); } } return; } foreach (KeyValuePair<TKey, TValue> pair in dictionary) { Add(pair.Key, pair.Value); } } public Dictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection) : this(collection, null) { } public Dictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection, IEqualityComparer<TKey>? comparer) : this((collection as ICollection<KeyValuePair<TKey, TValue>>)?.Count ?? 0, comparer) { if (collection == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection); } foreach (KeyValuePair<TKey, TValue> pair in collection) { Add(pair.Key, pair.Value); } } protected Dictionary(SerializationInfo info, StreamingContext context) { // We can't do anything with the keys and values until the entire graph has been deserialized // and we have a resonable estimate that GetHashCode is not going to fail. For the time being, // we'll just cache this. The graph is not valid until OnDeserialization has been called. HashHelpers.SerializationInfoTable.Add(this, info); } public IEqualityComparer<TKey> Comparer { get { return (_comparer == null || _comparer is NonRandomizedStringEqualityComparer) ? EqualityComparer<TKey>.Default : _comparer; } } public int Count { get { return _count - _freeCount; } } public KeyCollection Keys { get { if (_keys == null) _keys = new KeyCollection(this); return _keys; } } ICollection<TKey> IDictionary<TKey, TValue>.Keys { get { if (_keys == null) _keys = new KeyCollection(this); return _keys; } } IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys { get { if (_keys == null) _keys = new KeyCollection(this); return _keys; } } public ValueCollection Values { get { if (_values == null) _values = new ValueCollection(this); return _values; } } ICollection<TValue> IDictionary<TKey, TValue>.Values { get { if (_values == null) _values = new ValueCollection(this); return _values; } } IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values { get { if (_values == null) _values = new ValueCollection(this); return _values; } } public TValue this[TKey key] { get { int i = FindEntry(key); if (i >= 0) return _entries![i].value; ThrowHelper.ThrowKeyNotFoundException(key); return default; } set { bool modified = TryInsert(key, value, InsertionBehavior.OverwriteExisting); Debug.Assert(modified); } } public void Add(TKey key, TValue value) { bool modified = TryInsert(key, value, InsertionBehavior.ThrowOnExisting); Debug.Assert(modified); // If there was an existing key and the Add failed, an exception will already have been thrown. } void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair) => Add(keyValuePair.Key, keyValuePair.Value); bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair) { int i = FindEntry(keyValuePair.Key); if (i >= 0 && EqualityComparer<TValue>.Default.Equals(_entries![i].value, keyValuePair.Value)) { return true; } return false; } bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair) { int i = FindEntry(keyValuePair.Key); if (i >= 0 && EqualityComparer<TValue>.Default.Equals(_entries![i].value, keyValuePair.Value)) { Remove(keyValuePair.Key); return true; } return false; } public void Clear() { int count = _count; if (count > 0) { Debug.Assert(_buckets != null, "_buckets should be non-null"); Debug.Assert(_entries != null, "_entries should be non-null"); Array.Clear(_buckets, 0, _buckets.Length); _count = 0; _freeList = -1; _freeCount = 0; Array.Clear(_entries, 0, count); } } public bool ContainsKey(TKey key) => FindEntry(key) >= 0; public bool ContainsValue(TValue value) { Entry[]? entries = _entries; if (value == null) { for (int i = 0; i < _count; i++) { if (entries![i].next >= -1 && entries[i].value == null) return true; } } else { if (default(TValue)! != null) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) { // ValueType: Devirtualize with EqualityComparer<TValue>.Default intrinsic for (int i = 0; i < _count; i++) { if (entries![i].next >= -1 && EqualityComparer<TValue>.Default.Equals(entries[i].value, value)) return true; } } else { // Object type: Shared Generic, EqualityComparer<TValue>.Default won't devirtualize // https://github.com/dotnet/coreclr/issues/17273 // So cache in a local rather than get EqualityComparer per loop iteration EqualityComparer<TValue> defaultComparer = EqualityComparer<TValue>.Default; for (int i = 0; i < _count; i++) { if (entries![i].next >= -1 && defaultComparer.Equals(entries[i].value, value)) return true; } } } return false; } private void CopyTo(KeyValuePair<TKey, TValue>[] array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if ((uint)index > (uint)array.Length) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (array.Length - index < Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } int count = _count; Entry[]? entries = _entries; for (int i = 0; i < count; i++) { if (entries![i].next >= -1) { array[index++] = new KeyValuePair<TKey, TValue>(entries[i].key, entries[i].value); } } } public Enumerator GetEnumerator() => new Enumerator(this, Enumerator.KeyValuePair); IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() => new Enumerator(this, Enumerator.KeyValuePair); public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.info); } info.AddValue(VersionName, _version); info.AddValue(ComparerName, _comparer ?? EqualityComparer<TKey>.Default, typeof(IEqualityComparer<TKey>)); info.AddValue(HashSizeName, _buckets == null ? 0 : _buckets.Length); // This is the length of the bucket array if (_buckets != null) { var array = new KeyValuePair<TKey, TValue>[Count]; CopyTo(array, 0); info.AddValue(KeyValuePairsName, array, typeof(KeyValuePair<TKey, TValue>[])); } } private int FindEntry(TKey key) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } int i = -1; int[]? buckets = _buckets; Entry[]? entries = _entries; int collisionCount = 0; if (buckets != null) { Debug.Assert(entries != null, "expected entries to be != null"); IEqualityComparer<TKey>? comparer = _comparer; if (comparer == null) { uint hashCode = (uint)key.GetHashCode(); // Value in _buckets is 1-based i = buckets[hashCode % (uint)buckets.Length] - 1; if (default(TKey)! != null) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) { // ValueType: Devirtualize with EqualityComparer<TValue>.Default intrinsic do { // Should be a while loop https://github.com/dotnet/coreclr/issues/15476 // Test in if to drop range check for following array access if ((uint)i >= (uint)entries.Length || (entries[i].hashCode == hashCode && EqualityComparer<TKey>.Default.Equals(entries[i].key, key))) { break; } i = entries[i].next; if (collisionCount >= entries.Length) { // The chain of entries forms a loop; which means a concurrent update has happened. // Break out of the loop and throw, rather than looping forever. ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported(); } collisionCount++; } while (true); } else { // Object type: Shared Generic, EqualityComparer<TValue>.Default won't devirtualize // https://github.com/dotnet/coreclr/issues/17273 // So cache in a local rather than get EqualityComparer per loop iteration EqualityComparer<TKey> defaultComparer = EqualityComparer<TKey>.Default; do { // Should be a while loop https://github.com/dotnet/coreclr/issues/15476 // Test in if to drop range check for following array access if ((uint)i >= (uint)entries.Length || (entries[i].hashCode == hashCode && defaultComparer.Equals(entries[i].key, key))) { break; } i = entries[i].next; if (collisionCount >= entries.Length) { // The chain of entries forms a loop; which means a concurrent update has happened. // Break out of the loop and throw, rather than looping forever. ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported(); } collisionCount++; } while (true); } } else { uint hashCode = (uint)comparer.GetHashCode(key); // Value in _buckets is 1-based i = buckets[hashCode % (uint)buckets.Length] - 1; do { // Should be a while loop https://github.com/dotnet/coreclr/issues/15476 // Test in if to drop range check for following array access if ((uint)i >= (uint)entries.Length || (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key))) { break; } i = entries[i].next; if (collisionCount >= entries.Length) { // The chain of entries forms a loop; which means a concurrent update has happened. // Break out of the loop and throw, rather than looping forever. ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported(); } collisionCount++; } while (true); } } return i; } private int Initialize(int capacity) { int size = HashHelpers.GetPrime(capacity); _freeList = -1; _buckets = new int[size]; _entries = new Entry[size]; return size; } private bool TryInsert(TKey key, TValue value, InsertionBehavior behavior) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } if (_buckets == null) { Initialize(0); } Debug.Assert(_buckets != null); Entry[]? entries = _entries; Debug.Assert(entries != null, "expected entries to be non-null"); IEqualityComparer<TKey>? comparer = _comparer; uint hashCode = (uint)((comparer == null) ? key.GetHashCode() : comparer.GetHashCode(key)); int collisionCount = 0; ref int bucket = ref _buckets[hashCode % (uint)_buckets.Length]; // Value in _buckets is 1-based int i = bucket - 1; if (comparer == null) { if (default(TKey)! != null) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) { // ValueType: Devirtualize with EqualityComparer<TValue>.Default intrinsic do { // Should be a while loop https://github.com/dotnet/coreclr/issues/15476 // Test uint in if rather than loop condition to drop range check for following array access if ((uint)i >= (uint)entries.Length) { break; } if (entries[i].hashCode == hashCode && EqualityComparer<TKey>.Default.Equals(entries[i].key, key)) { if (behavior == InsertionBehavior.OverwriteExisting) { entries[i].value = value; _version++; return true; } if (behavior == InsertionBehavior.ThrowOnExisting) { ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(key); } return false; } i = entries[i].next; if (collisionCount >= entries.Length) { // The chain of entries forms a loop; which means a concurrent update has happened. // Break out of the loop and throw, rather than looping forever. ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported(); } collisionCount++; } while (true); } else { // Object type: Shared Generic, EqualityComparer<TValue>.Default won't devirtualize // https://github.com/dotnet/coreclr/issues/17273 // So cache in a local rather than get EqualityComparer per loop iteration EqualityComparer<TKey> defaultComparer = EqualityComparer<TKey>.Default; do { // Should be a while loop https://github.com/dotnet/coreclr/issues/15476 // Test uint in if rather than loop condition to drop range check for following array access if ((uint)i >= (uint)entries.Length) { break; } if (entries[i].hashCode == hashCode && defaultComparer.Equals(entries[i].key, key)) { if (behavior == InsertionBehavior.OverwriteExisting) { entries[i].value = value; _version++; return true; } if (behavior == InsertionBehavior.ThrowOnExisting) { ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(key); } return false; } i = entries[i].next; if (collisionCount >= entries.Length) { // The chain of entries forms a loop; which means a concurrent update has happened. // Break out of the loop and throw, rather than looping forever. ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported(); } collisionCount++; } while (true); } } else { do { // Should be a while loop https://github.com/dotnet/coreclr/issues/15476 // Test uint in if rather than loop condition to drop range check for following array access if ((uint)i >= (uint)entries.Length) { break; } if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) { if (behavior == InsertionBehavior.OverwriteExisting) { entries[i].value = value; _version++; return true; } if (behavior == InsertionBehavior.ThrowOnExisting) { ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(key); } return false; } i = entries[i].next; if (collisionCount >= entries.Length) { // The chain of entries forms a loop; which means a concurrent update has happened. // Break out of the loop and throw, rather than looping forever. ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported(); } collisionCount++; } while (true); } bool updateFreeList = false; int index; if (_freeCount > 0) { index = _freeList; updateFreeList = true; _freeCount--; } else { int count = _count; if (count == entries.Length) { Resize(); bucket = ref _buckets[hashCode % (uint)_buckets.Length]; } index = count; _count = count + 1; entries = _entries; } ref Entry entry = ref entries![index]; if (updateFreeList) { Debug.Assert((StartOfFreeList - entries[_freeList].next) >= -1, "shouldn't overflow because `next` cannot underflow"); _freeList = StartOfFreeList - entries[_freeList].next; } entry.hashCode = hashCode; // Value in _buckets is 1-based entry.next = bucket - 1; entry.key = key; entry.value = value; // Value in _buckets is 1-based bucket = index + 1; _version++; // Value types never rehash if (default(TKey)! == null && collisionCount > HashHelpers.HashCollisionThreshold && comparer is NonRandomizedStringEqualityComparer) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) { // If we hit the collision threshold we'll need to switch to the comparer which is using randomized string hashing // i.e. EqualityComparer<string>.Default. _comparer = null; Resize(entries.Length, true); } return true; } public virtual void OnDeserialization(object? sender) { HashHelpers.SerializationInfoTable.TryGetValue(this, out SerializationInfo? siInfo); if (siInfo == null) { // We can return immediately if this function is called twice. // Note we remove the serialization info from the table at the end of this method. return; } int realVersion = siInfo.GetInt32(VersionName); int hashsize = siInfo.GetInt32(HashSizeName); _comparer = (IEqualityComparer<TKey>)siInfo.GetValue(ComparerName, typeof(IEqualityComparer<TKey>))!; // When serialized if comparer is null, we use the default. if (hashsize != 0) { Initialize(hashsize); KeyValuePair<TKey, TValue>[]? array = (KeyValuePair<TKey, TValue>[]?) siInfo.GetValue(KeyValuePairsName, typeof(KeyValuePair<TKey, TValue>[])); if (array == null) { ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_MissingKeys); } for (int i = 0; i < array.Length; i++) { if (array[i].Key == null) { ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_NullKey); } Add(array[i].Key, array[i].Value); } } else { _buckets = null; } _version = realVersion; HashHelpers.SerializationInfoTable.Remove(this); } private void Resize() => Resize(HashHelpers.ExpandPrime(_count), false); private void Resize(int newSize, bool forceNewHashCodes) { // Value types never rehash Debug.Assert(!forceNewHashCodes || default(TKey)! == null); // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) Debug.Assert(_entries != null, "_entries should be non-null"); Debug.Assert(newSize >= _entries.Length); int[] buckets = new int[newSize]; Entry[] entries = new Entry[newSize]; int count = _count; Array.Copy(_entries, 0, entries, 0, count); if (default(TKey)! == null && forceNewHashCodes) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) { for (int i = 0; i < count; i++) { if (entries[i].next >= -1) { Debug.Assert(_comparer == null); entries[i].hashCode = (uint)entries[i].key.GetHashCode(); } } } for (int i = 0; i < count; i++) { if (entries[i].next >= -1) { uint bucket = entries[i].hashCode % (uint)newSize; // Value in _buckets is 1-based entries[i].next = buckets[bucket] - 1; // Value in _buckets is 1-based buckets[bucket] = i + 1; } } _buckets = buckets; _entries = entries; } // The overload Remove(TKey key, out TValue value) is a copy of this method with one additional // statement to copy the value for entry being removed into the output parameter. // Code has been intentionally duplicated for performance reasons. public bool Remove(TKey key) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } int[]? buckets = _buckets; Entry[]? entries = _entries; int collisionCount = 0; if (buckets != null) { Debug.Assert(entries != null, "entries should be non-null"); uint hashCode = (uint)(_comparer?.GetHashCode(key) ?? key.GetHashCode()); uint bucket = hashCode % (uint)buckets.Length; int last = -1; // Value in buckets is 1-based int i = buckets[bucket] - 1; while (i >= 0) { ref Entry entry = ref entries[i]; if (entry.hashCode == hashCode && (_comparer?.Equals(entry.key, key) ?? EqualityComparer<TKey>.Default.Equals(entry.key, key))) { if (last < 0) { // Value in buckets is 1-based buckets[bucket] = entry.next + 1; } else { entries[last].next = entry.next; } Debug.Assert((StartOfFreeList - _freeList) < 0, "shouldn't underflow because max hashtable length is MaxPrimeArrayLength = 0x7FEFFFFD(2146435069) _freelist underflow threshold 2147483646"); entry.next = StartOfFreeList - _freeList; if (RuntimeHelpers.IsReferenceOrContainsReferences<TKey>()) { entry.key = default!; } if (RuntimeHelpers.IsReferenceOrContainsReferences<TValue>()) { entry.value = default!; } _freeList = i; _freeCount++; return true; } last = i; i = entry.next; if (collisionCount >= entries.Length) { // The chain of entries forms a loop; which means a concurrent update has happened. // Break out of the loop and throw, rather than looping forever. ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported(); } collisionCount++; } } return false; } // This overload is a copy of the overload Remove(TKey key) with one additional // statement to copy the value for entry being removed into the output parameter. // Code has been intentionally duplicated for performance reasons. public bool Remove(TKey key, [MaybeNullWhen(false)] out TValue value) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } int[]? buckets = _buckets; Entry[]? entries = _entries; int collisionCount = 0; if (buckets != null) { Debug.Assert(entries != null, "entries should be non-null"); uint hashCode = (uint)(_comparer?.GetHashCode(key) ?? key.GetHashCode()); uint bucket = hashCode % (uint)buckets.Length; int last = -1; // Value in buckets is 1-based int i = buckets[bucket] - 1; while (i >= 0) { ref Entry entry = ref entries[i]; if (entry.hashCode == hashCode && (_comparer?.Equals(entry.key, key) ?? EqualityComparer<TKey>.Default.Equals(entry.key, key))) { if (last < 0) { // Value in buckets is 1-based buckets[bucket] = entry.next + 1; } else { entries[last].next = entry.next; } value = entry.value; Debug.Assert((StartOfFreeList - _freeList) < 0, "shouldn't underflow because max hashtable length is MaxPrimeArrayLength = 0x7FEFFFFD(2146435069) _freelist underflow threshold 2147483646"); entry.next = StartOfFreeList - _freeList; if (RuntimeHelpers.IsReferenceOrContainsReferences<TKey>()) { entry.key = default!; } if (RuntimeHelpers.IsReferenceOrContainsReferences<TValue>()) { entry.value = default!; } _freeList = i; _freeCount++; return true; } last = i; i = entry.next; if (collisionCount >= entries.Length) { // The chain of entries forms a loop; which means a concurrent update has happened. // Break out of the loop and throw, rather than looping forever. ThrowHelper.ThrowInvalidOperationException_ConcurrentOperationsNotSupported(); } collisionCount++; } } value = default!; return false; } public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) { int i = FindEntry(key); if (i >= 0) { value = _entries![i].value; return true; } value = default!; return false; } public bool TryAdd(TKey key, TValue value) => TryInsert(key, value, InsertionBehavior.None); bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly => false; void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int index) => CopyTo(array, index); void ICollection.CopyTo(Array array, int index) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); if (array.Rank != 1) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); if (array.GetLowerBound(0) != 0) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); if ((uint)index > (uint)array.Length) ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); if (array.Length - index < Count) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); if (array is KeyValuePair<TKey, TValue>[] pairs) { CopyTo(pairs, index); } else if (array is DictionaryEntry[] dictEntryArray) { Entry[]? entries = _entries; for (int i = 0; i < _count; i++) { if (entries![i].next >= -1) { dictEntryArray[index++] = new DictionaryEntry(entries[i].key, entries[i].value); } } } else { object[]? objects = array as object[]; if (objects == null) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } try { int count = _count; Entry[]? entries = _entries; for (int i = 0; i < count; i++) { if (entries![i].next >= -1) { objects[index++] = new KeyValuePair<TKey, TValue>(entries[i].key, entries[i].value); } } } catch (ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } } } IEnumerator IEnumerable.GetEnumerator() => new Enumerator(this, Enumerator.KeyValuePair); /// <summary> /// Ensures that the dictionary can hold up to 'capacity' entries without any further expansion of its backing storage /// </summary> public int EnsureCapacity(int capacity) { if (capacity < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity); int currentCapacity = _entries == null ? 0 : _entries.Length; if (currentCapacity >= capacity) return currentCapacity; _version++; if (_buckets == null) return Initialize(capacity); int newSize = HashHelpers.GetPrime(capacity); Resize(newSize, forceNewHashCodes: false); return newSize; } /// <summary> /// Sets the capacity of this dictionary to what it would be if it had been originally initialized with all its entries /// /// This method can be used to minimize the memory overhead /// once it is known that no new elements will be added. /// /// To allocate minimum size storage array, execute the following statements: /// /// dictionary.Clear(); /// dictionary.TrimExcess(); /// </summary> public void TrimExcess() => TrimExcess(Count); /// <summary> /// Sets the capacity of this dictionary to hold up 'capacity' entries without any further expansion of its backing storage /// /// This method can be used to minimize the memory overhead /// once it is known that no new elements will be added. /// </summary> public void TrimExcess(int capacity) { if (capacity < Count) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity); int newSize = HashHelpers.GetPrime(capacity); Entry[]? oldEntries = _entries; int currentCapacity = oldEntries == null ? 0 : oldEntries.Length; if (newSize >= currentCapacity) return; int oldCount = _count; _version++; Initialize(newSize); Entry[]? entries = _entries; int[]? buckets = _buckets; int count = 0; for (int i = 0; i < oldCount; i++) { uint hashCode = oldEntries![i].hashCode; // At this point, we know we have entries. if (oldEntries[i].next >= -1) { ref Entry entry = ref entries![count]; entry = oldEntries[i]; uint bucket = hashCode % (uint)newSize; // Value in _buckets is 1-based entry.next = buckets![bucket] - 1; // If we get here, we have entries, therefore buckets is not null. // Value in _buckets is 1-based buckets[bucket] = count + 1; count++; } } _count = count; _freeCount = 0; } bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => this; bool IDictionary.IsFixedSize => false; bool IDictionary.IsReadOnly => false; ICollection IDictionary.Keys => (ICollection)Keys; ICollection IDictionary.Values => (ICollection)Values; object? IDictionary.this[object key] { get { if (IsCompatibleKey(key)) { int i = FindEntry((TKey)key); if (i >= 0) { return _entries![i].value; } } return null; } set { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } ThrowHelper.IfNullAndNullsAreIllegalThenThrow<TValue>(value, ExceptionArgument.value); try { TKey tempKey = (TKey)key; try { this[tempKey] = (TValue)value!; } catch (InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue)); } } catch (InvalidCastException) { ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey)); } } } private static bool IsCompatibleKey(object key) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } return (key is TKey); } void IDictionary.Add(object key, object? value) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } ThrowHelper.IfNullAndNullsAreIllegalThenThrow<TValue>(value, ExceptionArgument.value); try { TKey tempKey = (TKey)key; try { Add(tempKey, (TValue)value!); } catch (InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue)); } } catch (InvalidCastException) { ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey)); } } bool IDictionary.Contains(object key) { if (IsCompatibleKey(key)) { return ContainsKey((TKey)key); } return false; } IDictionaryEnumerator IDictionary.GetEnumerator() => new Enumerator(this, Enumerator.DictEntry); void IDictionary.Remove(object key) { if (IsCompatibleKey(key)) { Remove((TKey)key); } } public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IDictionaryEnumerator { private readonly Dictionary<TKey, TValue> _dictionary; private readonly int _version; private int _index; private KeyValuePair<TKey, TValue> _current; private readonly int _getEnumeratorRetType; // What should Enumerator.Current return? internal const int DictEntry = 1; internal const int KeyValuePair = 2; internal Enumerator(Dictionary<TKey, TValue> dictionary, int getEnumeratorRetType) { _dictionary = dictionary; _version = dictionary._version; _index = 0; _getEnumeratorRetType = getEnumeratorRetType; _current = new KeyValuePair<TKey, TValue>(); } public bool MoveNext() { if (_version != _dictionary._version) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } // Use unsigned comparison since we set index to dictionary.count+1 when the enumeration ends. // dictionary.count+1 could be negative if dictionary.count is int.MaxValue while ((uint)_index < (uint)_dictionary._count) { ref Entry entry = ref _dictionary._entries![_index++]; if (entry.next >= -1) { _current = new KeyValuePair<TKey, TValue>(entry.key, entry.value); return true; } } _index = _dictionary._count + 1; _current = new KeyValuePair<TKey, TValue>(); return false; } public KeyValuePair<TKey, TValue> Current => _current; public void Dispose() { } object? IEnumerator.Current { get { if (_index == 0 || (_index == _dictionary._count + 1)) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); } if (_getEnumeratorRetType == DictEntry) { return new DictionaryEntry(_current.Key, _current.Value); } else { return new KeyValuePair<TKey, TValue>(_current.Key, _current.Value); } } } void IEnumerator.Reset() { if (_version != _dictionary._version) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } _index = 0; _current = new KeyValuePair<TKey, TValue>(); } DictionaryEntry IDictionaryEnumerator.Entry { get { if (_index == 0 || (_index == _dictionary._count + 1)) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); } return new DictionaryEntry(_current.Key, _current.Value); } } object IDictionaryEnumerator.Key { get { if (_index == 0 || (_index == _dictionary._count + 1)) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); } return _current.Key; } } object? IDictionaryEnumerator.Value { get { if (_index == 0 || (_index == _dictionary._count + 1)) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); } return _current.Value; } } } [DebuggerTypeProxy(typeof(DictionaryKeyCollectionDebugView<,>))] [DebuggerDisplay("Count = {Count}")] public sealed class KeyCollection : ICollection<TKey>, ICollection, IReadOnlyCollection<TKey> { private Dictionary<TKey, TValue> _dictionary; public KeyCollection(Dictionary<TKey, TValue> dictionary) { if (dictionary == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary); } _dictionary = dictionary; } public Enumerator GetEnumerator() => new Enumerator(_dictionary); public void CopyTo(TKey[] array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (array.Length - index < _dictionary.Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } int count = _dictionary._count; Entry[]? entries = _dictionary._entries; for (int i = 0; i < count; i++) { if (entries![i].next >= -1) array[index++] = entries[i].key; } } public int Count => _dictionary.Count; bool ICollection<TKey>.IsReadOnly => true; void ICollection<TKey>.Add(TKey item) => ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet); void ICollection<TKey>.Clear() => ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet); bool ICollection<TKey>.Contains(TKey item) => _dictionary.ContainsKey(item); bool ICollection<TKey>.Remove(TKey item) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet); return false; } IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator() => new Enumerator(_dictionary); IEnumerator IEnumerable.GetEnumerator() => new Enumerator(_dictionary); void ICollection.CopyTo(Array array, int index) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); if (array.Rank != 1) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); if (array.GetLowerBound(0) != 0) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); if ((uint)index > (uint)array.Length) ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); if (array.Length - index < _dictionary.Count) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); if (array is TKey[] keys) { CopyTo(keys, index); } else { object[]? objects = array as object[]; if (objects == null) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } int count = _dictionary._count; Entry[]? entries = _dictionary._entries; try { for (int i = 0; i < count; i++) { if (entries![i].next >= -1) objects[index++] = entries[i].key; } } catch (ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } } } bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => ((ICollection)_dictionary).SyncRoot; public struct Enumerator : IEnumerator<TKey>, IEnumerator { private readonly Dictionary<TKey, TValue> _dictionary; private int _index; private readonly int _version; [AllowNull, MaybeNull] private TKey _currentKey; internal Enumerator(Dictionary<TKey, TValue> dictionary) { _dictionary = dictionary; _version = dictionary._version; _index = 0; _currentKey = default; } public void Dispose() { } public bool MoveNext() { if (_version != _dictionary._version) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } while ((uint)_index < (uint)_dictionary._count) { ref Entry entry = ref _dictionary._entries![_index++]; if (entry.next >= -1) { _currentKey = entry.key; return true; } } _index = _dictionary._count + 1; _currentKey = default; return false; } public TKey Current => _currentKey!; object? IEnumerator.Current { get { if (_index == 0 || (_index == _dictionary._count + 1)) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); } return _currentKey; } } void IEnumerator.Reset() { if (_version != _dictionary._version) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } _index = 0; _currentKey = default; } } } [DebuggerTypeProxy(typeof(DictionaryValueCollectionDebugView<,>))] [DebuggerDisplay("Count = {Count}")] public sealed class ValueCollection : ICollection<TValue>, ICollection, IReadOnlyCollection<TValue> { private Dictionary<TKey, TValue> _dictionary; public ValueCollection(Dictionary<TKey, TValue> dictionary) { if (dictionary == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary); } _dictionary = dictionary; } public Enumerator GetEnumerator() => new Enumerator(_dictionary); public void CopyTo(TValue[] array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if ((uint)index > array.Length) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (array.Length - index < _dictionary.Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } int count = _dictionary._count; Entry[]? entries = _dictionary._entries; for (int i = 0; i < count; i++) { if (entries![i].next >= -1) array[index++] = entries[i].value; } } public int Count => _dictionary.Count; bool ICollection<TValue>.IsReadOnly => true; void ICollection<TValue>.Add(TValue item) => ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet); bool ICollection<TValue>.Remove(TValue item) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet); return false; } void ICollection<TValue>.Clear() => ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet); bool ICollection<TValue>.Contains(TValue item) => _dictionary.ContainsValue(item); IEnumerator<TValue> IEnumerable<TValue>.GetEnumerator() => new Enumerator(_dictionary); IEnumerator IEnumerable.GetEnumerator() => new Enumerator(_dictionary); void ICollection.CopyTo(Array array, int index) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); if (array.Rank != 1) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); if (array.GetLowerBound(0) != 0) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); if ((uint)index > (uint)array.Length) ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); if (array.Length - index < _dictionary.Count) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); if (array is TValue[] values) { CopyTo(values, index); } else { object[]? objects = array as object[]; if (objects == null) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } int count = _dictionary._count; Entry[]? entries = _dictionary._entries; try { for (int i = 0; i < count; i++) { if (entries![i].next >= -1) objects[index++] = entries[i].value!; } } catch (ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } } } bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => ((ICollection)_dictionary).SyncRoot; public struct Enumerator : IEnumerator<TValue>, IEnumerator { private readonly Dictionary<TKey, TValue> _dictionary; private int _index; private readonly int _version; [AllowNull, MaybeNull] private TValue _currentValue; internal Enumerator(Dictionary<TKey, TValue> dictionary) { _dictionary = dictionary; _version = dictionary._version; _index = 0; _currentValue = default; } public void Dispose() { } public bool MoveNext() { if (_version != _dictionary._version) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } while ((uint)_index < (uint)_dictionary._count) { ref Entry entry = ref _dictionary._entries![_index++]; if (entry.next >= -1) { _currentValue = entry.value; return true; } } _index = _dictionary._count + 1; _currentValue = default; return false; } public TValue Current => _currentValue!; object? IEnumerator.Current { get { if (_index == 0 || (_index == _dictionary._count + 1)) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); } return _currentValue; } } void IEnumerator.Reset() { if (_version != _dictionary._version) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } _index = 0; _currentValue = default; } } } } }
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> /// Schools Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class SKGSDataSet : EduHubDataSet<SKGS> { /// <inheritdoc /> public override string Name { get { return "SKGS"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal SKGSDataSet(EduHubContext Context) : base(Context) { Index_LW_DATE = new Lazy<NullDictionary<DateTime?, IReadOnlyList<SKGS>>>(() => this.ToGroupedNullDictionary(i => i.LW_DATE)); Index_SCHOOL = new Lazy<Dictionary<string, SKGS>>(() => this.ToDictionary(i => i.SCHOOL)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="SKGS" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="SKGS" /> fields for each CSV column header</returns> internal override Action<SKGS, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<SKGS, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "SCHOOL": mapper[i] = (e, v) => e.SCHOOL = v; break; case "NAME": mapper[i] = (e, v) => e.NAME = v; break; case "SCHOOL_TYPE": mapper[i] = (e, v) => e.SCHOOL_TYPE = v; break; case "ENTITY": mapper[i] = (e, v) => e.ENTITY = v; break; case "SCHOOL_ID": mapper[i] = (e, v) => e.SCHOOL_ID = v; break; case "SCHOOL_NUMBER": mapper[i] = (e, v) => e.SCHOOL_NUMBER = v; break; case "CAMPUS_TYPE": mapper[i] = (e, v) => e.CAMPUS_TYPE = v; break; case "CAMPUS_NAME": mapper[i] = (e, v) => e.CAMPUS_NAME = v; break; case "REGION": mapper[i] = (e, v) => e.REGION = v == null ? (short?)null : short.Parse(v); break; case "REGION_NAME": mapper[i] = (e, v) => e.REGION_NAME = v; break; case "ADDRESS01": mapper[i] = (e, v) => e.ADDRESS01 = v; break; case "ADDRESS02": mapper[i] = (e, v) => e.ADDRESS02 = v; break; case "SUBURB": mapper[i] = (e, v) => e.SUBURB = v; break; case "STATE": mapper[i] = (e, v) => e.STATE = v; break; case "POSTCODE": mapper[i] = (e, v) => e.POSTCODE = v; break; case "TELEPHONE": mapper[i] = (e, v) => e.TELEPHONE = v; break; case "FAX": mapper[i] = (e, v) => e.FAX = v; break; case "MAILING_ADDRESS01": mapper[i] = (e, v) => e.MAILING_ADDRESS01 = v; break; case "MAILING_ADDRESS02": mapper[i] = (e, v) => e.MAILING_ADDRESS02 = v; break; case "MAILING_SUBURB": mapper[i] = (e, v) => e.MAILING_SUBURB = v; break; case "MAILING_STATE": mapper[i] = (e, v) => e.MAILING_STATE = v; break; case "MAILING_POSTCODE": mapper[i] = (e, v) => e.MAILING_POSTCODE = v; break; case "DELIVERY_ADDRESS01": mapper[i] = (e, v) => e.DELIVERY_ADDRESS01 = v; break; case "DELIVERY_ADDRESS02": mapper[i] = (e, v) => e.DELIVERY_ADDRESS02 = v; break; case "DELIVERY_SUBURB": mapper[i] = (e, v) => e.DELIVERY_SUBURB = v; break; case "DELIVERY_STATE": mapper[i] = (e, v) => e.DELIVERY_STATE = v; break; case "DELIVERY_POSTCODE": mapper[i] = (e, v) => e.DELIVERY_POSTCODE = v; break; case "DELIVERY_TELEPHONE": mapper[i] = (e, v) => e.DELIVERY_TELEPHONE = v; break; case "DELIVERY_FAX": mapper[i] = (e, v) => e.DELIVERY_FAX = v; break; case "E_MAIL": mapper[i] = (e, v) => e.E_MAIL = v; break; case "INTERNET_ADDRESS": mapper[i] = (e, v) => e.INTERNET_ADDRESS = v; break; case "CASES21_RELEASE": mapper[i] = (e, v) => e.CASES21_RELEASE = v; break; case "MAP_TYPE": mapper[i] = (e, v) => e.MAP_TYPE = v; break; case "MAP_NUM": mapper[i] = (e, v) => e.MAP_NUM = v; break; case "X_AXIS": mapper[i] = (e, v) => e.X_AXIS = v; break; case "Y_AXIS": mapper[i] = (e, v) => e.Y_AXIS = v; break; case "SCH_PRINCIPAL_SALUTATION": mapper[i] = (e, v) => e.SCH_PRINCIPAL_SALUTATION = v; break; case "SCH_PRINCIPAL_FIRST_NAME": mapper[i] = (e, v) => e.SCH_PRINCIPAL_FIRST_NAME = v; break; case "SCH_PRINCIPAL_SURNAME": mapper[i] = (e, v) => e.SCH_PRINCIPAL_SURNAME = v; break; case "SCH_PRINCIPAL_TELEPHONE": mapper[i] = (e, v) => e.SCH_PRINCIPAL_TELEPHONE = v; break; case "SALUTATION": mapper[i] = (e, v) => e.SALUTATION = v; break; case "SURNAME": mapper[i] = (e, v) => e.SURNAME = v; break; case "FIRST_NAME": mapper[i] = (e, v) => e.FIRST_NAME = v; break; case "CLOSED": mapper[i] = (e, v) => e.CLOSED = v; break; case "CONCURRENT_ENROL": mapper[i] = (e, v) => e.CONCURRENT_ENROL = 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="SKGS" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="SKGS" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="SKGS" /> entities</param> /// <returns>A merged <see cref="IEnumerable{SKGS}"/> of entities</returns> internal override IEnumerable<SKGS> ApplyDeltaEntities(IEnumerable<SKGS> Entities, List<SKGS> DeltaEntities) { HashSet<string> Index_SCHOOL = new HashSet<string>(DeltaEntities.Select(i => i.SCHOOL)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.SCHOOL; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_SCHOOL.Remove(entity.SCHOOL); if (entity.SCHOOL.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<NullDictionary<DateTime?, IReadOnlyList<SKGS>>> Index_LW_DATE; private Lazy<Dictionary<string, SKGS>> Index_SCHOOL; #endregion #region Index Methods /// <summary> /// Find SKGS by LW_DATE field /// </summary> /// <param name="LW_DATE">LW_DATE value used to find SKGS</param> /// <returns>List of related SKGS entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SKGS> FindByLW_DATE(DateTime? LW_DATE) { return Index_LW_DATE.Value[LW_DATE]; } /// <summary> /// Attempt to find SKGS by LW_DATE field /// </summary> /// <param name="LW_DATE">LW_DATE value used to find SKGS</param> /// <param name="Value">List of related SKGS entities</param> /// <returns>True if the list of related SKGS entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByLW_DATE(DateTime? LW_DATE, out IReadOnlyList<SKGS> Value) { return Index_LW_DATE.Value.TryGetValue(LW_DATE, out Value); } /// <summary> /// Attempt to find SKGS by LW_DATE field /// </summary> /// <param name="LW_DATE">LW_DATE value used to find SKGS</param> /// <returns>List of related SKGS entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SKGS> TryFindByLW_DATE(DateTime? LW_DATE) { IReadOnlyList<SKGS> value; if (Index_LW_DATE.Value.TryGetValue(LW_DATE, out value)) { return value; } else { return null; } } /// <summary> /// Find SKGS by SCHOOL field /// </summary> /// <param name="SCHOOL">SCHOOL value used to find SKGS</param> /// <returns>Related SKGS entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SKGS FindBySCHOOL(string SCHOOL) { return Index_SCHOOL.Value[SCHOOL]; } /// <summary> /// Attempt to find SKGS by SCHOOL field /// </summary> /// <param name="SCHOOL">SCHOOL value used to find SKGS</param> /// <param name="Value">Related SKGS entity</param> /// <returns>True if the related SKGS entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindBySCHOOL(string SCHOOL, out SKGS Value) { return Index_SCHOOL.Value.TryGetValue(SCHOOL, out Value); } /// <summary> /// Attempt to find SKGS by SCHOOL field /// </summary> /// <param name="SCHOOL">SCHOOL value used to find SKGS</param> /// <returns>Related SKGS entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SKGS TryFindBySCHOOL(string SCHOOL) { SKGS value; if (Index_SCHOOL.Value.TryGetValue(SCHOOL, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a SKGS 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].[SKGS]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[SKGS]( [SCHOOL] varchar(8) NOT NULL, [NAME] varchar(40) NULL, [SCHOOL_TYPE] varchar(33) NULL, [ENTITY] varchar(2) NULL, [SCHOOL_ID] varchar(4) NULL, [SCHOOL_NUMBER] varchar(2) NULL, [CAMPUS_TYPE] varchar(33) NULL, [CAMPUS_NAME] varchar(40) NULL, [REGION] smallint NULL, [REGION_NAME] varchar(30) NULL, [ADDRESS01] varchar(30) NULL, [ADDRESS02] varchar(30) NULL, [SUBURB] varchar(30) NULL, [STATE] varchar(3) NULL, [POSTCODE] varchar(4) NULL, [TELEPHONE] varchar(20) NULL, [FAX] varchar(20) NULL, [MAILING_ADDRESS01] varchar(30) NULL, [MAILING_ADDRESS02] varchar(30) NULL, [MAILING_SUBURB] varchar(30) NULL, [MAILING_STATE] varchar(3) NULL, [MAILING_POSTCODE] varchar(4) NULL, [DELIVERY_ADDRESS01] varchar(30) NULL, [DELIVERY_ADDRESS02] varchar(30) NULL, [DELIVERY_SUBURB] varchar(30) NULL, [DELIVERY_STATE] varchar(3) NULL, [DELIVERY_POSTCODE] varchar(4) NULL, [DELIVERY_TELEPHONE] varchar(20) NULL, [DELIVERY_FAX] varchar(20) NULL, [E_MAIL] varchar(255) NULL, [INTERNET_ADDRESS] varchar(255) NULL, [CASES21_RELEASE] varchar(12) NULL, [MAP_TYPE] varchar(1) NULL, [MAP_NUM] varchar(4) NULL, [X_AXIS] varchar(2) NULL, [Y_AXIS] varchar(2) NULL, [SCH_PRINCIPAL_SALUTATION] varchar(4) NULL, [SCH_PRINCIPAL_FIRST_NAME] varchar(20) NULL, [SCH_PRINCIPAL_SURNAME] varchar(30) NULL, [SCH_PRINCIPAL_TELEPHONE] varchar(20) NULL, [SALUTATION] varchar(4) NULL, [SURNAME] varchar(30) NULL, [FIRST_NAME] varchar(20) NULL, [CLOSED] varchar(1) NULL, [CONCURRENT_ENROL] varchar(1) NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [SKGS_Index_SCHOOL] PRIMARY KEY CLUSTERED ( [SCHOOL] ASC ) ); CREATE NONCLUSTERED INDEX [SKGS_Index_LW_DATE] ON [dbo].[SKGS] ( [LW_DATE] 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].[SKGS]') AND name = N'SKGS_Index_LW_DATE') ALTER INDEX [SKGS_Index_LW_DATE] ON [dbo].[SKGS] 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].[SKGS]') AND name = N'SKGS_Index_LW_DATE') ALTER INDEX [SKGS_Index_LW_DATE] ON [dbo].[SKGS] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="SKGS"/> 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="SKGS"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<SKGS> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<string> Index_SCHOOL = new List<string>(); foreach (var entity in Entities) { Index_SCHOOL.Add(entity.SCHOOL); } builder.AppendLine("DELETE [dbo].[SKGS] WHERE"); // Index_SCHOOL builder.Append("[SCHOOL] IN ("); for (int index = 0; index < Index_SCHOOL.Count; index++) { if (index != 0) builder.Append(", "); // SCHOOL var parameterSCHOOL = $"@p{parameterIndex++}"; builder.Append(parameterSCHOOL); command.Parameters.Add(parameterSCHOOL, SqlDbType.VarChar, 8).Value = Index_SCHOOL[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the SKGS data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the SKGS data set</returns> public override EduHubDataSetDataReader<SKGS> GetDataSetDataReader() { return new SKGSDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the SKGS data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the SKGS data set</returns> public override EduHubDataSetDataReader<SKGS> GetDataSetDataReader(List<SKGS> Entities) { return new SKGSDataReader(new EduHubDataSetLoadedReader<SKGS>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class SKGSDataReader : EduHubDataSetDataReader<SKGS> { public SKGSDataReader(IEduHubDataSetReader<SKGS> Reader) : base (Reader) { } public override int FieldCount { get { return 48; } } public override object GetValue(int i) { switch (i) { case 0: // SCHOOL return Current.SCHOOL; case 1: // NAME return Current.NAME; case 2: // SCHOOL_TYPE return Current.SCHOOL_TYPE; case 3: // ENTITY return Current.ENTITY; case 4: // SCHOOL_ID return Current.SCHOOL_ID; case 5: // SCHOOL_NUMBER return Current.SCHOOL_NUMBER; case 6: // CAMPUS_TYPE return Current.CAMPUS_TYPE; case 7: // CAMPUS_NAME return Current.CAMPUS_NAME; case 8: // REGION return Current.REGION; case 9: // REGION_NAME return Current.REGION_NAME; case 10: // ADDRESS01 return Current.ADDRESS01; case 11: // ADDRESS02 return Current.ADDRESS02; case 12: // SUBURB return Current.SUBURB; case 13: // STATE return Current.STATE; case 14: // POSTCODE return Current.POSTCODE; case 15: // TELEPHONE return Current.TELEPHONE; case 16: // FAX return Current.FAX; case 17: // MAILING_ADDRESS01 return Current.MAILING_ADDRESS01; case 18: // MAILING_ADDRESS02 return Current.MAILING_ADDRESS02; case 19: // MAILING_SUBURB return Current.MAILING_SUBURB; case 20: // MAILING_STATE return Current.MAILING_STATE; case 21: // MAILING_POSTCODE return Current.MAILING_POSTCODE; case 22: // DELIVERY_ADDRESS01 return Current.DELIVERY_ADDRESS01; case 23: // DELIVERY_ADDRESS02 return Current.DELIVERY_ADDRESS02; case 24: // DELIVERY_SUBURB return Current.DELIVERY_SUBURB; case 25: // DELIVERY_STATE return Current.DELIVERY_STATE; case 26: // DELIVERY_POSTCODE return Current.DELIVERY_POSTCODE; case 27: // DELIVERY_TELEPHONE return Current.DELIVERY_TELEPHONE; case 28: // DELIVERY_FAX return Current.DELIVERY_FAX; case 29: // E_MAIL return Current.E_MAIL; case 30: // INTERNET_ADDRESS return Current.INTERNET_ADDRESS; case 31: // CASES21_RELEASE return Current.CASES21_RELEASE; case 32: // MAP_TYPE return Current.MAP_TYPE; case 33: // MAP_NUM return Current.MAP_NUM; case 34: // X_AXIS return Current.X_AXIS; case 35: // Y_AXIS return Current.Y_AXIS; case 36: // SCH_PRINCIPAL_SALUTATION return Current.SCH_PRINCIPAL_SALUTATION; case 37: // SCH_PRINCIPAL_FIRST_NAME return Current.SCH_PRINCIPAL_FIRST_NAME; case 38: // SCH_PRINCIPAL_SURNAME return Current.SCH_PRINCIPAL_SURNAME; case 39: // SCH_PRINCIPAL_TELEPHONE return Current.SCH_PRINCIPAL_TELEPHONE; case 40: // SALUTATION return Current.SALUTATION; case 41: // SURNAME return Current.SURNAME; case 42: // FIRST_NAME return Current.FIRST_NAME; case 43: // CLOSED return Current.CLOSED; case 44: // CONCURRENT_ENROL return Current.CONCURRENT_ENROL; case 45: // LW_DATE return Current.LW_DATE; case 46: // LW_TIME return Current.LW_TIME; case 47: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 1: // NAME return Current.NAME == null; case 2: // SCHOOL_TYPE return Current.SCHOOL_TYPE == null; case 3: // ENTITY return Current.ENTITY == null; case 4: // SCHOOL_ID return Current.SCHOOL_ID == null; case 5: // SCHOOL_NUMBER return Current.SCHOOL_NUMBER == null; case 6: // CAMPUS_TYPE return Current.CAMPUS_TYPE == null; case 7: // CAMPUS_NAME return Current.CAMPUS_NAME == null; case 8: // REGION return Current.REGION == null; case 9: // REGION_NAME return Current.REGION_NAME == null; case 10: // ADDRESS01 return Current.ADDRESS01 == null; case 11: // ADDRESS02 return Current.ADDRESS02 == null; case 12: // SUBURB return Current.SUBURB == null; case 13: // STATE return Current.STATE == null; case 14: // POSTCODE return Current.POSTCODE == null; case 15: // TELEPHONE return Current.TELEPHONE == null; case 16: // FAX return Current.FAX == null; case 17: // MAILING_ADDRESS01 return Current.MAILING_ADDRESS01 == null; case 18: // MAILING_ADDRESS02 return Current.MAILING_ADDRESS02 == null; case 19: // MAILING_SUBURB return Current.MAILING_SUBURB == null; case 20: // MAILING_STATE return Current.MAILING_STATE == null; case 21: // MAILING_POSTCODE return Current.MAILING_POSTCODE == null; case 22: // DELIVERY_ADDRESS01 return Current.DELIVERY_ADDRESS01 == null; case 23: // DELIVERY_ADDRESS02 return Current.DELIVERY_ADDRESS02 == null; case 24: // DELIVERY_SUBURB return Current.DELIVERY_SUBURB == null; case 25: // DELIVERY_STATE return Current.DELIVERY_STATE == null; case 26: // DELIVERY_POSTCODE return Current.DELIVERY_POSTCODE == null; case 27: // DELIVERY_TELEPHONE return Current.DELIVERY_TELEPHONE == null; case 28: // DELIVERY_FAX return Current.DELIVERY_FAX == null; case 29: // E_MAIL return Current.E_MAIL == null; case 30: // INTERNET_ADDRESS return Current.INTERNET_ADDRESS == null; case 31: // CASES21_RELEASE return Current.CASES21_RELEASE == null; case 32: // MAP_TYPE return Current.MAP_TYPE == null; case 33: // MAP_NUM return Current.MAP_NUM == null; case 34: // X_AXIS return Current.X_AXIS == null; case 35: // Y_AXIS return Current.Y_AXIS == null; case 36: // SCH_PRINCIPAL_SALUTATION return Current.SCH_PRINCIPAL_SALUTATION == null; case 37: // SCH_PRINCIPAL_FIRST_NAME return Current.SCH_PRINCIPAL_FIRST_NAME == null; case 38: // SCH_PRINCIPAL_SURNAME return Current.SCH_PRINCIPAL_SURNAME == null; case 39: // SCH_PRINCIPAL_TELEPHONE return Current.SCH_PRINCIPAL_TELEPHONE == null; case 40: // SALUTATION return Current.SALUTATION == null; case 41: // SURNAME return Current.SURNAME == null; case 42: // FIRST_NAME return Current.FIRST_NAME == null; case 43: // CLOSED return Current.CLOSED == null; case 44: // CONCURRENT_ENROL return Current.CONCURRENT_ENROL == null; case 45: // LW_DATE return Current.LW_DATE == null; case 46: // LW_TIME return Current.LW_TIME == null; case 47: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // SCHOOL return "SCHOOL"; case 1: // NAME return "NAME"; case 2: // SCHOOL_TYPE return "SCHOOL_TYPE"; case 3: // ENTITY return "ENTITY"; case 4: // SCHOOL_ID return "SCHOOL_ID"; case 5: // SCHOOL_NUMBER return "SCHOOL_NUMBER"; case 6: // CAMPUS_TYPE return "CAMPUS_TYPE"; case 7: // CAMPUS_NAME return "CAMPUS_NAME"; case 8: // REGION return "REGION"; case 9: // REGION_NAME return "REGION_NAME"; case 10: // ADDRESS01 return "ADDRESS01"; case 11: // ADDRESS02 return "ADDRESS02"; case 12: // SUBURB return "SUBURB"; case 13: // STATE return "STATE"; case 14: // POSTCODE return "POSTCODE"; case 15: // TELEPHONE return "TELEPHONE"; case 16: // FAX return "FAX"; case 17: // MAILING_ADDRESS01 return "MAILING_ADDRESS01"; case 18: // MAILING_ADDRESS02 return "MAILING_ADDRESS02"; case 19: // MAILING_SUBURB return "MAILING_SUBURB"; case 20: // MAILING_STATE return "MAILING_STATE"; case 21: // MAILING_POSTCODE return "MAILING_POSTCODE"; case 22: // DELIVERY_ADDRESS01 return "DELIVERY_ADDRESS01"; case 23: // DELIVERY_ADDRESS02 return "DELIVERY_ADDRESS02"; case 24: // DELIVERY_SUBURB return "DELIVERY_SUBURB"; case 25: // DELIVERY_STATE return "DELIVERY_STATE"; case 26: // DELIVERY_POSTCODE return "DELIVERY_POSTCODE"; case 27: // DELIVERY_TELEPHONE return "DELIVERY_TELEPHONE"; case 28: // DELIVERY_FAX return "DELIVERY_FAX"; case 29: // E_MAIL return "E_MAIL"; case 30: // INTERNET_ADDRESS return "INTERNET_ADDRESS"; case 31: // CASES21_RELEASE return "CASES21_RELEASE"; case 32: // MAP_TYPE return "MAP_TYPE"; case 33: // MAP_NUM return "MAP_NUM"; case 34: // X_AXIS return "X_AXIS"; case 35: // Y_AXIS return "Y_AXIS"; case 36: // SCH_PRINCIPAL_SALUTATION return "SCH_PRINCIPAL_SALUTATION"; case 37: // SCH_PRINCIPAL_FIRST_NAME return "SCH_PRINCIPAL_FIRST_NAME"; case 38: // SCH_PRINCIPAL_SURNAME return "SCH_PRINCIPAL_SURNAME"; case 39: // SCH_PRINCIPAL_TELEPHONE return "SCH_PRINCIPAL_TELEPHONE"; case 40: // SALUTATION return "SALUTATION"; case 41: // SURNAME return "SURNAME"; case 42: // FIRST_NAME return "FIRST_NAME"; case 43: // CLOSED return "CLOSED"; case 44: // CONCURRENT_ENROL return "CONCURRENT_ENROL"; case 45: // LW_DATE return "LW_DATE"; case 46: // LW_TIME return "LW_TIME"; case 47: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "SCHOOL": return 0; case "NAME": return 1; case "SCHOOL_TYPE": return 2; case "ENTITY": return 3; case "SCHOOL_ID": return 4; case "SCHOOL_NUMBER": return 5; case "CAMPUS_TYPE": return 6; case "CAMPUS_NAME": return 7; case "REGION": return 8; case "REGION_NAME": return 9; case "ADDRESS01": return 10; case "ADDRESS02": return 11; case "SUBURB": return 12; case "STATE": return 13; case "POSTCODE": return 14; case "TELEPHONE": return 15; case "FAX": return 16; case "MAILING_ADDRESS01": return 17; case "MAILING_ADDRESS02": return 18; case "MAILING_SUBURB": return 19; case "MAILING_STATE": return 20; case "MAILING_POSTCODE": return 21; case "DELIVERY_ADDRESS01": return 22; case "DELIVERY_ADDRESS02": return 23; case "DELIVERY_SUBURB": return 24; case "DELIVERY_STATE": return 25; case "DELIVERY_POSTCODE": return 26; case "DELIVERY_TELEPHONE": return 27; case "DELIVERY_FAX": return 28; case "E_MAIL": return 29; case "INTERNET_ADDRESS": return 30; case "CASES21_RELEASE": return 31; case "MAP_TYPE": return 32; case "MAP_NUM": return 33; case "X_AXIS": return 34; case "Y_AXIS": return 35; case "SCH_PRINCIPAL_SALUTATION": return 36; case "SCH_PRINCIPAL_FIRST_NAME": return 37; case "SCH_PRINCIPAL_SURNAME": return 38; case "SCH_PRINCIPAL_TELEPHONE": return 39; case "SALUTATION": return 40; case "SURNAME": return 41; case "FIRST_NAME": return 42; case "CLOSED": return 43; case "CONCURRENT_ENROL": return 44; case "LW_DATE": return 45; case "LW_TIME": return 46; case "LW_USER": return 47; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
namespace PlugInDemo.Migrations { using System; using System.Collections.Generic; using System.Data.Entity.Infrastructure.Annotations; using System.Data.Entity.Migrations; public partial class Upgraded_To_V0_9 : DbMigration { public override void Up() { DropForeignKey("dbo.AbpSettings", "TenantId", "dbo.AbpTenants"); DropForeignKey("dbo.AbpUsers", "TenantId", "dbo.AbpTenants"); DropForeignKey("dbo.AbpRoles", "TenantId", "dbo.AbpTenants"); DropIndex("dbo.AbpUserLoginAttempts", new[] { "TenancyName", "UserNameOrEmailAddress", "Result" }); CreateTable( "dbo.AbpTenantNotifications", c => new { Id = c.Guid(nullable: false), TenantId = c.Int(), NotificationName = c.String(nullable: false, maxLength: 96), Data = c.String(), DataTypeName = c.String(maxLength: 512), EntityTypeName = c.String(maxLength: 250), EntityTypeAssemblyQualifiedName = c.String(maxLength: 512), EntityId = c.String(maxLength: 96), Severity = c.Byte(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_TenantNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); AlterTableAnnotations( "dbo.AbpFeatures", c => new { Id = c.Long(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 128), Value = c.String(nullable: false, maxLength: 2000), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), EditionId = c.Int(), TenantId = c.Int(), Discriminator = c.String(nullable: false, maxLength: 128), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_TenantFeatureSetting_MustHaveTenant", new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition") }, }); AlterTableAnnotations( "dbo.AbpNotificationSubscriptions", c => new { Id = c.Guid(nullable: false), TenantId = c.Int(), UserId = c.Long(nullable: false), NotificationName = c.String(maxLength: 96), EntityTypeName = c.String(maxLength: 250), EntityTypeAssemblyQualifiedName = c.String(maxLength: 512), EntityId = c.String(maxLength: 96), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_NotificationSubscriptionInfo_MayHaveTenant", new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition") }, }); AlterTableAnnotations( "dbo.AbpPermissions", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), Name = c.String(nullable: false, maxLength: 128), IsGranted = c.Boolean(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), RoleId = c.Int(), UserId = c.Long(), Discriminator = c.String(nullable: false, maxLength: 128), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_PermissionSetting_MayHaveTenant", new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition") }, { "DynamicFilter_RolePermissionSetting_MayHaveTenant", new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition") }, { "DynamicFilter_UserPermissionSetting_MayHaveTenant", new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition") }, }); AlterTableAnnotations( "dbo.AbpUserLogins", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(nullable: false), LoginProvider = c.String(nullable: false, maxLength: 128), ProviderKey = c.String(nullable: false, maxLength: 256), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_UserLogin_MayHaveTenant", new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition") }, }); AlterTableAnnotations( "dbo.AbpUserRoles", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(nullable: false), RoleId = c.Int(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_UserRole_MayHaveTenant", new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition") }, }); AlterTableAnnotations( "dbo.AbpSettings", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(), Name = c.String(nullable: false, maxLength: 256), Value = c.String(maxLength: 2000), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_Setting_MayHaveTenant", new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition") }, }); AlterTableAnnotations( "dbo.AbpUserLoginAttempts", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), TenancyName = c.String(maxLength: 64), UserId = c.Long(), UserNameOrEmailAddress = c.String(maxLength: 255), ClientIpAddress = c.String(maxLength: 64), ClientName = c.String(maxLength: 128), BrowserInfo = c.String(maxLength: 256), Result = c.Byte(nullable: false), CreationTime = c.DateTime(nullable: false), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_UserLoginAttempt_MayHaveTenant", new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition") }, }); AlterTableAnnotations( "dbo.AbpUserNotifications", c => new { Id = c.Guid(nullable: false), TenantId = c.Int(), UserId = c.Long(nullable: false), NotificationId = c.Guid(nullable: false), State = c.Int(nullable: false), CreationTime = c.DateTime(nullable: false), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_UserNotificationInfo_MayHaveTenant", new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition") }, }); AddColumn("dbo.AbpPermissions", "TenantId", c => c.Int()); AddColumn("dbo.AbpUserLogins", "TenantId", c => c.Int()); AddColumn("dbo.AbpUserRoles", "TenantId", c => c.Int()); AddColumn("dbo.AbpUserNotifications", "TenantId", c => c.Int()); AlterColumn("dbo.AbpUserLoginAttempts", "UserNameOrEmailAddress", c => c.String(maxLength: 255)); CreateIndex("dbo.AbpUserLoginAttempts", new[] { "UserId", "TenantId" }); CreateIndex("dbo.AbpUserLoginAttempts", new[] { "TenancyName", "UserNameOrEmailAddress", "Result" }); //Update current AbpUserRoles.TenantId values Sql(@"UPDATE AbpUserRoles SET TenantId = AbpUsers.TenantId FROM AbpUsers WHERE AbpUserRoles.UserId = AbpUsers.Id"); //Update current AbpUserLogins.TenantId values Sql(@"UPDATE AbpUserLogins SET TenantId = AbpUsers.TenantId FROM AbpUsers WHERE AbpUserLogins.UserId = AbpUsers.Id"); //Update current AbpPermissions.TenantId values Sql(@"UPDATE AbpPermissions SET TenantId = AbpUsers.TenantId FROM AbpUsers WHERE AbpPermissions.UserId = AbpUsers.Id"); Sql(@"UPDATE AbpPermissions SET TenantId = AbpRoles.TenantId FROM AbpRoles WHERE AbpPermissions.RoleId = AbpRoles.Id"); //Update current AbpUserNotifications.TenantId values Sql(@"UPDATE AbpUserNotifications SET TenantId = AbpUsers.TenantId FROM AbpUsers WHERE AbpUserNotifications.UserId = AbpUsers.Id"); //Update current AbpSettings.TenantId values Sql(@"UPDATE AbpSettings SET TenantId = AbpUsers.TenantId FROM AbpUsers WHERE AbpSettings.UserId = AbpUsers.Id"); } public override void Down() { DropIndex("dbo.AbpUserLoginAttempts", new[] { "TenancyName", "UserNameOrEmailAddress", "Result" }); DropIndex("dbo.AbpUserLoginAttempts", new[] { "UserId", "TenantId" }); AlterColumn("dbo.AbpUserLoginAttempts", "UserNameOrEmailAddress", c => c.String(maxLength: 256)); DropColumn("dbo.AbpUserNotifications", "TenantId"); DropColumn("dbo.AbpUserRoles", "TenantId"); DropColumn("dbo.AbpUserLogins", "TenantId"); DropColumn("dbo.AbpPermissions", "TenantId"); AlterTableAnnotations( "dbo.AbpUserNotifications", c => new { Id = c.Guid(nullable: false), TenantId = c.Int(), UserId = c.Long(nullable: false), NotificationId = c.Guid(nullable: false), State = c.Int(nullable: false), CreationTime = c.DateTime(nullable: false), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_UserNotificationInfo_MayHaveTenant", new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null) }, }); AlterTableAnnotations( "dbo.AbpUserLoginAttempts", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), TenancyName = c.String(maxLength: 64), UserId = c.Long(), UserNameOrEmailAddress = c.String(maxLength: 255), ClientIpAddress = c.String(maxLength: 64), ClientName = c.String(maxLength: 128), BrowserInfo = c.String(maxLength: 256), Result = c.Byte(nullable: false), CreationTime = c.DateTime(nullable: false), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_UserLoginAttempt_MayHaveTenant", new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null) }, }); AlterTableAnnotations( "dbo.AbpSettings", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(), Name = c.String(nullable: false, maxLength: 256), Value = c.String(maxLength: 2000), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_Setting_MayHaveTenant", new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null) }, }); AlterTableAnnotations( "dbo.AbpUserRoles", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(nullable: false), RoleId = c.Int(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_UserRole_MayHaveTenant", new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null) }, }); AlterTableAnnotations( "dbo.AbpUserLogins", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(nullable: false), LoginProvider = c.String(nullable: false, maxLength: 128), ProviderKey = c.String(nullable: false, maxLength: 256), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_UserLogin_MayHaveTenant", new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null) }, }); AlterTableAnnotations( "dbo.AbpPermissions", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), Name = c.String(nullable: false, maxLength: 128), IsGranted = c.Boolean(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), RoleId = c.Int(), UserId = c.Long(), Discriminator = c.String(nullable: false, maxLength: 128), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_PermissionSetting_MayHaveTenant", new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null) }, { "DynamicFilter_RolePermissionSetting_MayHaveTenant", new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null) }, { "DynamicFilter_UserPermissionSetting_MayHaveTenant", new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null) }, }); AlterTableAnnotations( "dbo.AbpNotificationSubscriptions", c => new { Id = c.Guid(nullable: false), TenantId = c.Int(), UserId = c.Long(nullable: false), NotificationName = c.String(maxLength: 96), EntityTypeName = c.String(maxLength: 250), EntityTypeAssemblyQualifiedName = c.String(maxLength: 512), EntityId = c.String(maxLength: 96), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_NotificationSubscriptionInfo_MayHaveTenant", new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null) }, }); AlterTableAnnotations( "dbo.AbpFeatures", c => new { Id = c.Long(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 128), Value = c.String(nullable: false, maxLength: 2000), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), EditionId = c.Int(), TenantId = c.Int(), Discriminator = c.String(nullable: false, maxLength: 128), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_TenantFeatureSetting_MustHaveTenant", new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null) }, }); DropTable("dbo.AbpTenantNotifications", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_TenantNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); CreateIndex("dbo.AbpUserLoginAttempts", new[] { "TenancyName", "UserNameOrEmailAddress", "Result" }); AddForeignKey("dbo.AbpRoles", "TenantId", "dbo.AbpTenants", "Id"); AddForeignKey("dbo.AbpUsers", "TenantId", "dbo.AbpTenants", "Id"); AddForeignKey("dbo.AbpSettings", "TenantId", "dbo.AbpTenants", "Id"); } } }