context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* * 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.Linq; using System.Reflection; using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "LocalSimulationConnectorModule")] public class LocalSimulationConnectorModule : ISharedRegionModule, ISimulationService { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Version of this service. /// </summary> /// <remarks> /// Currently valid versions are "SIMULATION/0.1" and "SIMULATION/0.2" /// </remarks> public string ServiceVersion { get; set; } private float m_VersionNumber = 0.3f; /// <summary> /// Map region ID to scene. /// </summary> private Dictionary<UUID, Scene> m_scenes = new Dictionary<UUID, Scene>(); /// <summary> /// Is this module enabled? /// </summary> private bool m_ModuleEnabled = false; #region Region Module interface public void Initialise(IConfigSource configSource) { IConfig moduleConfig = configSource.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("SimulationServices", ""); if (name == Name) { InitialiseService(configSource); m_ModuleEnabled = true; m_log.Info("[LOCAL SIMULATION CONNECTOR]: Local simulation enabled."); } } } public void InitialiseService(IConfigSource configSource) { ServiceVersion = "SIMULATION/0.3"; IConfig config = configSource.Configs["SimulationService"]; if (config != null) { ServiceVersion = config.GetString("ConnectorProtocolVersion", ServiceVersion); if (ServiceVersion != "SIMULATION/0.1" && ServiceVersion != "SIMULATION/0.2" && ServiceVersion != "SIMULATION/0.3") throw new Exception(string.Format("Invalid ConnectorProtocolVersion {0}", ServiceVersion)); string[] versionComponents = ServiceVersion.Split(new char[] { '/' }); if (versionComponents.Length >= 2) float.TryParse(versionComponents[1], out m_VersionNumber); m_log.InfoFormat( "[LOCAL SIMULATION CONNECTOR]: Initialized with connector protocol version {0}", ServiceVersion); } } public void PostInitialise() { } public void AddRegion(Scene scene) { if (!m_ModuleEnabled) return; Init(scene); scene.RegisterModuleInterface<ISimulationService>(this); } public void RemoveRegion(Scene scene) { if (!m_ModuleEnabled) return; RemoveScene(scene); scene.UnregisterModuleInterface<ISimulationService>(this); } public void RegionLoaded(Scene scene) { } public void Close() { } public Type ReplaceableInterface { get { return null; } } public string Name { get { return "LocalSimulationConnectorModule"; } } /// <summary> /// Can be called from other modules. /// </summary> /// <param name="scene"></param> public void RemoveScene(Scene scene) { lock (m_scenes) { if (m_scenes.ContainsKey(scene.RegionInfo.RegionID)) m_scenes.Remove(scene.RegionInfo.RegionID); else m_log.WarnFormat( "[LOCAL SIMULATION CONNECTOR]: Tried to remove region {0} but it was not present", scene.RegionInfo.RegionName); } } /// <summary> /// Can be called from other modules. /// </summary> /// <param name="scene"></param> public void Init(Scene scene) { lock (m_scenes) { if (!m_scenes.ContainsKey(scene.RegionInfo.RegionID)) m_scenes[scene.RegionInfo.RegionID] = scene; else m_log.WarnFormat( "[LOCAL SIMULATION CONNECTOR]: Tried to add region {0} but it is already present", scene.RegionInfo.RegionName); } } #endregion #region ISimulationService public IScene GetScene(UUID regionId) { if (m_scenes.ContainsKey(regionId)) { return m_scenes[regionId]; } else { // FIXME: This was pre-existing behaviour but possibly not a good idea, since it hides an error rather // than making it obvious and fixable. Need to see if the error message comes up in practice. Scene s = m_scenes.Values.ToArray()[0]; m_log.ErrorFormat( "[LOCAL SIMULATION CONNECTOR]: Region with id {0} not found. Returning {1} {2} instead", regionId, s.RegionInfo.RegionName, s.RegionInfo.RegionID); return s; } } public ISimulationService GetInnerService() { return this; } /** * Agent-related communications */ public bool CreateAgent(GridRegion source, GridRegion destination, AgentCircuitData aCircuit, uint teleportFlags, out string reason) { if (destination == null) { reason = "Given destination was null"; m_log.DebugFormat("[LOCAL SIMULATION CONNECTOR]: CreateAgent was given a null destination"); return false; } if (m_scenes.ContainsKey(destination.RegionID)) { // m_log.DebugFormat("[LOCAL SIMULATION CONNECTOR]: Found region {0} to send SendCreateChildAgent", destination.RegionName); return m_scenes[destination.RegionID].NewUserConnection(aCircuit, teleportFlags, source, out reason); } reason = "Did not find region " + destination.RegionName; return false; } public bool UpdateAgent(GridRegion destination, AgentData cAgentData) { if (destination == null) return false; if (m_scenes.ContainsKey(destination.RegionID)) { // m_log.DebugFormat( // "[LOCAL SIMULATION CONNECTOR]: Found region {0} {1} to send AgentUpdate", // destination.RegionName, destination.RegionID); return m_scenes[destination.RegionID].IncomingUpdateChildAgent(cAgentData); } // m_log.DebugFormat( // "[LOCAL COMMS]: Did not find region {0} {1} for ChildAgentUpdate", // destination.RegionName, destination.RegionID); return false; } public bool UpdateAgent(GridRegion destination, AgentPosition agentPosition) { if (destination == null) return false; // We limit the number of messages sent for a position change to just one per // simulator so when we receive the update we need to hand it to each of the // scenes; scenes each check to see if the is a scene presence for the avatar // note that we really don't need the GridRegion for this call foreach (Scene s in m_scenes.Values) { // m_log.Debug("[LOCAL COMMS]: Found region to send ChildAgentUpdate"); s.IncomingUpdateChildAgent(agentPosition); } //m_log.Debug("[LOCAL COMMS]: region not found for ChildAgentUpdate"); return true; } public bool QueryAccess(GridRegion destination, UUID agentID, string agentHomeURI, bool viaTeleport, Vector3 position, string theirversion, out string version, out string reason) { reason = "Communications failure"; version = ServiceVersion; if (destination == null) return false; if (m_scenes.ContainsKey(destination.RegionID)) { // m_log.DebugFormat( // "[LOCAL SIMULATION CONNECTOR]: Found region {0} {1} to send AgentUpdate", // s.RegionInfo.RegionName, destination.RegionHandle); uint size = m_scenes[destination.RegionID].RegionInfo.RegionSizeX; float theirVersionNumber = 0f; string[] versionComponents = theirversion.Split(new char[] { '/' }); if (versionComponents.Length >= 2) float.TryParse(versionComponents[1], out theirVersionNumber); // Var regions here, and the requesting simulator is in an older version. // We will forbide this, because it crashes the viewers if (theirVersionNumber < 0.3f && size > 256) { reason = "Destination is a variable-sized region, and source is an old simulator. Consider upgrading."; m_log.DebugFormat("[LOCAL SIMULATION CONNECTOR]: Request to access this variable-sized region from {0} simulator was denied", theirVersionNumber); return false; } return m_scenes[destination.RegionID].QueryAccess(agentID, agentHomeURI, viaTeleport, position, out reason); } //m_log.Debug("[LOCAL COMMS]: region not found for QueryAccess"); return false; } public bool ReleaseAgent(UUID originId, UUID agentId, string uri) { if (m_scenes.ContainsKey(originId)) { // m_log.DebugFormat( // "[LOCAL SIMULATION CONNECTOR]: Found region {0} {1} to send AgentUpdate", // s.RegionInfo.RegionName, destination.RegionHandle); m_scenes[originId].EntityTransferModule.AgentArrivedAtDestination(agentId); return true; } //m_log.Debug("[LOCAL COMMS]: region not found in SendReleaseAgent " + origin); return false; } public bool CloseAgent(GridRegion destination, UUID id, string auth_token) { if (destination == null) return false; if (m_scenes.ContainsKey(destination.RegionID)) { // m_log.DebugFormat( // "[LOCAL SIMULATION CONNECTOR]: Found region {0} {1} to send AgentUpdate", // s.RegionInfo.RegionName, destination.RegionHandle); m_scenes[destination.RegionID].CloseAgent(id, false, auth_token); return true; } //m_log.Debug("[LOCAL COMMS]: region not found in SendCloseAgent"); return false; } /** * Object-related communications */ public bool CreateObject(GridRegion destination, Vector3 newPosition, ISceneObject sog, bool isLocalCall) { if (destination == null) return false; if (m_scenes.ContainsKey(destination.RegionID)) { // m_log.DebugFormat( // "[LOCAL SIMULATION CONNECTOR]: Found region {0} {1} to send AgentUpdate", // s.RegionInfo.RegionName, destination.RegionHandle); Scene s = m_scenes[destination.RegionID]; if (isLocalCall) { // We need to make a local copy of the object ISceneObject sogClone = sog.CloneForNewScene(); sogClone.SetState(sog.GetStateSnapshot(), s); return s.IncomingCreateObject(newPosition, sogClone); } else { // Use the object as it came through the wire return s.IncomingCreateObject(newPosition, sog); } } return false; } #endregion #region Misc public bool IsLocalRegion(ulong regionhandle) { foreach (Scene s in m_scenes.Values) if (s.RegionInfo.RegionHandle == regionhandle) return true; return false; } public bool IsLocalRegion(UUID id) { return m_scenes.ContainsKey(id); } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Services_Common.Areas.HelpPage.ModelDescriptions; using Services_Common.Areas.HelpPage.Models; namespace Services_Common.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Web; using System.Xml; using Common.Logging; using WebDAVSharp.Server.Adapters; using WebDAVSharp.Server.Exceptions; using WebDAVSharp.Server.Stores; using WebDAVSharp.Server.Utilities; namespace WebDAVSharp.Server.MethodHandlers { /// <summary> /// This class implements the <c>PROPFIND</c> HTTP method for WebDAV#. /// </summary> internal class WebDavPropfindMethodHandler : WebDavMethodHandlerBase, IWebDavMethodHandler { private ILog _log; private Uri _requestUri; private List<WebDavProperty> _requestedProperties; private List<IWebDavStoreItem> _webDavStoreItems; /// <summary> /// Gets the collection of the names of the HTTP methods handled by this instance. /// </summary> /// <value> /// The names. /// </value> public IEnumerable<string> Names { get { return new[] { "PROPFIND" }; } } /// <summary> /// Processes the request. /// </summary> /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param> /// <param name="context">The /// <see cref="IHttpListenerContext" /> object containing both the request and response /// objects to use.</param> /// <param name="store">The <see cref="IWebDavStore" /> that the <see cref="WebDavServer" /> is hosting.</param> /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavUnauthorizedException"></exception> public void ProcessRequest(WebDavServer server, IHttpListenerContext context, IWebDavStore store) { _log = LogManager.GetCurrentClassLogger(); /*************************************************************************************************** * Retreive all the information from the request ***************************************************************************************************/ // Read the headers, ... bool isPropname = false; int depth = GetDepthHeader(context.Request); _requestUri = GetRequestUri(context.Request.Url.ToString()); try { _webDavStoreItems = GetWebDavStoreItems(context.Request.Url.GetItem(server, store), depth); } catch (UnauthorizedAccessException) { throw new WebDavUnauthorizedException(); } // Get the XmlDocument from the request XmlDocument requestDoc = GetXmlDocument(context.Request); // See what is requested _requestedProperties = new List<WebDavProperty>(); if (requestDoc.DocumentElement != null) { if (requestDoc.DocumentElement.LocalName != "propfind") _log.Debug("PROPFIND method without propfind in xml document"); else { XmlNode n = requestDoc.DocumentElement.FirstChild; if (n == null) _log.Debug("propfind element without children"); else { switch (n.LocalName) { case "allprop": _requestedProperties = GetAllProperties(); break; case "propname": isPropname = true; _requestedProperties = GetAllProperties(); break; case "prop": foreach (XmlNode child in n.ChildNodes) _requestedProperties.Add(new WebDavProperty(child.LocalName, "", child.NamespaceURI)); break; default: _requestedProperties.Add(new WebDavProperty(n.LocalName, "", n.NamespaceURI)); break; } } } } else _requestedProperties = GetAllProperties(); /*************************************************************************************************** * Create the body for the response ***************************************************************************************************/ XmlDocument responseDoc = ResponseDocument(context, isPropname); /*************************************************************************************************** * Send the response ***************************************************************************************************/ SendResponse(context, responseDoc); } #region RetrieveInformation /// <summary> /// Get the URI to the location /// If no slash at the end of the URI, this method adds one /// </summary> /// <param name="uri">The <see cref="string" /> that contains the URI</param> /// <returns> /// The <see cref="Uri" /> that contains the given uri /// </returns> private static Uri GetRequestUri(string uri) { return new Uri(uri.EndsWith("/") ? uri : uri + "/"); } /// <summary> /// Convert the given /// <see cref="IWebDavStoreItem" /> to a /// <see cref="List{T}" /> of /// <see cref="IWebDavStoreItem" /> /// This list depends on the "Depth" header /// </summary> /// <param name="iWebDavStoreItem">The <see cref="IWebDavStoreItem" /> that needs to be converted</param> /// <param name="depth">The "Depth" header</param> /// <returns> /// A <see cref="List{T}" /> of <see cref="IWebDavStoreItem" /> /// </returns> /// <exception cref="WebDAVSharp.Server.Exceptions.WebDavConflictException"></exception> private static List<IWebDavStoreItem> GetWebDavStoreItems(IWebDavStoreItem iWebDavStoreItem, int depth) { ILog _log = LogManager.GetCurrentClassLogger(); List<IWebDavStoreItem> list = new List<IWebDavStoreItem>(); //IWebDavStoreCollection // if the item is a collection IWebDavStoreCollection collection = iWebDavStoreItem as IWebDavStoreCollection; if (collection != null) { list.Add(collection); if (depth == 0) return list; foreach (IWebDavStoreItem item in collection.Items) { try { list.Add(item); } catch (Exception ex) { _log.Debug(ex.Message + "\r\n" + ex.StackTrace); } } return list; } // if the item is not a document, throw conflict exception if (!(iWebDavStoreItem is IWebDavStoreDocument)) throw new WebDavConflictException(); // add the item to the list list.Add(iWebDavStoreItem); return list; } /// <summary> /// Reads the XML body of the /// <see cref="IHttpListenerRequest" /> /// and converts it to an /// <see cref="XmlDocument" /> /// </summary> /// <param name="request">The <see cref="IHttpListenerRequest" /></param> /// <returns> /// The <see cref="XmlDocument" /> that contains the request body /// </returns> private XmlDocument GetXmlDocument(IHttpListenerRequest request) { try { StreamReader reader = new StreamReader(request.InputStream, Encoding.UTF8); string requestBody = reader.ReadToEnd(); reader.Close(); if (!String.IsNullOrEmpty(requestBody)) { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml(requestBody); return xmlDocument; } } catch (Exception) { _log.Warn("XmlDocument has not been read correctly"); } return new XmlDocument(); } /// <summary> /// Adds the standard properties for an Propfind allprop request to a <see cref="List{T}" /> of <see cref="WebDavProperty" /> /// </summary> /// <returns> /// The list with all the <see cref="WebDavProperty" /> /// </returns> private List<WebDavProperty> GetAllProperties() { List<WebDavProperty> list = new List<WebDavProperty> { new WebDavProperty("creationdate"), new WebDavProperty("displayname"), new WebDavProperty("getcontentlength"), new WebDavProperty("getcontenttype"), new WebDavProperty("getetag"), new WebDavProperty("getlastmodified"), new WebDavProperty("resourcetype"), new WebDavProperty("supportedlock"), new WebDavProperty("ishidden") }; //list.Add(new WebDAVProperty("getcontentlanguage")); //list.Add(new WebDAVProperty("lockdiscovery")); return list; } #endregion #region BuildResponseBody /// <summary> /// Builds the <see cref="XmlDocument" /> containing the response body /// </summary> /// <param name="context">The <see cref="IHttpListenerContext" /></param> /// <param name="propname">The boolean defining the Propfind propname request</param> /// <returns> /// The <see cref="XmlDocument" /> containing the response body /// </returns> private XmlDocument ResponseDocument(IHttpListenerContext context, bool propname) { // Create the basic response XmlDocument XmlDocument responseDoc = new XmlDocument(); const string responseXml = "<?xml version=\"1.0\"?><D:multistatus xmlns:D=\"DAV:\"></D:multistatus>"; responseDoc.LoadXml(responseXml); // Generate the manager XmlNamespaceManager manager = new XmlNamespaceManager(responseDoc.NameTable); manager.AddNamespace("D", "DAV:"); manager.AddNamespace("Office", "schemas-microsoft-com:office:office"); manager.AddNamespace("Repl", "http://schemas.microsoft.com/repl/"); manager.AddNamespace("Z", "urn:schemas-microsoft-com:"); int count = 0; foreach (IWebDavStoreItem webDavStoreItem in _webDavStoreItems) { // Create the response element WebDavProperty responseProperty = new WebDavProperty("response", ""); XmlElement responseElement = responseProperty.ToXmlElement(responseDoc); // The href element Uri result; if (count == 0) { Uri.TryCreate(_requestUri, "", out result); } else { Uri.TryCreate(_requestUri, webDavStoreItem.Name, out result); } WebDavProperty hrefProperty = new WebDavProperty("href", result.AbsoluteUri); responseElement.AppendChild(hrefProperty.ToXmlElement(responseDoc)); count++; // The propstat element WebDavProperty propstatProperty = new WebDavProperty("propstat", ""); XmlElement propstatElement = propstatProperty.ToXmlElement(responseDoc); // The prop element WebDavProperty propProperty = new WebDavProperty("prop", ""); XmlElement propElement = propProperty.ToXmlElement(responseDoc); foreach (WebDavProperty davProperty in _requestedProperties) { propElement.AppendChild(PropChildElement(davProperty, responseDoc, webDavStoreItem, propname)); } // Add the prop element to the propstat element propstatElement.AppendChild(propElement); // The status element WebDavProperty statusProperty = new WebDavProperty("status", "HTTP/1.1 " + context.Response.StatusCode + " " + HttpWorkerRequest.GetStatusDescription(context.Response.StatusCode)); propstatElement.AppendChild(statusProperty.ToXmlElement(responseDoc)); // Add the propstat element to the response element responseElement.AppendChild(propstatElement); // Add the response element to the multistatus element responseDoc.DocumentElement.AppendChild(responseElement); } return responseDoc; } /// <summary> /// Gives the /// <see cref="XmlElement" /> of a /// <see cref="WebDavProperty" /> /// with or without values /// or with or without child elements /// </summary> /// <param name="webDavProperty">The <see cref="WebDavProperty" /></param> /// <param name="xmlDocument">The <see cref="XmlDocument" /> containing the response body</param> /// <param name="iWebDavStoreItem">The <see cref="IWebDavStoreItem" /></param> /// <param name="isPropname">The boolean defining the Propfind propname request</param> /// <returns> /// The <see cref="XmlElement" /> of the <see cref="WebDavProperty" /> containing a value or child elements /// </returns> private XmlElement PropChildElement(WebDavProperty webDavProperty, XmlDocument xmlDocument, IWebDavStoreItem iWebDavStoreItem, bool isPropname) { // If Propfind request contains a propname element if (isPropname) { webDavProperty.Value = String.Empty; return webDavProperty.ToXmlElement(xmlDocument); } // If not, add the values to webDavProperty webDavProperty.Value = GetWebDavPropertyValue(iWebDavStoreItem, webDavProperty); XmlElement xmlElement = webDavProperty.ToXmlElement(xmlDocument); // If the webDavProperty is the resourcetype property // and the webDavStoreItem is a collection // add the collection XmlElement as a child to the xmlElement if (webDavProperty.Name != "resourcetype" || !iWebDavStoreItem.IsCollection) return xmlElement; WebDavProperty collectionProperty = new WebDavProperty("collection", ""); xmlElement.AppendChild(collectionProperty.ToXmlElement(xmlDocument)); return xmlElement; } /// <summary> /// Gets the correct value for a <see cref="WebDavProperty" /> /// </summary> /// <param name="webDavStoreItem">The <see cref="IWebDavStoreItem" /> defines the values</param> /// <param name="davProperty">The <see cref="WebDavProperty" /> that needs a value</param> /// <returns> /// A <see cref="string" /> containing the value /// </returns> private string GetWebDavPropertyValue(IWebDavStoreItem webDavStoreItem, WebDavProperty davProperty) { switch (davProperty.Name) { case "creationdate": return webDavStoreItem.CreationDate.ToUniversalTime().ToString("s") + "Z"; case "displayname": return webDavStoreItem.Name; case "getcontentlanguage": // still to implement !!! return String.Empty; case "getcontentlength": return (!webDavStoreItem.IsCollection ? "" + ((IWebDavStoreDocument) webDavStoreItem).Size : ""); case "getcontenttype": return (!webDavStoreItem.IsCollection ? "" + ((IWebDavStoreDocument) webDavStoreItem).MimeType : ""); case "getetag": return (!webDavStoreItem.IsCollection ? "" + ((IWebDavStoreDocument) webDavStoreItem).Etag : ""); case "getlastmodified": return webDavStoreItem.ModificationDate.ToUniversalTime().ToString("R"); case "lockdiscovery": // still to implement !!! return String.Empty; case "resourcetype": return ""; case "supportedlock": // still to implement !!! return ""; //webDavProperty.Value = "<D:lockentry><D:lockscope><D:shared/></D:lockscope><D:locktype><D:write/></D:locktype></D:lockentry>"; case "ishidden": return "" + webDavStoreItem.Hidden; default: return String.Empty; } } #endregion #region SendResponse /// <summary> /// Sends the response /// </summary> /// <param name="context">The <see cref="IHttpListenerContext" /> containing the response</param> /// <param name="responseDocument">The <see cref="XmlDocument" /> containing the response body</param> private static void SendResponse(IHttpListenerContext context, XmlDocument responseDocument) { // convert the XmlDocument byte[] responseBytes = Encoding.UTF8.GetBytes(responseDocument.InnerXml); // HttpStatusCode doesn't contain WebDav status codes, but HttpWorkerRequest can handle these WebDav status codes context.Response.StatusCode = (int)WebDavStatusCode.MultiStatus; context.Response.StatusDescription = HttpWorkerRequest.GetStatusDescription((int)WebDavStatusCode.MultiStatus); context.Response.ContentLength64 = responseBytes.Length; context.Response.AdaptedInstance.ContentType = "text/xml"; context.Response.OutputStream.Write(responseBytes, 0, responseBytes.Length); context.Response.Close(); } #endregion } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Diagnostics; namespace PanGu.Framework { public class Regex { static public bool GetMatchStrings(String text, String regx, bool ignoreCase, out List<string> output) { output = new List<string>(); output.Clear(); System.Text.RegularExpressions.Regex reg; int index = 0; int begin = 0; index = regx.IndexOf("(.+)"); if (index < 0) { index = regx.IndexOf("(.+?)"); if (index >= 0) { begin = index + 5; } } else { begin = index + 4; } if (index >= 0) { String endText = regx.Substring(begin); if (GetMatch(text, endText, ignoreCase) == "") { return false; } } if (ignoreCase) { reg = new System.Text.RegularExpressions.Regex(regx, System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Singleline); } else { reg = new System.Text.RegularExpressions.Regex(regx, System.Text.RegularExpressions.RegexOptions.Singleline); } System.Text.RegularExpressions.MatchCollection m = reg.Matches(text); if (m.Count == 0) return false; for (int j = 0; j < m.Count; j++) { int count = m[j].Groups.Count; for (int i = 1; i < count; i++) { output.Add(m[j].Groups[i].Value.Trim()); } } return true; } static public bool GetSingleMatchStrings(String text, String regx, bool ignoreCase, out List<string> output) { output = new List<string>(); System.Text.RegularExpressions.Regex reg; int index = 0; int begin = 0; index = regx.IndexOf("(.+)"); if (index < 0) { index = regx.IndexOf("(.+?)"); if (index >= 0) { begin = index + 5; } } else { begin = index + 4; } if (index >= 0) { String endText = regx.Substring(begin); if (GetMatch(text, endText, ignoreCase) == "") { return false; } } if (ignoreCase) { reg = new System.Text.RegularExpressions.Regex(regx, System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Singleline); } else { reg = new System.Text.RegularExpressions.Regex(regx, System.Text.RegularExpressions.RegexOptions.Singleline); } System.Text.RegularExpressions.MatchCollection m = reg.Matches(text); if (m.Count == 0) return false; for (int j = 0; j < m.Count; j++) { int count = m[j].Groups.Count; if (count > 0) { output.Add(m[j].Groups[count - 1].Value.Trim()); } } return true; } static public bool GetSplitWithoutFirstStrings(String text, String regx, bool ignoreCase, ref ArrayList output) { if (output == null) { Debug.Assert(false); return false; } output.Clear(); System.Text.RegularExpressions.Regex reg; if (ignoreCase) { reg = new System.Text.RegularExpressions.Regex(regx, System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Singleline); } else { reg = new System.Text.RegularExpressions.Regex(regx, System.Text.RegularExpressions.RegexOptions.Singleline); } String[] strs = reg.Split(text); if (strs == null) { return false; } if (strs.Length <= 1) { return false; } for (int j = 1; j < strs.Length; j++) { output.Add(strs[j]); } return true; } static public String GetMatch(String text, String regx, bool ignoreCase) { System.Text.RegularExpressions.Regex reg; int index = 0; int begin = 0; index = regx.IndexOf("(.+)"); if (index < 0) { index = regx.IndexOf("(.+?)"); if (index >= 0) { begin = index + 5; } } else { begin = index + 4; } if (index >= 0) { String endText = regx.Substring(begin); if (endText != "") { if (GetMatch(text, endText, ignoreCase) == "") { return ""; } } } if (ignoreCase) { reg = new System.Text.RegularExpressions.Regex(regx, System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Singleline); } else { reg = new System.Text.RegularExpressions.Regex(regx, System.Text.RegularExpressions.RegexOptions.Singleline); } String ret = ""; System.Text.RegularExpressions.Match m = reg.Match(text); if (m.Groups.Count > 0) { ret = m.Groups[m.Groups.Count - 1].Value; } return ret; } static public String GetMatchSum(String text, String regx, bool ignoreCase) { System.Text.RegularExpressions.Regex reg; int index = 0; int begin = 0; index = regx.IndexOf("(.+)"); if (index < 0) { index = regx.IndexOf("(.+?)"); if (index >= 0) { begin = index + 5; } } else { begin = index + 4; } if (index >= 0) { String endText = regx.Substring(begin); if (GetMatch(text, endText, ignoreCase) == "") { return ""; } } if (ignoreCase) { reg = new System.Text.RegularExpressions.Regex(regx, System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Singleline); } else { reg = new System.Text.RegularExpressions.Regex(regx, System.Text.RegularExpressions.RegexOptions.Singleline); } String ret = ""; System.Text.RegularExpressions.Match m = reg.Match(text); for (int i = 1; i < m.Groups.Count; i++) { ret += m.Groups[i].Value; } return ret; } public static String[] Split(String Src, String SplitStr) { System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(SplitStr); return reg.Split(Src); } public static String[] Split(String Src, String SplitStr, System.Text.RegularExpressions.RegexOptions option) { System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(SplitStr, option); return reg.Split(Src); } public static String Replace(String text, String regx, String newText, bool ignoreCase) { System.Text.RegularExpressions.Regex reg; if (ignoreCase) { reg = new System.Text.RegularExpressions.Regex(regx, System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Singleline); } else { reg = new System.Text.RegularExpressions.Regex(regx, System.Text.RegularExpressions.RegexOptions.Singleline); } return reg.Replace(text, newText); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Hyak.Common.Internals; using Microsoft.Azure; using Microsoft.WindowsAzure.Management.Automation; using Microsoft.WindowsAzure.Management.Automation.Models; using Newtonsoft.Json.Linq; namespace Microsoft.WindowsAzure.Management.Automation { /// <summary> /// Service operation for automation runbook draft. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> internal partial class RunbookDraftOperations : IServiceOperations<AutomationManagementClient>, IRunbookDraftOperations { /// <summary> /// Initializes a new instance of the RunbookDraftOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal RunbookDraftOperations(AutomationManagementClient client) { this._client = client; } private AutomationManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.Automation.AutomationManagementClient. /// </summary> public AutomationManagementClient Client { get { return this._client; } } /// <summary> /// Retrieve the runbook identified by runbook name. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the publish runbook operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public async Task<LongRunningOperationResultResponse> BeginPublishAsync(string automationAccount, RunbookDraftPublishParameters parameters, CancellationToken cancellationToken) { // Validate if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Name == null) { throw new ArgumentNullException("parameters.Name"); } if (parameters.PublishedBy == null) { throw new ArgumentNullException("parameters.PublishedBy"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "BeginPublishAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/cloudservices/OaaSCS/resources/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/~/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/runbooks/"; url = url + Uri.EscapeDataString(parameters.Name); url = url + "/draft/publish"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-12-08"); 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.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("ocp-referer", url); httpRequest.Headers.Add("x-ms-version", "2013-06-01"); // 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.Accepted) { 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 LongRunningOperationResultResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new LongRunningOperationResultResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("ocp-location")) { result.OperationStatusLink = httpResponse.Headers.GetValues("ocp-location").FirstOrDefault(); } if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Updates the runbook draft with runbookStream as its content. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The runbook draft update parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public async Task<LongRunningOperationResultResponse> BeginUpdateAsync(string automationAccount, RunbookDraftUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Name == null) { throw new ArgumentNullException("parameters.Name"); } if (parameters.Stream == null) { throw new ArgumentNullException("parameters.Stream"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "BeginUpdateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/cloudservices/OaaSCS/resources/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/~/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/runbooks/"; url = url + Uri.EscapeDataString(parameters.Name); url = url + "/draft/content"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-12-08"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("ocp-referer", url); httpRequest.Headers.Add("x-ms-version", "2013-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = parameters.Stream; httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("text/powershell"); // 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.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result LongRunningOperationResultResponse result = null; // Deserialize Response result = new LongRunningOperationResultResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("ocp-location")) { result.OperationStatusLink = httpResponse.Headers.GetValues("ocp-location").FirstOrDefault(); } if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieve the content of runbook draft identified by runbook name. /// (see http://aka.ms/azureautomationsdk/runbookdraftoperations for /// more information) /// </summary> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the runbook content operation. /// </returns> public async Task<RunbookContentResponse> ContentAsync(string automationAccount, string runbookName, CancellationToken cancellationToken) { // Validate if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (runbookName == null) { throw new ArgumentNullException("runbookName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("runbookName", runbookName); TracingAdapter.Enter(invocationId, this, "ContentAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/cloudservices/OaaSCS/resources/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/~/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/runbooks/"; url = url + Uri.EscapeDataString(runbookName); url = url + "/draft/content"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-12-08"); 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 httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2013-06-01"); // 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 RunbookContentResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new RunbookContentResponse(); result.Stream = responseContent; } 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> /// Retrieve the runbook draft identified by runbook name. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the get runbook draft operation. /// </returns> public async Task<RunbookDraftGetResponse> GetAsync(string automationAccount, string runbookName, CancellationToken cancellationToken) { // Validate if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (runbookName == null) { throw new ArgumentNullException("runbookName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("runbookName", runbookName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/cloudservices/OaaSCS/resources/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/~/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/runbooks/"; url = url + Uri.EscapeDataString(runbookName); url = url + "/draft"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-12-08"); 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 httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2013-06-01"); // 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 RunbookDraftGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new RunbookDraftGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { RunbookDraft runbookDraftInstance = new RunbookDraft(); result.RunbookDraft = runbookDraftInstance; JToken inEditValue = responseDoc["inEdit"]; if (inEditValue != null && inEditValue.Type != JTokenType.Null) { bool inEditInstance = ((bool)inEditValue); runbookDraftInstance.InEdit = inEditInstance; } JToken draftContentLinkValue = responseDoc["draftContentLink"]; if (draftContentLinkValue != null && draftContentLinkValue.Type != JTokenType.Null) { ContentLink draftContentLinkInstance = new ContentLink(); runbookDraftInstance.DraftContentLink = draftContentLinkInstance; JToken uriValue = draftContentLinkValue["uri"]; if (uriValue != null && uriValue.Type != JTokenType.Null) { Uri uriInstance = TypeConversion.TryParseUri(((string)uriValue)); draftContentLinkInstance.Uri = uriInstance; } JToken contentHashValue = draftContentLinkValue["contentHash"]; if (contentHashValue != null && contentHashValue.Type != JTokenType.Null) { ContentHash contentHashInstance = new ContentHash(); draftContentLinkInstance.ContentHash = contentHashInstance; JToken algorithmValue = contentHashValue["algorithm"]; if (algorithmValue != null && algorithmValue.Type != JTokenType.Null) { string algorithmInstance = ((string)algorithmValue); contentHashInstance.Algorithm = algorithmInstance; } JToken valueValue = contentHashValue["value"]; if (valueValue != null && valueValue.Type != JTokenType.Null) { string valueInstance = ((string)valueValue); contentHashInstance.Value = valueInstance; } } JToken versionValue = draftContentLinkValue["version"]; if (versionValue != null && versionValue.Type != JTokenType.Null) { string versionInstance = ((string)versionValue); draftContentLinkInstance.Version = versionInstance; } } JToken creationTimeValue = responseDoc["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); runbookDraftInstance.CreationTime = creationTimeInstance; } JToken lastModifiedTimeValue = responseDoc["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); runbookDraftInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken parametersSequenceElement = ((JToken)responseDoc["parameters"]); if (parametersSequenceElement != null && parametersSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in parametersSequenceElement) { string parametersKey = ((string)property.Name); JObject varToken = ((JObject)property.Value); RunbookParameter runbookParameterInstance = new RunbookParameter(); runbookDraftInstance.Parameters.Add(parametersKey, runbookParameterInstance); JToken typeValue = varToken["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); runbookParameterInstance.Type = typeInstance; } JToken isMandatoryValue = varToken["isMandatory"]; if (isMandatoryValue != null && isMandatoryValue.Type != JTokenType.Null) { bool isMandatoryInstance = ((bool)isMandatoryValue); runbookParameterInstance.IsMandatory = isMandatoryInstance; } JToken positionValue = varToken["position"]; if (positionValue != null && positionValue.Type != JTokenType.Null) { int positionInstance = ((int)positionValue); runbookParameterInstance.Position = positionInstance; } JToken defaultValueValue = varToken["defaultValue"]; if (defaultValueValue != null && defaultValueValue.Type != JTokenType.Null) { string defaultValueInstance = ((string)defaultValueValue); runbookParameterInstance.DefaultValue = defaultValueInstance; } } } } } 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> /// Retrieve the runbook identified by runbook name. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the publish runbook operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public async Task<LongRunningOperationResultResponse> PublishAsync(string automationAccount, RunbookDraftPublishParameters parameters, CancellationToken cancellationToken) { AutomationManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "PublishAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); LongRunningOperationResultResponse response = await client.RunbookDraft.BeginPublishAsync(automationAccount, parameters, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); LongRunningOperationResultResponse result = await client.GetOperationResultStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); int delayInSeconds = response.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 30; } if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while ((result.Status != OperationStatus.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationResultStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); delayInSeconds = result.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 15; } if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } /// <summary> /// Retrieve the runbook identified by runbook name. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the undoedit runbook operation. /// </returns> public async Task<RunbookDraftUndoEditResponse> UndoEditAsync(string automationAccount, string runbookName, CancellationToken cancellationToken) { // Validate if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (runbookName == null) { throw new ArgumentNullException("runbookName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("runbookName", runbookName); TracingAdapter.Enter(invocationId, this, "UndoEditAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/cloudservices/OaaSCS/resources/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/~/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/runbooks/"; url = url + Uri.EscapeDataString(runbookName); url = url + "/draft/undoEdit"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-12-08"); 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.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2013-06-01"); // 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 RunbookDraftUndoEditResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new RunbookDraftUndoEditResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { } } 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> /// Updates the runbook draft with runbookStream as its content. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The runbook draft update parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public async Task<LongRunningOperationResultResponse> UpdateAsync(string automationAccount, RunbookDraftUpdateParameters parameters, CancellationToken cancellationToken) { AutomationManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "UpdateAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); LongRunningOperationResultResponse response = await client.RunbookDraft.BeginUpdateAsync(automationAccount, parameters, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); LongRunningOperationResultResponse result = await client.GetOperationResultStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); int delayInSeconds = response.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 30; } if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while ((result.Status != OperationStatus.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationResultStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); delayInSeconds = result.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 15; } if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System.Reflection; using OpenMetaverse; using Aurora.Framework; namespace OpenSim.Region.Framework.Scenes { public partial class SceneObjectGroup : EntityBase { #region ISceneObject Members public void BackupPreparation() { foreach (SceneObjectPart part in m_partsList) { part.Inventory.SaveScriptStateSaves(); } } /// <summary> /// Start the scripts contained in all the prims in this group. /// </summary> public void CreateScriptInstances(int startParam, bool postOnRez, StateSource stateSource, UUID RezzedFrom) { // Don't start scripts if they're turned off in the region! if (!m_scene.RegionInfo.RegionSettings.DisableScripts) { foreach (SceneObjectPart part in m_partsList) { part.Inventory.CreateScriptInstances(startParam, postOnRez, stateSource, RezzedFrom); } } } /// <summary> /// Stop the scripts contained in all the prims in this group /// </summary> /// <param name = "sceneObjectBeingDeleted"> /// Should be true if these scripts are being removed because the scene /// object is being deleted. This will prevent spurious updates to the client. /// </param> public void RemoveScriptInstances(bool sceneObjectBeingDeleted) { foreach (SceneObjectPart part in m_partsList) { part.Inventory.RemoveScriptInstances(sceneObjectBeingDeleted); } } /// <summary> /// Add an inventory item to a prim in this group. /// </summary> /// <param name = "remoteClient"></param> /// <param name = "localID"></param> /// <param name = "item"></param> /// <param name = "copyItemID">The item UUID that should be used by the new item.</param> /// <returns></returns> public bool AddInventoryItem(IClientAPI remoteClient, uint localID, InventoryItemBase item, UUID copyItemID) { UUID newItemId = (copyItemID != UUID.Zero) ? copyItemID : item.ID; SceneObjectPart part = (SceneObjectPart) GetChildPart(localID); if (part != null) { TaskInventoryItem taskItem = new TaskInventoryItem { ItemID = newItemId, AssetID = item.AssetID, Name = item.Name, Description = item.Description, OwnerID = part.OwnerID, CreatorID = item.CreatorIdAsUuid, Type = item.AssetType, InvType = item.InvType }; // Transfer ownership if (remoteClient != null && remoteClient.AgentId != part.OwnerID && m_scene.Permissions.PropagatePermissions()) { taskItem.BasePermissions = item.BasePermissions & item.NextPermissions; taskItem.CurrentPermissions = item.CurrentPermissions & item.NextPermissions; taskItem.EveryonePermissions = item.EveryOnePermissions & item.NextPermissions; taskItem.GroupPermissions = item.GroupPermissions & item.NextPermissions; taskItem.NextPermissions = item.NextPermissions; // We're adding this to a prim we don't own. Force // owner change taskItem.CurrentPermissions |= 16; // Slam } else { taskItem.BasePermissions = item.BasePermissions; taskItem.CurrentPermissions = item.CurrentPermissions; taskItem.EveryonePermissions = item.EveryOnePermissions; taskItem.GroupPermissions = item.GroupPermissions; taskItem.NextPermissions = item.NextPermissions; } taskItem.Flags = item.Flags; taskItem.SalePrice = item.SalePrice; taskItem.SaleType = item.SaleType; taskItem.CreationDate = (uint) item.CreationDate; bool addFromAllowedDrop = false; if (remoteClient != null) { addFromAllowedDrop = remoteClient.AgentId != part.OwnerID; } part.Inventory.AddInventoryItem(taskItem, addFromAllowedDrop); return true; } MainConsole.Instance.ErrorFormat( "[PRIM INVENTORY]: " + "Couldn't find prim local ID {0} in group {1}, {2} to add inventory item ID {3}", localID, Name, UUID, newItemId); return false; } /// <summary> /// Returns an existing inventory item. Returns the original, so any changes will be live. /// </summary> /// <param name = "primID"></param> /// <param name = "itemID"></param> /// <returns>null if the item does not exist</returns> public TaskInventoryItem GetInventoryItem(uint primID, UUID itemID) { SceneObjectPart part = (SceneObjectPart) GetChildPart(primID); if (part != null) { return part.Inventory.GetInventoryItem(itemID); } MainConsole.Instance.ErrorFormat( "[PRIM INVENTORY]: " + "Couldn't find prim local ID {0} in prim {1}, {2} to get inventory item ID {3}", primID, "unknown", "unknown", itemID); return null; } /// <summary> /// Update an existing inventory item. /// </summary> /// <param name = "item">The updated item. An item with the same id must already exist /// in this prim's inventory</param> /// <returns>false if the item did not exist, true if the update occurred succesfully</returns> public bool UpdateInventoryItem(TaskInventoryItem item) { SceneObjectPart part = (SceneObjectPart) GetChildPart(item.ParentPartID); if (part != null) { part.Inventory.UpdateInventoryItem(item); return true; } MainConsole.Instance.ErrorFormat( "[PRIM INVENTORY]: " + "Couldn't find prim ID {0} to update item {1}, {2}", item.ParentPartID, item.Name, item.ItemID); return false; } public int RemoveInventoryItem(uint localID, UUID itemID) { SceneObjectPart part = (SceneObjectPart) GetChildPart(localID); if (part != null) { int type = part.Inventory.RemoveInventoryItem(itemID); return type; } return -1; } public uint GetEffectivePermissions() { uint perms = (uint) (PermissionMask.Modify | PermissionMask.Copy | PermissionMask.Move | PermissionMask.Transfer) | 7; uint ownerMask = 0x7ffffff; foreach (SceneObjectPart part in m_partsList) { ownerMask &= part.OwnerMask; perms &= part.Inventory.MaskEffectivePermissions(); } if ((ownerMask & (uint) PermissionMask.Modify) == 0) perms &= ~(uint) PermissionMask.Modify; if ((ownerMask & (uint) PermissionMask.Copy) == 0) perms &= ~(uint) PermissionMask.Copy; if ((ownerMask & (uint) PermissionMask.Transfer) == 0) perms &= ~(uint) PermissionMask.Transfer; // If root prim permissions are applied here, this would screw // with in-inventory manipulation of the next owner perms // in a major way. So, let's move this to the give itself. // Yes. I know. Evil. // if ((ownerMask & RootPart.NextOwnerMask & (uint)PermissionMask.Modify) == 0) // perms &= ~((uint)PermissionMask.Modify >> 13); // if ((ownerMask & RootPart.NextOwnerMask & (uint)PermissionMask.Copy) == 0) // perms &= ~((uint)PermissionMask.Copy >> 13); // if ((ownerMask & RootPart.NextOwnerMask & (uint)PermissionMask.Transfer) == 0) // perms &= ~((uint)PermissionMask.Transfer >> 13); return perms; } public void ApplyNextOwnerPermissions() { foreach (SceneObjectPart part in m_partsList) { part.ApplyNextOwnerPermissions(); } } public void ResumeScripts() { foreach (SceneObjectPart part in m_partsList) { part.Inventory.ResumeScripts(); } } #endregion /// <summary> /// Force all task inventories of prims in the scene object to persist /// </summary> public void ForceInventoryPersistence() { foreach (SceneObjectPart part in m_partsList) { part.Inventory.ForceInventoryPersistence(); } } public void ApplyPermissions(uint permissions) { foreach (SceneObjectPart part in m_partsList) { part.ApplyPermissions(permissions); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Text; using Microsoft.Scripting; using Microsoft.Scripting.Actions; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronPython.Modules; using IronPython.Runtime.Exceptions; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; namespace IronPython.Runtime { /// <summary> /// Importer class - used for importing modules. Used by Ops and __builtin__ /// Singleton living on Python engine. /// </summary> public static class Importer { internal const string ModuleReloadMethod = "PerformModuleReload"; #region Internal API Surface /// <summary> /// Gateway into importing ... called from Ops. Performs the initial import of /// a module and returns the module. /// </summary> public static object Import(CodeContext/*!*/ context, string fullName, PythonTuple from, int level) { return LightExceptions.CheckAndThrow(ImportLightThrow(context, fullName, from, level)); } /// <summary> /// Gateway into importing ... called from Ops. Performs the initial import of /// a module and returns the module. This version returns light exceptions instead of throwing. /// </summary> [LightThrowing] internal static object ImportLightThrow(CodeContext/*!*/ context, string fullName, PythonTuple from, int level) { PythonContext pc = context.LanguageContext; if (level == -1) { // no specific level provided, call the 4 param version so legacy code continues to work var site = pc.OldImportSite; return site.Target( site, context, FindImportFunction(context), fullName, Builtin.globals(context), context.Dict, from ); } else { // relative import or absolute import, in other words: // // from . import xyz // or // from __future__ import absolute_import var site = pc.ImportSite; return site.Target( site, context, FindImportFunction(context), fullName, Builtin.globals(context), context.Dict, from, level ); } } /// <summary> /// Gateway into importing ... called from Ops. This is called after /// importing the module and is used to return individual items from /// the module. The outer modules dictionary is then updated with the /// result. /// </summary> public static object ImportFrom(CodeContext/*!*/ context, object from, string name) { PythonModule scope = from as PythonModule; PythonType pt; NamespaceTracker nt; if (scope != null) { object ret; if (scope.GetType() == typeof(PythonModule)) { if (scope.__dict__.TryGetValue(name, out ret)) { return ret; } } else { // subclass of module, it could have overridden __getattr__ or __getattribute__ if (PythonOps.TryGetBoundAttr(context, scope, name, out ret)) { return ret; } } object path; List listPath; string stringPath; if (scope.__dict__._storage.TryGetPath(out path)) { if ((listPath = path as List) != null) { return ImportNestedModule(context, scope, new[] { name }, 0, listPath); } else if((stringPath = path as string) != null) { return ImportNestedModule(context, scope, new[] { name }, 0, List.FromArrayNoCopy(stringPath)); } } } else if ((pt = from as PythonType) != null) { PythonTypeSlot pts; object res; if (pt.TryResolveSlot(context, name, out pts) && pts.TryGetValue(context, null, pt, out res)) { return res; } } else if ((nt = from as NamespaceTracker) != null) { object res = NamespaceTrackerOps.GetCustomMember(context, nt, name); if (res != OperationFailed.Value) { return res; } } else { // This is too lax, for example it allows from module.class import member object ret; if (PythonOps.TryGetBoundAttr(context, from, name, out ret)) { return ret; } } throw PythonOps.ImportError("Cannot import name {0}", name); } private static object ImportModuleFrom(CodeContext/*!*/ context, object from, string[] parts, int current) { if (from is PythonModule scope) { if (scope.__dict__._storage.TryGetPath(out object path) || DynamicHelpers.GetPythonType(scope).TryGetMember(context, scope, "__path__", out path)) { if (path is List listPath) { return ImportNestedModule(context, scope, parts, current, listPath); } if (path is string stringPath) { return ImportNestedModule(context, scope, parts, current, List.FromArrayNoCopy(stringPath)); } } } if (from is NamespaceTracker ns) { if (ns.TryGetValue(parts[current], out object val)) { return MemberTrackerToPython(context, val); } } throw PythonOps.ImportError("No module named {0}", parts[current]); } /// <summary> /// Called by the __builtin__.__import__ functions (general importing) and ScriptEngine (for site.py) /// /// level indiciates whether to perform absolute or relative imports. /// -1 indicates both should be performed /// 0 indicates only absolute imports should be performed /// Positive numbers indicate the # of parent directories to search relative to the calling module /// </summary> public static object ImportModule(CodeContext/*!*/ context, object globals, string/*!*/ modName, bool bottom, int level) { if (modName.IndexOf(Path.DirectorySeparatorChar) != -1) { throw PythonOps.ImportError("Import by filename is not supported.", modName); } string package = null; object attribute; if (globals is PythonDictionary pyGlobals) { if (pyGlobals._storage.TryGetPackage(out attribute)) { package = attribute as string; if (package == null && attribute != null) { throw PythonOps.ValueError("__package__ set to non-string"); } } else { package = null; if (level > 0) { // explicit relative import, calculate and store __package__ object pathAttr, nameAttr; if (pyGlobals._storage.TryGetName(out nameAttr) && nameAttr is string) { if (pyGlobals._storage.TryGetPath(out pathAttr)) { pyGlobals["__package__"] = nameAttr; } else { pyGlobals["__package__"] = ((string)nameAttr).rpartition(".")[0]; } } } } } object newmod = null; string firstName; int firstDot = modName.IndexOf('.'); if (firstDot == -1) { firstName = modName; } else { firstName = modName.Substring(0, firstDot); } string finalName = null; if (level != 0) { // try a relative import // if importing a.b.c, import "a" first and then import b.c from a string name; // name of the module we are to import in relation to the current module PythonModule parentModule; List path; // path to search if (TryGetNameAndPath(context, globals, firstName, level, package, out name, out path, out parentModule)) { finalName = name; // import relative if (!TryGetExistingOrMetaPathModule(context, name, path, out newmod)) { newmod = ImportFromPath(context, firstName, name, path); if (newmod == null) { // add an indirection entry saying this module does not exist // see http://www.python.org/doc/essays/packages.html "Dummy Entries" context.LanguageContext.SystemStateModules[name] = null; } else if (parentModule != null) { parentModule.__dict__[firstName] = newmod; } } else if (firstDot == -1) { // if we imported before having the assembly // loaded and then loaded the assembly we want // to make the assembly available now. if (newmod is NamespaceTracker) { context.ShowCls = true; } } } } if (level <= 0) { // try an absolute import if (newmod == null) { object parentPkg; if (!String.IsNullOrEmpty(package) && !context.LanguageContext.SystemStateModules.TryGetValue(package, out parentPkg)) { PythonModule warnModule = new PythonModule(); warnModule.__dict__["__file__"] = package; warnModule.__dict__["__name__"] = package; ModuleContext modContext = new ModuleContext(warnModule.__dict__, context.LanguageContext); PythonOps.Warn( modContext.GlobalContext, PythonExceptions.RuntimeWarning, "Parent module '{0}' not found while handling absolute import", package); } newmod = ImportTopAbsolute(context, firstName); finalName = firstName; if (newmod == null) { return null; } } } // now import the a.b.c etc. a needs to be included here // because the process of importing could have modified // sys.modules. string[] parts = modName.Split('.'); object next = newmod; string curName = null; for (int i = 0; i < parts.Length; i++) { curName = i == 0 ? finalName : curName + "." + parts[i]; object tmpNext; if (TryGetExistingModule(context, curName, out tmpNext)) { next = tmpNext; if (i == 0) { // need to update newmod if we pulled it out of sys.modules // just in case we're in bottom mode. newmod = next; } } else if (i != 0) { // child module isn't loaded yet, import it. next = ImportModuleFrom(context, next, parts, i); } else { // top-level module doesn't exist in sys.modules, probably // came from some weird meta path hook. newmod = next; } } return bottom ? next : newmod; } /// <summary> /// Interrogates the importing module for __name__ and __path__, which determine /// whether the imported module (whose name is 'name') is being imported as nested /// module (__path__ is present) or as sibling. /// /// For sibling import, the full name of the imported module is parent.sibling /// For nested import, the full name of the imported module is parent.module.nested /// where parent.module is the mod.__name__ /// </summary> /// <param name="context"></param> /// <param name="globals">the globals dictionary</param> /// <param name="name">Name of the module to be imported</param> /// <param name="full">Output - full name of the module being imported</param> /// <param name="path">Path to use to search for "full"</param> /// <param name="level">the import level for relaive imports</param> /// <param name="parentMod">the parent module</param> /// <param name="package">the global __package__ value</param> /// <returns></returns> private static bool TryGetNameAndPath(CodeContext/*!*/ context, object globals, string name, int level, string package, out string full, out List path, out PythonModule parentMod) { Debug.Assert(level != 0); // shouldn't be here for absolute imports // Unless we can find enough information to perform relative import, // we are going to import the module whose name we got full = name; path = null; parentMod = null; // We need to get __name__ to find the name of the imported module. // If absent, fall back to absolute import object attribute; if (!(globals is PythonDictionary pyGlobals) || !pyGlobals._storage.TryGetName(out attribute)) { return false; } // And the __name__ needs to be string if (!(attribute is string modName)) { return false; } string pn; if (package == null) { // If the module has __path__ (and __path__ is list), nested module is being imported // otherwise, importing sibling to the importing module if (pyGlobals._storage.TryGetPath(out attribute) && (path = attribute as List) != null) { // found __path__, importing nested module. The actual name of the nested module // is the name of the mod plus the name of the imported module if (level == -1) { // absolute import of some module full = modName + "." + name; object parentModule; if (context.LanguageContext.SystemStateModules.TryGetValue(modName, out parentModule)) { parentMod = parentModule as PythonModule; } } else if (String.IsNullOrEmpty(name)) { // relative import of ancestor full = (StringOps.rsplit(modName, ".", level - 1)[0] as string); } else { // relative import of some ancestors child string parentName = (StringOps.rsplit(modName, ".", level - 1)[0] as string); full = parentName + "." + name; object parentModule; if (context.LanguageContext.SystemStateModules.TryGetValue(parentName, out parentModule)) { parentMod = parentModule as PythonModule; } } return true; } // importing sibling. The name of the imported module replaces // the last element in the importing module name int lastDot = modName.LastIndexOf('.'); if (lastDot == -1) { // name doesn't include dot, only absolute import possible if (level > 0) { throw PythonOps.ValueError("Attempted relative import in non-package"); } return false; } // need to remove more than one name int tmpLevel = level; while (tmpLevel > 1 && lastDot != -1) { lastDot = modName.LastIndexOf('.', lastDot - 1); tmpLevel--; } if (lastDot == -1) { pn = modName; } else { pn = modName.Substring(0, lastDot); } } else { // __package__ doesn't include module name, so level is - 1. pn = GetParentPackageName(level - 1, package.Split('.')); } path = GetParentPathAndModule(context, pn, out parentMod); if (path != null) { if (String.IsNullOrEmpty(name)) { full = pn; } else { full = pn + "." + name; } return true; } if (level > 0) { throw PythonOps.SystemError("Parent module '{0}' not loaded, cannot perform relative import", pn); } // not enough information - absolute import return false; } private static string GetParentPackageName(int level, string[] names) { StringBuilder parentName = new StringBuilder(names[0]); if (level < 0) level = 1; for (int i = 1; i < names.Length - level; i++) { parentName.Append('.'); parentName.Append(names[i]); } return parentName.ToString(); } public static object ReloadModule(CodeContext/*!*/ context, PythonModule/*!*/ module) { return ReloadModule(context, module, null); } internal static object ReloadModule(CodeContext/*!*/ context, PythonModule/*!*/ module, PythonFile file) { PythonContext pc = context.LanguageContext; // We created the module and it only contains Python code. If the user changes // __file__ we'll reload from that file. // built-in module: if (!(module.GetFile() is string fileName)) { ReloadBuiltinModule(context, module); return module; } string name = module.GetName() as string; if (name != null) { List path = null; // find the parent module and get it's __path__ property int dotIndex = name.LastIndexOf('.'); if (dotIndex != -1) { PythonModule parentModule; path = GetParentPathAndModule(context, name.Substring(0, dotIndex), out parentModule); } object reloaded; if (TryLoadMetaPathModule(context, module.GetName() as string, path, out reloaded) && reloaded != null) { return module; } List sysPath; if (context.LanguageContext.TryGetSystemPath(out sysPath)) { object ret = ImportFromPathHook(context, name, name, sysPath, null); if (ret != null) { return ret; } } } SourceUnit sourceUnit; if (file != null) { sourceUnit = pc.CreateSourceUnit(new PythonFileStreamContentProvider(file), fileName, file.Encoding, SourceCodeKind.File); } else { if (!pc.DomainManager.Platform.FileExists(fileName)) { throw PythonOps.SystemError("module source file not found"); } sourceUnit = pc.CreateFileUnit(fileName, pc.DefaultEncoding, SourceCodeKind.File); } pc.GetScriptCode(sourceUnit, name, ModuleOptions.None, Compiler.CompilationMode.Lookup).Run(module.Scope); return module; } class PythonFileStreamContentProvider : StreamContentProvider { private readonly PythonFile _file; public PythonFileStreamContentProvider(PythonFile file) { _file = file; } public override Stream GetStream() { return _file._stream; } } /// <summary> /// Given the parent module name looks up the __path__ property. /// </summary> private static List GetParentPathAndModule(CodeContext/*!*/ context, string/*!*/ parentModuleName, out PythonModule parentModule) { List path = null; object parentModuleObj; parentModule = null; // Try lookup parent module in the sys.modules if (context.LanguageContext.SystemStateModules.TryGetValue(parentModuleName, out parentModuleObj)) { // see if it's a module parentModule = parentModuleObj as PythonModule; if (parentModule != null) { object objPath; // get its path as a List if it's there if (parentModule.__dict__._storage.TryGetPath(out objPath)) { path = objPath as List; } } } return path; } private static void ReloadBuiltinModule(CodeContext/*!*/ context, PythonModule/*!*/ module) { Assert.NotNull(module); Debug.Assert(module.GetName() is string, "Module is reloadable only if its name is a non-null string"); Type type; string name = (string)module.GetName(); PythonContext pc = context.LanguageContext; if (!pc.BuiltinModules.TryGetValue(name, out type)) { throw PythonOps.ImportError("no module named {0}", module.GetName()); } // should be a built-in module which we can reload. Debug.Assert(((PythonDictionary)module.__dict__)._storage is ModuleDictionaryStorage); ((ModuleDictionaryStorage)module.__dict__._storage).Reload(); } /// <summary> /// Trys to get an existing module and if that fails fall backs to searching /// </summary> private static bool TryGetExistingOrMetaPathModule(CodeContext/*!*/ context, string fullName, List path, out object ret) { if (TryGetExistingModule(context, fullName, out ret)) { return true; } return TryLoadMetaPathModule(context, fullName, path, out ret); } /// <summary> /// Attempts to load a module from sys.meta_path as defined in PEP 302. /// /// The meta_path provides a list of importer objects which can be used to load modules before /// searching sys.path but after searching built-in modules. /// </summary> private static bool TryLoadMetaPathModule(CodeContext/*!*/ context, string fullName, List path, out object ret) { if (context.LanguageContext.GetSystemStateValue("meta_path") is List metaPath) { foreach (object importer in (IEnumerable)metaPath) { if (FindAndLoadModuleFromImporter(context, importer, fullName, path, out ret)) { return true; } } } ret = null; return false; } /// <summary> /// Given a user defined importer object as defined in PEP 302 tries to load a module. /// /// First the find_module(fullName, path) is invoked to get a loader, then load_module(fullName) is invoked /// </summary> private static bool FindAndLoadModuleFromImporter(CodeContext/*!*/ context, object importer, string fullName, List path, out object ret) { object find_module = PythonOps.GetBoundAttr(context, importer, "find_module"); PythonContext pycontext = context.LanguageContext; object loader = pycontext.Call(context, find_module, fullName, path); if (loader != null) { object findMod = PythonOps.GetBoundAttr(context, loader, "load_module"); ret = pycontext.Call(context, findMod, fullName); return ret != null; } ret = null; return false; } internal static bool TryGetExistingModule(CodeContext/*!*/ context, string/*!*/ fullName, out object ret) { if (context.LanguageContext.SystemStateModules.TryGetValue(fullName, out ret)) { return true; } return false; } #endregion #region Private Implementation Details private static object ImportTopAbsolute(CodeContext/*!*/ context, string/*!*/ name) { object ret; if (TryGetExistingModule(context, name, out ret)) { if (IsReflected(ret)) { // Even though we found something in sys.modules, we need to check if a // clr.AddReference has invalidated it. So try ImportReflected again. ret = ImportReflected(context, name) ?? ret; } if (ret is NamespaceTracker rp || ret == context.LanguageContext.ClrModule) { context.ShowCls = true; } return ret; } if (TryLoadMetaPathModule(context, name, null, out ret)) { return ret; } ret = ImportBuiltin(context, name); if (ret != null) return ret; List path; if (context.LanguageContext.TryGetSystemPath(out path)) { ret = ImportFromPath(context, name, name, path); if (ret != null) return ret; } ret = ImportReflected(context, name); if (ret != null) return ret; return null; } private static string [] SubArray(string[] t, int len) { var ret = new string[len]; Array.Copy(t, ret, len); return ret; } private static bool TryGetNestedModule(CodeContext/*!*/ context, PythonModule/*!*/ scope, string[]/*!*/ parts, int current, out object nested) { string name = parts[current]; Assert.NotNull(context, scope, name); if (scope.__dict__.TryGetValue(name, out nested)) { if (nested is PythonModule pm) { var fullPath = ".".join(SubArray(parts, current)); // double check, some packages mess with package namespace // see cp35116 if (pm.GetName() == fullPath) { return true; } } // This allows from System.Math import * if (nested is PythonType dt && dt.IsSystemType) { return true; } } return false; } private static object ImportNestedModule(CodeContext/*!*/ context, PythonModule/*!*/ module, string[] parts, int current, List/*!*/ path) { object ret; string name = parts[current]; string fullName = CreateFullName(module.GetName() as string, name); if (TryGetExistingOrMetaPathModule(context, fullName, path, out ret)) { module.__dict__[name] = ret; return ret; } if (TryGetNestedModule(context, module, parts, current, out ret)) { return ret; } ImportFromPath(context, name, fullName, path); object importedModule; if (context.LanguageContext.SystemStateModules.TryGetValue(fullName, out importedModule)) { module.__dict__[name] = importedModule; return importedModule; } throw PythonOps.ImportError("cannot import {0} from {1}", name, module.GetName()); } private static object FindImportFunction(CodeContext/*!*/ context) { PythonDictionary builtins = context.GetBuiltinsDict() ?? context.LanguageContext.BuiltinModuleDict; object import; if (builtins._storage.TryGetImport(out import)) { return import; } throw PythonOps.ImportError("cannot find __import__"); } internal static object ImportBuiltin(CodeContext/*!*/ context, string/*!*/ name) { Assert.NotNull(context, name); PythonContext pc = context.LanguageContext; if (name == "sys") { return pc.SystemState; } else if (name == "clr") { context.ShowCls = true; pc.SystemStateModules["clr"] = pc.ClrModule; return pc.ClrModule; } return pc.GetBuiltinModule(name); } private static object ImportReflected(CodeContext/*!*/ context, string/*!*/ name) { object ret; PythonContext pc = context.LanguageContext; if (!PythonOps.ScopeTryGetMember(context, pc.DomainManager.Globals, name, out ret) && (ret = pc.TopNamespace.TryGetPackageAny(name)) == null) { ret = TryImportSourceFile(pc, name); } ret = MemberTrackerToPython(context, ret); if (ret != null) { context.LanguageContext.SystemStateModules[name] = ret; } return ret; } internal static object MemberTrackerToPython(CodeContext/*!*/ context, object ret) { if (ret is MemberTracker res) { context.ShowCls = true; object realRes = res; switch (res.MemberType) { case TrackerTypes.Type: realRes = DynamicHelpers.GetPythonTypeFromType(((TypeTracker)res).Type); break; case TrackerTypes.Field: realRes = PythonTypeOps.GetReflectedField(((FieldTracker)res).Field); break; case TrackerTypes.Event: realRes = PythonTypeOps.GetReflectedEvent((EventTracker)res); break; case TrackerTypes.Method: MethodTracker mt = res as MethodTracker; realRes = PythonTypeOps.GetBuiltinFunction(mt.DeclaringType, mt.Name, new MemberInfo[] { mt.Method }); break; } ret = realRes; } return ret; } internal static PythonModule TryImportSourceFile(PythonContext/*!*/ context, string/*!*/ name) { var sourceUnit = TryFindSourceFile(context, name); PlatformAdaptationLayer pal = context.DomainManager.Platform; if (sourceUnit == null || GetFullPathAndValidateCase(context, pal.CombinePaths(pal.GetDirectoryName(sourceUnit.Path), name + pal.GetExtension(sourceUnit.Path)), false) == null) { return null; } var scope = ExecuteSourceUnit(context, sourceUnit); if (sourceUnit.LanguageContext != context) { // foreign language, we should publish in sys.modules too context.SystemStateModules[name] = scope; } PythonOps.ScopeSetMember(context.SharedContext, sourceUnit.LanguageContext.DomainManager.Globals, name, scope); return scope; } internal static PythonModule ExecuteSourceUnit(PythonContext context, SourceUnit/*!*/ sourceUnit) { ScriptCode compiledCode = sourceUnit.Compile(); Scope scope = compiledCode.CreateScope(); PythonModule res = ((PythonScopeExtension)context.EnsureScopeExtension(scope)).Module; compiledCode.Run(scope); return res; } internal static SourceUnit TryFindSourceFile(PythonContext/*!*/ context, string/*!*/ name) { List paths; if (!context.TryGetSystemPath(out paths)) { return null; } foreach (object dirObj in paths) { if (!(dirObj is string directory)) continue; // skip invalid entries string candidatePath = null; LanguageContext candidateLanguage = null; foreach (string extension in context.DomainManager.Configuration.GetFileExtensions()) { string fullPath; try { fullPath = context.DomainManager.Platform.CombinePaths(directory, name + extension); } catch (ArgumentException) { // skip invalid paths continue; } if (context.DomainManager.Platform.FileExists(fullPath)) { if (candidatePath != null) { throw PythonOps.ImportError(String.Format("Found multiple modules of the same name '{0}': '{1}' and '{2}'", name, candidatePath, fullPath)); } candidatePath = fullPath; candidateLanguage = context.DomainManager.GetLanguageByExtension(extension); } } if (candidatePath != null) { return candidateLanguage.CreateFileUnit(candidatePath); } } return null; } private static bool IsReflected(object module) { // corresponds to the list of types that can be returned by ImportReflected return module is MemberTracker || module is PythonType || module is ReflectedEvent || module is ReflectedField || module is BuiltinFunction; } private static string CreateFullName(string/*!*/ baseName, string name) { if (baseName == null || baseName.Length == 0 || baseName == "__main__") { return name; } return baseName + "." + name; } #endregion private static object ImportFromPath(CodeContext/*!*/ context, string/*!*/ name, string/*!*/ fullName, List/*!*/ path) { return ImportFromPathHook(context, name, fullName, path, LoadFromDisk); } private static object ImportFromPathHook(CodeContext/*!*/ context, string/*!*/ name, string/*!*/ fullName, List/*!*/ path, Func<CodeContext, string, string, string, object> defaultLoader) { Assert.NotNull(context, name, fullName, path); if (!(context.LanguageContext.GetSystemStateValue("path_importer_cache") is IDictionary<object, object> importCache)) { return null; } foreach (object dirname in (IEnumerable)path) { string str = dirname as string; if (str != null || (Converter.TryConvertToString(dirname, out str) && str != null)) { // ignore non-string object importer; if (!importCache.TryGetValue(str, out importer)) { importCache[str] = importer = FindImporterForPath(context, str); } if (importer != null) { // user defined importer object, get the loader and use it. object ret; if (FindAndLoadModuleFromImporter(context, importer, fullName, null, out ret)) { return ret; } } else if (defaultLoader != null) { object res = defaultLoader(context, name, fullName, str); if (res != null) { return res; } } } } return null; } internal static bool TryImportMainFromZip(CodeContext/*!*/ context, string/*!*/ path, out object importer) { Assert.NotNull(context, path); if (!(context.LanguageContext.GetSystemStateValue("path_importer_cache") is IDictionary<object, object> importCache)) { importer = null; return false; } importCache[path] = importer = FindImporterForPath(context, path); if (importer is null || importer is PythonImport.NullImporter) { return false; } // for consistency with cpython, insert zip as a first entry into sys.path if (context.LanguageContext.GetSystemStateValue("path") is List syspath) { syspath.Insert(0, path); } return FindAndLoadModuleFromImporter(context, importer, "__main__", null, out _); } private static object LoadFromDisk(CodeContext context, string name, string fullName, string str) { // default behavior PythonModule module; string pathname = context.LanguageContext.DomainManager.Platform.CombinePaths(str, name); module = LoadPackageFromSource(context, fullName, pathname); if (module != null) { return module; } string filename = pathname + ".py"; module = LoadModuleFromSource(context, fullName, filename); if (module != null) { return module; } return null; } /// <summary> /// Finds a user defined importer for the given path or returns null if no importer /// handles this path. /// </summary> private static object FindImporterForPath(CodeContext/*!*/ context, string dirname) { List pathHooks = context.LanguageContext.GetSystemStateValue("path_hooks") as List; foreach (object hook in (IEnumerable)pathHooks) { try { object handler = PythonCalls.Call(context, hook, dirname); if (handler != null) { return handler; } } catch (ImportException) { // we can't handle the path } } if (!context.LanguageContext.DomainManager.Platform.DirectoryExists(dirname)) { return new PythonImport.NullImporter(dirname); } return null; } private static PythonModule LoadModuleFromSource(CodeContext/*!*/ context, string/*!*/ name, string/*!*/ path) { Assert.NotNull(context, name, path); PythonContext pc = context.LanguageContext; string fullPath = GetFullPathAndValidateCase(pc, path, false); if (fullPath == null || !pc.DomainManager.Platform.FileExists(fullPath)) { return null; } SourceUnit sourceUnit = pc.CreateFileUnit(fullPath, pc.DefaultEncoding, SourceCodeKind.File); return LoadFromSourceUnit(context, sourceUnit, name, sourceUnit.Path); } private static string GetFullPathAndValidateCase(LanguageContext/*!*/ context, string path, bool isDir) { PlatformAdaptationLayer pal = context.DomainManager.Platform; string dir = pal.GetDirectoryName(path); if (!pal.DirectoryExists(dir)) { return null; } try { string file = pal.GetFileName(path); string[] files = pal.GetFileSystemEntries(dir, file, !isDir, isDir); if (files.Length != 1 || pal.GetFileName(files[0]) != file) { return null; } return pal.GetFullPath(files[0]); } catch (IOException) { return null; } } internal static PythonModule LoadPackageFromSource(CodeContext/*!*/ context, string/*!*/ name, string/*!*/ path) { Assert.NotNull(context, name, path); path = GetFullPathAndValidateCase(context.LanguageContext, path, true); if (path == null) { return null; } if(context.LanguageContext.DomainManager.Platform.DirectoryExists(path) && !context.LanguageContext.DomainManager.Platform.FileExists(context.LanguageContext.DomainManager.Platform.CombinePaths(path, "__init__.py"))) { PythonOps.Warn(context, PythonExceptions.ImportWarning, "Not importing directory '{0}': missing __init__.py", path); } return LoadModuleFromSource(context, name, context.LanguageContext.DomainManager.Platform.CombinePaths(path, "__init__.py")); } private static PythonModule/*!*/ LoadFromSourceUnit(CodeContext/*!*/ context, SourceUnit/*!*/ sourceCode, string/*!*/ name, string/*!*/ path) { Assert.NotNull(sourceCode, name, path); return context.LanguageContext.CompileModule(path, name, sourceCode, ModuleOptions.Initialize | ModuleOptions.Optimized); } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.AUTH { #region usings using System; using System.Security.Cryptography; using System.Text; #endregion /// <summary> /// Provides helper methods for authentications(APOP,CRAM-MD5,DIGEST-MD5). /// </summary> [Obsolete] public class AuthHelper { #region Methods /// <summary> /// Calculates APOP authentication compare value. /// </summary> /// <param name="password">Password.</param> /// <param name="passwordTag">Password tag.</param> /// <returns>Returns value what must be used for comparing passwords.</returns> public static string Apop(string password, string passwordTag) { /* RFC 1939 7. APOP * * value = Hex(Md5(passwordTag + password)) */ return Hex(Md5(passwordTag + password)); } /// <summary> /// Calculates CRAM-MD5 authentication compare value. /// </summary> /// <param name="password">Password.</param> /// <param name="hashKey">Hash calculation key</param> /// <returns>Returns value what must be used for comparing passwords.</returns> public static string Cram_Md5(string password, string hashKey) { /* RFC 2195 AUTH CRAM-MD5 * * value = Hex(HmacMd5(hashKey,password)) */ return Hex(HmacMd5(hashKey, password)); } /// <summary> /// Calculates DIGEST-MD5 authentication compare value. /// </summary> /// <param name="client_server">Specifies if client or server value calculated. /// Client and server has diffrent calculation method.</param> /// <param name="realm">Use domain or machine name for this.</param> /// <param name="userName">User name.</param> /// <param name="password">Password.</param> /// <param name="nonce">Server password tag.</param> /// <param name="cnonce">Client password tag.</param> /// <param name="digest_uri"></param> /// <returns>Returns value what must be used for comparing passwords.</returns> public static string Digest_Md5(bool client_server, string realm, string userName, string password, string nonce, string cnonce, string digest_uri) { /* RFC 2831 AUTH DIGEST-MD5 * * qop = "auth"; // We support auth only auth-int and auth-conf isn't supported * nc = "00000001" * * A1 = Md5(userName + ":" + realm + ":" + passw) + ":" + nonce + ":" + cnonce * A2(client response) = "AUTHENTICATE:" + digest_uri * A2(server response) = ":" + digest_uri * * resp-value = Hex(Md5(Hex(Md5(a1)) + ":" + (nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + Hex(Md5(a2))))); */ // string realm = "elwood.innosoft.com"; // string userName = "chris"; // string passw = "secret"; // string nonce = "OA6MG9tEQGm2hh"; // string cnonce = "OA6MHXh6VqTrRk"; // string digest_uri = "imap/elwood.innosoft.com"; string qop = "auth"; string nc = "00000001"; //**** string a1 = Md5(userName + ":" + realm + ":" + password) + ":" + nonce + ":" + cnonce; string a2 = ""; if (client_server) { a2 = "AUTHENTICATE:" + digest_uri; } else { a2 = ":" + digest_uri; } return Hex( Md5(Hex(Md5(a1)) + ":" + (nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + Hex(Md5(a2))))); } /// <summary> /// Creates AUTH Digest-md5 server response what server must send to client. /// </summary> /// <param name="realm">Use domain or machine name for this.</param> /// <param name="nonce">Server password tag. Random hex string is suggested.</param> /// <returns></returns> public static string Create_Digest_Md5_ServerResponse(string realm, string nonce) { return "realm=\"" + realm + "\",nonce=\"" + nonce + "\",qop=\"auth\",algorithm=md5-sess"; } /// <summary> /// Generates random nonce value. /// </summary> /// <returns></returns> public static string GenerateNonce() { return Guid.NewGuid().ToString().Replace("-", "").Substring(0, 16); } /// <summary> /// Calculates keyed md5 hash from specifieed text and with specified hash key. /// </summary> /// <param name="hashKey"></param> /// <param name="text"></param> /// <returns></returns> public static string HmacMd5(string hashKey, string text) { HMACMD5 kMd5 = new HMACMD5(Encoding.Default.GetBytes(text)); return Encoding.Default.GetString(kMd5.ComputeHash(Encoding.ASCII.GetBytes(hashKey))); } /// <summary> /// Calculates md5 hash from specified string. /// </summary> /// <param name="text"></param> /// <returns></returns> public static string Md5(string text) { MD5 md5 = new MD5CryptoServiceProvider(); byte[] hash = md5.ComputeHash(Encoding.Default.GetBytes(text)); return Encoding.Default.GetString(hash); } /// <summary> /// Converts specified string to hexa string. /// </summary> /// <param name="text"></param> /// <returns></returns> public static string Hex(string text) { return BitConverter.ToString(Encoding.Default.GetBytes(text)).ToLower().Replace("-", ""); } /// <summary> /// Encodes specified string to base64 string. /// </summary> /// <param name="text">Text to encode.</param> /// <returns>Returns encoded string.</returns> public static string Base64en(string text) { return Convert.ToBase64String(Encoding.Default.GetBytes(text)); } /// <summary> /// Decodes specified base64 string. /// </summary> /// <param name="text">Base64 string to decode.</param> /// <returns>Returns decoded string.</returns> public static string Base64de(string text) { return Encoding.Default.GetString(Convert.FromBase64String(text)); } #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.Common.Tests; using System.Globalization; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Net.WebSockets.Client.Tests { /// <summary> /// ClientWebSocket unit tests that do not require a remote server. /// </summary> public class ClientWebSocketUnitTest { private static bool WebSocketsSupported { get { return WebSocketHelper.WebSocketsSupported; } } [ConditionalFact(nameof(WebSocketsSupported))] public void Ctor_Success() { var cws = new ClientWebSocket(); cws.Dispose(); } [ConditionalFact(nameof(WebSocketsSupported))] public void Abort_CreateAndAbort_StateIsClosed() { using (var cws = new ClientWebSocket()) { cws.Abort(); Assert.Equal(WebSocketState.Closed, cws.State); } } [ConditionalFact(nameof(WebSocketsSupported))] public void CloseAsync_CreateAndClose_ThrowsInvalidOperationException() { using (var cws = new ClientWebSocket()) { Assert.Throws<InvalidOperationException>(() => { Task t = cws.CloseAsync(WebSocketCloseStatus.Empty, "", new CancellationToken()); }); Assert.Equal(WebSocketState.None, cws.State); } } [ConditionalFact(nameof(WebSocketsSupported))] public async Task CloseAsync_CreateAndCloseOutput_ThrowsInvalidOperationExceptionWithMessage() { using (var cws = new ClientWebSocket()) { InvalidOperationException exception; using (var tcc = new ThreadCultureChange()) { tcc.ChangeCultureInfo(CultureInfo.InvariantCulture); exception = await Assert.ThrowsAsync<InvalidOperationException>( () => cws.CloseOutputAsync(WebSocketCloseStatus.Empty, "", new CancellationToken())); } string expectedMessage = ResourceHelper.GetExceptionMessage("net_WebSockets_NotConnected"); Assert.Equal(expectedMessage, exception.Message); Assert.Equal(WebSocketState.None, cws.State); } } [ConditionalFact(nameof(WebSocketsSupported))] public void CloseAsync_CreateAndReceive_ThrowsInvalidOperationException() { using (var cws = new ClientWebSocket()) { var buffer = new byte[100]; var segment = new ArraySegment<byte>(buffer); var ct = new CancellationToken(); Assert.Throws<InvalidOperationException>(() => { Task t = cws.ReceiveAsync(segment, ct); }); Assert.Equal(WebSocketState.None, cws.State); } } [ConditionalFact(nameof(WebSocketsSupported))] public async Task CloseAsync_CreateAndReceive_ThrowsInvalidOperationExceptionWithMessage() { using (var cws = new ClientWebSocket()) { var buffer = new byte[100]; var segment = new ArraySegment<byte>(buffer); var ct = new CancellationToken(); InvalidOperationException exception; using (var tcc = new ThreadCultureChange()) { tcc.ChangeCultureInfo(CultureInfo.InvariantCulture); exception = await Assert.ThrowsAsync<InvalidOperationException>( () => cws.ReceiveAsync(segment, ct)); } string expectedMessage = ResourceHelper.GetExceptionMessage("net_WebSockets_NotConnected"); Assert.Equal(expectedMessage, exception.Message); Assert.Equal(WebSocketState.None, cws.State); } } [ConditionalFact(nameof(WebSocketsSupported))] public void CloseAsync_CreateAndSend_ThrowsInvalidOperationException() { using (var cws = new ClientWebSocket()) { var buffer = new byte[100]; var segment = new ArraySegment<byte>(buffer); var ct = new CancellationToken(); Assert.Throws<InvalidOperationException>(() => { Task t = cws.SendAsync(segment, WebSocketMessageType.Text, false, ct); }); Assert.Equal(WebSocketState.None, cws.State); } } [ConditionalFact(nameof(WebSocketsSupported))] public async Task CloseAsync_CreateAndSend_ThrowsInvalidOperationExceptionWithMessage() { using (var cws = new ClientWebSocket()) { var buffer = new byte[100]; var segment = new ArraySegment<byte>(buffer); var ct = new CancellationToken(); InvalidOperationException exception; using (var tcc = new ThreadCultureChange()) { tcc.ChangeCultureInfo(CultureInfo.InvariantCulture); exception = await Assert.ThrowsAsync<InvalidOperationException>( () => cws.SendAsync(segment, WebSocketMessageType.Text, false, ct)); } string expectedMessage = ResourceHelper.GetExceptionMessage("net_WebSockets_NotConnected"); Assert.Equal(expectedMessage, exception.Message); Assert.Equal(WebSocketState.None, cws.State); } } [ConditionalFact(nameof(WebSocketsSupported))] public void Ctor_ExpectedPropertyValues() { using (var cws = new ClientWebSocket()) { Assert.Equal(null, cws.CloseStatus); Assert.Equal(null, cws.CloseStatusDescription); Assert.NotEqual(null, cws.Options); Assert.Equal(WebSocketState.None, cws.State); Assert.Equal(null, cws.SubProtocol); Assert.Equal("System.Net.WebSockets.ClientWebSocket", cws.ToString()); } } [ConditionalFact(nameof(WebSocketsSupported))] public void Abort_CreateAndDisposeAndAbort_StateIsClosedSuccess() { var cws = new ClientWebSocket(); cws.Dispose(); cws.Abort(); Assert.Equal(WebSocketState.Closed, cws.State); } [ConditionalFact(nameof(WebSocketsSupported))] public void CloseAsync_DisposeAndClose_ThrowsObjectDisposedException() { var cws = new ClientWebSocket(); cws.Dispose(); Assert.Throws<ObjectDisposedException>(() => { Task t = cws.CloseAsync(WebSocketCloseStatus.Empty, "", new CancellationToken()); }); Assert.Equal(WebSocketState.Closed, cws.State); } [ConditionalFact(nameof(WebSocketsSupported))] public void CloseAsync_DisposeAndCloseOutput_ThrowsObjectDisposedExceptionWithMessage() { var cws = new ClientWebSocket(); cws.Dispose(); var expectedException = new ObjectDisposedException(cws.GetType().FullName); AssertExtensions.Throws<ObjectDisposedException>( () => cws.CloseOutputAsync(WebSocketCloseStatus.Empty, "", new CancellationToken()).GetAwaiter().GetResult(), expectedException.Message); Assert.Equal(WebSocketState.Closed, cws.State); } [ConditionalFact(nameof(WebSocketsSupported))] public void ReceiveAsync_CreateAndDisposeAndReceive_ThrowsObjectDisposedExceptionWithMessage() { var cws = new ClientWebSocket(); cws.Dispose(); var buffer = new byte[100]; var segment = new ArraySegment<byte>(buffer); var ct = new CancellationToken(); var expectedException = new ObjectDisposedException(cws.GetType().FullName); AssertExtensions.Throws<ObjectDisposedException>( () => cws.ReceiveAsync(segment, ct).GetAwaiter().GetResult(), expectedException.Message); Assert.Equal(WebSocketState.Closed, cws.State); } [ConditionalFact(nameof(WebSocketsSupported))] public void SendAsync_CreateAndDisposeAndSend_ThrowsObjectDisposedExceptionWithMessage() { var cws = new ClientWebSocket(); cws.Dispose(); var buffer = new byte[100]; var segment = new ArraySegment<byte>(buffer); var ct = new CancellationToken(); var expectedException = new ObjectDisposedException(cws.GetType().FullName); AssertExtensions.Throws<ObjectDisposedException>( () => cws.SendAsync(segment, WebSocketMessageType.Text, false, ct).GetAwaiter().GetResult(), expectedException.Message); Assert.Equal(WebSocketState.Closed, cws.State); } [ConditionalFact(nameof(WebSocketsSupported))] public void Dispose_CreateAndDispose_ExpectedPropertyValues() { var cws = new ClientWebSocket(); cws.Dispose(); Assert.Equal(null, cws.CloseStatus); Assert.Equal(null, cws.CloseStatusDescription); Assert.NotEqual(null, cws.Options); Assert.Equal(WebSocketState.Closed, cws.State); Assert.Equal(null, cws.SubProtocol); Assert.Equal("System.Net.WebSockets.ClientWebSocket", cws.ToString()); } } }
using System; using System.Collections.Generic; using NinthChevron.Data; using NinthChevron.Data.Entity; using NinthChevron.Helpers; using NinthChevron.ComponentModel.DataAnnotations; using NinthChevron.Data.SqlServer.Test.AdventureWorks2012; using NinthChevron.Data.SqlServer.Test.AdventureWorks2012.PersonSchema; using NinthChevron.Data.SqlServer.Test.AdventureWorks2012.ProductionSchema; using NinthChevron.Data.SqlServer.Test.AdventureWorks2012.PurchasingSchema; using NinthChevron.Data.SqlServer.Test.AdventureWorks2012.SalesSchema; namespace NinthChevron.Data.SqlServer.Test.AdventureWorks2012.HumanResourcesSchema { [Table("Department", "HumanResources", "AdventureWorks2012")] public partial class Department : Entity<Department> { static Department() { Join<EmployeeDepartmentHistory>(t => t.DepartmentEmployeeDepartmentHistory, (t, f) => t.DepartmentID == f.DepartmentID); // Reverse Relation } [NotifyPropertyChanged, Column("DepartmentID", true, true, false)] public short DepartmentID { get { return this.EntityIdentity == null ? TypeHelper.GetDefault<short>() : (short)Convert.ChangeType(this.EntityIdentity, typeof(short)); } set { this.EntityIdentity = (short)value; } } [NotifyPropertyChanged, Column("Name", false, false, false)] public string Name { get; set; } [NotifyPropertyChanged, Column("GroupName", false, false, false)] public string GroupName { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } [InnerJoinColumn] public EmployeeDepartmentHistory DepartmentEmployeeDepartmentHistory { get; set; } } [Table("Employee", "HumanResources", "AdventureWorks2012")] public partial class Employee : Entity<Employee> { static Employee() { Join<EmployeeDepartmentHistory>(t => t.BusinessEntityEmployeeDepartmentHistory, (t, f) => t.BusinessEntityID == f.BusinessEntityID); // Reverse Relation Join<EmployeePayHistory>(t => t.BusinessEntityEmployeePayHistory, (t, f) => t.BusinessEntityID == f.BusinessEntityID); // Reverse Relation Join<JobCandidate>(t => t.BusinessEntityJobCandidate, (t, f) => t.BusinessEntityID == f.BusinessEntityID); // Reverse Relation Join<Document>(t => t.OwnerDocument, (t, f) => t.BusinessEntityID == f.Owner); // Reverse Relation Join<PurchaseOrderHeader>(t => t.EmployeePurchaseOrderHeader, (t, f) => t.BusinessEntityID == f.EmployeeID); // Reverse Relation Join<SalesPerson>(t => t.BusinessEntitySalesPerson, (t, f) => t.BusinessEntityID == f.BusinessEntityID); // Reverse Relation Join<Person>(t => t.BusinessEntityPerson, (t, f) => t.BusinessEntityID == f.BusinessEntityID); // Relation } [NotifyPropertyChanged, Column("BusinessEntityID", true, false, false)] public int BusinessEntityID { get; set; } [NotifyPropertyChanged, Column("NationalIDNumber", false, false, false)] public string NationalIDNumber { get; set; } [NotifyPropertyChanged, Column("LoginID", false, false, false)] public string LoginID { get; set; } [NotifyPropertyChanged, Column("OrganizationNode", false, false, true)] public object OrganizationNode { get; set; } [NotifyPropertyChanged, Column("OrganizationLevel", false, false, true)] public System.Nullable<short> OrganizationLevel { get; set; } [NotifyPropertyChanged, Column("JobTitle", false, false, false)] public string JobTitle { get; set; } [NotifyPropertyChanged, Column("BirthDate", true, false, false)] public object BirthDate { get; set; } [NotifyPropertyChanged, Column("MaritalStatus", true, false, false)] public string MaritalStatus { get; set; } [NotifyPropertyChanged, Column("Gender", true, false, false)] public string Gender { get; set; } [NotifyPropertyChanged, Column("HireDate", true, false, false)] public object HireDate { get; set; } [NotifyPropertyChanged, Column("SalariedFlag", false, false, false)] public bool SalariedFlag { get; set; } [NotifyPropertyChanged, Column("VacationHours", true, false, false)] public short VacationHours { get; set; } [NotifyPropertyChanged, Column("SickLeaveHours", true, false, false)] public short SickLeaveHours { get; set; } [NotifyPropertyChanged, Column("CurrentFlag", false, false, false)] public bool CurrentFlag { get; set; } [NotifyPropertyChanged, Column("rowguid", false, false, false)] public System.Guid Rowguid { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } [InnerJoinColumn] public EmployeeDepartmentHistory BusinessEntityEmployeeDepartmentHistory { get; set; } [InnerJoinColumn] public EmployeePayHistory BusinessEntityEmployeePayHistory { get; set; } [InnerJoinColumn] public JobCandidate BusinessEntityJobCandidate { get; set; } [InnerJoinColumn] public Document OwnerDocument { get; set; } [InnerJoinColumn] public PurchaseOrderHeader EmployeePurchaseOrderHeader { get; set; } [InnerJoinColumn] public SalesPerson BusinessEntitySalesPerson { get; set; } [InnerJoinColumn] public Person BusinessEntityPerson { get; set; } } [Table("EmployeeDepartmentHistory", "HumanResources", "AdventureWorks2012")] public partial class EmployeeDepartmentHistory : Entity<EmployeeDepartmentHistory> { static EmployeeDepartmentHistory() { Join<Department>(t => t.DepartmentDepartment, (t, f) => t.DepartmentID == f.DepartmentID); // Relation Join<Employee>(t => t.BusinessEntityEmployee, (t, f) => t.BusinessEntityID == f.BusinessEntityID); // Relation Join<Shift>(t => t.ShiftShift, (t, f) => t.ShiftID == f.ShiftID); // Relation } [NotifyPropertyChanged, Column("BusinessEntityID", true, false, false)] public int BusinessEntityID { get; set; } [NotifyPropertyChanged, Column("DepartmentID", true, false, false)] public short DepartmentID { get; set; } [NotifyPropertyChanged, Column("ShiftID", true, false, false)] public byte ShiftID { get; set; } [NotifyPropertyChanged, Column("StartDate", true, false, false)] public object StartDate { get; set; } [NotifyPropertyChanged, Column("EndDate", true, false, true)] public object EndDate { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } [InnerJoinColumn] public Department DepartmentDepartment { get; set; } [InnerJoinColumn] public Employee BusinessEntityEmployee { get; set; } [InnerJoinColumn] public Shift ShiftShift { get; set; } } [Table("EmployeePayHistory", "HumanResources", "AdventureWorks2012")] public partial class EmployeePayHistory : Entity<EmployeePayHistory> { static EmployeePayHistory() { Join<Employee>(t => t.BusinessEntityEmployee, (t, f) => t.BusinessEntityID == f.BusinessEntityID); // Relation } [NotifyPropertyChanged, Column("BusinessEntityID", true, false, false)] public int BusinessEntityID { get; set; } [NotifyPropertyChanged, Column("RateChangeDate", true, false, false)] public System.DateTime RateChangeDate { get; set; } [NotifyPropertyChanged, Column("Rate", true, false, false)] public object Rate { get; set; } [NotifyPropertyChanged, Column("PayFrequency", true, false, false)] public byte PayFrequency { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } [InnerJoinColumn] public Employee BusinessEntityEmployee { get; set; } } [Table("JobCandidate", "HumanResources", "AdventureWorks2012")] public partial class JobCandidate : Entity<JobCandidate> { static JobCandidate() { Join<Employee>(t => t.BusinessEntityEmployee, (t, f) => t.BusinessEntityID == f.BusinessEntityID); // Relation } [NotifyPropertyChanged, Column("JobCandidateID", true, true, false)] public int JobCandidateID { get { return this.EntityIdentity == null ? TypeHelper.GetDefault<int>() : (int)Convert.ChangeType(this.EntityIdentity, typeof(int)); } set { this.EntityIdentity = (int)value; } } [NotifyPropertyChanged, Column("BusinessEntityID", true, false, true)] public System.Nullable<int> BusinessEntityID { get; set; } [NotifyPropertyChanged, Column("Resume", false, false, true)] public object Resume { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } [InnerJoinColumn] public Employee BusinessEntityEmployee { get; set; } } [Table("Shift", "HumanResources", "AdventureWorks2012")] public partial class Shift : Entity<Shift> { static Shift() { Join<EmployeeDepartmentHistory>(t => t.ShiftEmployeeDepartmentHistory, (t, f) => t.ShiftID == f.ShiftID); // Reverse Relation } [NotifyPropertyChanged, Column("ShiftID", true, true, false)] public byte ShiftID { get { return this.EntityIdentity == null ? TypeHelper.GetDefault<byte>() : (byte)Convert.ChangeType(this.EntityIdentity, typeof(byte)); } set { this.EntityIdentity = (byte)value; } } [NotifyPropertyChanged, Column("Name", false, false, false)] public string Name { get; set; } [NotifyPropertyChanged, Column("StartTime", false, false, false)] public object StartTime { get; set; } [NotifyPropertyChanged, Column("EndTime", false, false, false)] public object EndTime { get; set; } [NotifyPropertyChanged, Column("ModifiedDate", false, false, false)] public System.DateTime ModifiedDate { get; set; } [InnerJoinColumn] public EmployeeDepartmentHistory ShiftEmployeeDepartmentHistory { get; set; } } }
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 SysPai class. /// </summary> [Serializable] public partial class SysPaiCollection : ActiveList<SysPai, SysPaiCollection> { public SysPaiCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>SysPaiCollection</returns> public SysPaiCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { SysPai 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_Pais table. /// </summary> [Serializable] public partial class SysPai : ActiveRecord<SysPai>, IActiveRecord { #region .ctors and Default Settings public SysPai() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public SysPai(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public SysPai(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public SysPai(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_Pais", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdPais = new TableSchema.TableColumn(schema); colvarIdPais.ColumnName = "idPais"; colvarIdPais.DataType = DbType.Int32; colvarIdPais.MaxLength = 0; colvarIdPais.AutoIncrement = true; colvarIdPais.IsNullable = false; colvarIdPais.IsPrimaryKey = true; colvarIdPais.IsForeignKey = false; colvarIdPais.IsReadOnly = false; colvarIdPais.DefaultSetting = @""; colvarIdPais.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdPais); 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 colvarCodigoINDEC = new TableSchema.TableColumn(schema); colvarCodigoINDEC.ColumnName = "codigoINDEC"; colvarCodigoINDEC.DataType = DbType.String; colvarCodigoINDEC.MaxLength = 100; colvarCodigoINDEC.AutoIncrement = false; colvarCodigoINDEC.IsNullable = true; colvarCodigoINDEC.IsPrimaryKey = false; colvarCodigoINDEC.IsForeignKey = false; colvarCodigoINDEC.IsReadOnly = false; colvarCodigoINDEC.DefaultSetting = @""; colvarCodigoINDEC.ForeignKeyTableName = ""; schema.Columns.Add(colvarCodigoINDEC); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("Sys_Pais",schema); } } #endregion #region Props [XmlAttribute("IdPais")] [Bindable(true)] public int IdPais { get { return GetColumnValue<int>(Columns.IdPais); } set { SetColumnValue(Columns.IdPais, value); } } [XmlAttribute("Nombre")] [Bindable(true)] public string Nombre { get { return GetColumnValue<string>(Columns.Nombre); } set { SetColumnValue(Columns.Nombre, value); } } [XmlAttribute("CodigoINDEC")] [Bindable(true)] public string CodigoINDEC { get { return GetColumnValue<string>(Columns.CodigoINDEC); } set { SetColumnValue(Columns.CodigoINDEC, value); } } #endregion #region PrimaryKey Methods protected override void SetPrimaryKey(object oValue) { base.SetPrimaryKey(oValue); SetPKValues(); } private DalSic.SysParentescoCollection colSysParentescoRecords; public DalSic.SysParentescoCollection SysParentescoRecords { get { if(colSysParentescoRecords == null) { colSysParentescoRecords = new DalSic.SysParentescoCollection().Where(SysParentesco.Columns.IdPais, IdPais).Load(); colSysParentescoRecords.ListChanged += new ListChangedEventHandler(colSysParentescoRecords_ListChanged); } return colSysParentescoRecords; } set { colSysParentescoRecords = value; colSysParentescoRecords.ListChanged += new ListChangedEventHandler(colSysParentescoRecords_ListChanged); } } void colSysParentescoRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colSysParentescoRecords[e.NewIndex].IdPais = IdPais; } } private DalSic.SysPacienteCollection colSysPacienteRecords; public DalSic.SysPacienteCollection SysPacienteRecords { get { if(colSysPacienteRecords == null) { colSysPacienteRecords = new DalSic.SysPacienteCollection().Where(SysPaciente.Columns.IdPais, IdPais).Load(); colSysPacienteRecords.ListChanged += new ListChangedEventHandler(colSysPacienteRecords_ListChanged); } return colSysPacienteRecords; } set { colSysPacienteRecords = value; colSysPacienteRecords.ListChanged += new ListChangedEventHandler(colSysPacienteRecords_ListChanged); } } void colSysPacienteRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colSysPacienteRecords[e.NewIndex].IdPais = IdPais; } } #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,string varCodigoINDEC) { SysPai item = new SysPai(); item.Nombre = varNombre; item.CodigoINDEC = varCodigoINDEC; 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 varIdPais,string varNombre,string varCodigoINDEC) { SysPai item = new SysPai(); item.IdPais = varIdPais; item.Nombre = varNombre; item.CodigoINDEC = varCodigoINDEC; 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 IdPaisColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn NombreColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn CodigoINDECColumn { get { return Schema.Columns[2]; } } #endregion #region Columns Struct public struct Columns { public static string IdPais = @"idPais"; public static string Nombre = @"nombre"; public static string CodigoINDEC = @"codigoINDEC"; } #endregion #region Update PK Collections public void SetPKValues() { if (colSysParentescoRecords != null) { foreach (DalSic.SysParentesco item in colSysParentescoRecords) { if (item.IdPais != IdPais) { item.IdPais = IdPais; } } } if (colSysPacienteRecords != null) { foreach (DalSic.SysPaciente item in colSysPacienteRecords) { if (item.IdPais != IdPais) { item.IdPais = IdPais; } } } } #endregion #region Deep Save public void DeepSave() { Save(); if (colSysParentescoRecords != null) { colSysParentescoRecords.SaveAll(); } if (colSysPacienteRecords != null) { colSysPacienteRecords.SaveAll(); } } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; using System.Threading; using NUnit.Framework; using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenSim.Data; using OpenSim.Framework; using OpenSim.Framework.Serialization; using OpenSim.Framework.Serialization.External; using OpenSim.Framework.Communications; using OpenSim.Framework.Communications.Cache; using OpenSim.Framework.Communications.Osp; using OpenSim.Region.CoreModules.Avatar.Inventory.Archiver; using OpenSim.Region.CoreModules.World.Serialiser; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes.Serialization; using OpenSim.Tests.Common; using OpenSim.Tests.Common.Mock; using OpenSim.Tests.Common.Setup; namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests { [TestFixture] public class InventoryArchiverTests { private void InventoryReceived(UUID userId) { lock (this) { Monitor.PulseAll(this); } } private void SaveCompleted( bool succeeded, CachedUserInfo userInfo, string invPath, Stream saveStream, Exception reportedException) { lock (this) { Monitor.PulseAll(this); } } /// <summary> /// Test saving a V0.1 OpenSim Inventory Archive (subject to change since there is no fixed format yet). /// </summary> // Commenting for now! The mock inventory service needs more beef, at least for // GetFolderForType //[Test] public void TestSaveIarV0_1() { TestHelper.InMethod(); log4net.Config.XmlConfigurator.Configure(); InventoryArchiverModule archiverModule = new InventoryArchiverModule(); Scene scene = SceneSetupHelpers.SetupScene("Inventory"); SceneSetupHelpers.SetupSceneModules(scene, archiverModule); CommunicationsManager cm = scene.CommsManager; // Create user string userFirstName = "Jock"; string userLastName = "Stirrup"; UUID userId = UUID.Parse("00000000-0000-0000-0000-000000000020"); CachedUserInfo userInfo; lock (this) { userInfo = UserProfileTestUtils.CreateUserWithInventory( cm, userFirstName, userLastName, userId, InventoryReceived); Monitor.Wait(this, 60000); } /* cm.UserAdminService.AddUser(userFirstName, userLastName, string.Empty, string.Empty, 1000, 1000, userId); CachedUserInfo userInfo = cm.UserProfileCacheService.GetUserDetails(userId, InventoryReceived); userInfo.FetchInventory(); for (int i = 0 ; i < 50 ; i++) { if (userInfo.HasReceivedInventory == true) break; Thread.Sleep(200); } Assert.That(userInfo.HasReceivedInventory, Is.True, "FetchInventory timed out (10 seconds)"); */ // Create asset SceneObjectGroup object1; SceneObjectPart part1; { string partName = "My Little Dog Object"; UUID ownerId = UUID.Parse("00000000-0000-0000-0000-000000000040"); PrimitiveBaseShape shape = PrimitiveBaseShape.CreateSphere(); Vector3 groupPosition = new Vector3(10, 20, 30); Quaternion rotationOffset = new Quaternion(20, 30, 40, 50); Vector3 offsetPosition = new Vector3(5, 10, 15); part1 = new SceneObjectPart( ownerId, shape, groupPosition, rotationOffset, offsetPosition); part1.Name = partName; object1 = new SceneObjectGroup(part1); scene.AddNewSceneObject(object1, false); } UUID asset1Id = UUID.Parse("00000000-0000-0000-0000-000000000060"); AssetBase asset1 = new AssetBase(); asset1.FullID = asset1Id; asset1.Data = Encoding.ASCII.GetBytes(SceneObjectSerializer.ToXml2Format(object1)); scene.AssetService.Store(asset1); // Create item UUID item1Id = UUID.Parse("00000000-0000-0000-0000-000000000080"); InventoryItemBase item1 = new InventoryItemBase(); item1.Name = "My Little Dog"; item1.AssetID = asset1.FullID; item1.ID = item1Id; //userInfo.RootFolder.FindFolderByPath("Objects").ID; InventoryFolderBase objsFolder = scene.InventoryService.GetFolderForType(userId, AssetType.Object); item1.Folder = objsFolder.ID; scene.AddInventoryItem(userId, item1); MemoryStream archiveWriteStream = new MemoryStream(); archiverModule.OnInventoryArchiveSaved += SaveCompleted; lock (this) { archiverModule.ArchiveInventory(userFirstName, userLastName, "Objects", archiveWriteStream); Monitor.Wait(this, 60000); } byte[] archive = archiveWriteStream.ToArray(); MemoryStream archiveReadStream = new MemoryStream(archive); TarArchiveReader tar = new TarArchiveReader(archiveReadStream); //bool gotControlFile = false; bool gotObject1File = false; //bool gotObject2File = false; string expectedObject1FilePath = string.Format( "{0}{1}/{2}_{3}.xml", ArchiveConstants.INVENTORY_PATH, string.Format( "Objects{0}{1}", ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR, objsFolder.ID), item1.Name, item1Id); // string expectedObject2FileName = string.Format( // "{0}_{1:000}-{2:000}-{3:000}__{4}.xml", // part2.Name, // Math.Round(part2.GroupPosition.X), Math.Round(part2.GroupPosition.Y), Math.Round(part2.GroupPosition.Z), // part2.UUID); string filePath; TarArchiveReader.TarEntryType tarEntryType; Console.WriteLine("Reading archive"); while (tar.ReadEntry(out filePath, out tarEntryType) != null) { Console.WriteLine("Got {0}", filePath); // if (ArchiveConstants.CONTROL_FILE_PATH == filePath) // { // gotControlFile = true; // } if (filePath.StartsWith(ArchiveConstants.INVENTORY_PATH) && filePath.EndsWith(".xml")) { // string fileName = filePath.Remove(0, "Objects/".Length); // // if (fileName.StartsWith(part1.Name)) // { Assert.That(filePath, Is.EqualTo(expectedObject1FilePath)); gotObject1File = true; // } // else if (fileName.StartsWith(part2.Name)) // { // Assert.That(fileName, Is.EqualTo(expectedObject2FileName)); // gotObject2File = true; // } } } // Assert.That(gotControlFile, Is.True, "No control file in archive"); Assert.That(gotObject1File, Is.True, "No item1 file in archive"); // Assert.That(gotObject2File, Is.True, "No object2 file in archive"); // TODO: Test presence of more files and contents of files. } /// <summary> /// Test loading a V0.1 OpenSim Inventory Archive (subject to change since there is no fixed format yet) where /// an account exists with the creator name. /// </summary> [Test] public void TestLoadIarV0_1ExistingUsers() { TestHelper.InMethod(); log4net.Config.XmlConfigurator.Configure(); string userFirstName = "Mr"; string userLastName = "Tiddles"; UUID userUuid = UUID.Parse("00000000-0000-0000-0000-000000000555"); string userItemCreatorFirstName = "Lord"; string userItemCreatorLastName = "Lucan"; UUID userItemCreatorUuid = UUID.Parse("00000000-0000-0000-0000-000000000666"); string itemName = "b.lsl"; string archiveItemName = string.Format("{0}{1}{2}", itemName, "_", UUID.Random()); MemoryStream archiveWriteStream = new MemoryStream(); TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream); InventoryItemBase item1 = new InventoryItemBase(); item1.Name = itemName; item1.AssetID = UUID.Random(); item1.GroupID = UUID.Random(); item1.CreatorId = OspResolver.MakeOspa(userItemCreatorFirstName, userItemCreatorLastName); //item1.CreatorId = userUuid.ToString(); //item1.CreatorId = "00000000-0000-0000-0000-000000000444"; item1.Owner = UUID.Zero; string item1FileName = string.Format("{0}{1}", ArchiveConstants.INVENTORY_PATH, archiveItemName); tar.WriteFile(item1FileName, UserInventoryItemSerializer.Serialize(item1)); tar.Close(); MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray()); SerialiserModule serialiserModule = new SerialiserModule(); InventoryArchiverModule archiverModule = new InventoryArchiverModule(); // Annoyingly, we have to set up a scene even though inventory loading has nothing to do with a scene Scene scene = SceneSetupHelpers.SetupScene("inventory"); IUserAdminService userAdminService = scene.CommsManager.UserAdminService; SceneSetupHelpers.SetupSceneModules(scene, serialiserModule, archiverModule); userAdminService.AddUser( userFirstName, userLastName, "meowfood", String.Empty, 1000, 1000, userUuid); userAdminService.AddUser( userItemCreatorFirstName, userItemCreatorLastName, "hampshire", String.Empty, 1000, 1000, userItemCreatorUuid); archiverModule.DearchiveInventory(userFirstName, userLastName, "/", archiveReadStream); CachedUserInfo userInfo = scene.CommsManager.UserProfileCacheService.GetUserDetails(userFirstName, userLastName); InventoryItemBase foundItem = userInfo.RootFolder.FindItemByPath(itemName); Assert.That(foundItem, Is.Not.Null, "Didn't find loaded item"); Assert.That( foundItem.CreatorId, Is.EqualTo(item1.CreatorId), "Loaded item non-uuid creator doesn't match original"); Assert.That( foundItem.CreatorIdAsUuid, Is.EqualTo(userItemCreatorUuid), "Loaded item uuid creator doesn't match original"); Assert.That(foundItem.Owner, Is.EqualTo(userUuid), "Loaded item owner doesn't match inventory reciever"); } /// <summary> /// Test loading a V0.1 OpenSim Inventory Archive (subject to change since there is no fixed format yet) where /// no account exists with the creator name /// </summary> //[Test] public void TestLoadIarV0_1TempProfiles() { TestHelper.InMethod(); log4net.Config.XmlConfigurator.Configure(); string userFirstName = "Dennis"; string userLastName = "Menace"; UUID userUuid = UUID.Parse("00000000-0000-0000-0000-000000000aaa"); string user2FirstName = "Walter"; string user2LastName = "Mitty"; string itemName = "b.lsl"; string archiveItemName = string.Format("{0}{1}{2}", itemName, "_", UUID.Random()); MemoryStream archiveWriteStream = new MemoryStream(); TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream); InventoryItemBase item1 = new InventoryItemBase(); item1.Name = itemName; item1.AssetID = UUID.Random(); item1.GroupID = UUID.Random(); item1.CreatorId = OspResolver.MakeOspa(user2FirstName, user2LastName); item1.Owner = UUID.Zero; string item1FileName = string.Format("{0}{1}", ArchiveConstants.INVENTORY_PATH, archiveItemName); tar.WriteFile(item1FileName, UserInventoryItemSerializer.Serialize(item1)); tar.Close(); MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray()); SerialiserModule serialiserModule = new SerialiserModule(); InventoryArchiverModule archiverModule = new InventoryArchiverModule(); // Annoyingly, we have to set up a scene even though inventory loading has nothing to do with a scene Scene scene = SceneSetupHelpers.SetupScene(); IUserAdminService userAdminService = scene.CommsManager.UserAdminService; SceneSetupHelpers.SetupSceneModules(scene, serialiserModule, archiverModule); userAdminService.AddUser( userFirstName, userLastName, "meowfood", String.Empty, 1000, 1000, userUuid); archiverModule.DearchiveInventory(userFirstName, userLastName, "/", archiveReadStream); // Check that a suitable temporary user profile has been created. UserProfileData user2Profile = scene.CommsManager.UserService.GetUserProfile( OspResolver.HashName(user2FirstName + " " + user2LastName)); Assert.That(user2Profile, Is.Not.Null); Assert.That(user2Profile.FirstName == user2FirstName); Assert.That(user2Profile.SurName == user2LastName); CachedUserInfo userInfo = scene.CommsManager.UserProfileCacheService.GetUserDetails(userFirstName, userLastName); userInfo.OnInventoryReceived += InventoryReceived; lock (this) { userInfo.FetchInventory(); Monitor.Wait(this, 60000); } InventoryItemBase foundItem = userInfo.RootFolder.FindItemByPath(itemName); Assert.That(foundItem.CreatorId, Is.EqualTo(item1.CreatorId)); Assert.That( foundItem.CreatorIdAsUuid, Is.EqualTo(OspResolver.HashName(user2FirstName + " " + user2LastName))); Assert.That(foundItem.Owner, Is.EqualTo(userUuid)); Console.WriteLine("### Successfully completed {0} ###", MethodBase.GetCurrentMethod()); } /// <summary> /// Test replication of an archive path to the user's inventory. /// </summary> [Test] public void TestReplicateArchivePathToUserInventory() { TestHelper.InMethod(); log4net.Config.XmlConfigurator.Configure(); Scene scene = SceneSetupHelpers.SetupScene("inventory"); CommunicationsManager commsManager = scene.CommsManager; CachedUserInfo userInfo; lock (this) { userInfo = UserProfileTestUtils.CreateUserWithInventory(commsManager, InventoryReceived); Monitor.Wait(this, 60000); } Console.WriteLine("userInfo.RootFolder 1: {0}", userInfo.RootFolder); Dictionary <string, InventoryFolderImpl> foldersCreated = new Dictionary<string, InventoryFolderImpl>(); List<InventoryNodeBase> nodesLoaded = new List<InventoryNodeBase>(); string folder1Name = "a"; string folder2Name = "b"; string itemName = "c.lsl"; string folder1ArchiveName = string.Format( "{0}{1}{2}", folder1Name, ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR, UUID.Random()); string folder2ArchiveName = string.Format( "{0}{1}{2}", folder2Name, ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR, UUID.Random()); string itemArchivePath = string.Format( "{0}{1}/{2}/{3}", ArchiveConstants.INVENTORY_PATH, folder1ArchiveName, folder2ArchiveName, itemName); Console.WriteLine("userInfo.RootFolder 2: {0}", userInfo.RootFolder); new InventoryArchiveReadRequest(userInfo, null, (Stream)null, null, null) .ReplicateArchivePathToUserInventory( itemArchivePath, false, userInfo.RootFolder, foldersCreated, nodesLoaded); Console.WriteLine("userInfo.RootFolder 3: {0}", userInfo.RootFolder); InventoryFolderImpl folder1 = userInfo.RootFolder.FindFolderByPath("a"); Assert.That(folder1, Is.Not.Null, "Could not find folder a"); InventoryFolderImpl folder2 = folder1.FindFolderByPath("b"); Assert.That(folder2, Is.Not.Null, "Could not find folder b"); } } }
using System.Linq; using System.Linq.Expressions; using System.Net; using Microsoft.Azure.Management.ManagementGroups; using Microsoft.Azure.Management.ManagementGroups.Models; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Resource.Tests.Helpers; using Xunit; namespace ResourceGroups.Tests { public class LiveManagementGroupsTests : TestBase { [Fact] public void ListGroups() { using (MockContext context = MockContext.Start(this.GetType())) { var managementGroupsClient = ManagementGroupsTestUtilities.GetManagementGroupsApiClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); var managementGroups = managementGroupsClient.ManagementGroups.List(); Assert.NotNull(managementGroups); Assert.NotEmpty(managementGroups); Assert.NotNull(managementGroups.First().Id); Assert.NotNull(managementGroups.First().Type); Assert.NotNull(managementGroups.First().Name); Assert.NotNull(managementGroups.First().DisplayName); Assert.NotNull(managementGroups.First().TenantId); } } [Fact] public void GetGroup() { using (MockContext context = MockContext.Start(this.GetType())) { var managementGroupsClient = ManagementGroupsTestUtilities.GetManagementGroupsApiClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); var groupId = "TestGroup1Child1"; var managementGroup = managementGroupsClient.ManagementGroups.Get(groupId); Assert.NotNull(managementGroup); Assert.Equal("/providers/Microsoft.Management/managementGroups/TestGroup1Child1", managementGroup.Id); Assert.Equal("TestGroup1Child1", managementGroup.Name); Assert.Equal("TestGroup1->Child1", managementGroup.DisplayName); Assert.Equal("/providers/Microsoft.Management/managementGroups", managementGroup.Type); Assert.Equal("/providers/Microsoft.Management/managementGroups/TestGroup1", managementGroup.Details.Parent.Id); Assert.Equal("TestGroup1", managementGroup.Details.Parent.Name); Assert.Equal("TestGroup1", managementGroup.Details.Parent.DisplayName); } } [Fact] public void GetGroupExpand() { using (MockContext context = MockContext.Start(this.GetType())) { var managementGroupsClient = ManagementGroupsTestUtilities.GetManagementGroupsApiClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); var groupId = "TestGroup1Child1"; var managementGroup = managementGroupsClient.ManagementGroups.Get(groupId, "children"); Assert.NotNull(managementGroup); Assert.Equal("/providers/Microsoft.Management/managementGroups/TestGroup1Child1", managementGroup.Id); Assert.Equal("TestGroup1Child1", managementGroup.Name); Assert.Equal("TestGroup1->Child1", managementGroup.DisplayName); Assert.Equal("/providers/Microsoft.Management/managementGroups", managementGroup.Type); Assert.Equal("/providers/Microsoft.Management/managementGroups/TestGroup1", managementGroup.Details.Parent.Id); Assert.Equal("TestGroup1", managementGroup.Details.Parent.Name); Assert.Equal("TestGroup1", managementGroup.Details.Parent.DisplayName); Assert.NotNull(managementGroup.Children); Assert.Null(managementGroup.Children.First().Children); Assert.Equal("/providers/Microsoft.Management/managementGroups/TestGroup1Child1Child1", managementGroup.Children.First().Id); Assert.Equal("TestGroup1Child1Child1", managementGroup.Children.First().Name); Assert.Equal("TestGroup1->Child1->Child1", managementGroup.Children.First().DisplayName); Assert.Equal("/providers/Microsoft.Management/managementGroups", managementGroup.Children.First().Type); } } [Fact] public void GetGroupExpandRecurse() { using (MockContext context = MockContext.Start(this.GetType())) { var managementGroupsClient = ManagementGroupsTestUtilities.GetManagementGroupsApiClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); var groupId = "TestGroup1"; var managementGroup = managementGroupsClient.ManagementGroups.Get(groupId, "children", true); Assert.NotNull(managementGroup); Assert.Equal("/providers/Microsoft.Management/managementGroups/TestGroup1", managementGroup.Id); Assert.Equal("TestGroup1", managementGroup.Name); Assert.Equal("TestGroup1", managementGroup.DisplayName); Assert.Equal("/providers/Microsoft.Management/managementGroups", managementGroup.Type); Assert.NotNull(managementGroup.Children); Assert.NotNull(managementGroup.Children.First().Children); Assert.Equal("/providers/Microsoft.Management/managementGroups/TestGroup1Child1", managementGroup.Children.First().Id); Assert.Equal("TestGroup1Child1", managementGroup.Children.First().Name); Assert.Equal("TestGroup1->Child1", managementGroup.Children.First().DisplayName); Assert.Equal("/providers/Microsoft.Management/managementGroups", managementGroup.Children.First().Type); Assert.Equal("/providers/Microsoft.Management/managementGroups/TestGroup1Child1Child1", managementGroup.Children.First().Children.First().Id); Assert.Equal("TestGroup1Child1Child1", managementGroup.Children.First().Children.First().Name); Assert.Equal("TestGroup1->Child1->Child1", managementGroup.Children.First().Children.First().DisplayName); Assert.Equal("/providers/Microsoft.Management/managementGroups", managementGroup.Children.First().Children.First().Type); } } [Fact(Skip="Skipping for now. Investigating why it is failing.")] public void GetEntities() { using (MockContext context = MockContext.Start(this.GetType())) { var managementGroupsClient = ManagementGroupsTestUtilities.GetManagementGroupsApiClient(context, new RecordedDelegatingHandler {StatusCodeToReturn = HttpStatusCode.OK}); var groupId = "TestGroup1"; var entities = managementGroupsClient.Entities.List(groupId); Assert.NotNull(entities); Assert.Equal("/providers/Microsoft.Management/managementGroups/TestGroup1", entities.ElementAt(1).Id); Assert.Equal("TestGroup1", entities.ElementAt(1).Name); Assert.Equal("TestGroup1", entities.ElementAt(1).DisplayName); Assert.Equal("/providers/Microsoft.Management/managementGroups", entities.ElementAt(1).Type); Assert.NotNull(entities.ElementAt(2)); Assert.Equal("/providers/Microsoft.Management/managementGroups/TestGroup1Child1", entities.ElementAt(2).Id); Assert.Equal("TestGroup1Child1", entities.ElementAt(2).Name); Assert.Equal("TestGroup1->Child1", entities.ElementAt(2).DisplayName); Assert.Equal("/providers/Microsoft.Management/managementGroups", entities.ElementAt(2).Type); } } [Fact] public void CreateGroup() { using (MockContext context = MockContext.Start(this.GetType())) { var managementGroupsClient = ManagementGroupsTestUtilities.GetManagementGroupsApiClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); var groupId = "TestGroup1Child2"; var managementGroup = ((JObject) managementGroupsClient.ManagementGroups.CreateOrUpdate(groupId, new CreateManagementGroupRequest( id: "/providers/Microsoft.Management/managementGroups/TestGroup1Child2", type: "/providers/Microsoft.Management/managementGroups", name: "TestGroup1Child2", displayName: "TestGroup1->Child2", details: new CreateManagementGroupDetails() { Parent = new CreateParentGroupInfo() { Id = "/providers/Microsoft.Management/managementGroups/TestGroup1" } }), cacheControl: "no-cache")).ToObject<ManagementGroup>(JsonSerializer.Create(managementGroupsClient.DeserializationSettings)); Assert.NotNull(managementGroup); Assert.Equal("/providers/Microsoft.Management/managementGroups/TestGroup1Child2", managementGroup.Id); Assert.Equal("TestGroup1Child2", managementGroup.Name); Assert.Equal("TestGroup1->Child2", managementGroup.DisplayName); Assert.Equal("/providers/Microsoft.Management/managementGroups", managementGroup.Type); Assert.Equal("/providers/Microsoft.Management/managementGroups/TestGroup1", managementGroup.Details.Parent.Id); Assert.Equal("TestGroup1", managementGroup.Details.Parent.Name); Assert.Equal("TestGroup1", managementGroup.Details.Parent.DisplayName); } } [Fact] public void CreateGroupSubscription() { using (MockContext context = MockContext.Start(this.GetType())) { var managementGroupsClient = ManagementGroupsTestUtilities.GetManagementGroupsApiClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.NoContent }); var groupId = "TestGroup1Child1Child1"; var subscriptionId = "afe8f803-7190-48e3-b41a-bc454e8aad1a"; managementGroupsClient.ManagementGroupSubscriptions.Create(groupId, subscriptionId, cacheControl: "no-cache"); } } [Fact] public void DeleteGroupSubscription() { using (MockContext context = MockContext.Start(this.GetType())) { var managementGroupsClient = ManagementGroupsTestUtilities.GetManagementGroupsApiClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.NoContent }); var groupId = "TestGroup1Child1Child1"; var subscriptionId = "afe8f803-7190-48e3-b41a-bc454e8aad1a"; managementGroupsClient.ManagementGroupSubscriptions.Create(groupId, subscriptionId, cacheControl: "no-cache"); managementGroupsClient.ManagementGroupSubscriptions.Delete(groupId, subscriptionId, cacheControl: "no-cache"); } } [Fact] public void DeleteGroup() { using (MockContext context = MockContext.Start(this.GetType())) { var managementGroupsClient = ManagementGroupsTestUtilities.GetManagementGroupsApiClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); var groupId = "TestGroup1Child2"; managementGroupsClient.ManagementGroups.Delete(groupId, cacheControl: "no-cache"); } } [Fact] public void CheckNameAvailibilityTrue() { using (MockContext context = MockContext.Start(this.GetType())) { var managementGroupsClient = ManagementGroupsTestUtilities.GetManagementGroupsApiClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); var groupName = "TestGroup2"; var response = managementGroupsClient.CheckNameAvailability(new CheckNameAvailabilityRequest(groupName, Type.HyphenMinusprovidersHyphenMinusMicrosoftFullStopManagementHyphenMinusmanagementGroups)); Assert.True(response.NameAvailable); } } [Fact] public void CheckNameAvailibilityFalse() { using (MockContext context = MockContext.Start(this.GetType())) { var managementGroupsClient = ManagementGroupsTestUtilities.GetManagementGroupsApiClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); var groupName = "TestGroup1"; var response = managementGroupsClient.CheckNameAvailability(new CheckNameAvailabilityRequest(groupName, Type.HyphenMinusprovidersHyphenMinusMicrosoftFullStopManagementHyphenMinusmanagementGroups)); Assert.False(response.NameAvailable); } } [Fact] public void StartTenantBackfill() { using (MockContext context = MockContext.Start(this.GetType())) { var managementGroupsClient = ManagementGroupsTestUtilities.GetManagementGroupsApiClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); var response = managementGroupsClient.StartTenantBackfill(); Assert.Equal(Status.Completed, response.Status); } } [Fact] public void TenantBackfillStatus() { using (MockContext context = MockContext.Start(this.GetType())) { var managementGroupsClient = ManagementGroupsTestUtilities.GetManagementGroupsApiClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); var response = managementGroupsClient.TenantBackfillStatus(); Assert.Equal(Status.Completed, response.Status); } } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmLangGet { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmLangGet() : base() { //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; public System.Windows.Forms.CheckBox chkRTL; public System.Windows.Forms.TextBox txtTrans; private System.Windows.Forms.Button withEventsField_Command1; public System.Windows.Forms.Button Command1 { get { return withEventsField_Command1; } set { if (withEventsField_Command1 != null) { withEventsField_Command1.Click -= Command1_Click; } withEventsField_Command1 = value; if (withEventsField_Command1 != null) { withEventsField_Command1.Click += Command1_Click; } } } private System.Windows.Forms.Button withEventsField_cmdAccept; public System.Windows.Forms.Button cmdAccept { get { return withEventsField_cmdAccept; } set { if (withEventsField_cmdAccept != null) { withEventsField_cmdAccept.Click -= cmdAccept_Click; } withEventsField_cmdAccept = value; if (withEventsField_cmdAccept != null) { withEventsField_cmdAccept.Click += cmdAccept_Click; } } } private System.Windows.Forms.TextBox withEventsField_Text1; public System.Windows.Forms.TextBox Text1 { get { return withEventsField_Text1; } set { if (withEventsField_Text1 != null) { withEventsField_Text1.KeyDown -= Text1_KeyDown; withEventsField_Text1.KeyPress -= Text1_KeyPress; } withEventsField_Text1 = value; if (withEventsField_Text1 != null) { withEventsField_Text1.KeyDown += Text1_KeyDown; withEventsField_Text1.KeyPress += Text1_KeyPress; } } } public System.Windows.Forms.Label lblName; public System.Windows.Forms.Label Label1; public System.Windows.Forms.Label lblKey; //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmLangGet)); this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(components); this.chkRTL = new System.Windows.Forms.CheckBox(); this.txtTrans = new System.Windows.Forms.TextBox(); this.Command1 = new System.Windows.Forms.Button(); this.cmdAccept = new System.Windows.Forms.Button(); this.Text1 = new System.Windows.Forms.TextBox(); this.lblName = new System.Windows.Forms.Label(); this.Label1 = new System.Windows.Forms.Label(); this.lblKey = new System.Windows.Forms.Label(); this.SuspendLayout(); this.ToolTip1.Active = true; this.ControlBox = false; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.ClientSize = new System.Drawing.Size(352, 173); this.Location = new System.Drawing.Point(3, 3); this.MaximizeBox = false; this.MinimizeBox = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.Control; this.Enabled = true; this.KeyPreview = false; this.Cursor = System.Windows.Forms.Cursors.Default; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.HelpButton = false; this.WindowState = System.Windows.Forms.FormWindowState.Normal; this.Name = "frmLangGet"; this.chkRTL.Text = "Right to Left"; this.chkRTL.Size = new System.Drawing.Size(185, 25); this.chkRTL.Location = new System.Drawing.Point(8, 144); this.chkRTL.TabIndex = 1; this.chkRTL.CheckAlign = System.Drawing.ContentAlignment.MiddleLeft; this.chkRTL.FlatStyle = System.Windows.Forms.FlatStyle.Standard; this.chkRTL.BackColor = System.Drawing.SystemColors.Control; this.chkRTL.CausesValidation = true; this.chkRTL.Enabled = true; this.chkRTL.ForeColor = System.Drawing.SystemColors.ControlText; this.chkRTL.Cursor = System.Windows.Forms.Cursors.Default; this.chkRTL.RightToLeft = System.Windows.Forms.RightToLeft.No; this.chkRTL.Appearance = System.Windows.Forms.Appearance.Normal; this.chkRTL.TabStop = true; this.chkRTL.CheckState = System.Windows.Forms.CheckState.Unchecked; this.chkRTL.Visible = true; this.chkRTL.Name = "chkRTL"; this.txtTrans.AutoSize = false; this.txtTrans.Size = new System.Drawing.Size(337, 113); this.txtTrans.Location = new System.Drawing.Point(8, 24); this.txtTrans.Multiline = true; this.txtTrans.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtTrans.TabIndex = 0; this.txtTrans.AcceptsReturn = true; this.txtTrans.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this.txtTrans.BackColor = System.Drawing.SystemColors.Window; this.txtTrans.CausesValidation = true; this.txtTrans.Enabled = true; this.txtTrans.ForeColor = System.Drawing.SystemColors.WindowText; this.txtTrans.HideSelection = true; this.txtTrans.ReadOnly = false; this.txtTrans.MaxLength = 0; this.txtTrans.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtTrans.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtTrans.TabStop = true; this.txtTrans.Visible = true; this.txtTrans.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtTrans.Name = "txtTrans"; this.Command1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.Command1.Text = "Decline"; this.Command1.Size = new System.Drawing.Size(73, 22); this.Command1.Location = new System.Drawing.Point(270, 146); this.Command1.TabIndex = 3; this.Command1.TabStop = false; this.Command1.BackColor = System.Drawing.SystemColors.Control; this.Command1.CausesValidation = true; this.Command1.Enabled = true; this.Command1.ForeColor = System.Drawing.SystemColors.ControlText; this.Command1.Cursor = System.Windows.Forms.Cursors.Default; this.Command1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Command1.Name = "Command1"; this.cmdAccept.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdAccept.Text = "Accept"; this.cmdAccept.Size = new System.Drawing.Size(73, 22); this.cmdAccept.Location = new System.Drawing.Point(195, 146); this.cmdAccept.TabIndex = 2; this.cmdAccept.TabStop = false; this.cmdAccept.BackColor = System.Drawing.SystemColors.Control; this.cmdAccept.CausesValidation = true; this.cmdAccept.Enabled = true; this.cmdAccept.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdAccept.Cursor = System.Windows.Forms.Cursors.Default; this.cmdAccept.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdAccept.Name = "cmdAccept"; this.Text1.AutoSize = false; this.Text1.Size = new System.Drawing.Size(149, 25); this.Text1.Location = new System.Drawing.Point(0, 184); this.Text1.TabIndex = 4; this.Text1.TabStop = false; this.Text1.Text = "Text1"; this.Text1.AcceptsReturn = true; this.Text1.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this.Text1.BackColor = System.Drawing.SystemColors.Window; this.Text1.CausesValidation = true; this.Text1.Enabled = true; this.Text1.ForeColor = System.Drawing.SystemColors.WindowText; this.Text1.HideSelection = true; this.Text1.ReadOnly = false; this.Text1.MaxLength = 0; this.Text1.Cursor = System.Windows.Forms.Cursors.IBeam; this.Text1.Multiline = false; this.Text1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Text1.ScrollBars = System.Windows.Forms.ScrollBars.None; this.Text1.Visible = true; this.Text1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.Text1.Name = "Text1"; this.lblName.Text = "..."; this.lblName.Size = new System.Drawing.Size(241, 16); this.lblName.Location = new System.Drawing.Point(3, 21); this.lblName.TabIndex = 7; this.lblName.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.lblName.BackColor = System.Drawing.Color.Transparent; this.lblName.Enabled = true; this.lblName.ForeColor = System.Drawing.SystemColors.ControlText; this.lblName.Cursor = System.Windows.Forms.Cursors.Default; this.lblName.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblName.UseMnemonic = true; this.lblName.Visible = true; this.lblName.AutoSize = false; this.lblName.BorderStyle = System.Windows.Forms.BorderStyle.None; this.lblName.Name = "lblName"; this.Label1.Text = "Type in Translation"; this.Label1.Size = new System.Drawing.Size(241, 16); this.Label1.Location = new System.Drawing.Point(3, 0); this.Label1.TabIndex = 6; this.Label1.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.Label1.BackColor = System.Drawing.SystemColors.Control; this.Label1.Enabled = true; this.Label1.ForeColor = System.Drawing.SystemColors.ControlText; this.Label1.Cursor = System.Windows.Forms.Cursors.Default; this.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No; this.Label1.UseMnemonic = true; this.Label1.Visible = true; this.Label1.AutoSize = false; this.Label1.BorderStyle = System.Windows.Forms.BorderStyle.None; this.Label1.Name = "Label1"; this.lblKey.Text = "Label1"; this.lblKey.Size = new System.Drawing.Size(86, 20); this.lblKey.Location = new System.Drawing.Point(152, 192); this.lblKey.TabIndex = 5; this.lblKey.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.lblKey.BackColor = System.Drawing.SystemColors.Control; this.lblKey.Enabled = true; this.lblKey.ForeColor = System.Drawing.SystemColors.ControlText; this.lblKey.Cursor = System.Windows.Forms.Cursors.Default; this.lblKey.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblKey.UseMnemonic = true; this.lblKey.Visible = true; this.lblKey.AutoSize = false; this.lblKey.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblKey.Name = "lblKey"; this.Controls.Add(chkRTL); this.Controls.Add(txtTrans); this.Controls.Add(Command1); this.Controls.Add(cmdAccept); this.Controls.Add(Text1); this.Controls.Add(lblName); this.Controls.Add(Label1); this.Controls.Add(lblKey); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
#region Copyright // // Nini Configuration Project. // Copyright (C) 2006 Brent R. Matzelle. All rights reserved. // // This software is published under the terms of the MIT X11 license, a copy of // which has been included with this distribution in the LICENSE.txt file. // #endregion using System; using System.IO; using System.Collections; using Microsoft.Win32; using Nini.Ini; namespace Nini.Config { #region RegistryRecurse enumeration /// <include file='RegistryConfigSource.xml' path='//Enum[@name="RegistryRecurse"]/docs/*' /> public enum RegistryRecurse { /// <include file='RegistryConfigSource.xml' path='//Enum[@name="RegistryRecurse"]/Value[@name="None"]/docs/*' /> None, /// <include file='RegistryConfigSource.xml' path='//Enum[@name="RegistryRecurse"]/Value[@name="Flattened"]/docs/*' /> Flattened, /// <include file='RegistryConfigSource.xml' path='//Enum[@name="RegistryRecurse"]/Value[@name="Namespacing"]/docs/*' /> Namespacing } #endregion /// <include file='RegistryConfigSource.xml' path='//Class[@name="RegistryConfigSource"]/docs/*' /> public class RegistryConfigSource : ConfigSourceBase { #region Private variables RegistryKey defaultKey = null; #endregion #region Public properties /// <include file='RegistryConfigSource.xml' path='//Property[@name="DefaultKey"]/docs/*' /> public RegistryKey DefaultKey { get { return defaultKey; } set { defaultKey = value; } } #endregion #region Constructors #endregion #region Public methods /// <include file='RegistryConfigSource.xml' path='//Method[@name="AddConfig"]/docs/*' /> public override IConfig AddConfig (string name) { if (this.DefaultKey == null) { throw new ApplicationException ("You must set DefaultKey"); } return AddConfig (name, this.DefaultKey); } /// <include file='RegistryConfigSource.xml' path='//Method[@name="AddConfigKey"]/docs/*' /> public IConfig AddConfig (string name, RegistryKey key) { RegistryConfig result = new RegistryConfig (name, this); result.Key = key; result.ParentKey = true; this.Configs.Add (result); return result; } /// <include file='RegistryConfigSource.xml' path='//Method[@name="AddMapping"]/docs/*' /> public void AddMapping (RegistryKey registryKey, string path) { RegistryKey key = registryKey.OpenSubKey (path, true); if (key == null) { throw new ArgumentException ("The specified key does not exist"); } LoadKeyValues (key, ShortKeyName (key)); } /// <include file='RegistryConfigSource.xml' path='//Method[@name="AddMappingRecurse"]/docs/*' /> public void AddMapping (RegistryKey registryKey, string path, RegistryRecurse recurse) { RegistryKey key = registryKey.OpenSubKey (path, true); if (key == null) { throw new ArgumentException ("The specified key does not exist"); } if (recurse == RegistryRecurse.Namespacing) { LoadKeyValues (key, path); } else { LoadKeyValues (key, ShortKeyName (key)); } string[] subKeys = key.GetSubKeyNames (); for (int i = 0; i < subKeys.Length; i++) { switch (recurse) { case RegistryRecurse.None: // no recursion break; case RegistryRecurse.Namespacing: AddMapping (registryKey, path + "\\" + subKeys[i], recurse); break; case RegistryRecurse.Flattened: AddMapping (key, subKeys[i], recurse); break; } } } /// <include file='IConfigSource.xml' path='//Method[@name="Save"]/docs/*' /> public override void Save () { MergeConfigsIntoDocument (); for (int i = 0; i < this.Configs.Count; i++) { // New merged configs are not RegistryConfigs if (this.Configs[i] is RegistryConfig) { RegistryConfig config = (RegistryConfig)this.Configs[i]; string[] keys = config.GetKeys (); for (int j = 0; j < keys.Length; j++) { config.Key.SetValue (keys[j], config.Get (keys[j])); } } } } /// <include file='IConfigSource.xml' path='//Method[@name="Reload"]/docs/*' /> public override void Reload () { ReloadKeys (); } #endregion #region Private methods /// <summary> /// Loads all values from the registry key. /// </summary> private void LoadKeyValues (RegistryKey key, string keyName) { RegistryConfig config = new RegistryConfig (keyName, this); config.Key = key; string[] values = key.GetValueNames (); foreach (string value in values) { config.Add (value, key.GetValue (value).ToString ()); } this.Configs.Add (config); } /// <summary> /// Merges all of the configs from the config collection into the /// registry. /// </summary> private void MergeConfigsIntoDocument () { foreach (IConfig config in this.Configs) { if (config is RegistryConfig) { RegistryConfig registryConfig = (RegistryConfig)config; if (registryConfig.ParentKey) { registryConfig.Key = registryConfig.Key.CreateSubKey (registryConfig.Name); } RemoveKeys (registryConfig); string[] keys = config.GetKeys (); for (int i = 0; i < keys.Length; i++) { registryConfig.Key.SetValue (keys[i], config.Get (keys[i])); } registryConfig.Key.Flush (); } } } /// <summary> /// Reloads all keys. /// </summary> private void ReloadKeys () { RegistryKey[] keys = new RegistryKey[this.Configs.Count]; for (int i = 0; i < keys.Length; i++) { keys[i] = ((RegistryConfig)this.Configs[i]).Key; } this.Configs.Clear (); for (int i = 0; i < keys.Length; i++) { LoadKeyValues (keys[i], ShortKeyName (keys[i])); } } /// <summary> /// Removes all keys not present in the current config. /// </summary> private void RemoveKeys (RegistryConfig config) { foreach (string valueName in config.Key.GetValueNames ()) { if (!config.Contains (valueName)) { config.Key.DeleteValue (valueName); } } } /// <summary> /// Returns the key name without the fully qualified path. /// e.g. no HKEY_LOCAL_MACHINE\\MyKey, just MyKey /// </summary> private string ShortKeyName (RegistryKey key) { int index = key.Name.LastIndexOf ("\\"); return (index == -1) ? key.Name : key.Name.Substring (index + 1); } #region RegistryConfig class /// <summary> /// Registry Config class. /// </summary> private class RegistryConfig : ConfigBase { #region Private variables RegistryKey key = null; bool parentKey = false; #endregion #region Constructor /// <summary> /// Constructor. /// </summary> public RegistryConfig (string name, IConfigSource source) : base (name, source) { } #endregion #region Public properties /// <summary> /// Gets or sets whether the key is a parent key. /// </summary> public bool ParentKey { get { return parentKey; } set { parentKey = value; } } /// <summary> /// Registry key for the Config. /// </summary> public RegistryKey Key { get { return key; } set { key = value; } } #endregion } #endregion #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace API_GrupoE.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
#if UNITY_IOS // Copyright (C) 2015 Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Runtime.InteropServices; namespace GoogleMobileAds.iOS { // Externs used by the iOS component. internal class Externs { #region Common externs [DllImport("__Internal")] internal static extern void GADUInitializeWithCallback( IntPtr mobileAdsClient, MobileAdsClient.GADUInitializationCompleteCallback callback); [DllImport("__Internal")] internal static extern void GADUDisableMediationInitialization(); [DllImport("__Internal")] internal static extern IntPtr GADUGetInitDescription(IntPtr status, string className); [DllImport("__Internal")] internal static extern int GADUGetInitLatency(IntPtr status, string className); [DllImport("__Internal")] internal static extern int GADUGetInitState(IntPtr status, string className); [DllImport("__Internal")] internal static extern IntPtr GADUGetInitAdapterClasses(IntPtr status); [DllImport("__Internal")] internal static extern int GADUGetInitNumberOfAdapterClasses(IntPtr status); [DllImport("__Internal")] internal static extern void GADUSetApplicationVolume(float volume); [DllImport("__Internal")] internal static extern void GADUSetApplicationMuted(bool muted); [DllImport("__Internal")] internal static extern void GADUSetiOSAppPauseOnBackground(bool pause); [DllImport("__Internal")] internal static extern float GADUDeviceScale(); [DllImport("__Internal")] internal static extern int GADUDeviceSafeWidth(); [DllImport("__Internal")] internal static extern IntPtr GADUCreateRequest(); [DllImport("__Internal")] internal static extern IntPtr GADUCreateMutableDictionary(); [DllImport("__Internal")] internal static extern void GADUMutableDictionarySetValue( IntPtr mutableDictionaryPtr, string key, string value); [DllImport("__Internal")] internal static extern void GADUSetMediationExtras( IntPtr request, IntPtr mutableDictionaryPtr, string adNetworkExtrasClassName); [DllImport("__Internal")] internal static extern void GADUAddKeyword(IntPtr request, string keyword); [DllImport("__Internal")] internal static extern void GADUSetExtra(IntPtr request, string key, string value); [DllImport("__Internal")] internal static extern void GADUSetRequestAgent(IntPtr request, string requestAgent); [DllImport("__Internal")] internal static extern void GADURelease(IntPtr obj); [DllImport("__Internal")] internal static extern IntPtr GADUCreateRequestConfiguration(); [DllImport("__Internal")] internal static extern void GADUSetRequestConfiguration(IntPtr requestConfiguration); [DllImport("__Internal")] internal static extern void GADUSetRequestConfigurationTestDeviceIdentifiers( IntPtr requestConfiguration, string[] testDeviceIDs, int testDeviceIDLength); [DllImport("__Internal")] internal static extern void GADUSetRequestConfigurationMaxAdContentRating( IntPtr requestConfiguration, string maxAdContentRating); [DllImport("__Internal")] internal static extern void GADUSetRequestConfigurationTagForUnderAgeOfConsent( IntPtr requestConfiguration, int tagForUnderAgeOfConsent); [DllImport("__Internal")] internal static extern void GADUSetRequestConfigurationTagForChildDirectedTreatment( IntPtr requestConfiguration, int tagForChildDirectedTreatment); [DllImport("__Internal")] internal static extern void GADUSetRequestConfigurationSameAppKeyEnabled( IntPtr requestConfiguration, bool enabled); [DllImport("__Internal")] internal static extern IntPtr GADUGetTestDeviceIdentifiers(IntPtr request); [DllImport("__Internal")] internal static extern int GADUGetTestDeviceIdentifiersCount(IntPtr request); [DllImport("__Internal")] internal static extern string GADUGetMaxAdContentRating(IntPtr requestConfiguration); [DllImport("__Internal")] internal static extern int GADUGetRequestConfigurationTagForUnderAgeOfConsent( IntPtr requestConfiguration); [DllImport("__Internal")] internal static extern int GADUGetRequestConfigurationTagForChildDirectedTreatment( IntPtr requestConfiguration); [DllImport("__Internal")] internal static extern bool GADUGetRequestConfigurationSameAppKeyEnabled( IntPtr requestConfiguration); #endregion #region AppOpenAd externs [DllImport("__Internal")] internal static extern IntPtr GADUCreateAppOpenAd(IntPtr appOpenAdClient); [DllImport("__Internal")] internal static extern void GADULoadAppOpenAd( IntPtr appOpenAd, string adUnitID, int orientation, IntPtr request); [DllImport("__Internal")] internal static extern void GADUShowAppOpenAd(IntPtr appOpenAd); [DllImport("__Internal")] internal static extern void GADUSetAppOpenAdCallbacks( IntPtr appOpenAd, AppOpenAdClient.GADUAppOpenAdLoadedCallback adLoadedCallback, AppOpenAdClient.GADUAppOpenAdFailToLoadCallback adFailedToLoadCallback, AppOpenAdClient.GADUAppOpenAdPaidEventCallback paidEventCallback, AppOpenAdClient.GADUAppOpenAdFailedToPresentFullScreenContentCallback adFailToPresentFullScreenContentCallback, AppOpenAdClient.GADUAppOpenAdWillPresentFullScreenContentCallback adWillPresentFullScreenContentCallback, AppOpenAdClient.GADUAppOpenAdDidDismissFullScreenContentCallback adDidDismissFullScreenContentCallback, AppOpenAdClient.GADUAppOpenAdDidRecordImpressionCallback adDidRecordImpressionCallback ); #endregion #region Banner externs [DllImport("__Internal")] internal static extern IntPtr GADUCreateBannerView( IntPtr bannerClient, string adUnitId, int width, int height, int positionAtTop); [DllImport("__Internal")] internal static extern IntPtr GADUCreateBannerViewWithCustomPosition( IntPtr bannerClient, string adUnitId, int width, int height, int x, int y); [DllImport("__Internal")] internal static extern IntPtr GADUCreateSmartBannerView( IntPtr bannerClient, string adUnitId, int positionAtTop); [DllImport("__Internal")] internal static extern IntPtr GADUCreateSmartBannerViewWithCustomPosition( IntPtr bannerClient, string adUnitId, int x, int y); [DllImport("__Internal")] internal static extern IntPtr GADUCreateAnchoredAdaptiveBannerView( IntPtr bannerClient, string adUnitId, int width, int orientation, int positionAtTop); [DllImport("__Internal")] internal static extern IntPtr GADUCreateAnchoredAdaptiveBannerViewWithCustomPosition( IntPtr bannerClient, string adUnitId, int width, int orientation, int x, int y); [DllImport("__Internal")] internal static extern void GADUSetBannerCallbacks( IntPtr bannerView, BannerClient.GADUAdViewDidReceiveAdCallback adReceivedCallback, BannerClient.GADUAdViewDidFailToReceiveAdWithErrorCallback adFailedCallback, BannerClient.GADUAdViewWillPresentScreenCallback willPresentCallback, BannerClient.GADUAdViewDidDismissScreenCallback didDismissCallback, BannerClient.GADUAdViewPaidEventCallback paidEventCallback ); [DllImport("__Internal")] internal static extern void GADUHideBannerView(IntPtr bannerView); [DllImport("__Internal")] internal static extern void GADUShowBannerView(IntPtr bannerView); [DllImport("__Internal")] internal static extern void GADURemoveBannerView(IntPtr bannerView); [DllImport("__Internal")] internal static extern void GADURequestBannerAd(IntPtr bannerView, IntPtr request); [DllImport("__Internal")] internal static extern float GADUGetBannerViewHeightInPixels(IntPtr bannerView); [DllImport("__Internal")] internal static extern float GADUGetBannerViewWidthInPixels(IntPtr bannerView); [DllImport("__Internal")] internal static extern void GADUSetBannerViewAdPosition(IntPtr bannerView, int position); [DllImport("__Internal")] internal static extern void GADUSetBannerViewCustomPosition(IntPtr bannerView, int x, int y); [DllImport("__Internal")] internal static extern IntPtr GADUGetResponseInfo(IntPtr adFormat); [DllImport("__Internal")] internal static extern string GADUResponseInfoMediationAdapterClassName(IntPtr responseInfo); [DllImport("__Internal")] internal static extern string GADUResponseInfoResponseId(IntPtr responseInfo); [DllImport("__Internal")] internal static extern string GADUGetResponseInfoDescription(IntPtr responseInfo); [DllImport("__Internal")] internal static extern int GADUGetAdErrorCode(IntPtr error); [DllImport("__Internal")] internal static extern string GADUGetAdErrorDomain(IntPtr error); [DllImport("__Internal")] internal static extern string GADUGetAdErrorMessage(IntPtr error); [DllImport("__Internal")] internal static extern IntPtr GADUGetAdErrorUnderLyingError(IntPtr error); [DllImport("__Internal")] internal static extern IntPtr GADUGetAdErrorResponseInfo(IntPtr error); [DllImport("__Internal")] internal static extern string GADUGetAdErrorDescription(IntPtr error); #endregion #region Interstitial externs [DllImport("__Internal")] internal static extern IntPtr GADUCreateInterstitial(IntPtr interstitialClient); [DllImport("__Internal")] internal static extern IntPtr GADULoadInterstitialAd(IntPtr interstitialAd, string adUnitID, IntPtr request); [DllImport("__Internal")] internal static extern void GADUSetInterstitialCallbacks( IntPtr interstitial, InterstitialClient.GADUInterstitialAdLoadedCallback adReceivedCallback, InterstitialClient.GADUInterstitialAdFailedToLoadCallback adFailedCallback, InterstitialClient.GADUInterstitialAdWillPresentFullScreenContentCallback adWillPresentFullScreenContentCallback, InterstitialClient.GADUInterstitialAdFailedToPresentFullScreenContentCallback adFailToPresentFullScreenContentCallback, InterstitialClient.GADUInterstitialAdDidDismissFullScreenContentCallback adDidDismissFullScreenContentCallback, InterstitialClient.GADUInterstitialAdDidRecordImpressionCallback adDidRecordImpressionCallback, InterstitialClient.GADUInterstitialPaidEventCallback paidEventCallback ); [DllImport("__Internal")] internal static extern void GADUShowInterstitial(IntPtr interstitial); #endregion #region RewardedAd externs [DllImport("__Internal")] internal static extern IntPtr GADUCreateRewardedAd(IntPtr rewardedAd); [DllImport("__Internal")] internal static extern IntPtr GADULoadRewardedAd(IntPtr interstitialAd, string adUnitID, IntPtr request); [DllImport("__Internal")] internal static extern void GADUShowRewardedAd(IntPtr rewardedAd); [DllImport("__Internal")] internal static extern void GADUSetRewardedAdCallbacks( IntPtr rewardedAd, RewardedAdClient.GADURewardedAdLoadedCallback adLoadedCallback, RewardedAdClient.GADURewardedAdFailedToLoadCallback adFailedToLoadCallback, RewardedAdClient.GADURewardedAdWillPresentFullScreenContentCallback adWillPresentFullScreenContentCallback, RewardedAdClient.GADURewardedAdFailedToPresentFullScreenContentCallback adFailToPresentFullScreenContentCallback, RewardedAdClient.GADURewardedAdDidDismissFullScreenContentCallback adDidDismissFullScreenContentCallback, RewardedAdClient.GADURewardedAdDidRecordImpressionCallback adDidRecordImpressionCallback, RewardedAdClient.GADURewardedAdUserEarnedRewardCallback adDidEarnRewardCallback, RewardedAdClient.GADURewardedAdPaidEventCallback paidEventCallback ); [DllImport("__Internal")] internal static extern IntPtr GADUCreateServerSideVerificationOptions(); [DllImport("__Internal")] internal static extern void GADUServerSideVerificationOptionsSetUserId( IntPtr options, string userId); [DllImport("__Internal")] internal static extern void GADUServerSideVerificationOptionsSetCustomRewardString( IntPtr options, string customRewardString); [DllImport("__Internal")] internal static extern void GADURewardedAdSetServerSideVerificationOptions( IntPtr rewardedAd, IntPtr options); [DllImport("__Internal")] internal static extern string GADURewardedAdGetRewardType(IntPtr rewardedAd); [DllImport("__Internal")] internal static extern double GADURewardedAdGetRewardAmount(IntPtr rewardedAd); #endregion #region RewardedInterstitialAd externs [DllImport("__Internal")] internal static extern IntPtr GADUCreateRewardedInterstitialAd(IntPtr rewardedInterstitialAd); [DllImport("__Internal")] internal static extern IntPtr GADULoadRewardedInterstitialAd(IntPtr rewardedInterstitialAd, string adUnitID, IntPtr request); [DllImport("__Internal")] internal static extern void GADUShowRewardedInterstitialAd(IntPtr rewardedInterstitialAd); [DllImport("__Internal")] internal static extern void GADUSetRewardedInterstitialAdCallbacks( IntPtr rewardedInterstitialAd, RewardedInterstitialAdClient.GADURewardedInterstitialAdLoadedCallback adLoadedCallback, RewardedInterstitialAdClient.GADURewardedInterstitialAdFailedToLoadCallback adFailedToLoadCallback, RewardedInterstitialAdClient.GADURewardedInterstitialAdUserEarnedRewardCallback adDidEarnRewardCallback, RewardedInterstitialAdClient.GADURewardedInterstitialAdPaidEventCallback paidEventCallback, RewardedInterstitialAdClient.GADURewardedInterstitialAdFailedToPresentFullScreenContentCallback adFailToPresentFullScreenContentCallback, RewardedInterstitialAdClient.GADURewardedInterstitialAdWillPresentFullScreenContentCallback adWillPresentFullScreenContentCallback, RewardedInterstitialAdClient.GADURewardedInterstitialAdDidDismissFullScreenContentCallback adDidDismissFullScreenContentCallback, RewardedInterstitialAdClient.GADURewardedInterstitialAdDidRecordImpressionCallback adDidRecordImpressionCallback ); [DllImport("__Internal")] internal static extern void GADURewardedInterstitialAdSetServerSideVerificationOptions( IntPtr rewardedAd, IntPtr options); [DllImport("__Internal")] internal static extern string GADURewardedInterstitialAdGetRewardType( IntPtr rewardedInterstitialAd); [DllImport("__Internal")] internal static extern double GADURewardedInterstitialAdGetRewardAmount( IntPtr rewardedInterstitialAd); #endregion #region AdInspector externs [DllImport("__Internal")] internal static extern void GADUPresentAdInspector( IntPtr mobileAdsClient, MobileAdsClient.GADUAdInspectorClosedCallback callback); #endregion } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace System.Xml { /// <devdoc> /// <para> /// XmlNameTable implemented as a simple hash table. /// </para> /// </devdoc> public class NameTable : XmlNameTable { // // Private types // private class Entry { internal string str; internal int hashCode; internal Entry next; internal Entry(string str, int hashCode, Entry next) { this.str = str; this.hashCode = hashCode; this.next = next; } } // // Fields // private Entry[] _entries; private int _count; private int _mask; // // Constructor /// <devdoc> /// Public constructor. /// </devdoc> public NameTable() { _mask = 31; _entries = new Entry[_mask + 1]; } // // XmlNameTable public methods /// <devdoc> /// Add the given string to the NameTable or return /// the existing string if it is already in the NameTable. /// </devdoc> public override string Add(string key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } int len = key.Length; if (len == 0) { return string.Empty; } int hashCode = ComputeHash32(key); for (Entry e = _entries[hashCode & _mask]; e != null; e = e.next) { if (e.hashCode == hashCode && e.str.Equals(key)) { return e.str; } } return AddEntry(key, hashCode); } /// <devdoc> /// Add the given string to the NameTable or return /// the existing string if it is already in the NameTable. /// </devdoc> public override string Add(char[] key, int start, int len) { if (len == 0) { return string.Empty; } // Compatibility check to ensure same exception as previous versions // independently of any exceptions throw by the hashing function. // note that NullReferenceException is the first one if key is null. if (start >= key.Length || start < 0 || (long)start + len > (long)key.Length) { throw new IndexOutOfRangeException(); } // Compatibility check for len < 0, just throw the same exception as new string(key, start, len) if (len < 0) { throw new ArgumentOutOfRangeException(); } int hashCode = ComputeHash32(key, start, len); for (Entry e = _entries[hashCode & _mask]; e != null; e = e.next) { if (e.hashCode == hashCode && TextEquals(e.str, key, start, len)) { return e.str; } } return AddEntry(new string(key, start, len), hashCode); } /// <devdoc> /// Find the matching string in the NameTable. /// </devdoc> public override string Get(string value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } if (value.Length == 0) { return string.Empty; } int hashCode = ComputeHash32(value); for (Entry e = _entries[hashCode & _mask]; e != null; e = e.next) { if (e.hashCode == hashCode && e.str.Equals(value)) { return e.str; } } return null; } /// <devdoc> /// Find the matching string atom given a range of /// characters. /// </devdoc> public override string Get(char[] key, int start, int len) { if (len == 0) { return string.Empty; } if (start >= key.Length || start < 0 || (long)start + len > (long)key.Length) { throw new IndexOutOfRangeException(); } // Compatibility check for len < 0, just return null if (len < 0) { return null; } int hashCode = ComputeHash32(key, start, len); for (Entry e = _entries[hashCode & _mask]; e != null; e = e.next) { if (e.hashCode == hashCode && TextEquals(e.str, key, start, len)) { return e.str; } } return null; } // // Private methods // private string AddEntry(string str, int hashCode) { int index = hashCode & _mask; Entry e = new Entry(str, hashCode, _entries[index]); _entries[index] = e; if (_count++ == _mask) { Grow(); } return e.str; } private void Grow() { int newMask = _mask * 2 + 1; Entry[] oldEntries = _entries; Entry[] newEntries = new Entry[newMask + 1]; // use oldEntries.Length to eliminate the range check for (int i = 0; i < oldEntries.Length; i++) { Entry e = oldEntries[i]; while (e != null) { int newIndex = e.hashCode & newMask; Entry tmp = e.next; e.next = newEntries[newIndex]; newEntries[newIndex] = e; e = tmp; } } _entries = newEntries; _mask = newMask; } private static bool TextEquals(string str1, char[] str2, int str2Start, int str2Length) { if (str1.Length != str2Length) { return false; } // use array.Length to eliminate the range check for (int i = 0; i < str1.Length; i++) { if (str1[i] != str2[str2Start + i]) { return false; } } return true; } private static int ComputeHash32(string key) { ReadOnlySpan<byte> bytes = key.AsReadOnlySpan().AsBytes(); return Marvin.ComputeHash32(bytes, Marvin.DefaultSeed); } private static int ComputeHash32(char[] key, int start, int len) { ReadOnlySpan<byte> bytes = key.AsReadOnlySpan().Slice(start, len).AsBytes(); return Marvin.ComputeHash32(bytes, Marvin.DefaultSeed); } } }
using GuiLabs.Canvas.Controls; using GuiLabs.Editor.Actions; namespace GuiLabs.Editor.Blocks { public abstract partial class Block { /// <summary> /// Tries to set focus to the block. /// </summary> /// <param name="shouldRedraw">If the draw window should be repainted.</param> /// <remarks>The draw window is only repainted when the focus was set successfully</remarks> /// <returns>true if the focus was set, otherwise false.</returns> public virtual bool SetFocus() { return SetFocusCore(); } protected bool SetFocusCore() { if (Root == null) { return false; } Block toFocus = FindFirstFocusableBlock(); if (toFocus != null && toFocus.CanGetFocus) { if (this.ActionManager != null && this.ActionManager.RecordingTransaction != null) { // was: //this. // ActionManager. // RecordingTransaction. // AccumulatingAction. // BlockToFocus = toFocus; toFocus.SetFocus(SetFocusOptions.General); } else { return toFocus.MyControl.SetFocus(); } } return false; } /// <summary> /// Tries to set the focus to the default control inside current block. /// Normally equivalent to SetFocus, but can be redefined to set the focus /// to arbitrary control. /// </summary> /// <param name="shouldRedraw">If the screen should be repainted.</param> public virtual void SetDefaultFocus() { Control toFocus = this.DefaultFocusableControl(); if (toFocus != null) { toFocus.SetFocus(); } else { SetFocus(); } } public virtual Control DefaultFocusableControl() { return MyControl; } public virtual bool CanGetFocus { get { return MyControl != null && MyControl.CanGetFocus; } } /// <summary> /// Searches this block depth-first top-to-bottom /// and all children recursively /// </summary> /// <returns>First found focusable block (may be self). null if none found.</returns> public virtual Block FindFirstFocusableBlock() { if (CanGetFocus) { return this; } return null; } /// <summary> /// Searches this block depth-first bottom-to-top /// and all children recursively /// </summary> /// <returns>Last found focusable block (may be self). null if none found.</returns> public virtual Block FindLastFocusableBlock() { if (CanGetFocus) { return this; } return null; } /// <summary> /// Searches depth-first recursively, without considering the current block. /// Can only be non-null for containers. /// </summary> /// <returns>The first focusable child block of the current block, /// if such a block exists, null otherwise.</returns> public virtual Block FindFirstFocusableChild() { return null; } public virtual Block FindLastFocusableChild() { return null; } public enum MoveFocusDirection { SelectPrev, SelectNext, SelectPrevInChain, SelectNextInChain, SelectParent } /// <summary> /// Puts focus to the next available block. /// </summary> /// <param name="shouldRedraw">If the screen should be repainted afterwards</param> public bool RemoveFocus() { return RemoveFocus(MoveFocusDirection.SelectNext); } /// <summary> /// Puts focus to some other block. /// </summary> /// <returns>true if successful, false if the method had no effect</returns> /// <remarks>Normally called before deleting a block.</remarks> public bool RemoveFocus(MoveFocusDirection direction) { Block neighbour = null; if (direction == MoveFocusDirection.SelectPrev || direction == MoveFocusDirection.SelectPrevInChain) { if (direction == MoveFocusDirection.SelectPrev) { neighbour = this.FindPrevFocusableBlock(); } else { neighbour = this.FindPrevFocusableBlockInChain(); } if (neighbour == null) { // if there is no prev block, // try to select next block neighbour = this.FindNextFocusableBlock(); } } else if (direction == MoveFocusDirection.SelectNext || direction == MoveFocusDirection.SelectNextInChain) { if (direction == MoveFocusDirection.SelectNext) { neighbour = this.FindNextFocusableBlock(); } else { neighbour = this.FindNextFocusableBlockInChain(); } if (neighbour == null) { // if there is no next block, // try to select previous block neighbour = this.FindPrevFocusableBlock(); } } if (neighbour == null) { // if toRemoveFocusFrom is the only block, // try to select parent neighbour = this.FindNearestFocusableParent(); } if (neighbour != null) { // if found someone, select it neighbour.SetFocus(); } return neighbour != null; } /// <summary> /// Searches a "brother" block upwards of startFrom, /// that is above startFrom and is focusable. /// If no such block is found, returns null. /// </summary> /// <param name="startFrom">Block, above which to search (upwards)</param> /// <returns>Focusable sibling block, if found; otherwise null.</returns> //public Block FindPrevFocusableSibling() //{ // Block current = this.Prev; // while (current != null && !current.CanGetFocus) // { // current = current.Prev; // } // return current; //} /// <summary> /// Searches a "brother" block downwards of startFrom, /// that is below startFrom and is focusable. /// If no such block is found, returns null. /// </summary> /// <param name="startFrom">Block, down from which to search (downwards)</param> /// <returns>Focusable sibling block, if found; otherwise null.</returns> //public Block FindNextFocusableSibling() //{ // Block current = this.Next; // while (current != null && !current.CanGetFocus) // { // current = current.Next; // } // return current; //} /// <summary> /// Searches for a previous block "deep" /// (includes children of previous blocks recursively) /// </summary> /// <returns>Focusable block if found; otherwise null</returns> public Block FindPrevFocusableBlock() { Block current = this.Prev; while (current != null) { Block foundFocusableBlock = current.FindLastFocusableBlock(); if (foundFocusableBlock != null) { return foundFocusableBlock; } current = current.Prev; } return null; } /// <summary> /// Searches for a next block "deep" /// (includes children of following blocks recursively) /// </summary> /// <returns></returns> public Block FindNextFocusableBlock() { Block current = this.Next; while (current != null) { Block foundFocusableBlock = current.FindFirstFocusableBlock(); if (foundFocusableBlock != null) { return foundFocusableBlock; } current = current.Next; } return null; } /// <summary> /// Searches for a previous focused block in the same parent, no recursion. /// </summary> /// <returns>Nearest previous sibling, doesn't go deep.</returns> public Block FindPrevFocusableSibling() { Block current = this.Prev; while (current != null) { if (current.CanGetFocus) { return current; } current = current.Prev; } return null; } /// <summary> /// Searches for the next focused block in the same parent, no recursion. /// </summary> /// <returns>Nearest next sibling, doesn't go deep.</returns> public Block FindNextFocusableSibling() { Block current = this.Next; while (current != null) { if (current.CanGetFocus) { return current; } current = current.Next; } return null; } /// <summary> /// Searches for a previous block "deep" /// (includes children of previous blocks recursively) /// </summary> /// <returns>Focusable block if found; otherwise null</returns> public Block FindPrevFocusableBlockInChain() { Block current = this.Prev; while (current != null) { Block foundFocusableBlock = current.FindLastFocusableBlock(); if (foundFocusableBlock != null && foundFocusableBlock.CanGetFocus) { return foundFocusableBlock; } current = current.Prev; } if (this.Parent != null) { if (this.Parent.CanGetFocus) { return this.Parent; } else { return this.Parent.FindPrevFocusableBlockInChain(); } } return null; } public virtual Block MoveFocusToPrevInChain() { Block prev = this.FindPrevFocusableBlockInChain(); if (prev != null) { prev.SetFocus(); } return prev; } public virtual Block MoveFocusToNextInChain() { Block next = this.FindNextFocusableBlockInChain(); if (next != null) { next.SetFocus(); } return next; } /// <summary> /// Searches for a next block "deep" /// (includes children of following blocks recursively) /// </summary> /// <returns></returns> public Block FindNextFocusableBlockInChain() { Block current = this.Next; while (current != null) { Block foundFocusableBlock = current.FindFirstFocusableBlock(); if (foundFocusableBlock != null && foundFocusableBlock.CanGetFocus) { return foundFocusableBlock; } current = current.Next; } if (this.Parent != null) { return this.Parent.FindNextFocusableBlockInChain(); } return null; } /// <summary> /// Searches for a first container block, /// which is focusable /// </summary> /// <returns>Nearest focusable parent or null if none found.</returns> public ContainerBlock FindNearestFocusableParent() { ContainerBlock current = this.Parent; while (current != null && !(current.CanGetFocus)) { current = current.Parent; } return current; } public virtual bool SetCursorToTheBeginning() { return this.SetFocusCore(); } public virtual bool SetCursorToTheEnd() { return SetCursorToTheBeginning(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Threading; using Windows.Foundation; using System.Runtime.WindowsRuntime.Internal; namespace System.Threading.Tasks { /// <summary> /// Implements a wrapper that allows to expose managed <code>System.Threading.Tasks.Task</code> objects as /// through the WinRT <code>Windows.Foundation.IAsyncInfo</code> interface. /// </summary> internal class TaskToAsyncInfoAdapter<TCompletedHandler, TProgressHandler, TResult, TProgressInfo> : IAsyncInfo, IProgress<TProgressInfo> where TCompletedHandler : class where TProgressHandler : class { // This class uses interlocked operations on volatile fields, and this pragma suppresses the compiler's complaint // that passing a volatile by ref to a function removes the volatility. That's not necessary for interlocked. #pragma warning disable 0420 #region Private Types, Statics and Constants // ! THIS DIAGRAM ILLUSTRATES THE CONSTANTS BELOW. UPDATE THIS IF UPDATING THE CONSTANTS BELOW!: // 3 2 1 0 // 10987654321098765432109876543210 // X............................... Reserved such that we can use Int32 and not worry about negative-valued state constants // ..X............................. STATEFLAG_COMPLETED_SYNCHRONOUSLY // ...X............................ STATEFLAG_MUST_RUN_COMPLETION_HNDL_WHEN_SET // ....X........................... STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED // ................................ STATE_NOT_INITIALIZED // ...............................X STATE_STARTED // ..............................X. STATE_RUN_TO_COMPLETION // .............................X.. STATE_CANCELLATION_REQUESTED // ............................X... STATE_CANCELLATION_COMPLETED // ...........................X.... STATE_ERROR // ..........................X..... STATE_CLOSED // ..........................XXXXXX STATEMASK_SELECT_ANY_ASYNC_STATE // XXXXXXXXXXXXXXXXXXXXXXXXXX...... STATEMASK_CLEAR_ALL_ASYNC_STATES // 3 2 1 0 // 10987654321098765432109876543210 // These STATE_XXXX constants describe the async state of this object. // Objects of this type are in exactly in one of these states at any given time: private const Int32 STATE_NOT_INITIALIZED = 0; // 0x00 private const Int32 STATE_STARTED = 1; // 0x01 private const Int32 STATE_RUN_TO_COMPLETION = 2; // 0x02 private const Int32 STATE_CANCELLATION_REQUESTED = 4; // 0x04 private const Int32 STATE_CANCELLATION_COMPLETED = 8; // 0x08 private const Int32 STATE_ERROR = 16; // 0x10 private const Int32 STATE_CLOSED = 32; // 0x20 // The STATEFLAG_XXXX constants can be bitmasked with the states to describe additional // state info that cannot be easily inferred from the async state: private const Int32 STATEFLAG_COMPLETED_SYNCHRONOUSLY = 0x20000000; private const Int32 STATEFLAG_MUST_RUN_COMPLETION_HNDL_WHEN_SET = 0x10000000; private const Int32 STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED = 0x8000000; // These two masks are used to select any STATE_XXXX bits and clear all other (i.e. STATEFLAG_XXXX) bits. // It is set to (next power of 2 after the largest STATE_XXXX value) - 1. // !!! Make sure to update this if a new STATE_XXXX value is added above !! private const Int32 STATEMASK_SELECT_ANY_ASYNC_STATE = (64 - 1); // These two masks are used to clear all STATE_XXXX bits and leave any STATEFLAG_XXXX bits. private const Int32 STATEMASK_CLEAR_ALL_ASYNC_STATES = ~STATEMASK_SELECT_ANY_ASYNC_STATE; private static InvalidOperationException CreateCannotGetResultsFromIncompleteOperationException(Exception cause) { InvalidOperationException ex = (cause == null) ? new InvalidOperationException(SR.InvalidOperation_CannotGetResultsFromIncompleteOperation) : new InvalidOperationException(SR.InvalidOperation_CannotGetResultsFromIncompleteOperation, cause); ex.SetErrorCode(__HResults.E_ILLEGAL_METHOD_CALL); return ex; } #endregion Private Types, Statics and Constants #region Instance variables /// <summary>The token source used to cancel running operations.</summary> private CancellationTokenSource _cancelTokenSource = null; /// <summary>The async info's ID. InvalidAsyncId stands for not yet been initialised.</summary> private UInt32 _id = AsyncInfoIdGenerator.InvalidId; /// <summary>The cached error code used to avoid creating several exception objects if the <code>ErrorCode</code> /// property is accessed several times. <code>null</code> indicates either no error or that <code>ErrorCode</code> /// has not yet been called.</summary> private Exception _error = null; /// <summary>The state of the async info. Interlocked operations are used to manipulate this field.</summary> private volatile Int32 _state = STATE_NOT_INITIALIZED; /// <summary>For IAsyncInfo instances that completed synchronously (at creation time) this field holds the result; /// for instances backed by an actual Task, this field holds a reference to the task generated by the task generator. /// Since we always know which of the above is the case, we can always cast this field to TResult in the former case /// or to one of Task or Task{TResult} in the latter case. This approach allows us to save a field on all IAsyncInfos. /// Notably, this makes us pay the added cost of boxing for synchronously completing IAsyncInfos where TResult is a /// value type, however, this is expected to occur rather rare compared to non-synchronously completed user-IAsyncInfos.</summary> private Object _dataContainer; /// <summary>Registered completed handler.</summary> private TCompletedHandler _completedHandler; /// <summary>Registered progress handler.</summary> private TProgressHandler _progressHandler; /// <summary>The synchronization context on which this instance was created/started. Used to callback invocations.</summary> private SynchronizationContext _startingContext; #endregion Instance variables #region Constructors and Destructor /// <summary>Creates an IAsyncInfo from the specified delegate. The delegate will be called to construct a task that will /// represent the future encapsulated by this IAsyncInfo.</summary> /// <param name="taskProvider">The task generator to use for creating the task.</param> internal TaskToAsyncInfoAdapter(Delegate taskProvider) { Debug.Assert(taskProvider != null); Debug.Assert((null != (taskProvider as Func<Task>)) || (null != (taskProvider as Func<CancellationToken, Task>)) || (null != (taskProvider as Func<IProgress<TProgressInfo>, Task>)) || (null != (taskProvider as Func<CancellationToken, IProgress<TProgressInfo>, Task>))); Contract.Ensures(!this.CompletedSynchronously); Contract.EndContractBlock(); // The IAsyncInfo is reasonably expected to be created/started by the same code that wires up the Completed and Progress handlers. // Record the current SynchronizationContext so that we can invoke completion and progress callbacks in it later. _startingContext = GetStartingContext(); // Construct task from the specified provider: Task task = InvokeTaskProvider(taskProvider); if (task == null) throw new NullReferenceException(SR.NullReference_TaskProviderReturnedNull); if (task.Status == TaskStatus.Created) throw new InvalidOperationException(SR.InvalidOperation_TaskProviderReturnedUnstartedTask); _dataContainer = task; _state = (STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED | STATE_STARTED); // Set the completion routine and let the task running: task.ContinueWith( (_, this_) => ((TaskToAsyncInfoAdapter<TCompletedHandler, TProgressHandler, TResult, TProgressInfo>)this_).TaskCompleted(), this, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } /// <summary> /// Creates an IAsyncInfo from the Task object. The specified task represents the future encapsulated by this IAsyncInfo. /// The specified CancellationTokenSource and Progress are assumed to be the source of the specified Task's cancellation and /// the Progress that receives reports from the specified Task. /// </summary> /// <param name="underlyingTask">The Task whose operation is represented by this IAsyncInfo</param> /// <param name="underlyingCancelTokenSource">The cancellation control for the cancellation token observed /// by <code>underlyingTask</code>.</param> /// <param name="underlyingProgressDispatcher">A progress listener/pugblisher that receives progress notifications /// form <code>underlyingTask</code>.</param> internal TaskToAsyncInfoAdapter(Task underlyingTask, CancellationTokenSource underlyingCancelTokenSource, Progress<TProgressInfo> underlyingProgressDispatcher) { if (underlyingTask == null) throw new ArgumentNullException(nameof(underlyingTask)); // Throw InvalidOperation and not Argument for parity with the constructor that takes Delegate taskProvider: if (underlyingTask.Status == TaskStatus.Created) throw new InvalidOperationException(SR.InvalidOperation_UnstartedTaskSpecified); Contract.Ensures(!this.CompletedSynchronously); Contract.EndContractBlock(); // The IAsyncInfo is reasonably expected to be created/started by the same code that wires up the Completed and Progress handlers. // Record the current SynchronizationContext so that we can invoke completion and progress callbacks in it later. _startingContext = GetStartingContext(); // We do not need to invoke any delegates to get the task, it is provided for us: _dataContainer = underlyingTask; // This must be the cancellation source for the token that the specified underlyingTask observes for cancellation: // (it may also be null in cases where the specified underlyingTask does nto support cancellation) _cancelTokenSource = underlyingCancelTokenSource; // Iff the specified underlyingTask reports progress, chain the reports to this IAsyncInfo's reporting method: if (underlyingProgressDispatcher != null) underlyingProgressDispatcher.ProgressChanged += OnReportChainedProgress; _state = (STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED | STATE_STARTED); underlyingTask.ContinueWith( (_, this_) => ((TaskToAsyncInfoAdapter<TCompletedHandler, TProgressHandler, TResult, TProgressInfo>)this_).TaskCompleted(), this, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } /// <summary> /// Creates an IAsyncInfo from the specified result value. The IAsyncInfo is created in the Completed state and the /// specified <code>synchronousResult</code> is used as the result value. /// </summary> /// <param name="synchronousResult">The result of this synchronously completed IAsyncInfo.</param> internal TaskToAsyncInfoAdapter(TResult synchronousResult) { Contract.Ensures(this.CompletedSynchronously); Contract.Ensures(this.IsInRunToCompletionState); // We already completed. There will be no progress callback invokations and a potential completed handler invokation will be synchronous. // We do not need the starting SynchronizationContext: _startingContext = null; // Set the synchronous result: _dataContainer = synchronousResult; // CompletedSynchronously + MustRunCompletionHandleImmediatelyWhenSet + CompletionHandlerNotYetInvoked + RUN_TO_COMPLETION: // (same state as assigned by DangerousSetCompleted()) _state = (STATEFLAG_COMPLETED_SYNCHRONOUSLY | STATEFLAG_MUST_RUN_COMPLETION_HNDL_WHEN_SET | STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED | STATE_RUN_TO_COMPLETION); } ~TaskToAsyncInfoAdapter() { TransitionToClosed(); } #endregion Constructors and Destructor #region Synchronous completion controls /// <summary> This method sets the result on a *synchronously completed* IAsyncInfo. /// It does not try to deal with the inherit races: Use it only when constructing a synchronously /// completed IAsyncInfo in a desired state when you understand the threading conditions well.</summary> /// <param name="synchronousResult">The new result of this synchronously completed IAsyncInfo (may be <code>default(TResult)</code>)</param> /// <returns>FALSE if this IAsyncInfo has not actually completed synchronously and this method had no effects, TRUE otherwise.</returns> internal bool DangerousSetCompleted(TResult synchronousResult) { if (!CompletedSynchronously) return false; _dataContainer = synchronousResult; _error = null; // CompletedSynchronously + MustRunCompletionHandleImmediatelyWhenSet + CompletionHandlerNotYetInvoked + RUN_TO_COMPLETION: _state = (STATEFLAG_COMPLETED_SYNCHRONOUSLY | STATEFLAG_MUST_RUN_COMPLETION_HNDL_WHEN_SET | STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED | STATE_RUN_TO_COMPLETION); return true; } internal bool DangerousSetCanceled() { if (!CompletedSynchronously) return false; // Here we do not try to deal with the inherit races: Use this method only when constructing a synchronously // completed IAsyncInfo in a desired state when you understand the threading conditions well. _dataContainer = null; _error = null; // CompletedSynchronously + MustRunCompletionHandleImmediatelyWhenSet + CompletionHandlerNotYetInvoked + CANCELLATION_COMPLETED: _state = (STATEFLAG_COMPLETED_SYNCHRONOUSLY | STATEFLAG_MUST_RUN_COMPLETION_HNDL_WHEN_SET | STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED | STATE_CANCELLATION_COMPLETED); return true; } internal bool DangerousSetError(Exception error) { if (!CompletedSynchronously) return false; if (error == null) throw new ArgumentNullException(nameof(error)); // Here we do not try to deal with the inherit races: Use this method only when constructing a synchronously // completed IAsyncInfo in a desired state when you understand the threading conditions well. _dataContainer = null; _error = error; // CompletedSynchronously + MustRunCompletionHandleImmediatelyWhenSet + CompletionHandlerNotYetInvoked + ERROR: _state = (STATEFLAG_COMPLETED_SYNCHRONOUSLY | STATEFLAG_MUST_RUN_COMPLETION_HNDL_WHEN_SET | STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED | STATE_ERROR); return true; } #endregion Synchronous completion controls #region State bit field operations internal bool CompletedSynchronously {[Pure] get { return (0 != (_state & STATEFLAG_COMPLETED_SYNCHRONOUSLY)); } } private bool IsInStartedState {[Pure] get { return (0 != (_state & STATE_STARTED)); } } private bool IsInRunToCompletionState {[Pure] get { return (0 != (_state & STATE_RUN_TO_COMPLETION)); } } private bool IsInErrorState {[Pure] get { return (0 != (_state & STATE_ERROR)); } } private bool IsInClosedState {[Pure] get { return (0 != (_state & STATE_CLOSED)); } } private bool IsInRunningState { [Pure] get { return (0 != (_state & (STATE_STARTED | STATE_CANCELLATION_REQUESTED))); } } private bool IsInTerminalState { [Pure] get { return (0 != (_state & (STATE_RUN_TO_COMPLETION | STATE_CANCELLATION_COMPLETED | STATE_ERROR))); } } [Pure] private bool CheckUniqueAsyncState(Int32 state) { unchecked { UInt32 asyncState = (UInt32)state; return (asyncState & (~asyncState + 1)) == asyncState; // This checks if asyncState is 0 or a power of 2. } } #endregion State bit field operations #region Infrastructure methods private SynchronizationContext GetStartingContext() { #if DESKTOP // as a reminder that on most platforms we want a different behavior return SynchronizationContext.CurrentNoFlow; #else return SynchronizationContext.Current; #endif } internal Task Task { get { EnsureNotClosed(); Contract.Ensures(CompletedSynchronously || Contract.Result<Task>() != null); Contract.EndContractBlock(); if (CompletedSynchronously) return null; return (Task)_dataContainer; } } internal CancellationTokenSource CancelTokenSource { get { return _cancelTokenSource; } } [Pure] internal void EnsureNotClosed() { if (!IsInClosedState) return; ObjectDisposedException ex = new ObjectDisposedException(SR.ObjectDisposed_AsyncInfoIsClosed); ex.SetErrorCode(__HResults.E_ILLEGAL_METHOD_CALL); throw ex; } internal virtual void OnCompleted(TCompletedHandler userCompletionHandler, AsyncStatus asyncStatus) { Debug.Assert(false, "This (sub-)type of IAsyncInfo does not support completion notifications " + " (" + this.GetType().ToString() + ")"); } internal virtual void OnProgress(TProgressHandler userProgressHandler, TProgressInfo progressInfo) { Debug.Assert(false, "This (sub-)type of IAsyncInfo does not support progress notifications " + " (" + this.GetType().ToString() + ")"); } private void OnCompletedInvoker(AsyncStatus status) { bool conditionFailed; // Get the handler: TCompletedHandler handler = Volatile.Read(ref _completedHandler); // If we might not run the handler now, we need to remember that if it is set later, it will need to be run then: if (handler == null) { // Remember to run the handler when it is set: SetState(STATEFLAG_MUST_RUN_COMPLETION_HNDL_WHEN_SET, ~STATEFLAG_MUST_RUN_COMPLETION_HNDL_WHEN_SET, conditionBitMask: 0, useCondition: false, conditionFailed: out conditionFailed); // The handler may have been set concurrently before we managed to SetState, so check for it again: handler = Volatile.Read(ref _completedHandler); // If handler was not set cuncurrently after all, then no worries: if (handler == null) return; } // This method might be running cuncurrently. Create a block by emulating an interlocked un-set of // the STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED-bit in the m_state bit field. Only the thread that wins the race // for unsetting this bit, wins, others give up: SetState(0, ~STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED, conditionBitMask: STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED, useCondition: true, conditionFailed: out conditionFailed); if (conditionFailed) return; // Invoke the user handler: OnCompleted(handler, status); } // This is a separate method from IProgress<TProgressInfo>.Report to avoid alocating the closure if it is not used. private void OnProgressInvokerCrossContext(TProgressHandler handler, TProgressInfo progressInfo) { Debug.Assert(handler != null); Debug.Assert(_startingContext != null); _startingContext.Post((tupleObject) => { var tuple = (Tuple<TaskToAsyncInfoAdapter<TCompletedHandler, TProgressHandler, TResult, TProgressInfo>, TProgressHandler, TProgressInfo>)tupleObject; tuple.Item1.OnProgress(tuple.Item2, tuple.Item3); }, Tuple.Create(this, handler, progressInfo)); } /// <summary>Reports a progress update.</summary> /// <param name="value">The new progress value to report.</param> void IProgress<TProgressInfo>.Report(TProgressInfo value) { // If no progress handler is set, there is nothing to do: TProgressHandler handler = Volatile.Read(ref _progressHandler); if (handler == null) return; // Try calling progress handler in the right synchronization context. // If the user callback throws an exception, it will bubble up through here and reach the // user worker code running as this async future. The user should catch it. // If the user does not catch it, it will be treated just as any other exception coming from the async execution code: // this AsyncInfo will be faulted. if (_startingContext == null) { // The starting context is null, invoke directly: OnProgress(handler, value); } else { // Invoke callback in the right context: OnProgressInvokerCrossContext(handler, value); } } private void OnReportChainedProgress(Object sender, TProgressInfo progressInfo) { ((IProgress<TProgressInfo>)this).Report(progressInfo); } /// <summary> /// Sets the <code>m_state</code> bit field to reflect the specified async state with the corresponding STATE_XXX bit mask. /// </summary> /// <param name="newAsyncState">Must be one of the STATE_XXX (not STATEYYY_ZZZ !) constants defined in this class.</param> /// <param name="conditionBitMask">If <code>useCondition</code> is FALSE: this field is ignored. /// If <code>useCondition</code> is TRUE: Unless this value has at least one bit with <code>m_state</code> in /// common, this method will not perform any action.</param> /// <param name="useCondition">If TRUE, use <code>conditionBitMask</code> to determine whether the state should be set; /// If FALSE, ignore <code>conditionBitMask</code>.</param> /// <param name="conditionFailed">If <code>useCondition</code> is FALSE: this field is set to FALSE; /// If <code>useCondition</code> is TRUE: this field indicated whether the specified <code>conditionBitMask</code> /// had at least one bit in common with <code>m_state</code> (TRUE) /// or not (FALSE). /// (!) Note that the meaning of this parameter to the caller is not quite the same as whether <code>m_state</code> /// is/was set to the specified value, because <code>m_state</code> may already have had the specified value, or it /// may be set and then immediately changed by another thread. The true meaning of this parameter is whether or not /// the specified condition did hold before trying to change the state.</param> /// <returns>The value at which the current invocation of this method left <code>m_state</code>.</returns> private Int32 SetAsyncState(Int32 newAsyncState, Int32 conditionBitMask, bool useCondition, out bool conditionFailed) { Debug.Assert(CheckUniqueAsyncState(newAsyncState & STATEMASK_SELECT_ANY_ASYNC_STATE)); Debug.Assert(CheckUniqueAsyncState(_state & STATEMASK_SELECT_ANY_ASYNC_STATE)); Int32 resultState = SetState(newAsyncState, STATEMASK_CLEAR_ALL_ASYNC_STATES, conditionBitMask, useCondition, out conditionFailed); Debug.Assert(CheckUniqueAsyncState(resultState & STATEMASK_SELECT_ANY_ASYNC_STATE)); return resultState; } /// <summary> /// Sets the specified bits in the <code>m_state</code> bit field according to the specified bit-mask parameters. /// </summary> /// <param name="newStateSetMask">The bits to turn ON in the <code>m_state</code> bit field</param> /// <param name="newStateIgnoreMask">Any bits that are OFF in this value will get turned OFF, /// unless they are explicitly switched on by <code>newStateSetMask</code>.</param> /// <param name="conditionBitMask">If <code>useCondition</code> is FALSE: this field is ignored. /// If <code>useCondition</code> is TRUE: Unless this value has at least one bit with <code>m_state</code> in /// common, this method will not perform any action.</param> /// <param name="useCondition">If TRUE, use <code>conditionBitMask</code> to determine whether the state should be set; /// If FALSE, ignore <code>conditionBitMask</code>.</param> /// <param name="conditionFailed">If <code>useCondition</code> is FALSE: this field is set to FALSE; /// If <code>useCondition</code> is TRUE: this field indicated whether the specified <code>conditionBitMask</code> /// had at least one bit in common with <code>m_state</code> (TRUE) /// or not (FALSE). /// (!) Note that the meaning of this parameter to the caller is not quite the same as whether <code>m_state</code> /// is/was set to the specified value, because <code>m_state</code> may already have had the specified value, or it /// may be set and then immediately changed by another thread. The true meaning of this parameter is whether or not /// the specified condition did hold before trying to change the state.</param> /// <returns>The value at which the current invocation of this method left <code>m_state</code>.</returns> private Int32 SetState(Int32 newStateSetMask, Int32 newStateIgnoreMask, Int32 conditionBitMask, bool useCondition, out bool conditionFailed) { Int32 origState = _state; if (useCondition && 0 == (origState & conditionBitMask)) { conditionFailed = true; return origState; } Int32 newState = (origState & newStateIgnoreMask) | newStateSetMask; Int32 prevState = Interlocked.CompareExchange(ref _state, newState, origState); // If m_state changed concurrently, we want to make sure that the change being made is based on a bitmask that is up to date: // (this relies of the fact that all state machines that save their state in m_state have no cycles) while (true) { if (prevState == origState) { conditionFailed = false; return newState; } origState = _state; if (useCondition && 0 == (origState & conditionBitMask)) { conditionFailed = true; return origState; } newState = (origState & newStateIgnoreMask) | newStateSetMask; prevState = Interlocked.CompareExchange(ref _state, newState, origState); } } private Int32 TransitionToTerminalState() { Debug.Assert(IsInRunningState); Debug.Assert(!CompletedSynchronously); Task task = _dataContainer as Task; Debug.Assert(task != null); Debug.Assert(task.IsCompleted); // Recall that STATE_CANCELLATION_REQUESTED and STATE_CANCELLATION_COMPLETED both map to the public CANCELED state. // So, we are STARTED or CANCELED. We will ask the task how it completed and possibly transition out of CANCELED. // This may happen if cancellation was requested while in STARTED state, but the task does not support cancellation, // or if it can support cancellation in principle, but the Cancel request came in while still STARTED, but after the // last opportunity to cancel. // If the underlying operation was not able to react to the cancellation request and instead either run to completion // or faulted, then the state will transition into COMPLETED or ERROR accordingly. If the operation was really cancelled, // the state will remain CANCELED. // If the switch below defaults, we have an erroneous implementation. Int32 terminalAsyncState = STATE_ERROR; switch (task.Status) { case TaskStatus.RanToCompletion: terminalAsyncState = STATE_RUN_TO_COMPLETION; break; case TaskStatus.Canceled: terminalAsyncState = STATE_CANCELLATION_COMPLETED; break; case TaskStatus.Faulted: terminalAsyncState = STATE_ERROR; break; default: Debug.Assert(false, "Unexpected task.Status: It should be terminal if TaskCompleted() is called."); break; } bool ignore; Int32 newState = SetAsyncState(terminalAsyncState, conditionBitMask: STATEMASK_SELECT_ANY_ASYNC_STATE, useCondition: true, conditionFailed: out ignore); Debug.Assert((newState & STATEMASK_SELECT_ANY_ASYNC_STATE) == terminalAsyncState); Debug.Assert((_state & STATEMASK_SELECT_ANY_ASYNC_STATE) == terminalAsyncState || IsInClosedState, "We must either be in a state we just entered or we were concurrently closed"); return newState; } private void TaskCompleted() { Int32 terminalState = TransitionToTerminalState(); Debug.Assert(IsInTerminalState); // We transitioned into a terminal state, so it became legal to close us concurrently. // So we use data from this stack and not m_state to get the completion status. // On this code path we will also fetch m_completedHandler, however that race is benign because in CLOSED the handler // can only change to null, so it won't be invoked, which is appropriate for CLOSED. AsyncStatus terminationStatus = GetStatus(terminalState); // Try calling completed handler in the right synchronization context. // If the user callback throws an exception, it will bubble up through here. // If we let it though, it will be caught and swallowed by the Task subsystem, which is just below us on the stack. // Instead we follow the same pattern as Task and other parallel libs and re-throw the excpetion on the threadpool // to ensure a diagnostic message and a fail-fast-like teardown. try { if (_startingContext == null) { // The starting context is null, invoking directly: OnCompletedInvoker(terminationStatus); } else { // Invoke callback in the right context (delegate cached by compiler): _startingContext.Post((tupleObject) => { var tuple = (Tuple<TaskToAsyncInfoAdapter<TCompletedHandler, TProgressHandler, TResult, TProgressInfo>, AsyncStatus>)tupleObject; tuple.Item1.OnCompletedInvoker(tuple.Item2); }, Tuple.Create(this, terminationStatus)); } } catch (Exception ex) { ExceptionDispatchHelper.ThrowAsync(ex, _startingContext); } } private AsyncStatus GetStatus(Int32 state) { Int32 asyncState = state & STATEMASK_SELECT_ANY_ASYNC_STATE; Debug.Assert(CheckUniqueAsyncState(asyncState)); switch (asyncState) { case STATE_NOT_INITIALIZED: Debug.Assert(false, "STATE_NOT_INITIALIZED should only occur when this object was not" + " fully constructed, in which case we should never get here"); return AsyncStatus.Error; case STATE_STARTED: return AsyncStatus.Started; case STATE_RUN_TO_COMPLETION: return AsyncStatus.Completed; case STATE_CANCELLATION_REQUESTED: case STATE_CANCELLATION_COMPLETED: return AsyncStatus.Canceled; case STATE_ERROR: return AsyncStatus.Error; case STATE_CLOSED: Debug.Assert(false, "This method should never be called is this IAsyncInfo is CLOSED"); return AsyncStatus.Error; } Debug.Assert(false, "The switch above is missing a case"); return AsyncStatus.Error; } internal TResult GetResultsInternal() { EnsureNotClosed(); // If this IAsyncInfo has actually faulted, GetResults will throw the same error as returned by ErrorCode: if (IsInErrorState) { Exception error = ErrorCode; Debug.Assert(error != null); ExceptionDispatchInfo.Capture(error).Throw(); } // IAsyncInfo throws E_ILLEGAL_METHOD_CALL when called in a state other than COMPLETED: if (!IsInRunToCompletionState) throw CreateCannotGetResultsFromIncompleteOperationException(null); // If this is a synchronous operation, use the cached result: if (CompletedSynchronously) return (TResult)_dataContainer; // The operation is asynchronous: Task<TResult> task = _dataContainer as Task<TResult>; // Since CompletedSynchronously is false and EnsureNotClosed() did not throw, task can only be null if: // - this IAsyncInfo has completed synchronously, however we checked for this above; // - it was not converted to Task<TResult>, which means it is a non-generic Task. In that case we cannot get a result from Task. if (task == null) return default(TResult); Debug.Assert(IsInRunToCompletionState); // Pull out the task result and return. // Any exceptions thrown in the task will be rethrown. // If this exception is a cancelation exception, meaning there was actually no error except for being cancelled, // return an error code appropriate for WinRT instead (InvalidOperation with E_ILLEGAL_METHOD_CALL). try { return task.GetAwaiter().GetResult(); } catch (TaskCanceledException tcEx) { throw CreateCannotGetResultsFromIncompleteOperationException(tcEx); } } private Task InvokeTaskProvider(Delegate taskProvider) { Contract.EndContractBlock(); var funcVoidTask = taskProvider as Func<Task>; if (funcVoidTask != null) { return funcVoidTask(); } var funcCTokTask = taskProvider as Func<CancellationToken, Task>; if (funcCTokTask != null) { _cancelTokenSource = new CancellationTokenSource(); return funcCTokTask(_cancelTokenSource.Token); } var funcIPrgrTask = taskProvider as Func<IProgress<TProgressInfo>, Task>; if (funcIPrgrTask != null) { return funcIPrgrTask(this); } var funcCTokIPrgrTask = taskProvider as Func<CancellationToken, IProgress<TProgressInfo>, Task>; if (funcCTokIPrgrTask != null) { _cancelTokenSource = new CancellationTokenSource(); return funcCTokIPrgrTask(_cancelTokenSource.Token, this); } Debug.Assert(false, "We should never get here!" + " Public methods creating instances of this class must be typesafe to ensure that taskProvider" + " can always be cast to one of the above Func types." + " The taskProvider is " + (taskProvider == null ? "null." : "a " + taskProvider.GetType().ToString()) + "."); return null; } private void TransitionToClosed() { // From the finaliser we always call this Close version since finalisation can happen any time, even when STARTED (e.g. process ends) // and we do not want to throw in those cases. // Always go to closed, even from STATE_NOT_INITIALIZED. // Any checking whether it is legal to call CLosed inthe current state, should occur in Close(). bool ignore; SetAsyncState(STATE_CLOSED, 0, useCondition: false, conditionFailed: out ignore); _cancelTokenSource = null; _dataContainer = null; _error = null; _completedHandler = null; _progressHandler = null; _startingContext = null; } #endregion Infrastructure methods #region Implementation of IAsyncInfo /// <summary> /// Gets or sets the completed handler. /// /// We will set the completion handler even when this IAsyncInfo is already started (no other choice). /// If we the completion handler is set BEFORE this IAsyncInfo completed, then the handler will be called upon completion as normal. /// If we the completion handler is set AFTER this IAsyncInfo already completed, then this setter will invoke the handler synchronously /// on the current context. /// </summary> public virtual TCompletedHandler Completed { get { TCompletedHandler handler = Volatile.Read(ref _completedHandler); EnsureNotClosed(); return handler; } set { EnsureNotClosed(); // Try setting completion handler, but only if this has not yet been done: // (Note: We allow setting Completed to null multiple times iff it has not yet been set to anything else than null. // Some other WinRT projection languages do not allow setting the Completed handler more than once, even if it is set to null. // We could do the same by introducing a new STATEFLAG_COMPLETION_HNDL_SET bit-flag constant and saving a this state into // the m_state field to indicate that the completion handler has been set previously, but we choose not to do this.) TCompletedHandler handlerBefore = Interlocked.CompareExchange(ref _completedHandler, value, null); if (handlerBefore != null) { InvalidOperationException ex = new InvalidOperationException(SR.InvalidOperation_CannotSetCompletionHanlderMoreThanOnce); ex.SetErrorCode(__HResults.E_ILLEGAL_DELEGATE_ASSIGNMENT); throw ex; } if (value == null) return; // If STATEFLAG_MUST_RUN_COMPLETION_HNDL_WHEN_SET is OFF then we are done (i.e. no need to invoke the handler synchronously) if (0 == (_state & STATEFLAG_MUST_RUN_COMPLETION_HNDL_WHEN_SET)) return; // We have changed the handler and at some point this IAsyncInfo may have transitioned to the Closed state. // This is OK, but if this happened we need to ensure that we only leave a null handler behind: if (IsInClosedState) { Interlocked.Exchange(ref _completedHandler, null); return; } // The STATEFLAG_MUST_RUN_COMPLETION_HNDL_WHEN_SET-flag was set, so we need to call the completion handler now: Debug.Assert(IsInTerminalState); OnCompletedInvoker(Status); } } /// <summary>Gets or sets the progress handler.</summary> public virtual TProgressHandler Progress { get { TProgressHandler handler = Volatile.Read(ref _progressHandler); EnsureNotClosed(); return handler; } set { EnsureNotClosed(); Interlocked.Exchange(ref _progressHandler, value); // We we transitioned into CLOSED after the above check, we will need to null out m_progressHandler: if (IsInClosedState) Interlocked.Exchange(ref _progressHandler, null); } } /// <summary>Cancels the async info.</summary> public virtual void Cancel() { // Cancel will be ignored in any terminal state including CLOSED. // In other words, it is ignored in any state except STARTED. bool stateWasNotStarted; SetAsyncState(STATE_CANCELLATION_REQUESTED, conditionBitMask: STATE_STARTED, useCondition: true, conditionFailed: out stateWasNotStarted); if (!stateWasNotStarted) { // i.e. if state was different from STATE_STARTED: if (_cancelTokenSource != null) _cancelTokenSource.Cancel(); } } /// <summary>Close the async info.</summary> public virtual void Close() { if (IsInClosedState) return; // Cannot Close from a non-terminal state: if (!IsInTerminalState) { // If we are STATE_NOT_INITIALIZED, the we probably threw from the ctor. // The finalizer will be called anyway and we need to free this partially constructed object correctly. // So we avoid throwing when we are in STATE_NOT_INITIALIZED. // In other words throw only if *some* async state is set: if (0 != (_state & STATEMASK_SELECT_ANY_ASYNC_STATE)) { InvalidOperationException ex = new InvalidOperationException(SR.InvalidOperation_IllegalStateChange); ex.SetErrorCode(__HResults.E_ILLEGAL_STATE_CHANGE); throw ex; } } TransitionToClosed(); } /// <summary>Gets the error code for the async info.</summary> public virtual Exception ErrorCode { get { EnsureNotClosed(); // If the task is faulted, hand back an HR representing its first exception. // Otherwise, hand back S_OK (which is a null Exception). if (!IsInErrorState) return null; Exception error = Volatile.Read(ref _error); // ERROR is a terminal state. SO if we have an error, just return it. // If we completed synchronously, we return the current error iven if it is null since we do not expect this to change: if (error != null || CompletedSynchronously) return error; Task task = _dataContainer as Task; Debug.Assert(task != null); AggregateException aggregateException = task.Exception; // By spec, if task.IsFaulted is true, then task.Exception must not be null and its InnerException must // also not be null. However, in case something is unexpected on the Task side of the road, let?s be defensive // instead of failing with an inexplicable NullReferenceException: if (aggregateException == null) { error = new Exception(SR.WinRtCOM_Error); error.SetErrorCode(__HResults.E_FAIL); } else { Exception innerException = aggregateException.InnerException; error = (innerException == null) ? aggregateException : innerException; } // If m_error was set concurrently, setError will be non-null. Then we use that - as it is the first m_error // that was set. If setError we know that we won any races and we can return error: Exception setError = Interlocked.CompareExchange(ref _error, error, null); return setError ?? error; } } public virtual UInt32 Id { get { EnsureNotClosed(); if (_id != AsyncInfoIdGenerator.InvalidId) return _id; return AsyncInfoIdGenerator.EnsureInitializedThreadsafe(ref _id); } } /// <summary>Gets the status of the async info.</summary> public virtual AsyncStatus Status { get { EnsureNotClosed(); return GetStatus(_state); } } #endregion Implementation of IAsyncInfo #pragma warning restore 0420 } // class TaskToAsyncInfoAdapter<TCompletedHandler, TProgressHandler, TResult, TProgressInfo> } // namespace // TaskToAsyncInfoAdapter.cs
// // Trust.cs: Implements the managed SecTrust wrapper. // // Authors: // Miguel de Icaza // Sebastien Pouliot <[email protected]> // // Copyright 2010 Novell, Inc // Copyright 2012 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.Linq; using System.Runtime.InteropServices; using System.Security; using System.Security.Cryptography.X509Certificates; using MonoMac.ObjCRuntime; using MonoMac.CoreFoundation; using MonoMac.Foundation; namespace MonoMac.Security { public class SecTrust : INativeObject, IDisposable { IntPtr handle; internal SecTrust (IntPtr handle) : this (handle, false) { } [Preserve (Conditional=true)] internal SecTrust (IntPtr handle, bool owns) { if (handle == IntPtr.Zero) throw new Exception ("Invalid handle"); this.handle = handle; if (!owns) CFObject.CFRetain (handle); } [DllImport (Constants.SecurityLibrary, EntryPoint="SecTrustGetTypeID")] public extern static int GetTypeID (); [DllImport (Constants.SecurityLibrary)] extern static SecStatusCode SecTrustCreateWithCertificates (IntPtr certOrCertArray, IntPtr policies, out IntPtr sectrustref); public SecTrust (X509Certificate certificate, SecPolicy policy) { if (certificate == null) throw new ArgumentNullException ("certificate"); using (SecCertificate cert = new SecCertificate (certificate)) { Initialize (cert.Handle, policy); } } public SecTrust (X509Certificate2 certificate, SecPolicy policy) { if (certificate == null) throw new ArgumentNullException ("certificate"); using (SecCertificate cert = new SecCertificate (certificate)) { Initialize (cert.Handle, policy); } } public SecTrust (X509CertificateCollection certificates, SecPolicy policy) { if (certificates == null) throw new ArgumentNullException ("certificates"); SecCertificate[] array = new SecCertificate [certificates.Count]; int i = 0; foreach (var certificate in certificates) array [i++] = new SecCertificate (certificate); Initialize (array, policy); } public SecTrust (X509Certificate2Collection certificates, SecPolicy policy) { if (certificates == null) throw new ArgumentNullException ("certificates"); SecCertificate[] array = new SecCertificate [certificates.Count]; int i = 0; foreach (var certificate in certificates) array [i++] = new SecCertificate (certificate); Initialize (array, policy); } void Initialize (SecCertificate[] array, SecPolicy policy) { using (var certs = CFArray.FromNativeObjects (array)) { Initialize (certs.Handle, policy); } } void Initialize (IntPtr certHandle, SecPolicy policy) { if (policy == null) throw new ArgumentNullException ("policy"); SecStatusCode result = SecTrustCreateWithCertificates (certHandle, policy.Handle, out handle); if (result != SecStatusCode.Success) throw new ArgumentException (result.ToString ()); } [DllImport (Constants.SecurityLibrary)] extern static SecStatusCode /* OSStatus */ SecTrustEvaluate (IntPtr /* SecTrustRef */ trust, out /* SecTrustResultType */ SecTrustResult result); public SecTrustResult Evaluate () { if (handle == IntPtr.Zero) throw new ObjectDisposedException ("SecTrust"); SecTrustResult trust; SecStatusCode result = SecTrustEvaluate (handle, out trust); if (result != SecStatusCode.Success) throw new InvalidOperationException (result.ToString ()); return trust; } [DllImport (Constants.SecurityLibrary)] extern static long /* CFIndex */ SecTrustGetCertificateCount (IntPtr /* SecTrustRef */ trust); public int Count { get { if (handle == IntPtr.Zero) return 0; return (int) SecTrustGetCertificateCount (handle); } } [DllImport (Constants.SecurityLibrary)] extern static IntPtr /* SecCertificateRef */ SecTrustGetCertificateAtIndex (IntPtr /* SecTrustRef */ trust, long /* CFIndex */ ix); public SecCertificate this [int index] { get { if (handle == IntPtr.Zero) throw new ObjectDisposedException ("SecTrust"); if ((index < 0) || (index >= Count)) throw new ArgumentOutOfRangeException ("index"); return new SecCertificate (SecTrustGetCertificateAtIndex (handle, index)); } } [DllImport (Constants.SecurityLibrary)] extern static IntPtr /* SecKeyRef */ SecTrustCopyPublicKey (IntPtr /* SecTrustRef */ trust); public SecKey GetPublicKey () { if (handle == IntPtr.Zero) throw new ObjectDisposedException ("SecTrust"); return new SecKey (SecTrustCopyPublicKey (handle), true); } [DllImport (Constants.SecurityLibrary)] extern static IntPtr /* CFDataRef */ SecTrustCopyExceptions (IntPtr /* SecTrustRef */ trust); public NSData GetExceptions () { if (handle == IntPtr.Zero) throw new ObjectDisposedException ("SecTrust"); return new NSData (SecTrustCopyExceptions (handle), false); // inverted boolean? } [DllImport (Constants.SecurityLibrary)] extern static bool SecTrustSetExceptions (IntPtr /* SecTrustRef */ trust, IntPtr /* CFDataRef */ exceptions); public bool SetExceptions (NSData data) { if (handle == IntPtr.Zero) throw new ObjectDisposedException ("SecTrust"); IntPtr p = data == null ? IntPtr.Zero : data.Handle; return SecTrustSetExceptions (handle, p); } [DllImport (Constants.SecurityLibrary)] extern static double /* CFAbsoluteTime */ SecTrustGetVerifyTime (IntPtr /* SecTrustRef */ trust); public double GetVerifyTime () { if (handle == IntPtr.Zero) throw new ObjectDisposedException ("SecTrust"); return SecTrustGetVerifyTime (handle); } [DllImport (Constants.SecurityLibrary)] extern static SecStatusCode /* OSStatus */ SecTrustSetVerifyDate (IntPtr /* SecTrustRef */ trust, IntPtr /* CFDateRef */ verifyDate); public SecStatusCode SetVerifyDate (DateTime date) { if (handle == IntPtr.Zero) throw new ObjectDisposedException ("SecTrust"); // CFDateRef amd NSDate are toll-freee bridged using (NSDate d = (NSDate) date) { return SecTrustSetVerifyDate (handle, d.Handle); } } [DllImport (Constants.SecurityLibrary)] extern static SecStatusCode /* OSStatus */ SecTrustSetAnchorCertificates (IntPtr /* SecTrustRef */ trust, IntPtr /* CFArrayRef */ anchorCertificates); public SecStatusCode SetAnchorCertificates (X509CertificateCollection certificates) { if (handle == IntPtr.Zero) throw new ObjectDisposedException ("SecTrust"); if (certificates == null) return SecTrustSetAnchorCertificates (handle, IntPtr.Zero); SecCertificate[] array = new SecCertificate [certificates.Count]; int i = 0; foreach (var certificate in certificates) array [i++] = new SecCertificate (certificate); return SetAnchorCertificates (array); } public SecStatusCode SetAnchorCertificates (X509Certificate2Collection certificates) { if (handle == IntPtr.Zero) throw new ObjectDisposedException ("SecTrust"); if (certificates == null) return SecTrustSetAnchorCertificates (handle, IntPtr.Zero); SecCertificate[] array = new SecCertificate [certificates.Count]; int i = 0; foreach (var certificate in certificates) array [i++] = new SecCertificate (certificate); return SetAnchorCertificates (array); } SecStatusCode SetAnchorCertificates (SecCertificate[] array) { using (var certs = CFArray.FromNativeObjects (array)) { return SecTrustSetAnchorCertificates (handle, certs.Handle); } } [DllImport (Constants.SecurityLibrary)] extern static SecStatusCode /* OSStatus */ SecTrustSetAnchorCertificatesOnly (IntPtr /* SecTrustRef */ trust, bool anchorCertificatesOnly); public SecStatusCode SetAnchorCertificatesOnly (bool anchorCertificatesOnly) { if (handle == IntPtr.Zero) throw new ObjectDisposedException ("SecTrust"); return SecTrustSetAnchorCertificatesOnly (handle, anchorCertificatesOnly); } ~SecTrust () { Dispose (false); } protected virtual void Dispose (bool disposing) { if (handle != IntPtr.Zero) { CFObject.CFRelease (handle); handle = IntPtr.Zero; } } public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } public IntPtr Handle { get { return handle; } } } }
/* * Copyright 2021 Google LLC All Rights Reserved. * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE file or at * https://developers.google.com/open-source/licenses/bsd */ // <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/type/localized_text.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Type { /// <summary>Holder for reflection information generated from google/type/localized_text.proto</summary> public static partial class LocalizedTextReflection { #region Descriptor /// <summary>File descriptor for google/type/localized_text.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static LocalizedTextReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiBnb29nbGUvdHlwZS9sb2NhbGl6ZWRfdGV4dC5wcm90bxILZ29vZ2xlLnR5", "cGUiNAoNTG9jYWxpemVkVGV4dBIMCgR0ZXh0GAEgASgJEhUKDWxhbmd1YWdl", "X2NvZGUYAiABKAlCegoPY29tLmdvb2dsZS50eXBlQhJMb2NhbGl6ZWRUZXh0", "UHJvdG9QAVpIZ29vZ2xlLmdvbGFuZy5vcmcvZ2VucHJvdG8vZ29vZ2xlYXBp", "cy90eXBlL2xvY2FsaXplZF90ZXh0O2xvY2FsaXplZF90ZXh0+AEBogIDR1RQ", "YgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Type.LocalizedText), global::Google.Type.LocalizedText.Parser, new[]{ "Text", "LanguageCode" }, null, null, null, null) })); } #endregion } #region Messages /// <summary> /// Localized variant of a text in a particular language. /// </summary> public sealed partial class LocalizedText : pb::IMessage<LocalizedText> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<LocalizedText> _parser = new pb::MessageParser<LocalizedText>(() => new LocalizedText()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<LocalizedText> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Type.LocalizedTextReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public LocalizedText() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public LocalizedText(LocalizedText other) : this() { text_ = other.text_; languageCode_ = other.languageCode_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public LocalizedText Clone() { return new LocalizedText(this); } /// <summary>Field number for the "text" field.</summary> public const int TextFieldNumber = 1; private string text_ = ""; /// <summary> /// Localized string in the language corresponding to `language_code' below. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Text { get { return text_; } set { text_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "language_code" field.</summary> public const int LanguageCodeFieldNumber = 2; private string languageCode_ = ""; /// <summary> /// The text's BCP-47 language code, such as "en-US" or "sr-Latn". /// /// For more information, see /// http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string LanguageCode { get { return languageCode_; } set { languageCode_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as LocalizedText); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(LocalizedText other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Text != other.Text) return false; if (LanguageCode != other.LanguageCode) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Text.Length != 0) hash ^= Text.GetHashCode(); if (LanguageCode.Length != 0) hash ^= LanguageCode.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.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 !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (Text.Length != 0) { output.WriteRawTag(10); output.WriteString(Text); } if (LanguageCode.Length != 0) { output.WriteRawTag(18); output.WriteString(LanguageCode); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (Text.Length != 0) { output.WriteRawTag(10); output.WriteString(Text); } if (LanguageCode.Length != 0) { output.WriteRawTag(18); output.WriteString(LanguageCode); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Text.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Text); } if (LanguageCode.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(LanguageCode); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(LocalizedText other) { if (other == null) { return; } if (other.Text.Length != 0) { Text = other.Text; } if (other.LanguageCode.Length != 0) { LanguageCode = other.LanguageCode; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Text = input.ReadString(); break; } case 18: { LanguageCode = input.ReadString(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { Text = input.ReadString(); break; } case 18: { LanguageCode = input.ReadString(); break; } } } } #endif } #endregion } #endregion Designer generated code
// // 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.Automation; using Microsoft.Azure.Management.Automation.Models; namespace Microsoft.Azure.Management.Automation { public static partial class DscConfigurationOperationsExtensions { /// <summary> /// Create the configuration identified by configuration name. (see /// http://aka.ms/azureautomationsdk/configurationoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IDscConfigurationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The create or update parameters for configuration. /// </param> /// <returns> /// The response model for the configuration create response. /// </returns> public static DscConfigurationCreateOrUpdateResponse CreateOrUpdate(this IDscConfigurationOperations operations, string resourceGroupName, string automationAccount, DscConfigurationCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IDscConfigurationOperations)s).CreateOrUpdateAsync(resourceGroupName, automationAccount, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create the configuration identified by configuration name. (see /// http://aka.ms/azureautomationsdk/configurationoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IDscConfigurationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The create or update parameters for configuration. /// </param> /// <returns> /// The response model for the configuration create response. /// </returns> public static Task<DscConfigurationCreateOrUpdateResponse> CreateOrUpdateAsync(this IDscConfigurationOperations operations, string resourceGroupName, string automationAccount, DscConfigurationCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, automationAccount, parameters, CancellationToken.None); } /// <summary> /// Delete the dsc configuration identified by configuration name. /// (see http://aka.ms/azureautomationsdk/configurationoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IDscConfigurationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='configurationName'> /// Required. The configuration name. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this IDscConfigurationOperations operations, string resourceGroupName, string automationAccount, string configurationName) { return Task.Factory.StartNew((object s) => { return ((IDscConfigurationOperations)s).DeleteAsync(resourceGroupName, automationAccount, configurationName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete the dsc configuration identified by configuration name. /// (see http://aka.ms/azureautomationsdk/configurationoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IDscConfigurationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='configurationName'> /// Required. The configuration name. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this IDscConfigurationOperations operations, string resourceGroupName, string automationAccount, string configurationName) { return operations.DeleteAsync(resourceGroupName, automationAccount, configurationName, CancellationToken.None); } /// <summary> /// Retrieve the configuration identified by configuration name. (see /// http://aka.ms/azureautomationsdk/configurationoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IDscConfigurationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='configurationName'> /// Required. The configuration name. /// </param> /// <returns> /// The response model for the get configuration operation. /// </returns> public static DscConfigurationGetResponse Get(this IDscConfigurationOperations operations, string resourceGroupName, string automationAccount, string configurationName) { return Task.Factory.StartNew((object s) => { return ((IDscConfigurationOperations)s).GetAsync(resourceGroupName, automationAccount, configurationName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve the configuration identified by configuration name. (see /// http://aka.ms/azureautomationsdk/configurationoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IDscConfigurationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='configurationName'> /// Required. The configuration name. /// </param> /// <returns> /// The response model for the get configuration operation. /// </returns> public static Task<DscConfigurationGetResponse> GetAsync(this IDscConfigurationOperations operations, string resourceGroupName, string automationAccount, string configurationName) { return operations.GetAsync(resourceGroupName, automationAccount, configurationName, CancellationToken.None); } /// <summary> /// Retrieve the configuration script identified by configuration name. /// (see http://aka.ms/azureautomationsdk/configurationoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IDscConfigurationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='configurationName'> /// Required. The configuration name. /// </param> /// <returns> /// The response model for the get configuration operation. /// </returns> public static DscConfigurationGetContentResponse GetContent(this IDscConfigurationOperations operations, string resourceGroupName, string automationAccount, string configurationName) { return Task.Factory.StartNew((object s) => { return ((IDscConfigurationOperations)s).GetContentAsync(resourceGroupName, automationAccount, configurationName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve the configuration script identified by configuration name. /// (see http://aka.ms/azureautomationsdk/configurationoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IDscConfigurationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='configurationName'> /// Required. The configuration name. /// </param> /// <returns> /// The response model for the get configuration operation. /// </returns> public static Task<DscConfigurationGetContentResponse> GetContentAsync(this IDscConfigurationOperations operations, string resourceGroupName, string automationAccount, string configurationName) { return operations.GetContentAsync(resourceGroupName, automationAccount, configurationName, CancellationToken.None); } /// <summary> /// Retrieve a list of configurations. (see /// http://aka.ms/azureautomationsdk/configurationoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IDscConfigurationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <returns> /// The response model for the list configuration operation. /// </returns> public static DscConfigurationListResponse List(this IDscConfigurationOperations operations, string resourceGroupName, string automationAccount) { return Task.Factory.StartNew((object s) => { return ((IDscConfigurationOperations)s).ListAsync(resourceGroupName, automationAccount); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve a list of configurations. (see /// http://aka.ms/azureautomationsdk/configurationoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IDscConfigurationOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <returns> /// The response model for the list configuration operation. /// </returns> public static Task<DscConfigurationListResponse> ListAsync(this IDscConfigurationOperations operations, string resourceGroupName, string automationAccount) { return operations.ListAsync(resourceGroupName, automationAccount, CancellationToken.None); } /// <summary> /// Retrieve next list of configurations. (see /// http://aka.ms/azureautomationsdk/configurationoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IDscConfigurationOperations. /// </param> /// <param name='nextLink'> /// Required. The link to retrieve next set of items. /// </param> /// <returns> /// The response model for the list configuration operation. /// </returns> public static DscConfigurationListResponse ListNext(this IDscConfigurationOperations operations, string nextLink) { return Task.Factory.StartNew((object s) => { return ((IDscConfigurationOperations)s).ListNextAsync(nextLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve next list of configurations. (see /// http://aka.ms/azureautomationsdk/configurationoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IDscConfigurationOperations. /// </param> /// <param name='nextLink'> /// Required. The link to retrieve next set of items. /// </param> /// <returns> /// The response model for the list configuration operation. /// </returns> public static Task<DscConfigurationListResponse> ListNextAsync(this IDscConfigurationOperations operations, string nextLink) { return operations.ListNextAsync(nextLink, CancellationToken.None); } } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using log4net.Core; using log4net.Appender; using log4net.Util; using log4net.Layout; using System.Text; namespace log4net.Appender { /// <summary> /// Logs events to a remote syslog daemon. /// </summary> /// <remarks> /// <para> /// The BSD syslog protocol is used to remotely log to /// a syslog daemon. The syslogd listens for for messages /// on UDP port 514. /// </para> /// <para> /// The syslog UDP protocol is not authenticated. Most syslog daemons /// do not accept remote log messages because of the security implications. /// You may be able to use the LocalSyslogAppender to talk to a local /// syslog service. /// </para> /// <para> /// There is an RFC 3164 that claims to document the BSD Syslog Protocol. /// This RFC can be seen here: http://www.faqs.org/rfcs/rfc3164.html. /// This appender generates what the RFC calls an "Original Device Message", /// i.e. does not include the TIMESTAMP or HOSTNAME fields. By observation /// this format of message will be accepted by all current syslog daemon /// implementations. The daemon will attach the current time and the source /// hostname or IP address to any messages received. /// </para> /// <para> /// Syslog messages must have a facility and and a severity. The severity /// is derived from the Level of the logging event. /// The facility must be chosen from the set of defined syslog /// <see cref="SyslogFacility"/> values. The facilities list is predefined /// and cannot be extended. /// </para> /// <para> /// An identifier is specified with each log message. This can be specified /// by setting the <see cref="Identity"/> property. The identity (also know /// as the tag) must not contain white space. The default value for the /// identity is the application name (from <see cref="LoggingEvent.Domain"/>). /// </para> /// </remarks> /// <author>Rob Lyon</author> /// <author>Nicko Cadell</author> public class RemoteSyslogAppender : UdpAppender { /// <summary> /// Syslog port 514 /// </summary> private const int DefaultSyslogPort = 514; #region Enumerations /// <summary> /// syslog severities /// </summary> /// <remarks> /// <para> /// The syslog severities. /// </para> /// </remarks> public enum SyslogSeverity { /// <summary> /// system is unusable /// </summary> Emergency = 0, /// <summary> /// action must be taken immediately /// </summary> Alert = 1, /// <summary> /// critical conditions /// </summary> Critical = 2, /// <summary> /// error conditions /// </summary> Error = 3, /// <summary> /// warning conditions /// </summary> Warning = 4, /// <summary> /// normal but significant condition /// </summary> Notice = 5, /// <summary> /// informational /// </summary> Informational = 6, /// <summary> /// debug-level messages /// </summary> Debug = 7 }; /// <summary> /// syslog facilities /// </summary> /// <remarks> /// <para> /// The syslog facilities /// </para> /// </remarks> public enum SyslogFacility { /// <summary> /// kernel messages /// </summary> Kernel = 0, /// <summary> /// random user-level messages /// </summary> User = 1, /// <summary> /// mail system /// </summary> Mail = 2, /// <summary> /// system daemons /// </summary> Daemons = 3, /// <summary> /// security/authorization messages /// </summary> Authorization = 4, /// <summary> /// messages generated internally by syslogd /// </summary> Syslog = 5, /// <summary> /// line printer subsystem /// </summary> Printer = 6, /// <summary> /// network news subsystem /// </summary> News = 7, /// <summary> /// UUCP subsystem /// </summary> Uucp = 8, /// <summary> /// clock (cron/at) daemon /// </summary> Clock = 9, /// <summary> /// security/authorization messages (private) /// </summary> Authorization2 = 10, /// <summary> /// ftp daemon /// </summary> Ftp = 11, /// <summary> /// NTP subsystem /// </summary> Ntp = 12, /// <summary> /// log audit /// </summary> Audit = 13, /// <summary> /// log alert /// </summary> Alert = 14, /// <summary> /// clock daemon /// </summary> Clock2 = 15, /// <summary> /// reserved for local use /// </summary> Local0 = 16, /// <summary> /// reserved for local use /// </summary> Local1 = 17, /// <summary> /// reserved for local use /// </summary> Local2 = 18, /// <summary> /// reserved for local use /// </summary> Local3 = 19, /// <summary> /// reserved for local use /// </summary> Local4 = 20, /// <summary> /// reserved for local use /// </summary> Local5 = 21, /// <summary> /// reserved for local use /// </summary> Local6 = 22, /// <summary> /// reserved for local use /// </summary> Local7 = 23 } #endregion Enumerations #region Public Instance Constructors /// <summary> /// Initializes a new instance of the <see cref="RemoteSyslogAppender" /> class. /// </summary> /// <remarks> /// This instance of the <see cref="RemoteSyslogAppender" /> class is set up to write /// to a remote syslog daemon. /// </remarks> public RemoteSyslogAppender() { // syslog udp defaults this.RemotePort = DefaultSyslogPort; this.RemoteAddress = System.Net.IPAddress.Parse("127.0.0.1"); this.Encoding = System.Text.Encoding.ASCII; } #endregion Public Instance Constructors #region Public Instance Properties /// <summary> /// Message identity /// </summary> /// <remarks> /// <para> /// An identifier is specified with each log message. This can be specified /// by setting the <see cref="Identity"/> property. The identity (also know /// as the tag) must not contain white space. The default value for the /// identity is the application name (from <see cref="LoggingEvent.Domain"/>). /// </para> /// </remarks> public PatternLayout Identity { get { return m_identity; } set { m_identity = value; } } /// <summary> /// Syslog facility /// </summary> /// <remarks> /// Set to one of the <see cref="SyslogFacility"/> values. The list of /// facilities is predefined and cannot be extended. The default value /// is <see cref="SyslogFacility.User"/>. /// </remarks> public SyslogFacility Facility { get { return m_facility; } set { m_facility = value; } } #endregion Public Instance Properties /// <summary> /// Add a mapping of level to severity /// </summary> /// <param name="mapping">The mapping to add</param> /// <remarks> /// <para> /// Add a <see cref="LevelSeverity"/> mapping to this appender. /// </para> /// </remarks> public void AddMapping(LevelSeverity mapping) { m_levelMapping.Add(mapping); } #region AppenderSkeleton Implementation /// <summary> /// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(LoggingEvent)"/> method. /// </summary> /// <param name="loggingEvent">The event to log.</param> /// <remarks> /// <para> /// Writes the event to a remote syslog daemon. /// </para> /// <para> /// The format of the output will depend on the appender's layout. /// </para> /// </remarks> protected override void Append(LoggingEvent loggingEvent) { try { // Priority int priority = GeneratePriority(m_facility, GetSeverity(loggingEvent.Level)); // Identity string identity; if (m_identity != null) { identity = m_identity.Format(loggingEvent); } else { identity = loggingEvent.Domain; } // Message. The message goes after the tag/identity string message = RenderLoggingEvent(loggingEvent); Byte[] buffer; int i = 0; char c; StringBuilder builder = new StringBuilder(); while (i < message.Length) { // Clear StringBuilder builder.Length = 0; // Write priority builder.Append('<'); builder.Append(priority); builder.Append('>'); // Write identity builder.Append(identity); builder.Append(": "); for (; i < message.Length; i++) { c = message[i]; // Accept only visible ASCII characters and space. See RFC 3164 section 4.1.3 if (((int)c >= 32) && ((int)c <= 126)) { builder.Append(c); } // If character is newline, break and send the current line else if ((c == '\r') || (c == '\n')) { // Check the next character to handle \r\n or \n\r if ((message.Length > i + 1) && ((message[i + 1] == '\r') || (message[i + 1] == '\n'))) { i++; } i++; break; } } // Grab as a byte array buffer = this.Encoding.GetBytes(builder.ToString()); #if NETSTANDARD1_3 Client.SendAsync(buffer, buffer.Length, RemoteEndPoint).Wait(); #else this.Client.Send(buffer, buffer.Length, this.RemoteEndPoint); #endif } } catch (Exception e) { ErrorHandler.Error( "Unable to send logging event to remote syslog " + this.RemoteAddress.ToString() + " on port " + this.RemotePort + ".", e, ErrorCode.WriteFailure); } } /// <summary> /// Initialize the options for this appender /// </summary> /// <remarks> /// <para> /// Initialize the level to syslog severity mappings set on this appender. /// </para> /// </remarks> public override void ActivateOptions() { base.ActivateOptions(); m_levelMapping.ActivateOptions(); } #endregion AppenderSkeleton Implementation #region Protected Members /// <summary> /// Translates a log4net level to a syslog severity. /// </summary> /// <param name="level">A log4net level.</param> /// <returns>A syslog severity.</returns> /// <remarks> /// <para> /// Translates a log4net level to a syslog severity. /// </para> /// </remarks> virtual protected SyslogSeverity GetSeverity(Level level) { LevelSeverity levelSeverity = m_levelMapping.Lookup(level) as LevelSeverity; if (levelSeverity != null) { return levelSeverity.Severity; } // // Fallback to sensible default values // if (level >= Level.Alert) { return SyslogSeverity.Alert; } else if (level >= Level.Critical) { return SyslogSeverity.Critical; } else if (level >= Level.Error) { return SyslogSeverity.Error; } else if (level >= Level.Warn) { return SyslogSeverity.Warning; } else if (level >= Level.Notice) { return SyslogSeverity.Notice; } else if (level >= Level.Info) { return SyslogSeverity.Informational; } // Default setting return SyslogSeverity.Debug; } #endregion Protected Members #region Public Static Members /// <summary> /// Generate a syslog priority. /// </summary> /// <param name="facility">The syslog facility.</param> /// <param name="severity">The syslog severity.</param> /// <returns>A syslog priority.</returns> /// <remarks> /// <para> /// Generate a syslog priority. /// </para> /// </remarks> public static int GeneratePriority(SyslogFacility facility, SyslogSeverity severity) { if (facility < SyslogFacility.Kernel || facility > SyslogFacility.Local7) { throw new ArgumentException("SyslogFacility out of range", "facility"); } if (severity < SyslogSeverity.Emergency || severity > SyslogSeverity.Debug) { throw new ArgumentException("SyslogSeverity out of range", "severity"); } unchecked { return ((int)facility * 8) + (int)severity; } } #endregion Public Static Members #region Private Instances Fields /// <summary> /// The facility. The default facility is <see cref="SyslogFacility.User"/>. /// </summary> private SyslogFacility m_facility = SyslogFacility.User; /// <summary> /// The message identity /// </summary> private PatternLayout m_identity; /// <summary> /// Mapping from level object to syslog severity /// </summary> private LevelMapping m_levelMapping = new LevelMapping(); /// <summary> /// Initial buffer size /// </summary> private const int c_renderBufferSize = 256; /// <summary> /// Maximum buffer size before it is recycled /// </summary> private const int c_renderBufferMaxCapacity = 1024; #endregion Private Instances Fields #region LevelSeverity LevelMapping Entry /// <summary> /// A class to act as a mapping between the level that a logging call is made at and /// the syslog severity that is should be logged at. /// </summary> /// <remarks> /// <para> /// A class to act as a mapping between the level that a logging call is made at and /// the syslog severity that is should be logged at. /// </para> /// </remarks> public class LevelSeverity : LevelMappingEntry { private SyslogSeverity m_severity; /// <summary> /// The mapped syslog severity for the specified level /// </summary> /// <remarks> /// <para> /// Required property. /// The mapped syslog severity for the specified level /// </para> /// </remarks> public SyslogSeverity Severity { get { return m_severity; } set { m_severity = value; } } } #endregion // LevelSeverity LevelMapping Entry } }
// 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 Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; using System; using System.Collections.Immutable; using System.Linq; using System.Reflection.Metadata; using Xunit; using Resources = Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests.Resources; using Roslyn.Test.PdbUtilities; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class WinMdTests : ExpressionCompilerTestBase { /// <summary> /// Handle runtime assemblies rather than Windows.winmd /// (compile-time assembly) since those are the assemblies /// loaded in the debuggee. /// </summary> [WorkItem(981104)] [ConditionalFact(typeof(OSVersionWin8))] public void Win8RuntimeAssemblies() { var source = @"class C { static void M(Windows.Storage.StorageFolder f, Windows.Foundation.Collections.PropertySet p) { } }"; var compilation0 = CreateCompilationWithMscorlib( source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(), references: WinRtRefs); var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections"); Assert.True(runtimeAssemblies.Length >= 2); byte[] exeBytes; byte[] pdbBytes; ImmutableArray<MetadataReference> references; compilation0.EmitAndGetReferences(out exeBytes, out pdbBytes, out references); var runtime = CreateRuntimeInstance( ExpressionCompilerUtilities.GenerateUniqueName(), ImmutableArray.Create(MscorlibRef).Concat(runtimeAssemblies), // no reference to Windows.winmd exeBytes, new SymReader(pdbBytes)); var context = CreateMethodContext(runtime, "C.M"); ResultProperties resultProperties; string error; var testData = new CompilationTestData(); context.CompileExpression("(p == null) ? f : null", out resultProperties, out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: brfalse.s IL_0005 IL_0003: ldnull IL_0004: ret IL_0005: ldarg.0 IL_0006: ret }"); } [ConditionalFact(typeof(OSVersionWin8))] public void Win8RuntimeAssemblies_ExternAlias() { var source = @"extern alias X; class C { static void M(X::Windows.Storage.StorageFolder f) { } }"; var compilation0 = CreateCompilationWithMscorlib( source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(), references: WinRtRefs.Select(r => r.Display == "Windows" ? r.WithAliases(new[] { "X" }) : r)); var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage"); Assert.True(runtimeAssemblies.Length >= 1); byte[] exeBytes; byte[] pdbBytes; ImmutableArray<MetadataReference> references; compilation0.EmitAndGetReferences(out exeBytes, out pdbBytes, out references); var runtime = CreateRuntimeInstance( ExpressionCompilerUtilities.GenerateUniqueName(), ImmutableArray.Create(MscorlibRef).Concat(runtimeAssemblies), // no reference to Windows.winmd exeBytes, new SymReader(pdbBytes)); var context = CreateMethodContext(runtime, "C.M"); ResultProperties resultProperties; string error; var testData = new CompilationTestData(); context.CompileExpression("X::Windows.Storage.FileProperties.PhotoOrientation.Unspecified", out resultProperties, out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret }"); } [Fact] public void Win8OnWin8() { CompileTimeAndRuntimeAssemblies( ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows_Data)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows_Storage)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), "Windows.Storage"); } [Fact] public void Win8OnWin10() { CompileTimeAndRuntimeAssemblies( ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Data)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Storage)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), "Windows.Storage"); } [WorkItem(1108135)] [Fact] public void Win10OnWin10() { CompileTimeAndRuntimeAssemblies( ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Data)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Storage)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), "Windows"); } private void CompileTimeAndRuntimeAssemblies( ImmutableArray<MetadataReference> compileReferences, ImmutableArray<MetadataReference> runtimeReferences, string storageAssemblyName) { var source = @"class C { static void M(LibraryA.A a, LibraryB.B b, Windows.Data.Text.TextSegment t, Windows.Storage.StorageFolder f) { } }"; var runtime = CreateRuntime(source, compileReferences, runtimeReferences); var context = CreateMethodContext(runtime, "C.M"); ResultProperties resultProperties; string error; var testData = new CompilationTestData(); context.CompileExpression("(object)a ?? (object)b ?? (object)t ?? f", out resultProperties, out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: brtrue.s IL_0010 IL_0004: pop IL_0005: ldarg.1 IL_0006: dup IL_0007: brtrue.s IL_0010 IL_0009: pop IL_000a: ldarg.2 IL_000b: dup IL_000c: brtrue.s IL_0010 IL_000e: pop IL_000f: ldarg.3 IL_0010: ret }"); testData = new CompilationTestData(); var result = context.CompileExpression("default(Windows.Storage.StorageFolder)", out resultProperties, out error, testData); Assert.Null(error); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); // Check return type is from runtime assembly. var assemblyReference = AssemblyMetadata.CreateFromImage(result.Assembly).GetReference(); var compilation = CSharpCompilation.Create( assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(), references: runtimeReferences.Concat(ImmutableArray.Create<MetadataReference>(assemblyReference))); var assembly = ImmutableArray.CreateRange(result.Assembly); using (var metadata = ModuleMetadata.CreateFromImage(ImmutableArray.CreateRange(assembly))) { var reader = metadata.MetadataReader; var typeDef = reader.GetTypeDef("<>x"); var methodHandle = reader.GetMethodDefHandle(typeDef, "<>m0"); var module = (PEModuleSymbol)compilation.GetMember("<>x").ContainingModule; var metadataDecoder = new MetadataDecoder(module); SignatureHeader signatureHeader; BadImageFormatException metadataException; var parameters = metadataDecoder.GetSignatureForMethod(methodHandle, out signatureHeader, out metadataException); Assert.Equal(parameters.Length, 5); var actualReturnType = parameters[0].Type; Assert.Equal(actualReturnType.TypeKind, TypeKind.Class); // not error var expectedReturnType = compilation.GetMember("Windows.Storage.StorageFolder"); Assert.Equal(expectedReturnType, actualReturnType); Assert.Equal(storageAssemblyName, actualReturnType.ContainingAssembly.Name); } } /// <summary> /// Assembly-qualified name containing "ContentType=WindowsRuntime", /// and referencing runtime assembly. /// </summary> [WorkItem(1116143)] [ConditionalFact(typeof(OSVersionWin8))] public void AssemblyQualifiedName() { var source = @"class C { static void M(Windows.Storage.StorageFolder f, Windows.Foundation.Collections.PropertySet p) { } }"; var runtime = CreateRuntime( source, ImmutableArray.CreateRange(WinRtRefs), ImmutableArray.Create(MscorlibRef).Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections"))); var context = CreateMethodContext(runtime, "C.M"); ResultProperties resultProperties; string error; var testData = new CompilationTestData(); ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; context.CompileExpression( InspectionContextFactory.Empty. Add("s", "Windows.Storage.StorageFolder, Windows.Storage, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime"). Add("d", "Windows.Foundation.DateTime, Windows.Foundation, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime"), "(object)s.Attributes ?? d.UniversalTime", DkmEvaluationFlags.TreatAsExpression, DiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Empty(missingAssemblyIdentities); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 55 (0x37) .maxstack 2 IL_0000: ldstr ""s"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: castclass ""Windows.Storage.StorageFolder"" IL_000f: callvirt ""Windows.Storage.FileAttributes Windows.Storage.StorageFolder.Attributes.get"" IL_0014: box ""Windows.Storage.FileAttributes"" IL_0019: dup IL_001a: brtrue.s IL_0036 IL_001c: pop IL_001d: ldstr ""d"" IL_0022: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_0027: unbox.any ""Windows.Foundation.DateTime"" IL_002c: ldfld ""long Windows.Foundation.DateTime.UniversalTime"" IL_0031: box ""long"" IL_0036: ret }"); } [WorkItem(1117084)] [Fact(Skip = "1114866")] public void OtherFrameworkAssembly() { var source = @"class C { static void M(Windows.UI.Xaml.FrameworkElement f) { } }"; var runtime = CreateRuntime( source, ImmutableArray.CreateRange(WinRtRefs), ImmutableArray.Create(MscorlibRef).Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Foundation", "Windows.UI", "Windows.UI.Xaml"))); var context = CreateMethodContext(runtime, "C.M"); ResultProperties resultProperties; string error; var testData = new CompilationTestData(); ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; context.CompileExpression( InspectionContextFactory.Empty, "f.RenderSize", DkmEvaluationFlags.TreatAsExpression, DiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Empty(missingAssemblyIdentities); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 55 (0x37) .maxstack 2 IL_0000: ldstr ""s"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: castclass ""Windows.Storage.StorageFolder"" IL_000f: callvirt ""Windows.Storage.FileAttributes Windows.Storage.StorageFolder.Attributes.get"" IL_0014: box ""Windows.Storage.FileAttributes"" IL_0019: dup IL_001a: brtrue.s IL_0036 IL_001c: pop IL_001d: ldstr ""d"" IL_0022: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_0027: unbox.any ""Windows.Foundation.DateTime"" IL_002c: ldfld ""long Windows.Foundation.DateTime.UniversalTime"" IL_0031: box ""long"" IL_0036: ret }"); } private RuntimeInstance CreateRuntime( string source, ImmutableArray<MetadataReference> compileReferences, ImmutableArray<MetadataReference> runtimeReferences) { var compilation0 = CreateCompilationWithMscorlib( source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(), references: compileReferences); byte[] exeBytes; byte[] pdbBytes; ImmutableArray<MetadataReference> references; compilation0.EmitAndGetReferences(out exeBytes, out pdbBytes, out references); return CreateRuntimeInstance( ExpressionCompilerUtilities.GenerateUniqueName(), runtimeReferences.AddIntrinsicAssembly(), exeBytes, new SymReader(pdbBytes)); } private static byte[] ToVersion1_3(byte[] bytes) { return ExpressionCompilerTestHelpers.ToVersion1_3(bytes); } private static byte[] ToVersion1_4(byte[] bytes) { return ExpressionCompilerTestHelpers.ToVersion1_4(bytes); } } }
#region Apache License, Version 2.0 // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // #endregion using System; using System.Collections.Generic; using System.IO; using System.Text; using log4net; namespace NPanday.Artifact { public sealed class ArtifactRepository { private static readonly ILog log = LogManager.GetLogger(typeof(ArtifactRepository)); public string Tokenize(string id) { return id.Replace(".", Path.DirectorySeparatorChar.ToString()); } public string GetLocalRepositoryPath(Artifact artifact, string ext) { return string.Format(@"{0}\{1}\{2}\{3}\{2}-{3}{4}", localRepository.FullName, artifact.GroupId.Replace(@".", @"\"), artifact.ArtifactId, artifact.Version, ext); } public string GetRemoteRepositoryPath(Artifact artifact, string url, string ext) { return string.Format("{0}/{1}/{2}/{3}/{2}-{3}{4}", url, artifact.GroupId.Replace('.', '/'), artifact.ArtifactId, artifact.Version, ext); } public string GetRemoteRepositoryPath(Artifact artifact, string timeStampVersion, string url, string ext) { return string.Format("{0}/{1}/{2}/{3}/{2}-{4}{5}", url, artifact.GroupId.Replace('.', '/'), artifact.ArtifactId, artifact.Version, timeStampVersion, ext); } public Artifact GetArtifactFor(String uri) { Artifact artifact = new Artifact(); String[] tokens = uri.Split("/".ToCharArray(), Int32.MaxValue, StringSplitOptions.RemoveEmptyEntries); int size = tokens.Length; if (size < 3) { System.Reflection.Assembly a = System.Reflection.Assembly.LoadFile(uri); string[] info = a.FullName.Split(",".ToCharArray(), Int32.MaxValue, StringSplitOptions.RemoveEmptyEntries); artifact.ArtifactId = info[0]; artifact.GroupId = info[0]; artifact.Version = info[1].Split(new char[] { '=' })[1]; artifact.Extension = tokens[0].Split(new char[] { '.' })[1]; if (artifact.Version == null) { artifact.Version = "1.0.0.0"; } } else { artifact.ArtifactId = tokens[size - 3]; StringBuilder buffer = new StringBuilder(); for (int i = 0; i < size - 3; i++) { buffer.Append(tokens[i]); if (i != size - 4) { buffer.Append("."); } } artifact.GroupId = buffer.ToString(); artifact.Version = tokens[size - 2]; String[] extToken = tokens[size - 1].Split(".".ToCharArray()); artifact.Extension = extToken[extToken.Length - 1]; } artifact.FileInfo = new FileInfo(localRepository.FullName + Path.DirectorySeparatorChar + Tokenize(artifact.GroupId) + Path.DirectorySeparatorChar + artifact.ArtifactId + Path.DirectorySeparatorChar + artifact.Version + Path.DirectorySeparatorChar + artifact.ArtifactId + "-" + artifact.Version + ".dll"); return artifact; } public List<Artifact> GetArtifacts() { List<Artifact> artifacts = new List<Artifact>(); try { List<FileInfo> fileInfos = GetArtifactsFromDirectory(localRepository); foreach (FileInfo fileInfo in fileInfos) { try { Artifact artifact = GetArtifact(localRepository, fileInfo); artifacts.Add(artifact); } catch { } } } catch (Exception e) { log.Error(e.Message, e); } return artifacts; } #region Repository Artifact Info Helper public Artifact GetArtifact(FileInfo artifactFile) { return GetArtifact(localRepository, artifactFile); } public Artifact GetArtifact(NPanday.Model.Pom.Dependency dependency) { Artifact artifact = new Artifact(); artifact.ArtifactId = dependency.artifactId; artifact.GroupId = dependency.groupId; artifact.Version = dependency.version; artifact.FileInfo = new FileInfo(GetLocalRepositoryPath(artifact, ".dll")); return artifact; } public Artifact GetArtifact(DirectoryInfo uacDirectory, FileInfo artifactFile) { string[] tokens; try { tokens = PathUtil.GetRelativePathTokens(uacDirectory, artifactFile); } catch { List<string> tk = new List<string>(artifactFile.FullName.Split(@"\".ToCharArray())); tk.RemoveRange(0, tk.Count - 3); tokens = tk.ToArray(); } //artifact for system path if (!artifactFile.FullName.Contains(".m2")) { return null; } string fileName = tokens[tokens.Length - 1]; int index = fileName.LastIndexOf("."); string ext = fileName.Substring(index); string version = tokens[tokens.Length - 2]; string artifactId = tokens[tokens.Length - 3]; StringBuilder group = new StringBuilder(); for (int i = 0; i < tokens.Length - 3; i++) { group.Append(tokens[i]).Append("."); } string groupId = group.ToString(0, group.Length - 1); Artifact artifact = new Artifact(); artifact.ArtifactId = artifactId; artifact.Version = version; artifact.GroupId = groupId; artifact.FileInfo = new FileInfo(GetLocalRepositoryPath(artifact, ext)); return artifact; } #endregion public void Init(ArtifactContext artifactContext, DirectoryInfo localRepository) { this.artifactContext = artifactContext; this.localRepository = localRepository; } private List<FileInfo> GetArtifactsFromDirectory(DirectoryInfo baseDirectoryInfo) { List<FileInfo> fileInfos = new List<FileInfo>(); DirectoryInfo[] directories = baseDirectoryInfo.GetDirectories(); foreach (DirectoryInfo directoryInfo in directories) { foreach (FileInfo fileInfo in directoryInfo.GetFiles()) { if (fileInfo.Name.EndsWith(".dll") || fileInfo.Name.EndsWith(".exe") || fileInfo.Name.EndsWith(".netmodule")) { fileInfos.Add(fileInfo); } } fileInfos.AddRange(GetArtifactsFromDirectory(directoryInfo)); } return fileInfos; } private ArtifactContext artifactContext; private DirectoryInfo localRepository; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using Microsoft.AspNetCore.Razor.Language.Extensions; using Xunit; namespace Microsoft.AspNetCore.Razor.Language.Legacy { public class HtmlDocumentTest : ParserTestBase { private static readonly TestFile Nested1000 = TestFile.Create("TestFiles/nested-1000.html", typeof(HtmlDocumentTest)); [Fact] public void NestedCodeBlockWithMarkupSetsDotAsMarkup() { ParseDocumentTest("@if (true) { @if(false) { <div>@something.</div> } }"); } [Fact] public void OutputsEmptyBlockWithEmptyMarkupSpanIfContentIsEmptyString() { ParseDocumentTest(string.Empty); } [Fact] public void OutputsWhitespaceOnlyContentAsSingleWhitespaceMarkupSpan() { ParseDocumentTest(" "); } [Fact] public void AcceptsSwapTokenAtEndOfFileAndOutputsZeroLengthCodeSpan() { ParseDocumentTest("@"); } [Fact] public void CorrectlyHandlesOddlySpacedHTMLElements() { ParseDocumentTest("<div ><p class = 'bar'> Foo </p></div >"); } [Fact] public void CorrectlyHandlesSingleLineOfMarkupWithEmbeddedStatement() { ParseDocumentTest("<div>Foo @if(true) {} Bar</div>"); } [Fact] public void WithinSectionDoesNotCreateDocumentLevelSpan() { ParseDocumentTest("@section Foo {" + Environment.NewLine + " <html></html>" + Environment.NewLine + "}", new[] { SectionDirective.Directive, }); } [Fact] public void ParsesWholeContentAsOneSpanIfNoSwapCharacterEncountered() { ParseDocumentTest("foo baz"); } [Fact] public void HandsParsingOverToCodeParserWhenAtSignEncounteredAndEmitsOutput() { ParseDocumentTest("foo @bar baz"); } [Fact] public void EmitsAtSignAsMarkupIfAtEndOfFile() { ParseDocumentTest("foo @"); } [Fact] public void EmitsCodeBlockIfFirstCharacterIsSwapCharacter() { ParseDocumentTest("@bar"); } [Fact] public void ParseDocumentDoesNotSwitchToCodeOnEmailAddressInText() { ParseDocumentTest("[email protected]"); } [Fact] public void DoesNotSwitchToCodeOnEmailAddressInAttribute() { ParseDocumentTest("<a href=\"mailto:[email protected]\">Email me</a>"); } [Fact] public void DoesNotReturnErrorOnMismatchedTags() { ParseDocumentTest("Foo <div><p></p></p> Baz"); } [Fact] public void ReturnsOneMarkupSegmentIfNoCodeBlocksEncountered() { ParseDocumentTest("Foo Baz<!--Foo-->Bar<!--F> Qux"); } [Fact] public void RendersTextPseudoTagAsMarkup() { ParseDocumentTest("Foo <text>Foo</text>"); } [Fact] public void AcceptsEndTagWithNoMatchingStartTag() { ParseDocumentTest("Foo </div> Bar"); } [Fact] public void NoLongerSupportsDollarOpenBraceCombination() { ParseDocumentTest("<foo>${bar}</foo>"); } [Fact] public void IgnoresTagsInContentsOfScriptTag() { ParseDocumentTest(@"<script>foo<bar baz='@boz'></script>"); } [Fact] public void DoesNotRenderExtraNewLineAtTheEndOfVerbatimBlock() { ParseDocumentTest("@{\r\n}\r\n<html>"); } [Fact] public void DoesNotRenderExtraWhitespaceAndNewLineAtTheEndOfVerbatimBlock() { ParseDocumentTest("@{\r\n} \t\r\n<html>"); } [Fact] public void DoesNotRenderNewlineAfterTextTagInVerbatimBlockIfFollowedByCSharp() { // ParseDocumentDoesNotRenderExtraNewlineAtTheEndTextTagInVerbatimBlockIfFollowedByCSharp ParseDocumentTest("@{<text>Blah</text>\r\n\r\n}<html>"); } [Fact] public void RendersExtraNewlineAtTheEndTextTagInVerbatimBlockIfFollowedByHtml() { ParseDocumentTest("@{<text>Blah</text>\r\n<input/>\r\n}<html>"); } [Fact] public void RendersNewlineAfterTextTagInVerbatimBlockIfFollowedByMarkupTransition() { // ParseDocumentRendersExtraNewlineAtTheEndTextTagInVerbatimBlockIfFollowedByMarkupTransition ParseDocumentTest("@{<text>Blah</text>\r\n@: Bleh\r\n}<html>"); } [Fact] public void DoesNotIgnoreNewLineAtTheEndOfMarkupBlock() { ParseDocumentTest("@{\r\n}\r\n<html>\r\n"); } [Fact] public void DoesNotIgnoreWhitespaceAtTheEndOfVerbatimBlockIfNoNewlinePresent() { ParseDocumentTest("@{\r\n} \t<html>\r\n"); } [Fact] public void HandlesNewLineInNestedBlock() { ParseDocumentTest("@{\r\n@if(true){\r\n} \r\n}\r\n<html>"); } [Fact] public void HandlesNewLineAndMarkupInNestedBlock() { ParseDocumentTest("@{\r\n@if(true){\r\n} <input> }"); } [Fact] public void HandlesExtraNewLineBeforeMarkupInNestedBlock() { ParseDocumentTest("@{\r\n@if(true){\r\n} \r\n<input> \r\n}<html>"); } [Fact] public void ParseSectionIgnoresTagsInContentsOfScriptTag() { ParseDocumentTest( @"@section Foo { <script>foo<bar baz='@boz'></script> }", new[] { SectionDirective.Directive, }); } [Fact] public void ParseBlockCanParse1000NestedElements() { var content = Nested1000.ReadAllText(); // Assert - does not throw ParseDocument(content); } [Fact] public void WithDoubleTransitionInAttributeValue_DoesNotThrow() { var input = "{<span foo='@@' />}"; ParseDocumentTest(input); } [Fact] public void WithDoubleTransitionAtEndOfAttributeValue_DoesNotThrow() { var input = "{<span foo='abc@@' />}"; ParseDocumentTest(input); } [Fact] public void WithDoubleTransitionAtBeginningOfAttributeValue_DoesNotThrow() { var input = "{<span foo='@@def' />}"; ParseDocumentTest(input); } [Fact] public void WithDoubleTransitionBetweenAttributeValue_DoesNotThrow() { var input = "{<span foo='abc @@ def' />}"; ParseDocumentTest(input); } [Fact] public void WithDoubleTransitionWithExpressionBlock_DoesNotThrow() { var input = "{<span foo='@@@(2+3)' bar='@(2+3)@@@DateTime.Now' baz='@DateTime.Now@@' bat='@DateTime.Now @@' zoo='@@@DateTime.Now' />}"; ParseDocumentTest(input); } [Fact] public void WithDoubleTransitionInEmail_DoesNotThrow() { var input = "{<span foo='[email protected] abc@@def.com @@' />}"; ParseDocumentTest(input); } [Fact] public void WithDoubleTransitionInRegex_DoesNotThrow() { var input = @"{<span foo=""/^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@@[a-z0-9]([a-z0-9-]*[a-z0-9])?\.([a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i"" />}"; ParseDocumentTest(input); } [Fact] public void WithUnexpectedTransitionsInAttributeValue_Throws() { ParseDocumentTest("<span foo='@ @' />"); } } }
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets.Wrappers { using System; using System.Collections.Generic; using NLog.Targets; using NLog.Targets.Wrappers; using Xunit; public class PostFilteringTargetWrapperTests : NLogTestBase { [Fact] public void PostFilteringTargetWrapperUsingDefaultFilterTest() { var target = new MyTarget(); var wrapper = new PostFilteringTargetWrapper() { WrappedTarget = target, Rules = { // if we had any warnings, log debug too new FilteringRule("level >= LogLevel.Warn", "level >= LogLevel.Debug"), // when there is an error, emit everything new FilteringRule { Exists = "level >= LogLevel.Error", Filter = "true", }, }, // by default log info and above DefaultFilter = "level >= LogLevel.Info", }; wrapper.Initialize(null); target.Initialize(null); var exceptions = new List<Exception>(); var events = new [] { new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Trace, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger3", "Hello").WithContinuation(exceptions.Add), }; wrapper.WriteAsyncLogEvents(events); // make sure all Info events went through Assert.Equal(3, target.Events.Count); Assert.Same(events[1].LogEvent, target.Events[0]); Assert.Same(events[2].LogEvent, target.Events[1]); Assert.Same(events[5].LogEvent, target.Events[2]); Assert.Equal(events.Length, exceptions.Count); } [Fact] public void PostFilteringTargetWrapperUsingDefaultNonFilterTest() { var target = new MyTarget(); var wrapper = new PostFilteringTargetWrapper() { WrappedTarget = target, Rules = { // if we had any warnings, log debug too new FilteringRule("level >= LogLevel.Warn", "level >= LogLevel.Debug"), // when there is an error, emit everything new FilteringRule("level >= LogLevel.Error", "true"), }, // by default log info and above DefaultFilter = "level >= LogLevel.Info", }; wrapper.Initialize(null); target.Initialize(null); var exceptions = new List<Exception>(); var events = new[] { new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Trace, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger3", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Warn, "Logger1", "Hello").WithContinuation(exceptions.Add), }; string result = RunAndCaptureInternalLog(() => wrapper.WriteAsyncLogEvents(events), LogLevel.Trace); Assert.True(result.IndexOf("Trace Running PostFilteringWrapper Target[(unnamed)](MyTarget) on 7 events") != -1); Assert.True(result.IndexOf("Trace Rule matched: (level >= Warn)") != -1); Assert.True(result.IndexOf("Trace Filter to apply: (level >= Debug)") != -1); Assert.True(result.IndexOf("Trace After filtering: 6 events.") != -1); Assert.True(result.IndexOf("Trace Sending to MyTarget") != -1); // make sure all Debug,Info,Warn events went through Assert.Equal(6, target.Events.Count); Assert.Same(events[0].LogEvent, target.Events[0]); Assert.Same(events[1].LogEvent, target.Events[1]); Assert.Same(events[2].LogEvent, target.Events[2]); Assert.Same(events[3].LogEvent, target.Events[3]); Assert.Same(events[5].LogEvent, target.Events[4]); Assert.Same(events[6].LogEvent, target.Events[5]); Assert.Equal(events.Length, exceptions.Count); } [Fact] public void PostFilteringTargetWrapperUsingDefaultNonFilterTest2() { // in this case both rules would match, but first one is picked var target = new MyTarget(); var wrapper = new PostFilteringTargetWrapper() { WrappedTarget = target, Rules = { // when there is an error, emit everything new FilteringRule("level >= LogLevel.Error", "true"), // if we had any warnings, log debug too new FilteringRule("level >= LogLevel.Warn", "level >= LogLevel.Debug"), }, // by default log info and above DefaultFilter = "level >= LogLevel.Info", }; wrapper.Initialize(null); target.Initialize(null); var exceptions = new List<Exception>(); var events = new [] { new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Trace, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger3", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Error, "Logger1", "Hello").WithContinuation(exceptions.Add), }; var result = RunAndCaptureInternalLog(() => wrapper.WriteAsyncLogEvents(events), LogLevel.Trace); Assert.True(result.IndexOf("Trace Running PostFilteringWrapper Target[(unnamed)](MyTarget) on 7 events") != -1); Assert.True(result.IndexOf("Trace Rule matched: (level >= Error)") != -1); Assert.True(result.IndexOf("Trace Filter to apply: True") != -1); Assert.True(result.IndexOf("Trace After filtering: 7 events.") != -1); Assert.True(result.IndexOf("Trace Sending to MyTarget") != -1); // make sure all events went through Assert.Equal(7, target.Events.Count); Assert.Same(events[0].LogEvent, target.Events[0]); Assert.Same(events[1].LogEvent, target.Events[1]); Assert.Same(events[2].LogEvent, target.Events[2]); Assert.Same(events[3].LogEvent, target.Events[3]); Assert.Same(events[4].LogEvent, target.Events[4]); Assert.Same(events[5].LogEvent, target.Events[5]); Assert.Same(events[6].LogEvent, target.Events[6]); Assert.Equal(events.Length, exceptions.Count); } [Fact] public void PostFilteringTargetWrapperNoFiltersDefined() { var target = new MyTarget(); var wrapper = new PostFilteringTargetWrapper() { WrappedTarget = target, }; wrapper.Initialize(null); target.Initialize(null); var exceptions = new List<Exception>(); var events = new[] { new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Trace, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger3", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Error, "Logger1", "Hello").WithContinuation(exceptions.Add), }; wrapper.WriteAsyncLogEvents(events); // make sure all events went through Assert.Equal(7, target.Events.Count); Assert.Same(events[0].LogEvent, target.Events[0]); Assert.Same(events[1].LogEvent, target.Events[1]); Assert.Same(events[2].LogEvent, target.Events[2]); Assert.Same(events[3].LogEvent, target.Events[3]); Assert.Same(events[4].LogEvent, target.Events[4]); Assert.Same(events[5].LogEvent, target.Events[5]); Assert.Same(events[6].LogEvent, target.Events[6]); Assert.Equal(events.Length, exceptions.Count); } public class MyTarget : Target { public MyTarget() { this.Events = new List<LogEventInfo>(); } public MyTarget(string name) : this() { this.Name = name; } public List<LogEventInfo> Events { get; set; } protected override void Write(LogEventInfo logEvent) { this.Events.Add(logEvent); } } } }
namespace android.widget { [global::MonoJavaBridge.JavaClass()] public partial class ExpandableListView : android.widget.ListView { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected ExpandableListView(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaClass()] public partial class ExpandableListContextMenuInfo : java.lang.Object, android.view.ContextMenu_ContextMenuInfo { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected ExpandableListContextMenuInfo(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public ExpandableListContextMenuInfo(android.view.View arg0, long arg1, long arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.ExpandableListView.ExpandableListContextMenuInfo._m0.native == global::System.IntPtr.Zero) global::android.widget.ExpandableListView.ExpandableListContextMenuInfo._m0 = @__env.GetMethodIDNoThrow(global::android.widget.ExpandableListView.ExpandableListContextMenuInfo.staticClass, "<init>", "(Landroid/view/View;JJ)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.ExpandableListView.ExpandableListContextMenuInfo.staticClass, global::android.widget.ExpandableListView.ExpandableListContextMenuInfo._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); Init(@__env, handle); } internal static global::MonoJavaBridge.FieldId _targetView6047; public global::android.view.View targetView { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetObjectField(this.JvmHandle, _targetView6047)) as android.view.View; } set { } } internal static global::MonoJavaBridge.FieldId _packedPosition6048; public long packedPosition { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.GetLongField(this.JvmHandle, _packedPosition6048); } set { } } internal static global::MonoJavaBridge.FieldId _id6049; public long id { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.GetLongField(this.JvmHandle, _id6049); } set { } } static ExpandableListContextMenuInfo() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.ExpandableListView.ExpandableListContextMenuInfo.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/ExpandableListView$ExpandableListContextMenuInfo")); global::android.widget.ExpandableListView.ExpandableListContextMenuInfo._targetView6047 = @__env.GetFieldIDNoThrow(global::android.widget.ExpandableListView.ExpandableListContextMenuInfo.staticClass, "targetView", "Landroid/view/View;"); global::android.widget.ExpandableListView.ExpandableListContextMenuInfo._packedPosition6048 = @__env.GetFieldIDNoThrow(global::android.widget.ExpandableListView.ExpandableListContextMenuInfo.staticClass, "packedPosition", "J"); global::android.widget.ExpandableListView.ExpandableListContextMenuInfo._id6049 = @__env.GetFieldIDNoThrow(global::android.widget.ExpandableListView.ExpandableListContextMenuInfo.staticClass, "id", "J"); } } [global::MonoJavaBridge.JavaInterface(typeof(global::android.widget.ExpandableListView.OnChildClickListener_))] public partial interface OnChildClickListener : global::MonoJavaBridge.IJavaObject { bool onChildClick(android.widget.ExpandableListView arg0, android.view.View arg1, int arg2, int arg3, long arg4); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.widget.ExpandableListView.OnChildClickListener))] internal sealed partial class OnChildClickListener_ : java.lang.Object, OnChildClickListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal OnChildClickListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; bool android.widget.ExpandableListView.OnChildClickListener.onChildClick(android.widget.ExpandableListView arg0, android.view.View arg1, int arg2, int arg3, long arg4) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.ExpandableListView.OnChildClickListener_.staticClass, "onChildClick", "(Landroid/widget/ExpandableListView;Landroid/view/View;IIJ)Z", ref global::android.widget.ExpandableListView.OnChildClickListener_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); } static OnChildClickListener_() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.ExpandableListView.OnChildClickListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/ExpandableListView$OnChildClickListener")); } } public delegate bool OnChildClickListenerDelegate(android.widget.ExpandableListView arg0, android.view.View arg1, int arg2, int arg3, long arg4); internal partial class OnChildClickListenerDelegateWrapper : java.lang.Object, OnChildClickListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected OnChildClickListenerDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public OnChildClickListenerDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.ExpandableListView.OnChildClickListenerDelegateWrapper._m0.native == global::System.IntPtr.Zero) global::android.widget.ExpandableListView.OnChildClickListenerDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.widget.ExpandableListView.OnChildClickListenerDelegateWrapper.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.ExpandableListView.OnChildClickListenerDelegateWrapper.staticClass, global::android.widget.ExpandableListView.OnChildClickListenerDelegateWrapper._m0); Init(@__env, handle); } static OnChildClickListenerDelegateWrapper() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.ExpandableListView.OnChildClickListenerDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/ExpandableListView_OnChildClickListenerDelegateWrapper")); } } internal partial class OnChildClickListenerDelegateWrapper { private OnChildClickListenerDelegate myDelegate; public bool onChildClick(android.widget.ExpandableListView arg0, android.view.View arg1, int arg2, int arg3, long arg4) { return myDelegate(arg0, arg1, arg2, arg3, arg4); } public static implicit operator OnChildClickListenerDelegateWrapper(OnChildClickListenerDelegate d) { global::android.widget.ExpandableListView.OnChildClickListenerDelegateWrapper ret = new global::android.widget.ExpandableListView.OnChildClickListenerDelegateWrapper(); ret.myDelegate = d; global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret); return ret; } } [global::MonoJavaBridge.JavaInterface(typeof(global::android.widget.ExpandableListView.OnGroupClickListener_))] public partial interface OnGroupClickListener : global::MonoJavaBridge.IJavaObject { bool onGroupClick(android.widget.ExpandableListView arg0, android.view.View arg1, int arg2, long arg3); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.widget.ExpandableListView.OnGroupClickListener))] internal sealed partial class OnGroupClickListener_ : java.lang.Object, OnGroupClickListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal OnGroupClickListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; bool android.widget.ExpandableListView.OnGroupClickListener.onGroupClick(android.widget.ExpandableListView arg0, android.view.View arg1, int arg2, long arg3) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.ExpandableListView.OnGroupClickListener_.staticClass, "onGroupClick", "(Landroid/widget/ExpandableListView;Landroid/view/View;IJ)Z", ref global::android.widget.ExpandableListView.OnGroupClickListener_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } static OnGroupClickListener_() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.ExpandableListView.OnGroupClickListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/ExpandableListView$OnGroupClickListener")); } } public delegate bool OnGroupClickListenerDelegate(android.widget.ExpandableListView arg0, android.view.View arg1, int arg2, long arg3); internal partial class OnGroupClickListenerDelegateWrapper : java.lang.Object, OnGroupClickListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected OnGroupClickListenerDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public OnGroupClickListenerDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.ExpandableListView.OnGroupClickListenerDelegateWrapper._m0.native == global::System.IntPtr.Zero) global::android.widget.ExpandableListView.OnGroupClickListenerDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.widget.ExpandableListView.OnGroupClickListenerDelegateWrapper.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.ExpandableListView.OnGroupClickListenerDelegateWrapper.staticClass, global::android.widget.ExpandableListView.OnGroupClickListenerDelegateWrapper._m0); Init(@__env, handle); } static OnGroupClickListenerDelegateWrapper() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.ExpandableListView.OnGroupClickListenerDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/ExpandableListView_OnGroupClickListenerDelegateWrapper")); } } internal partial class OnGroupClickListenerDelegateWrapper { private OnGroupClickListenerDelegate myDelegate; public bool onGroupClick(android.widget.ExpandableListView arg0, android.view.View arg1, int arg2, long arg3) { return myDelegate(arg0, arg1, arg2, arg3); } public static implicit operator OnGroupClickListenerDelegateWrapper(OnGroupClickListenerDelegate d) { global::android.widget.ExpandableListView.OnGroupClickListenerDelegateWrapper ret = new global::android.widget.ExpandableListView.OnGroupClickListenerDelegateWrapper(); ret.myDelegate = d; global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret); return ret; } } [global::MonoJavaBridge.JavaInterface(typeof(global::android.widget.ExpandableListView.OnGroupCollapseListener_))] public partial interface OnGroupCollapseListener : global::MonoJavaBridge.IJavaObject { void onGroupCollapse(int arg0); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.widget.ExpandableListView.OnGroupCollapseListener))] internal sealed partial class OnGroupCollapseListener_ : java.lang.Object, OnGroupCollapseListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal OnGroupCollapseListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; void android.widget.ExpandableListView.OnGroupCollapseListener.onGroupCollapse(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.ExpandableListView.OnGroupCollapseListener_.staticClass, "onGroupCollapse", "(I)V", ref global::android.widget.ExpandableListView.OnGroupCollapseListener_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } static OnGroupCollapseListener_() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.ExpandableListView.OnGroupCollapseListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/ExpandableListView$OnGroupCollapseListener")); } } public delegate void OnGroupCollapseListenerDelegate(int arg0); internal partial class OnGroupCollapseListenerDelegateWrapper : java.lang.Object, OnGroupCollapseListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected OnGroupCollapseListenerDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public OnGroupCollapseListenerDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.ExpandableListView.OnGroupCollapseListenerDelegateWrapper._m0.native == global::System.IntPtr.Zero) global::android.widget.ExpandableListView.OnGroupCollapseListenerDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.widget.ExpandableListView.OnGroupCollapseListenerDelegateWrapper.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.ExpandableListView.OnGroupCollapseListenerDelegateWrapper.staticClass, global::android.widget.ExpandableListView.OnGroupCollapseListenerDelegateWrapper._m0); Init(@__env, handle); } static OnGroupCollapseListenerDelegateWrapper() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.ExpandableListView.OnGroupCollapseListenerDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/ExpandableListView_OnGroupCollapseListenerDelegateWrapper")); } } internal partial class OnGroupCollapseListenerDelegateWrapper { private OnGroupCollapseListenerDelegate myDelegate; public void onGroupCollapse(int arg0) { myDelegate(arg0); } public static implicit operator OnGroupCollapseListenerDelegateWrapper(OnGroupCollapseListenerDelegate d) { global::android.widget.ExpandableListView.OnGroupCollapseListenerDelegateWrapper ret = new global::android.widget.ExpandableListView.OnGroupCollapseListenerDelegateWrapper(); ret.myDelegate = d; global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret); return ret; } } [global::MonoJavaBridge.JavaInterface(typeof(global::android.widget.ExpandableListView.OnGroupExpandListener_))] public partial interface OnGroupExpandListener : global::MonoJavaBridge.IJavaObject { void onGroupExpand(int arg0); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.widget.ExpandableListView.OnGroupExpandListener))] internal sealed partial class OnGroupExpandListener_ : java.lang.Object, OnGroupExpandListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal OnGroupExpandListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; void android.widget.ExpandableListView.OnGroupExpandListener.onGroupExpand(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.ExpandableListView.OnGroupExpandListener_.staticClass, "onGroupExpand", "(I)V", ref global::android.widget.ExpandableListView.OnGroupExpandListener_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } static OnGroupExpandListener_() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.ExpandableListView.OnGroupExpandListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/ExpandableListView$OnGroupExpandListener")); } } public delegate void OnGroupExpandListenerDelegate(int arg0); internal partial class OnGroupExpandListenerDelegateWrapper : java.lang.Object, OnGroupExpandListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected OnGroupExpandListenerDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public OnGroupExpandListenerDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.ExpandableListView.OnGroupExpandListenerDelegateWrapper._m0.native == global::System.IntPtr.Zero) global::android.widget.ExpandableListView.OnGroupExpandListenerDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.widget.ExpandableListView.OnGroupExpandListenerDelegateWrapper.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.ExpandableListView.OnGroupExpandListenerDelegateWrapper.staticClass, global::android.widget.ExpandableListView.OnGroupExpandListenerDelegateWrapper._m0); Init(@__env, handle); } static OnGroupExpandListenerDelegateWrapper() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.ExpandableListView.OnGroupExpandListenerDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/ExpandableListView_OnGroupExpandListenerDelegateWrapper")); } } internal partial class OnGroupExpandListenerDelegateWrapper { private OnGroupExpandListenerDelegate myDelegate; public void onGroupExpand(int arg0) { myDelegate(arg0); } public static implicit operator OnGroupExpandListenerDelegateWrapper(OnGroupExpandListenerDelegate d) { global::android.widget.ExpandableListView.OnGroupExpandListenerDelegateWrapper ret = new global::android.widget.ExpandableListView.OnGroupExpandListenerDelegateWrapper(); ret.myDelegate = d; global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret); return ret; } } private static global::MonoJavaBridge.MethodId _m0; public override void onRestoreInstanceState(android.os.Parcelable arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.ExpandableListView.staticClass, "onRestoreInstanceState", "(Landroid/os/Parcelable;)V", ref global::android.widget.ExpandableListView._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m1; public override global::android.os.Parcelable onSaveInstanceState() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<android.os.Parcelable>(this, global::android.widget.ExpandableListView.staticClass, "onSaveInstanceState", "()Landroid/os/Parcelable;", ref global::android.widget.ExpandableListView._m1) as android.os.Parcelable; } private static global::MonoJavaBridge.MethodId _m2; protected override void dispatchDraw(android.graphics.Canvas arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.ExpandableListView.staticClass, "dispatchDraw", "(Landroid/graphics/Canvas;)V", ref global::android.widget.ExpandableListView._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m3; public override void setAdapter(android.widget.ListAdapter arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.ExpandableListView.staticClass, "setAdapter", "(Landroid/widget/ListAdapter;)V", ref global::android.widget.ExpandableListView._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m4; public virtual void setAdapter(android.widget.ExpandableListAdapter arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.ExpandableListView.staticClass, "setAdapter", "(Landroid/widget/ExpandableListAdapter;)V", ref global::android.widget.ExpandableListView._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new global::android.widget.AdapterView.OnItemClickListener OnItemClickListener { set { setOnItemClickListener(value); } } private static global::MonoJavaBridge.MethodId _m5; public override void setOnItemClickListener(android.widget.AdapterView.OnItemClickListener arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.ExpandableListView.staticClass, "setOnItemClickListener", "(Landroid/widget/AdapterView$OnItemClickListener;)V", ref global::android.widget.ExpandableListView._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void setOnItemClickListener(global::android.widget.AdapterView.OnItemClickListenerDelegate arg0) { setOnItemClickListener((global::android.widget.AdapterView.OnItemClickListenerDelegateWrapper)arg0); } private static global::MonoJavaBridge.MethodId _m6; public override bool performItemClick(android.view.View arg0, int arg1, long arg2) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.ExpandableListView.staticClass, "performItemClick", "(Landroid/view/View;IJ)Z", ref global::android.widget.ExpandableListView._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } public new global::android.widget.ListAdapter Adapter { get { return getAdapter(); } set { setAdapter(value); } } private static global::MonoJavaBridge.MethodId _m7; public virtual global::android.widget.ListAdapter getAdapter() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<android.widget.ListAdapter>(this, global::android.widget.ExpandableListView.staticClass, "getAdapter", "()Landroid/widget/ListAdapter;", ref global::android.widget.ExpandableListView._m7) as android.widget.ListAdapter; } public new global::android.widget.ExpandableListAdapter ExpandableListAdapter { get { return getExpandableListAdapter(); } } private static global::MonoJavaBridge.MethodId _m8; public virtual global::android.widget.ExpandableListAdapter getExpandableListAdapter() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<android.widget.ExpandableListAdapter>(this, global::android.widget.ExpandableListView.staticClass, "getExpandableListAdapter", "()Landroid/widget/ExpandableListAdapter;", ref global::android.widget.ExpandableListView._m8) as android.widget.ExpandableListAdapter; } public new long SelectedId { get { return getSelectedId(); } } private static global::MonoJavaBridge.MethodId _m9; public virtual long getSelectedId() { return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::android.widget.ExpandableListView.staticClass, "getSelectedId", "()J", ref global::android.widget.ExpandableListView._m9); } public new long SelectedPosition { get { return getSelectedPosition(); } } private static global::MonoJavaBridge.MethodId _m10; public virtual long getSelectedPosition() { return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::android.widget.ExpandableListView.staticClass, "getSelectedPosition", "()J", ref global::android.widget.ExpandableListView._m10); } private static global::MonoJavaBridge.MethodId _m11; public virtual bool setSelectedChild(int arg0, int arg1, bool arg2) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.ExpandableListView.staticClass, "setSelectedChild", "(IIZ)Z", ref global::android.widget.ExpandableListView._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } public new int SelectedGroup { set { setSelectedGroup(value); } } private static global::MonoJavaBridge.MethodId _m12; public virtual void setSelectedGroup(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.ExpandableListView.staticClass, "setSelectedGroup", "(I)V", ref global::android.widget.ExpandableListView._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new global::android.graphics.drawable.Drawable ChildDivider { set { setChildDivider(value); } } private static global::MonoJavaBridge.MethodId _m13; public virtual void setChildDivider(android.graphics.drawable.Drawable arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.ExpandableListView.staticClass, "setChildDivider", "(Landroid/graphics/drawable/Drawable;)V", ref global::android.widget.ExpandableListView._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m14; public virtual bool expandGroup(int arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.ExpandableListView.staticClass, "expandGroup", "(I)Z", ref global::android.widget.ExpandableListView._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m15; public virtual bool collapseGroup(int arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.ExpandableListView.staticClass, "collapseGroup", "(I)Z", ref global::android.widget.ExpandableListView._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m16; public virtual void setOnGroupCollapseListener(android.widget.ExpandableListView.OnGroupCollapseListener arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.ExpandableListView.staticClass, "setOnGroupCollapseListener", "(Landroid/widget/ExpandableListView$OnGroupCollapseListener;)V", ref global::android.widget.ExpandableListView._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void setOnGroupCollapseListener(global::android.widget.ExpandableListView.OnGroupCollapseListenerDelegate arg0) { setOnGroupCollapseListener((global::android.widget.ExpandableListView.OnGroupCollapseListenerDelegateWrapper)arg0); } private static global::MonoJavaBridge.MethodId _m17; public virtual void setOnGroupExpandListener(android.widget.ExpandableListView.OnGroupExpandListener arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.ExpandableListView.staticClass, "setOnGroupExpandListener", "(Landroid/widget/ExpandableListView$OnGroupExpandListener;)V", ref global::android.widget.ExpandableListView._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void setOnGroupExpandListener(global::android.widget.ExpandableListView.OnGroupExpandListenerDelegate arg0) { setOnGroupExpandListener((global::android.widget.ExpandableListView.OnGroupExpandListenerDelegateWrapper)arg0); } private static global::MonoJavaBridge.MethodId _m18; public virtual void setOnGroupClickListener(android.widget.ExpandableListView.OnGroupClickListener arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.ExpandableListView.staticClass, "setOnGroupClickListener", "(Landroid/widget/ExpandableListView$OnGroupClickListener;)V", ref global::android.widget.ExpandableListView._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void setOnGroupClickListener(global::android.widget.ExpandableListView.OnGroupClickListenerDelegate arg0) { setOnGroupClickListener((global::android.widget.ExpandableListView.OnGroupClickListenerDelegateWrapper)arg0); } private static global::MonoJavaBridge.MethodId _m19; public virtual void setOnChildClickListener(android.widget.ExpandableListView.OnChildClickListener arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.ExpandableListView.staticClass, "setOnChildClickListener", "(Landroid/widget/ExpandableListView$OnChildClickListener;)V", ref global::android.widget.ExpandableListView._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void setOnChildClickListener(global::android.widget.ExpandableListView.OnChildClickListenerDelegate arg0) { setOnChildClickListener((global::android.widget.ExpandableListView.OnChildClickListenerDelegateWrapper)arg0); } private static global::MonoJavaBridge.MethodId _m20; public virtual long getExpandableListPosition(int arg0) { return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::android.widget.ExpandableListView.staticClass, "getExpandableListPosition", "(I)J", ref global::android.widget.ExpandableListView._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m21; public virtual int getFlatListPosition(long arg0) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.widget.ExpandableListView.staticClass, "getFlatListPosition", "(J)I", ref global::android.widget.ExpandableListView._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m22; public virtual bool isGroupExpanded(int arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.ExpandableListView.staticClass, "isGroupExpanded", "(I)Z", ref global::android.widget.ExpandableListView._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m23; public static int getPackedPositionType(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.ExpandableListView._m23.native == global::System.IntPtr.Zero) global::android.widget.ExpandableListView._m23 = @__env.GetStaticMethodIDNoThrow(global::android.widget.ExpandableListView.staticClass, "getPackedPositionType", "(J)I"); return @__env.CallStaticIntMethod(android.widget.ExpandableListView.staticClass, global::android.widget.ExpandableListView._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m24; public static int getPackedPositionGroup(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.ExpandableListView._m24.native == global::System.IntPtr.Zero) global::android.widget.ExpandableListView._m24 = @__env.GetStaticMethodIDNoThrow(global::android.widget.ExpandableListView.staticClass, "getPackedPositionGroup", "(J)I"); return @__env.CallStaticIntMethod(android.widget.ExpandableListView.staticClass, global::android.widget.ExpandableListView._m24, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m25; public static int getPackedPositionChild(long arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.ExpandableListView._m25.native == global::System.IntPtr.Zero) global::android.widget.ExpandableListView._m25 = @__env.GetStaticMethodIDNoThrow(global::android.widget.ExpandableListView.staticClass, "getPackedPositionChild", "(J)I"); return @__env.CallStaticIntMethod(android.widget.ExpandableListView.staticClass, global::android.widget.ExpandableListView._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m26; public static long getPackedPositionForChild(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.ExpandableListView._m26.native == global::System.IntPtr.Zero) global::android.widget.ExpandableListView._m26 = @__env.GetStaticMethodIDNoThrow(global::android.widget.ExpandableListView.staticClass, "getPackedPositionForChild", "(II)J"); return @__env.CallStaticLongMethod(android.widget.ExpandableListView.staticClass, global::android.widget.ExpandableListView._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m27; public static long getPackedPositionForGroup(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.ExpandableListView._m27.native == global::System.IntPtr.Zero) global::android.widget.ExpandableListView._m27 = @__env.GetStaticMethodIDNoThrow(global::android.widget.ExpandableListView.staticClass, "getPackedPositionForGroup", "(I)J"); return @__env.CallStaticLongMethod(android.widget.ExpandableListView.staticClass, global::android.widget.ExpandableListView._m27, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new global::android.graphics.drawable.Drawable ChildIndicator { set { setChildIndicator(value); } } private static global::MonoJavaBridge.MethodId _m28; public virtual void setChildIndicator(android.graphics.drawable.Drawable arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.ExpandableListView.staticClass, "setChildIndicator", "(Landroid/graphics/drawable/Drawable;)V", ref global::android.widget.ExpandableListView._m28, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m29; public virtual void setChildIndicatorBounds(int arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.ExpandableListView.staticClass, "setChildIndicatorBounds", "(II)V", ref global::android.widget.ExpandableListView._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } public new global::android.graphics.drawable.Drawable GroupIndicator { set { setGroupIndicator(value); } } private static global::MonoJavaBridge.MethodId _m30; public virtual void setGroupIndicator(android.graphics.drawable.Drawable arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.ExpandableListView.staticClass, "setGroupIndicator", "(Landroid/graphics/drawable/Drawable;)V", ref global::android.widget.ExpandableListView._m30, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m31; public virtual void setIndicatorBounds(int arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.ExpandableListView.staticClass, "setIndicatorBounds", "(II)V", ref global::android.widget.ExpandableListView._m31, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m32; public ExpandableListView(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.ExpandableListView._m32.native == global::System.IntPtr.Zero) global::android.widget.ExpandableListView._m32 = @__env.GetMethodIDNoThrow(global::android.widget.ExpandableListView.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.ExpandableListView.staticClass, global::android.widget.ExpandableListView._m32, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m33; public ExpandableListView(android.content.Context arg0, android.util.AttributeSet arg1, int arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.ExpandableListView._m33.native == global::System.IntPtr.Zero) global::android.widget.ExpandableListView._m33 = @__env.GetMethodIDNoThrow(global::android.widget.ExpandableListView.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;I)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.ExpandableListView.staticClass, global::android.widget.ExpandableListView._m33, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m34; public ExpandableListView(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.widget.ExpandableListView._m34.native == global::System.IntPtr.Zero) global::android.widget.ExpandableListView._m34 = @__env.GetMethodIDNoThrow(global::android.widget.ExpandableListView.staticClass, "<init>", "(Landroid/content/Context;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.ExpandableListView.staticClass, global::android.widget.ExpandableListView._m34, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } public static int PACKED_POSITION_TYPE_GROUP { get { return 0; } } public static int PACKED_POSITION_TYPE_CHILD { get { return 1; } } public static int PACKED_POSITION_TYPE_NULL { get { return 2; } } public static long PACKED_POSITION_VALUE_NULL { get { return 4294967295L; } } public static int CHILD_INDICATOR_INHERIT { get { return -1; } } static ExpandableListView() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.ExpandableListView.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/ExpandableListView")); } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.ComponentModel; using System.IO; using System.Linq; using DotSpatial.Projections; using DotSpatial.Serialization; namespace DotSpatial.Data { /// <summary> /// DataSet. /// </summary> public class DataSet : DisposeBase, IDataSet { #region Fields private static volatile bool canProject; private static volatile bool projectionLibraryTested; private string _fileName; private IProgressHandler _progressHandler; private ProgressMeter _progressMeter; private string _proj4String; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="DataSet"/> class. /// </summary> protected DataSet() { _progressHandler = DataManager.DefaultDataManager.ProgressHandler; } #endregion #region Properties /// <summary> /// Gets a value indicating whether the DotSpatial.Projections assembly is loaded. /// </summary> /// <returns>Boolean, true if the value can reproject.</returns> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool CanReproject => ProjectionSupported() && Projection != null && Projection.IsValid; /// <summary> /// Gets or sets the extent for the dataset. Usages to Envelope were replaced /// as they required an explicit using to DotSpatial.Topology which is not /// as intuitive. Extent.ToEnvelope() and new Extent(myEnvelope) convert them. /// This is designed to be a virtual member to be overridden by subclasses, /// and should not be called directly by the constructor of inheriting classes. /// </summary> public virtual Extent Extent { get { return MyExtent; } set { MyExtent = value; } } /// <summary> /// Gets or sets the file name of a file based data set. The file name should be the absolute path including /// the file extension. For data sets coming from a database or a web service, the Filename property is NULL. /// </summary> public virtual string Filename { get { return _fileName; } set { _fileName = string.IsNullOrEmpty(value) ? null : Path.GetFullPath(value); } } /// <summary> /// Gets or sets the current file path. This is the relative path relative to the current project folder. /// For data sets coming from a database or a web service, the FilePath property is NULL. /// This property is used when saving source file information to a DSPX project. /// </summary> [Serialize("FilePath", ConstructorArgumentIndex = 0, UseCase = SerializeAttribute.UseCases.Both)] [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual string FilePath { get { // do not construct FilePath for DataSets without a Filename return string.IsNullOrEmpty(Filename) ? null : FilePathUtils.RelativePathTo(Filename); } set { Filename = value; } } /// <summary> /// Gets or sets the string name. /// </summary> public string Name { get; set; } /// <summary> /// Gets or sets the progress handler to use for internal actions taken by this dataset. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual IProgressHandler ProgressHandler { get { return _progressHandler; } set { _progressHandler = value; if (_progressMeter == null && value != null) { _progressMeter = new ProgressMeter(_progressHandler); } } } /// <summary> /// Gets or sets the projection string. /// </summary> public ProjectionInfo Projection { get; set; } /// <summary> /// Gets or sets the raw projection string for this dataset. This handles both the /// case where projection is unavailable but a projection string needs to /// be passed around, and the case when a string is not recognized by the /// DotSpatial.Projections library. This is not format restricted, but should match /// the original data source as closely as possible. Setting this will also set /// the Projection if the Projection library is available and the format successfully /// defines a transform by either treating it as an Esri string or a proj4 string. /// </summary> public string ProjectionString { get { if (!string.IsNullOrEmpty(_proj4String)) return _proj4String; if (CanReproject) return Projection.ToProj4String(); return _proj4String; } set { if (_proj4String == value) return; _proj4String = value; var test = ProjectionInfo.FromProj4String(value); if (test.Transform == null) { // regardless of the result, the "Transform" will be null if this fails. test.TryParseEsriString(value); } if (test.Transform != null) { Projection = test; } } } /// <summary> /// Gets or sets the cached extent variable. The public Extent is the virtual accessor, /// and should not be used from a constructor. MyExtent is protected, not virtual, /// and is only visible to inheriting classes, and can be safely set in the constructor. /// </summary> protected Extent MyExtent { get; set; } /// <summary> /// Gets or sets the progress meter. This is an internal place holder to make it easier to pass around a single progress meter /// between methods. This will use lazy instantiation if it is requested before one has been created. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] protected ProgressMeter ProgressMeter { get { return _progressMeter ?? (_progressMeter = new ProgressMeter(ProgressHandler)); } set { _progressMeter = value; } } #endregion #region Methods /// <summary> /// Gets whether or not projection is based on having the libraries available. /// </summary> /// <returns>True, if the projection library was found.</returns> public static bool ProjectionSupported() { if (projectionLibraryTested) { return canProject; } projectionLibraryTested = true; canProject = AppDomain.CurrentDomain.GetAssemblies().Any(d => d.GetName().Name == "DotSpatial.Projections"); return canProject; } /// <summary> /// This can be overridden in specific classes if necessary. /// </summary> public virtual void Close() { } /// <summary> /// Reprojects all of the in-ram vertices of featuresets, or else this /// simply updates the "Bounds" of the image object. /// This will also update the projection to be the specified projection. /// </summary> /// <param name="targetProjection"> /// The projection information to reproject the coordinates to. /// </param> public virtual void Reproject(ProjectionInfo targetProjection) { } /// <summary> /// Allows overriding the dispose behavior to handle any resources in addition to what are handled in the /// image data class. /// </summary> /// <param name="disposeManagedResources">A Boolean value that indicates whether the overriding method /// should dispose managed resources, or just the unmanaged ones.</param> protected override void Dispose(bool disposeManagedResources) { if (disposeManagedResources) { Name = null; Projection = null; _progressHandler = null; _progressMeter = null; } base.Dispose(disposeManagedResources); } #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! using gagvr = Google.Ads.GoogleAds.V8.Resources; using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V8.Resources { /// <summary>Resource name for the <c>CarrierConstant</c> resource.</summary> public sealed partial class CarrierConstantName : gax::IResourceName, sys::IEquatable<CarrierConstantName> { /// <summary>The possible contents of <see cref="CarrierConstantName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary>A resource name with pattern <c>carrierConstants/{criterion_id}</c>.</summary> Criterion = 1, } private static gax::PathTemplate s_criterion = new gax::PathTemplate("carrierConstants/{criterion_id}"); /// <summary>Creates a <see cref="CarrierConstantName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="CarrierConstantName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static CarrierConstantName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new CarrierConstantName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="CarrierConstantName"/> with the pattern <c>carrierConstants/{criterion_id}</c>. /// </summary> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="CarrierConstantName"/> constructed from the provided ids.</returns> public static CarrierConstantName FromCriterion(string criterionId) => new CarrierConstantName(ResourceNameType.Criterion, criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="CarrierConstantName"/> with pattern /// <c>carrierConstants/{criterion_id}</c>. /// </summary> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CarrierConstantName"/> with pattern /// <c>carrierConstants/{criterion_id}</c>. /// </returns> public static string Format(string criterionId) => FormatCriterion(criterionId); /// <summary> /// Formats the IDs into the string representation of this <see cref="CarrierConstantName"/> with pattern /// <c>carrierConstants/{criterion_id}</c>. /// </summary> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CarrierConstantName"/> with pattern /// <c>carrierConstants/{criterion_id}</c>. /// </returns> public static string FormatCriterion(string criterionId) => s_criterion.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId))); /// <summary> /// Parses the given resource name string into a new <see cref="CarrierConstantName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"><item><description><c>carrierConstants/{criterion_id}</c></description></item></list> /// </remarks> /// <param name="carrierConstantName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="CarrierConstantName"/> if successful.</returns> public static CarrierConstantName Parse(string carrierConstantName) => Parse(carrierConstantName, false); /// <summary> /// Parses the given resource name string into a new <see cref="CarrierConstantName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"><item><description><c>carrierConstants/{criterion_id}</c></description></item></list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="carrierConstantName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="CarrierConstantName"/> if successful.</returns> public static CarrierConstantName Parse(string carrierConstantName, bool allowUnparsed) => TryParse(carrierConstantName, allowUnparsed, out CarrierConstantName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CarrierConstantName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"><item><description><c>carrierConstants/{criterion_id}</c></description></item></list> /// </remarks> /// <param name="carrierConstantName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="CarrierConstantName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string carrierConstantName, out CarrierConstantName result) => TryParse(carrierConstantName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CarrierConstantName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"><item><description><c>carrierConstants/{criterion_id}</c></description></item></list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="carrierConstantName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="CarrierConstantName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string carrierConstantName, bool allowUnparsed, out CarrierConstantName result) { gax::GaxPreconditions.CheckNotNull(carrierConstantName, nameof(carrierConstantName)); gax::TemplatedResourceName resourceName; if (s_criterion.TryParseName(carrierConstantName, out resourceName)) { result = FromCriterion(resourceName[0]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(carrierConstantName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private CarrierConstantName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string criterionId = null) { Type = type; UnparsedResource = unparsedResourceName; CriterionId = criterionId; } /// <summary> /// Constructs a new instance of a <see cref="CarrierConstantName"/> class from the component parts of pattern /// <c>carrierConstants/{criterion_id}</c> /// </summary> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> public CarrierConstantName(string criterionId) : this(ResourceNameType.Criterion, criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Criterion</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CriterionId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.Criterion: return s_criterion.Expand(CriterionId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as CarrierConstantName); /// <inheritdoc/> public bool Equals(CarrierConstantName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(CarrierConstantName a, CarrierConstantName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(CarrierConstantName a, CarrierConstantName b) => !(a == b); } public partial class CarrierConstant { /// <summary> /// <see cref="gagvr::CarrierConstantName"/>-typed view over the <see cref="ResourceName"/> resource name /// property. /// </summary> internal CarrierConstantName ResourceNameAsCarrierConstantName { get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::CarrierConstantName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagvr::CarrierConstantName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> internal CarrierConstantName CarrierConstantName { get => string.IsNullOrEmpty(Name) ? null : gagvr::CarrierConstantName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using Moq; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Controls.Templates; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.UnitTests; using Avalonia.VisualTree; using Xunit; namespace Avalonia.Controls.UnitTests.Primitives { public class TemplatedControlTests { [Fact] public void Template_Doesnt_Get_Executed_On_Set() { bool executed = false; var template = new FuncControlTemplate(_ => { executed = true; return new Control(); }); var target = new TemplatedControl { Template = template, }; Assert.False(executed); } [Fact] public void Template_Gets_Executed_On_Measure() { bool executed = false; var template = new FuncControlTemplate(_ => { executed = true; return new Control(); }); var target = new TemplatedControl { Template = template, }; target.Measure(new Size(100, 100)); Assert.True(executed); } [Fact] public void ApplyTemplate_Should_Create_Visual_Children() { var target = new TemplatedControl { Template = new FuncControlTemplate(_ => new Decorator { Child = new Panel { Children = { new TextBlock(), new Border(), } } }), }; target.ApplyTemplate(); var types = target.GetVisualDescendants().Select(x => x.GetType()).ToList(); Assert.Equal( new[] { typeof(Decorator), typeof(Panel), typeof(TextBlock), typeof(Border) }, types); Assert.Empty(target.GetLogicalChildren()); } [Fact] public void Templated_Child_Should_Be_NameScope() { var target = new TemplatedControl { Template = new FuncControlTemplate(_ => new Decorator { Child = new Panel { Children = { new TextBlock(), new Border(), } } }), }; target.ApplyTemplate(); Assert.NotNull(NameScope.GetNameScope((Control)target.GetVisualChildren().Single())); } [Fact] public void Templated_Children_Should_Have_TemplatedParent_Set() { var target = new TemplatedControl { Template = new FuncControlTemplate(_ => new Decorator { Child = new Panel { Children = { new TextBlock(), new Border(), } } }), }; target.ApplyTemplate(); var templatedParents = target.GetVisualDescendants() .OfType<IControl>() .Select(x => x.TemplatedParent) .ToList(); Assert.Equal(4, templatedParents.Count); Assert.True(templatedParents.All(x => x == target)); } [Fact] public void Templated_Child_Should_Have_Parent_Set() { var target = new TemplatedControl { Template = new FuncControlTemplate(_ => new Decorator()) }; target.ApplyTemplate(); var child = (Decorator)target.GetVisualChildren().Single(); Assert.Equal(target, child.Parent); Assert.Equal(target, child.GetLogicalParent()); } [Fact] public void Nested_Templated_Control_Should_Not_Have_Template_Applied() { var target = new TemplatedControl { Template = new FuncControlTemplate(_ => new ScrollViewer()) }; target.ApplyTemplate(); var child = (ScrollViewer)target.GetVisualChildren().Single(); Assert.Empty(child.GetVisualChildren()); } [Fact] public void Templated_Children_Should_Be_Styled() { using (UnitTestApplication.Start(TestServices.MockStyler)) { TestTemplatedControl target; var root = new TestRoot { Child = target = new TestTemplatedControl { Template = new FuncControlTemplate(_ => { return new StackPanel { Children = { new TextBlock { } } }; }), } }; target.ApplyTemplate(); var styler = Mock.Get(UnitTestApplication.Current.Services.Styler); styler.Verify(x => x.ApplyStyles(It.IsAny<TestTemplatedControl>()), Times.Once()); styler.Verify(x => x.ApplyStyles(It.IsAny<StackPanel>()), Times.Once()); styler.Verify(x => x.ApplyStyles(It.IsAny<TextBlock>()), Times.Once()); } } [Fact] public void Nested_Templated_Controls_Have_Correct_TemplatedParent() { var target = new TestTemplatedControl { Template = new FuncControlTemplate(_ => { return new ContentControl { Template = new FuncControlTemplate(parent => { return new Border { Child = new ContentPresenter { [~ContentPresenter.ContentProperty] = parent.GetObservable(ContentControl.ContentProperty).ToBinding(), } }; }), Content = new Decorator { Child = new TextBlock() } }; }), }; target.ApplyTemplate(); var contentControl = target.GetTemplateChildren().OfType<ContentControl>().Single(); contentControl.ApplyTemplate(); var border = contentControl.GetTemplateChildren().OfType<Border>().Single(); var presenter = contentControl.GetTemplateChildren().OfType<ContentPresenter>().Single(); var decorator = (Decorator)presenter.Content; var textBlock = (TextBlock)decorator.Child; Assert.Equal(target, contentControl.TemplatedParent); Assert.Equal(contentControl, border.TemplatedParent); Assert.Equal(contentControl, presenter.TemplatedParent); Assert.Equal(target, decorator.TemplatedParent); Assert.Equal(target, textBlock.TemplatedParent); } [Fact] public void Nested_TemplatedControls_Should_Register_With_Correct_NameScope() { var target = new ContentControl { Template = new FuncControlTemplate<ContentControl>(ScrollingContentControlTemplate), Content = "foo" }; var root = new TestRoot { Child = target }; target.ApplyTemplate(); var border = target.GetVisualChildren().FirstOrDefault(); Assert.IsType<Border>(border); var scrollViewer = border.GetVisualChildren().FirstOrDefault(); Assert.IsType<ScrollViewer>(scrollViewer); ((ScrollViewer)scrollViewer).ApplyTemplate(); var scrollContentPresenter = scrollViewer.GetVisualChildren().FirstOrDefault(); Assert.IsType<ScrollContentPresenter>(scrollContentPresenter); ((ContentPresenter)scrollContentPresenter).UpdateChild(); var contentPresenter = scrollContentPresenter.GetVisualChildren().FirstOrDefault(); Assert.IsType<ContentPresenter>(contentPresenter); var borderNs = NameScope.GetNameScope((Control)border); var scrollContentPresenterNs = NameScope.GetNameScope((Control)scrollContentPresenter); Assert.NotNull(borderNs); Assert.Same(scrollViewer, borderNs.Find("ScrollViewer")); Assert.Same(contentPresenter, borderNs.Find("PART_ContentPresenter")); Assert.Same(scrollContentPresenter, scrollContentPresenterNs.Find("PART_ContentPresenter")); } [Fact] public void ApplyTemplate_Should_Raise_TemplateApplied() { var target = new TestTemplatedControl { Template = new FuncControlTemplate(_ => new Decorator()) }; var raised = false; target.TemplateApplied += (s, e) => { Assert.Equal(TemplatedControl.TemplateAppliedEvent, e.RoutedEvent); Assert.Same(target, e.Source); Assert.NotNull(e.NameScope); raised = true; }; target.ApplyTemplate(); Assert.True(raised); } [Fact] public void Applying_New_Template_Clears_TemplatedParent_Of_Old_Template_Children() { var target = new TestTemplatedControl { Template = new FuncControlTemplate(_ => new Decorator { Child = new Border(), }) }; target.ApplyTemplate(); var decorator = (Decorator)target.GetVisualChildren().Single(); var border = (Border)decorator.Child; Assert.Equal(target, decorator.TemplatedParent); Assert.Equal(target, border.TemplatedParent); target.Template = new FuncControlTemplate(_ => new Canvas()); // Templated children should not be removed here: the control may be re-added // somewhere with the same template, so they could still be of use. Assert.Same(decorator, target.GetVisualChildren().Single()); Assert.Equal(target, decorator.TemplatedParent); Assert.Equal(target, border.TemplatedParent); target.ApplyTemplate(); Assert.Null(decorator.TemplatedParent); Assert.Null(border.TemplatedParent); } [Fact] public void TemplateChild_AttachedToLogicalTree_Should_Be_Raised() { Border templateChild = new Border(); var root = new TestRoot { Child = new TestTemplatedControl { Template = new FuncControlTemplate(_ => new Decorator { Child = templateChild, }) } }; var raised = false; templateChild.AttachedToLogicalTree += (s, e) => raised = true; root.Child.ApplyTemplate(); Assert.True(raised); } [Fact] public void TemplateChild_DetachedFromLogicalTree_Should_Be_Raised() { Border templateChild = new Border(); var root = new TestRoot { Child = new TestTemplatedControl { Template = new FuncControlTemplate(_ => new Decorator { Child = templateChild, }) } }; root.Child.ApplyTemplate(); var raised = false; templateChild.DetachedFromLogicalTree += (s, e) => raised = true; root.Child = null; Assert.True(raised); } [Fact] public void Removing_From_LogicalTree_Should_Not_Remove_Child() { using (UnitTestApplication.Start(TestServices.RealStyler)) { Border templateChild = new Border(); TestTemplatedControl target; var root = new TestRoot { Styles = { new Style(x => x.OfType<TestTemplatedControl>()) { Setters = new[] { new Setter( TemplatedControl.TemplateProperty, new FuncControlTemplate(_ => new Decorator { Child = new Border(), })) } } }, Child = target = new TestTemplatedControl() }; Assert.NotNull(target.Template); target.ApplyTemplate(); root.Child = null; Assert.Null(target.Template); Assert.IsType<Decorator>(target.GetVisualChildren().Single()); } } [Fact] public void Re_adding_To_Same_LogicalTree_Should_Not_Recreate_Template() { using (UnitTestApplication.Start(TestServices.RealStyler)) { TestTemplatedControl target; var root = new TestRoot { Styles = { new Style(x => x.OfType<TestTemplatedControl>()) { Setters = new[] { new Setter( TemplatedControl.TemplateProperty, new FuncControlTemplate(_ => new Decorator { Child = new Border(), })) } } }, Child = target = new TestTemplatedControl() }; Assert.NotNull(target.Template); target.ApplyTemplate(); var expected = (Decorator)target.GetVisualChildren().Single(); root.Child = null; root.Child = target; target.ApplyTemplate(); Assert.Same(expected, target.GetVisualChildren().Single()); } } [Fact] public void Re_adding_To_Different_LogicalTree_Should_Recreate_Template() { using (UnitTestApplication.Start(TestServices.RealStyler)) { TestTemplatedControl target; var root = new TestRoot { Styles = { new Style(x => x.OfType<TestTemplatedControl>()) { Setters = new[] { new Setter( TemplatedControl.TemplateProperty, new FuncControlTemplate(_ => new Decorator { Child = new Border(), })) } } }, Child = target = new TestTemplatedControl() }; var root2 = new TestRoot { Styles = { new Style(x => x.OfType<TestTemplatedControl>()) { Setters = new[] { new Setter( TemplatedControl.TemplateProperty, new FuncControlTemplate(_ => new Decorator { Child = new Border(), })) } } }, }; Assert.NotNull(target.Template); target.ApplyTemplate(); var expected = (Decorator)target.GetVisualChildren().Single(); root.Child = null; root2.Child = target; target.ApplyTemplate(); var child = target.GetVisualChildren().Single(); Assert.NotNull(target.Template); Assert.NotNull(child); Assert.NotSame(expected, child); } } [Fact] public void Moving_To_New_LogicalTree_Should_Detach_Attach_Template_Child() { using (UnitTestApplication.Start(TestServices.RealStyler)) { TestTemplatedControl target; var root = new TestRoot { Child = target = new TestTemplatedControl { Template = new FuncControlTemplate(_ => new Decorator()), } }; Assert.NotNull(target.Template); target.ApplyTemplate(); var templateChild = (ILogical)target.GetVisualChildren().Single(); Assert.True(templateChild.IsAttachedToLogicalTree); root.Child = null; Assert.False(templateChild.IsAttachedToLogicalTree); var newRoot = new TestRoot { Child = target }; Assert.True(templateChild.IsAttachedToLogicalTree); } } private static IControl ScrollingContentControlTemplate(ContentControl control) { return new Border { Child = new ScrollViewer { Template = new FuncControlTemplate<ScrollViewer>(ScrollViewerTemplate), Name = "ScrollViewer", Content = new ContentPresenter { Name = "PART_ContentPresenter", [!ContentPresenter.ContentProperty] = control[!ContentControl.ContentProperty], } } }; } private static Control ScrollViewerTemplate(ScrollViewer control) { var result = new ScrollContentPresenter { Name = "PART_ContentPresenter", [~ContentPresenter.ContentProperty] = control[~ContentControl.ContentProperty], }; return result; } } }
using FluentAssertions; using System; using System.Threading.Tasks; using Xunit; namespace CSharpFunctionalExtensions.Tests.ResultTests { public class ResultTests : TestBase { [Fact] public void Success_argument_is_null_Success_result_expected() { Result result = Result.Success<string>(null); result.IsSuccess.Should().BeTrue(); } [Fact] public void Fail_argument_is_default_Fail_result_expected() { Result<string, int> result = Result.Failure<string, int>(0); result.IsFailure.Should().BeTrue(); } [Fact] public void Fail_argument_is_not_default_Fail_result_expected() { Result<string, int> result = Result.Failure<string, int>(1); result.IsFailure.Should().BeTrue(); } [Fact] public void Fail_argument_is_null_Exception_expected() { var exception = Record.Exception(() => Result.Failure<string, string>(null)); Assert.IsType<ArgumentNullException>(exception); } [Fact] public void CreateFailure_value_is_null_Success_result_expected() { Result result = Result.FailureIf<string>(false, null, null); result.IsSuccess.Should().BeTrue(); } [Fact] public void CreateFailure_error_is_null_Exception_expected() { var exception = Record.Exception(() => Result.FailureIf<string, string>(true, null, null)); Assert.IsType<ArgumentNullException>(exception); } [Fact] public void CreateFailure_error_is_default_Failure_result_expected() { Result<bool, int> result = Result.FailureIf<bool, int>(true, false, 0); result.IsFailure.Should().BeTrue(); result.Error.Should().Be(0); } [Fact] public void CreateFailure_argument_is_false_Success_result_expected() { Result result = Result.FailureIf(false, string.Empty); result.IsSuccess.Should().BeTrue(); } [Fact] public void CreateFailure_argument_is_true_Failure_result_expected() { Result result = Result.FailureIf(true, "simple result error"); result.IsFailure.Should().BeTrue(); result.Error.Should().Be("simple result error"); } [Fact] public void CreateFailure_predicate_is_false_Success_result_expected() { Result result = Result.FailureIf(() => false, string.Empty); result.IsSuccess.Should().BeTrue(); } [Fact] public void CreateFailure_predicate_is_true_Failure_result_expected() { Result result = Result.FailureIf(() => true, "predicate result error"); result.IsFailure.Should().BeTrue(); result.Error.Should().Be("predicate result error"); } [Fact] public async Task CreateFailure_async_predicate_is_false_Success_result_expected() { Result result = await Result.FailureIf(() => Task.FromResult(false), string.Empty); result.IsSuccess.Should().BeTrue(); } [Fact] public async Task CreateFailure_async_predicate_is_true_Failure_result_expected() { Result result = await Result.FailureIf(() => Task.FromResult(true), "predicate result error"); result.IsFailure.Should().BeTrue(); result.Error.Should().Be("predicate result error"); } [Fact] public void CreateFailure_generic_argument_is_false_Success_result_expected() { byte val = 7; Result<byte> result = Result.FailureIf(false, val, string.Empty); result.IsSuccess.Should().BeTrue(); result.Value.Should().Be(val); } [Fact] public void CreateFailure_generic_argument_is_true_Failure_result_expected() { double val = .56; Result<double> result = Result.FailureIf(true, val, "simple result error"); result.IsFailure.Should().BeTrue(); result.Error.Should().Be("simple result error"); } [Fact] public void CreateFailure_generic_predicate_is_false_Success_result_expected() { DateTime val = new DateTime(2000, 1, 1); Result<DateTime> result = Result.FailureIf(() => false, val, string.Empty); result.IsSuccess.Should().BeTrue(); result.Value.Should().Be(val); } [Fact] public void CreateFailure_generic_predicate_is_true_Failure_result_expected() { string val = "string value"; Result<string> result = Result.FailureIf(() => true, val, "predicate result error"); result.IsFailure.Should().BeTrue(); result.Error.Should().Be("predicate result error"); } [Fact] public async Task CreateFailure_generic_async_predicate_is_false_Success_result_expected() { int val = 42; Result<int> result = await Result.FailureIf(() => Task.FromResult(false), val, string.Empty); result.IsSuccess.Should().BeTrue(); result.Value.Should().Be(val); } [Fact] public async Task CreateFailure_generic_async_predicate_is_true_Failure_result_expected() { bool val = true; Result<bool> result = await Result.FailureIf(() => Task.FromResult(true), val, "predicate result error"); result.IsFailure.Should().BeTrue(); result.Error.Should().Be("predicate result error"); } [Fact] public void CreateFailure_error_generic_argument_is_false_Success_result_expected() { byte val = 7; Result<byte, Error> result = Result.FailureIf(false, val, new Error()); result.IsSuccess.Should().BeTrue(); result.Value.Should().Be(val); } [Fact] public void CreateFailure_error_generic_argument_is_true_Failure_result_expected() { double val = .56; var error = new Error(); Result<double, Error> result = Result.FailureIf(true, val, error); result.IsFailure.Should().BeTrue(); result.Error.Should().Be(error); } [Fact] public void CreateFailure_error_generic_predicate_is_false_Success_result_expected() { DateTime val = new DateTime(2000, 1, 1); Result<DateTime, Error> result = Result.FailureIf(() => false, val, new Error()); result.IsSuccess.Should().BeTrue(); result.Value.Should().Be(val); } [Fact] public void CreateFailure_error_generic_predicate_is_true_Failure_result_expected() { string val = "string value"; var error = new Error(); Result<string, Error> result = Result.FailureIf(() => true, val, error); result.IsFailure.Should().BeTrue(); result.Error.Should().Be(error); } [Fact] public async Task CreateFailure_error_generic_async_predicate_is_false_Success_result_expected() { int val = 42; Result<int, Error> result = await Result.FailureIf(() => Task.FromResult(false), val, new Error()); result.IsSuccess.Should().BeTrue(); result.Value.Should().Be(val); } [Fact] public async Task CreateFailure_error_generic_async_predicate_is_true_Failure_result_expected() { bool val = true; var error = new Error(); Result<bool, Error> result = await Result.FailureIf(() => Task.FromResult(true), val, error); result.IsFailure.Should().BeTrue(); result.Error.Should().Be(error); } [Fact] public void Can_work_with_nullable_sructs() { Result<DateTime?> result = Result.Success((DateTime?)null); result.IsSuccess.Should().BeTrue(); result.Value.Should().Be(null); } [Fact] public void Can_work_with_maybe_of_struct() { Maybe<DateTime> maybe = Maybe<DateTime>.None; Result<Maybe<DateTime>> result = Result.Success(maybe); result.IsSuccess.Should().BeTrue(); result.Value.Should().Be(Maybe<DateTime>.None); } [Fact] public void Can_work_with_maybe_of_ref_type() { Maybe<string> maybe = Maybe<string>.None; Result<Maybe<string>> result = Result.Success(maybe); result.IsSuccess.Should().BeTrue(); result.Value.Should().Be(Maybe<string>.None); } } }
// // 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 Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.WebSites.Models; namespace Microsoft.Azure.Management.WebSites.Models { /// <summary> /// The Get Web Site Publish Profile operation response. /// </summary> public partial class WebSiteGetPublishProfileResponse : AzureOperationResponse, IEnumerable<WebSiteGetPublishProfileResponse.PublishProfile> { private IList<WebSiteGetPublishProfileResponse.PublishProfile> _publishProfiles; /// <summary> /// Optional. Contains one or more publish profiles. /// </summary> public IList<WebSiteGetPublishProfileResponse.PublishProfile> PublishProfiles { get { return this._publishProfiles; } set { this._publishProfiles = value; } } /// <summary> /// Initializes a new instance of the WebSiteGetPublishProfileResponse /// class. /// </summary> public WebSiteGetPublishProfileResponse() { this.PublishProfiles = new LazyList<WebSiteGetPublishProfileResponse.PublishProfile>(); } /// <summary> /// Gets the sequence of PublishProfiles. /// </summary> public IEnumerator<WebSiteGetPublishProfileResponse.PublishProfile> GetEnumerator() { return this.PublishProfiles.GetEnumerator(); } /// <summary> /// Gets the sequence of PublishProfiles. /// </summary> System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// Contains attributes that contain information for a single database /// connection. /// </summary> public partial class Database { private string _connectionString; /// <summary> /// Optional. Contains a database connection string. /// </summary> public string ConnectionString { get { return this._connectionString; } set { this._connectionString = value; } } private string _name; /// <summary> /// Optional. Contains the friendly name of the connection string. /// </summary> public string Name { get { return this._name; } set { this._name = value; } } private string _providerName; /// <summary> /// Optional. Contains the type of database provider (for example, /// "SQL" or "MySQL"). /// </summary> public string ProviderName { get { return this._providerName; } set { this._providerName = value; } } private string _type; /// <summary> /// Optional. /// </summary> public string Type { get { return this._type; } set { this._type = value; } } /// <summary> /// Initializes a new instance of the Database class. /// </summary> public Database() { } } /// <summary> /// Contains attributes that hold publish profile values. /// </summary> public partial class PublishProfile { private Uri _controlPanelUri; /// <summary> /// Optional. The URL of the control panel for the web site. /// </summary> public Uri ControlPanelUri { get { return this._controlPanelUri; } set { this._controlPanelUri = value; } } private IList<WebSiteGetPublishProfileResponse.Database> _databases; /// <summary> /// Optional. Contains connection information for the databases /// used by the web site application. /// </summary> public IList<WebSiteGetPublishProfileResponse.Database> Databases { get { return this._databases; } set { this._databases = value; } } private Uri _destinationAppUri; /// <summary> /// Optional. The URL of the website that will be published to. /// </summary> public Uri DestinationAppUri { get { return this._destinationAppUri; } set { this._destinationAppUri = value; } } private bool _ftpPassiveMode; /// <summary> /// Optional. True or False depending on whether FTP passive mode /// is being used. This attribute applies only if publishMethod is /// set to FTP. /// </summary> public bool FtpPassiveMode { get { return this._ftpPassiveMode; } set { this._ftpPassiveMode = value; } } private Uri _hostingProviderForumUri; /// <summary> /// Optional. The URL of the forum of the hosting provider. /// </summary> public Uri HostingProviderForumUri { get { return this._hostingProviderForumUri; } set { this._hostingProviderForumUri = value; } } private string _mSDeploySite; /// <summary> /// Optional. The name of the site that will be published to. This /// attribute applies only if publishMethod is set to MSDeploy. /// </summary> public string MSDeploySite { get { return this._mSDeploySite; } set { this._mSDeploySite = value; } } private string _mySqlConnectionString; /// <summary> /// Optional. The MySQL database connection string for the web site /// application, if the web site connects to a MySQL database. /// </summary> public string MySqlConnectionString { get { return this._mySqlConnectionString; } set { this._mySqlConnectionString = value; } } private string _profileName; /// <summary> /// Optional. The unique name of the publish profile. /// </summary> public string ProfileName { get { return this._profileName; } set { this._profileName = value; } } private string _publishMethod; /// <summary> /// Optional. The publish method, such as MSDeploy or FTP. /// </summary> public string PublishMethod { get { return this._publishMethod; } set { this._publishMethod = value; } } private string _publishUrl; /// <summary> /// Optional. The URL to which content will be uploaded. /// </summary> public string PublishUrl { get { return this._publishUrl; } set { this._publishUrl = value; } } private string _sqlServerConnectionString; /// <summary> /// Optional. The SQL Server database connection string for the web /// site application, if the web site connects to a SQL Server /// database. /// </summary> public string SqlServerConnectionString { get { return this._sqlServerConnectionString; } set { this._sqlServerConnectionString = value; } } private string _userName; /// <summary> /// Optional. The name for the identity that will be used for /// publishing. /// </summary> public string UserName { get { return this._userName; } set { this._userName = value; } } private string _userPassword; /// <summary> /// Optional. Hash value of the password that will be used for /// publishing. /// </summary> public string UserPassword { get { return this._userPassword; } set { this._userPassword = value; } } /// <summary> /// Initializes a new instance of the PublishProfile class. /// </summary> public PublishProfile() { this.Databases = new LazyList<WebSiteGetPublishProfileResponse.Database>(); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace TestApi.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using Newtonsoft.Json.Linq; using ReactNative.UIManager; using ReactNative.UIManager.Annotations; using ReactNative.Views.Split.Events; using System; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using static System.FormattableString; namespace ReactNative.Views.Split { class ReactSplitViewManager : ViewParentManager<SplitView> { private const int OpenPane = 1; private const int ClosePane = 2; public override string Name { get { return "WindowsSplitView"; } } public override JObject ViewCommandsMap { get { return new JObject { { "openPane", OpenPane }, { "closePane", ClosePane }, }; } } public override JObject CustomDirectEventTypeConstants { get { return new JObject { { SplitViewClosedEvent.EventNameValue, new JObject { { "registrationName", "onSplitViewClose" }, } }, { SplitViewOpenedEvent.EventNameValue, new JObject { { "registrationName", "onSplitViewOpen" }, } }, }; } } public override JObject ViewConstants { get { return new JObject { { "PanePositions", new JObject { { "Left", (int)SplitViewPanePlacement.Left }, { "Right", (int)SplitViewPanePlacement.Right }, } }, }; } } [ReactProp("panePosition", DefaultInt32 = 0 /* SplitViewPanePlacement.Left */)] public void SetPanePosition(SplitView view, int panePosition) { var placement = (SplitViewPanePlacement)panePosition; if (placement != SplitViewPanePlacement.Left && placement != SplitViewPanePlacement.Right) { throw new ArgumentOutOfRangeException( nameof(panePosition), Invariant($"Unknown pane position '{placement}'.")); } view.PanePlacement = placement; } [ReactProp("paneWidth", DefaultSingle = float.NaN)] public void SetPaneWidth(SplitView view, float width) { if (!float.IsNaN(width)) { view.OpenPaneLength = width; } else { view.OpenPaneLength = 320 /* default value */; } } public override void AddView(SplitView parent, DependencyObject child, int index) { if (index != 0 && index != 1) { throw new ArgumentOutOfRangeException( nameof(index), Invariant($"'{Name}' only supports two child, the content and the pane.")); } var uiElementChild = child.As<UIElement>(); if (index == 0) { parent.Content = uiElementChild; } else { parent.Pane = uiElementChild; } } public override DependencyObject GetChildAt(SplitView parent, int index) { if (index != 0 && index != 1) { throw new ArgumentOutOfRangeException( nameof(index), Invariant($"'{Name}' only supports two child, the content and the pane.")); } return index == 0 ? EnsureContent(parent) : EnsurePane(parent); } public override int GetChildCount(SplitView parent) { var count = parent.Content != null ? 1 : 0; count += parent.Pane != null ? 1 : 0; return count; } public override void OnDropViewInstance(ThemedReactContext reactContext, SplitView view) { base.OnDropViewInstance(reactContext, view); view.PaneClosed -= OnPaneClosed; } public override void ReceiveCommand(SplitView view, int commandId, JArray args) { switch (commandId) { case OpenPane: if (!view.IsPaneOpen) { view.IsPaneOpen = true; OnPaneOpened(view); } break; case ClosePane: if (view.IsPaneOpen) { view.IsPaneOpen = false; } break; } } public override void RemoveAllChildren(SplitView parent) { parent.Content = null; parent.Pane = null; } public override void RemoveChildAt(SplitView parent, int index) { if (index == 0) { parent.Content = null; } else if (index == 1) { parent.Pane = null; } else { throw new ArgumentOutOfRangeException( nameof(index), Invariant($"'{Name}' only supports two child, the content and the pane.")); } } public override void UpdateExtraData(SplitView root, object extraData) { } protected override void AddEventEmitters(ThemedReactContext reactContext, SplitView view) { base.AddEventEmitters(reactContext, view); view.PaneClosed += OnPaneClosed; } protected override SplitView CreateViewInstance(ThemedReactContext reactContext) { return new SplitView { DisplayMode = SplitViewDisplayMode.Overlay, }; } private void OnPaneClosed(SplitView sender, object args) { sender.GetReactContext() .GetNativeModule<UIManagerModule>() .EventDispatcher .DispatchEvent( new SplitViewClosedEvent(sender.GetTag())); } private void OnPaneOpened(SplitView view) { view.GetReactContext() .GetNativeModule<UIManagerModule>() .EventDispatcher .DispatchEvent( new SplitViewOpenedEvent(view.GetTag())); } private static DependencyObject EnsureContent(SplitView view) { var child = view.Content; if (child == null) { throw new InvalidOperationException(Invariant($"{nameof(SplitView)} does not have a content child.")); } return child; } private static DependencyObject EnsurePane(SplitView view) { var child = view.Pane; if (child == null) { throw new InvalidOperationException(Invariant($"{nameof(SplitView)} does not have a pane child.")); } return child; } } }
// *********************************************************************** // Copyright (c) 2009-2015 Charlie Poole // // 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.Collections; using System.Collections.Generic; using System.Reflection; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; using NUnit.TestData.TestCaseSourceAttributeFixture; using NUnit.TestUtilities; namespace NUnit.Framework.Attributes { [TestFixture] public class TestCaseSourceTests //: TestSourceMayBeInherited { [Test, TestCaseSource("StaticProperty")] public void SourceCanBeStaticProperty(string source) { Assert.AreEqual("StaticProperty", source); } //[Test, TestCaseSource("InheritedStaticProperty")] //public void TestSourceCanBeInheritedStaticProperty(bool source) //{ // Assert.AreEqual(true, source); //} static IEnumerable StaticProperty { get { return new object[] { new object[] { "StaticProperty" } }; } } [Test] public void SourceUsingInstancePropertyIsNotRunnable() { var result = TestBuilder.RunParameterizedMethodSuite(typeof(TestCaseSourceAttributeFixture), "MethodWithInstancePropertyAsSource"); Assert.AreEqual(result.Children[0].ResultState, ResultState.NotRunnable); } [Test, TestCaseSource("StaticMethod")] public void SourceCanBeStaticMethod(string source) { Assert.AreEqual("StaticMethod", source); } static IEnumerable StaticMethod() { return new object[] { new object[] { "StaticMethod" } }; } [Test] public void SourceUsingInstanceMethodIsNotRunnable() { var result = TestBuilder.RunParameterizedMethodSuite(typeof(TestCaseSourceAttributeFixture), "MethodWithInstanceMethodAsSource"); Assert.AreEqual(result.Children[0].ResultState, ResultState.NotRunnable); } IEnumerable InstanceMethod() { return new object[] { new object[] { "InstanceMethod" } }; } [Test, TestCaseSource("StaticField")] public void SourceCanBeStaticField(string source) { Assert.AreEqual("StaticField", source); } static object[] StaticField = { new object[] { "StaticField" } }; [Test] public void SourceUsingInstanceFieldIsNotRunnable() { var result = TestBuilder.RunParameterizedMethodSuite(typeof(TestCaseSourceAttributeFixture), "MethodWithInstanceFieldAsSource"); Assert.AreEqual(result.Children[0].ResultState, ResultState.NotRunnable); } [Test, TestCaseSource(typeof(DataSourceClass))] public void SourceCanBeInstanceOfIEnumerable(string source) { Assert.AreEqual("DataSourceClass", source); } class DataSourceClass : IEnumerable { public DataSourceClass() { } public IEnumerator GetEnumerator() { yield return "DataSourceClass"; } } [Test, TestCaseSource("MyData")] public void SourceMayReturnArgumentsAsObjectArray(int n, int d, int q) { Assert.AreEqual(q, n / d); } [TestCaseSource("MyData")] public void TestAttributeIsOptional(int n, int d, int q) { Assert.AreEqual(q, n / d); } [Test, TestCaseSource("MyIntData")] public void SourceMayReturnArgumentsAsIntArray(int n, int d, int q) { Assert.AreEqual(q, n / d); } [Test, TestCaseSource("EvenNumbers")] public void SourceMayReturnSinglePrimitiveArgumentAlone(int n) { Assert.AreEqual(0, n % 2); } [Test, TestCaseSource("Params")] public int SourceMayReturnArgumentsAsParamSet(int n, int d) { return n / d; } [Test] [TestCaseSource("MyData")] [TestCaseSource("MoreData", Category = "Extra")] [TestCase(12, 2, 6)] public void TestMayUseMultipleSourceAttributes(int n, int d, int q) { Assert.AreEqual(q, n / d); } [Test, TestCaseSource("FourArgs")] public void TestWithFourArguments(int n, int d, int q, int r) { Assert.AreEqual(q, n / d); Assert.AreEqual(r, n % d); } [Test, Category("Top"), TestCaseSource(typeof(DivideDataProvider), "HereIsTheData")] public void SourceMayBeInAnotherClass(int n, int d, int q) { Assert.AreEqual(q, n / d); } [Test, Category("Top"), TestCaseSource(typeof(DivideDataProvider), "HereIsTheDataWithParameters", new object[] { 100, 4, 25 })] public void SourceInAnotherClassPassingSomeDataToConstructor(int n, int d, int q) { Assert.AreEqual(q, n / d); } [Test] public void SourceInAnotherClassPassingParamsToField() { var testMethod = (TestMethod)TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseSourceAttributeFixture), "SourceInAnotherClassPassingParamsToField").Tests[0]; Assert.AreEqual(RunState.NotRunnable, testMethod.RunState); ITestResult result = TestBuilder.RunTest(testMethod, null); Assert.AreEqual(ResultState.NotRunnable, result.ResultState); Assert.AreEqual("You have specified a data source field but also given a set of parameters. Fields cannot take parameters, " + "please revise the 3rd parameter passed to the TestCaseSourceAttribute and either remove " + "it or specify a method.", result.Message); } [Test] public void SourceInAnotherClassPassingParamsToProperty() { var testMethod = (TestMethod)TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseSourceAttributeFixture), "SourceInAnotherClassPassingParamsToProperty").Tests[0]; Assert.AreEqual(RunState.NotRunnable, testMethod.RunState); ITestResult result = TestBuilder.RunTest(testMethod, null); Assert.AreEqual(ResultState.NotRunnable, result.ResultState); Assert.AreEqual("You have specified a data source property but also given a set of parameters. " + "Properties cannot take parameters, please revise the 3rd parameter passed to the " + "TestCaseSource attribute and either remove it or specify a method.", result.Message); } [Test] public void SourceInAnotherClassPassingSomeDataToConstructorWrongNumberParam() { var testMethod = (TestMethod)TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseSourceAttributeFixture), "SourceInAnotherClassPassingSomeDataToConstructorWrongNumberParam").Tests[0]; Assert.AreEqual(RunState.NotRunnable, testMethod.RunState); ITestResult result = TestBuilder.RunTest(testMethod, null); Assert.AreEqual(ResultState.NotRunnable, result.ResultState); Assert.AreEqual("You have given the wrong number of arguments to the method in the TestCaseSourceAttribute" + ", please check the number of parameters passed in the object is correct in the 3rd parameter for the " + "TestCaseSourceAttribute and this matches the number of parameters in the target method and try again.", result.Message); } [Test, TestCaseSource(typeof(DivideDataProviderWithReturnValue), "TestCases")] public int SourceMayBeInAnotherClassWithReturn(int n, int d) { return n / d; } [Test] public void IgnoreTakesPrecedenceOverExpectedException() { ITestResult result = TestBuilder.RunParameterizedMethodSuite( typeof(TestCaseSourceAttributeFixture), "MethodCallsIgnore").Children[0]; Assert.AreEqual(ResultState.Ignored, result.ResultState); Assert.AreEqual("Ignore this", result.Message); } [Test] public void CanIgnoreIndividualTestCases() { TestSuite suite = TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseSourceAttributeFixture), "MethodWithIgnoredTestCases"); Test testCase = TestFinder.Find("MethodWithIgnoredTestCases(1)", suite, false); Assert.That(testCase.RunState, Is.EqualTo(RunState.Runnable)); testCase = TestFinder.Find("MethodWithIgnoredTestCases(2)", suite, false); Assert.That(testCase.RunState, Is.EqualTo(RunState.Ignored)); Assert.That(testCase.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("Don't Run Me!")); } [Test] public void CanMarkIndividualTestCasesExplicit() { TestSuite suite = TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseSourceAttributeFixture), "MethodWithExplicitTestCases"); Test testCase = TestFinder.Find("MethodWithExplicitTestCases(1)", suite, false); Assert.That(testCase.RunState, Is.EqualTo(RunState.Runnable)); testCase = TestFinder.Find("MethodWithExplicitTestCases(2)", suite, false); Assert.That(testCase.RunState, Is.EqualTo(RunState.Explicit)); testCase = TestFinder.Find("MethodWithExplicitTestCases(3)", suite, false); Assert.That(testCase.RunState, Is.EqualTo(RunState.Explicit)); Assert.That(testCase.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("Connection failing")); } [Test] public void HandlesExceptionInTestCaseSource() { var testMethod = (TestMethod)TestBuilder.MakeParameterizedMethodSuite( typeof(TestCaseSourceAttributeFixture), "MethodWithSourceThrowingException").Tests[0]; Assert.AreEqual(RunState.NotRunnable, testMethod.RunState); ITestResult result = TestBuilder.RunTest(testMethod, null); Assert.AreEqual(ResultState.NotRunnable, result.ResultState); Assert.AreEqual("System.Exception : my message", result.Message); } [TestCaseSource("exception_source"), Explicit("Used for GUI tests")] public void HandlesExceptionInTestCaseSource_GuiDisplay(string lhs, string rhs) { Assert.AreEqual(lhs, rhs); } static object[] testCases = { new TestCaseData( new string[] { "A" }, new string[] { "B" }) }; [Test, TestCaseSource("testCases")] public void MethodTakingTwoStringArrays(string[] a, string[] b) { Assert.That(a, Is.TypeOf(typeof(string[]))); Assert.That(b, Is.TypeOf(typeof(string[]))); } #region Sources used by the tests static object[] MyData = new object[] { new object[] { 12, 3, 4 }, new object[] { 12, 4, 3 }, new object[] { 12, 6, 2 } }; static object[] MyIntData = new object[] { new int[] { 12, 3, 4 }, new int[] { 12, 4, 3 }, new int[] { 12, 6, 2 } }; static object[] FourArgs = new object[] { new TestCaseData( 12, 3, 4, 0 ), new TestCaseData( 12, 4, 3, 0 ), new TestCaseData( 12, 5, 2, 2 ) }; static int[] EvenNumbers = new int[] { 2, 4, 6, 8 }; static object[] MoreData = new object[] { new object[] { 12, 1, 12 }, new object[] { 12, 2, 6 } }; static object[] Params = new object[] { new TestCaseData(24, 3).Returns(8), new TestCaseData(24, 2).Returns(12) }; private class DivideDataProvider { private static object[] myObject; public static IEnumerable HereIsTheDataWithParameters(int inject1, int inject2, int inject3) { yield return new object[] { inject1, inject2, inject3 }; } public static IEnumerable HereIsTheData { get { yield return new object[] { 100, 20, 5 }; yield return new object[] { 100, 4, 25 }; } } } public class DivideDataProviderWithReturnValue { public static IEnumerable TestCases { get { return new object[] { new TestCaseData(12, 3).Returns(4).SetName("TC1"), new TestCaseData(12, 2).Returns(6).SetName("TC2"), new TestCaseData(12, 4).Returns(3).SetName("TC3") }; } } } private static IEnumerable exception_source { get { yield return new TestCaseData("a", "a"); yield return new TestCaseData("b", "b"); throw new System.Exception("my message"); } } #endregion } public class TestSourceMayBeInherited { protected static IEnumerable<bool> InheritedStaticProperty { get { yield return true; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.ComponentModel; using System.Globalization; using System.Net.Security; using System.Runtime.InteropServices; namespace System.Net { internal static class SSPIWrapper { internal static SecurityPackageInfoClass[] EnumerateSecurityPackages(SSPIInterface secModule) { GlobalLog.Enter("EnumerateSecurityPackages"); if (secModule.SecurityPackages == null) { lock (secModule) { if (secModule.SecurityPackages == null) { int moduleCount = 0; SafeFreeContextBuffer arrayBaseHandle = null; try { int errorCode = secModule.EnumerateSecurityPackages(out moduleCount, out arrayBaseHandle); GlobalLog.Print("SSPIWrapper::arrayBase: " + (arrayBaseHandle.DangerousGetHandle().ToString("x"))); if (errorCode != 0) { throw new Win32Exception(errorCode); } SecurityPackageInfoClass[] securityPackages = new SecurityPackageInfoClass[moduleCount]; if (Logging.On) { Logging.PrintInfo(Logging.Web, SR.net_log_sspi_enumerating_security_packages); } int i; for (i = 0; i < moduleCount; i++) { securityPackages[i] = new SecurityPackageInfoClass(arrayBaseHandle, i); if (Logging.On) { Logging.PrintInfo(Logging.Web, " " + securityPackages[i].Name); } } secModule.SecurityPackages = securityPackages; } finally { if (arrayBaseHandle != null) { arrayBaseHandle.Dispose(); } } } } } GlobalLog.Leave("EnumerateSecurityPackages"); return secModule.SecurityPackages; } internal static SecurityPackageInfoClass GetVerifyPackageInfo(SSPIInterface secModule, string packageName) { return GetVerifyPackageInfo(secModule, packageName, false); } internal static SecurityPackageInfoClass GetVerifyPackageInfo(SSPIInterface secModule, string packageName, bool throwIfMissing) { SecurityPackageInfoClass[] supportedSecurityPackages = EnumerateSecurityPackages(secModule); if (supportedSecurityPackages != null) { for (int i = 0; i < supportedSecurityPackages.Length; i++) { if (string.Compare(supportedSecurityPackages[i].Name, packageName, StringComparison.OrdinalIgnoreCase) == 0) { return supportedSecurityPackages[i]; } } } if (Logging.On) { Logging.PrintInfo(Logging.Web, SR.Format(SR.net_log_sspi_security_package_not_found, packageName)); } if (throwIfMissing) { throw new NotSupportedException(SR.net_securitypackagesupport); } return null; } public static SafeFreeCredentials AcquireDefaultCredential(SSPIInterface secModule, string package, Interop.Secur32.CredentialUse intent) { GlobalLog.Print("SSPIWrapper::AcquireDefaultCredential(): using " + package); if (Logging.On) { Logging.PrintInfo( Logging.Web, "AcquireDefaultCredential(" + "package = " + package + ", " + "intent = " + intent + ")"); } SafeFreeCredentials outCredential = null; int errorCode = secModule.AcquireDefaultCredential(package, intent, out outCredential); if (errorCode != 0) { #if TRACE_VERBOSE GlobalLog.Print("SSPIWrapper::AcquireDefaultCredential(): error " + Interop.MapSecurityStatus((uint)errorCode)); #endif if (Logging.On) { Logging.PrintError(Logging.Web, SR.Format(SR.net_log_operation_failed_with_error, "AcquireDefaultCredential()", String.Format(CultureInfo.CurrentCulture, "0X{0:X}", errorCode))); } throw new Win32Exception(errorCode); } return outCredential; } public static SafeFreeCredentials AcquireCredentialsHandle(SSPIInterface secModule, string package, Interop.Secur32.CredentialUse intent, ref Interop.Secur32.AuthIdentity authdata) { GlobalLog.Print("SSPIWrapper::AcquireCredentialsHandle#2(): using " + package); if (Logging.On) { Logging.PrintInfo(Logging.Web, "AcquireCredentialsHandle(" + "package = " + package + ", " + "intent = " + intent + ", " + "authdata = " + authdata + ")"); } SafeFreeCredentials credentialsHandle = null; int errorCode = secModule.AcquireCredentialsHandle(package, intent, ref authdata, out credentialsHandle ); if (errorCode != 0) { #if TRACE_VERBOSE GlobalLog.Print("SSPIWrapper::AcquireCredentialsHandle#2(): error " + Interop.MapSecurityStatus((uint)errorCode)); #endif if (Logging.On) { Logging.PrintError(Logging.Web, SR.Format(SR.net_log_operation_failed_with_error, "AcquireCredentialsHandle()", String.Format(CultureInfo.CurrentCulture, "0X{0:X}", errorCode))); } throw new Win32Exception(errorCode); } return credentialsHandle; } public static SafeFreeCredentials AcquireCredentialsHandle(SSPIInterface secModule, string package, Interop.Secur32.CredentialUse intent, ref SafeSspiAuthDataHandle authdata) { if (Logging.On) { Logging.PrintInfo(Logging.Web, "AcquireCredentialsHandle(" + "package = " + package + ", " + "intent = " + intent + ", " + "authdata = " + authdata + ")"); } SafeFreeCredentials credentialsHandle = null; int errorCode = secModule.AcquireCredentialsHandle(package, intent, ref authdata, out credentialsHandle); if (errorCode != 0) { if (Logging.On) { Logging.PrintError(Logging.Web, SR.Format(SR.net_log_operation_failed_with_error, "AcquireCredentialsHandle()", String.Format(CultureInfo.CurrentCulture, "0X{0:X}", errorCode))); } throw new Win32Exception(errorCode); } return credentialsHandle; } public static SafeFreeCredentials AcquireCredentialsHandle(SSPIInterface secModule, string package, Interop.Secur32.CredentialUse intent, Interop.Secur32.SecureCredential scc) { GlobalLog.Print("SSPIWrapper::AcquireCredentialsHandle#3(): using " + package); if (Logging.On) { Logging.PrintInfo(Logging.Web, "AcquireCredentialsHandle(" + "package = " + package + ", " + "intent = " + intent + ", " + "scc = " + scc + ")"); } SafeFreeCredentials outCredential = null; int errorCode = secModule.AcquireCredentialsHandle( package, intent, ref scc, out outCredential ); if (errorCode != 0) { #if TRACE_VERBOSE GlobalLog.Print("SSPIWrapper::AcquireCredentialsHandle#3(): error " + Interop.MapSecurityStatus((uint)errorCode)); #endif if (Logging.On) { Logging.PrintError(Logging.Web, SR.Format(SR.net_log_operation_failed_with_error, "AcquireCredentialsHandle()", String.Format(CultureInfo.CurrentCulture, "0X{0:X}", errorCode))); } throw new Win32Exception(errorCode); } #if TRACE_VERBOSE GlobalLog.Print("SSPIWrapper::AcquireCredentialsHandle#3(): cred handle = " + outCredential.ToString()); #endif return outCredential; } internal static int InitializeSecurityContext(SSPIInterface secModule, ref SafeFreeCredentials credential, ref SafeDeleteContext context, string targetName, Interop.Secur32.ContextFlags inFlags, Interop.Secur32.Endianness datarep, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, ref Interop.Secur32.ContextFlags outFlags) { if (Logging.On) { Logging.PrintInfo(Logging.Web, "InitializeSecurityContext(" + "credential = " + credential.ToString() + ", " + "context = " + Logging.ObjectToString(context) + ", " + "targetName = " + targetName + ", " + "inFlags = " + inFlags + ")"); } int errorCode = secModule.InitializeSecurityContext(ref credential, ref context, targetName, inFlags, datarep, inputBuffer, outputBuffer, ref outFlags); if (Logging.On) { Logging.PrintInfo(Logging.Web, SR.Format(SR.net_log_sspi_security_context_input_buffer, "InitializeSecurityContext", (inputBuffer == null ? 0 : inputBuffer.size), outputBuffer.size, (Interop.SecurityStatus)errorCode)); } return errorCode; } internal static int InitializeSecurityContext(SSPIInterface secModule, SafeFreeCredentials credential, ref SafeDeleteContext context, string targetName, Interop.Secur32.ContextFlags inFlags, Interop.Secur32.Endianness datarep, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer, ref Interop.Secur32.ContextFlags outFlags) { if (Logging.On) { Logging.PrintInfo(Logging.Web, "InitializeSecurityContext(" + "credential = " + credential.ToString() + ", " + "context = " + Logging.ObjectToString(context) + ", " + "targetName = " + targetName + ", " + "inFlags = " + inFlags + ")"); } int errorCode = secModule.InitializeSecurityContext(credential, ref context, targetName, inFlags, datarep, inputBuffers, outputBuffer, ref outFlags); if (Logging.On) { Logging.PrintInfo(Logging.Web, SR.Format(SR.net_log_sspi_security_context_input_buffers, "InitializeSecurityContext", (inputBuffers == null ? 0 : inputBuffers.Length), outputBuffer.size, (Interop.SecurityStatus)errorCode)); } return errorCode; } internal static int AcceptSecurityContext(SSPIInterface secModule, ref SafeFreeCredentials credential, ref SafeDeleteContext context, Interop.Secur32.ContextFlags inFlags, Interop.Secur32.Endianness datarep, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, ref Interop.Secur32.ContextFlags outFlags) { if (Logging.On) { Logging.PrintInfo(Logging.Web, "AcceptSecurityContext(" + "credential = " + credential.ToString() + ", " + "context = " + Logging.ObjectToString(context) + ", " + "inFlags = " + inFlags + ")"); } int errorCode = secModule.AcceptSecurityContext(ref credential, ref context, inputBuffer, inFlags, datarep, outputBuffer, ref outFlags); if (Logging.On) { Logging.PrintInfo(Logging.Web, SR.Format(SR.net_log_sspi_security_context_input_buffer, "AcceptSecurityContext", (inputBuffer == null ? 0 : inputBuffer.size), outputBuffer.size, (Interop.SecurityStatus)errorCode)); } return errorCode; } internal static int AcceptSecurityContext(SSPIInterface secModule, SafeFreeCredentials credential, ref SafeDeleteContext context, Interop.Secur32.ContextFlags inFlags, Interop.Secur32.Endianness datarep, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer, ref Interop.Secur32.ContextFlags outFlags) { if (Logging.On) { Logging.PrintInfo(Logging.Web, "AcceptSecurityContext(" + "credential = " + credential.ToString() + ", " + "context = " + Logging.ObjectToString(context) + ", " + "inFlags = " + inFlags + ")"); } int errorCode = secModule.AcceptSecurityContext(credential, ref context, inputBuffers, inFlags, datarep, outputBuffer, ref outFlags); if (Logging.On) { Logging.PrintInfo(Logging.Web, SR.Format(SR.net_log_sspi_security_context_input_buffers, "AcceptSecurityContext", (inputBuffers == null ? 0 : inputBuffers.Length), outputBuffer.size, (Interop.SecurityStatus)errorCode)); } return errorCode; } internal static int CompleteAuthToken(SSPIInterface secModule, ref SafeDeleteContext context, SecurityBuffer[] inputBuffers) { int errorCode = secModule.CompleteAuthToken(ref context, inputBuffers); if (Logging.On) { Logging.PrintInfo(Logging.Web, SR.Format(SR.net_log_operation_returned_something, "CompleteAuthToken()", (Interop.SecurityStatus)errorCode)); } return errorCode; } public static int QuerySecurityContextToken(SSPIInterface secModule, SafeDeleteContext context, out SecurityContextTokenHandle token) { return secModule.QuerySecurityContextToken(context, out token); } public static int EncryptMessage(SSPIInterface secModule, SafeDeleteContext context, SecurityBuffer[] input, uint sequenceNumber) { return EncryptDecryptHelper(OP.Encrypt, secModule, context, input, sequenceNumber); } public static int DecryptMessage(SSPIInterface secModule, SafeDeleteContext context, SecurityBuffer[] input, uint sequenceNumber) { return EncryptDecryptHelper(OP.Decrypt, secModule, context, input, sequenceNumber); } internal static int MakeSignature(SSPIInterface secModule, SafeDeleteContext context, SecurityBuffer[] input, uint sequenceNumber) { return EncryptDecryptHelper(OP.MakeSignature, secModule, context, input, sequenceNumber); } public static int VerifySignature(SSPIInterface secModule, SafeDeleteContext context, SecurityBuffer[] input, uint sequenceNumber) { return EncryptDecryptHelper(OP.VerifySignature, secModule, context, input, sequenceNumber); } private enum OP { Encrypt = 1, Decrypt, MakeSignature, VerifySignature } private unsafe static int EncryptDecryptHelper(OP op, SSPIInterface secModule, SafeDeleteContext context, SecurityBuffer[] input, uint sequenceNumber) { Interop.Secur32.SecurityBufferDescriptor sdcInOut = new Interop.Secur32.SecurityBufferDescriptor(input.Length); var unmanagedBuffer = new Interop.Secur32.SecurityBufferStruct[input.Length]; fixed (Interop.Secur32.SecurityBufferStruct* unmanagedBufferPtr = unmanagedBuffer) { sdcInOut.UnmanagedPointer = unmanagedBufferPtr; GCHandle[] pinnedBuffers = new GCHandle[input.Length]; byte[][] buffers = new byte[input.Length][]; try { for (int i = 0; i < input.Length; i++) { SecurityBuffer iBuffer = input[i]; unmanagedBuffer[i].count = iBuffer.size; unmanagedBuffer[i].type = iBuffer.type; if (iBuffer.token == null || iBuffer.token.Length == 0) { unmanagedBuffer[i].token = IntPtr.Zero; } else { pinnedBuffers[i] = GCHandle.Alloc(iBuffer.token, GCHandleType.Pinned); unmanagedBuffer[i].token = Marshal.UnsafeAddrOfPinnedArrayElement(iBuffer.token, iBuffer.offset); buffers[i] = iBuffer.token; } } // The result is written in the input Buffer passed as type=BufferType.Data. int errorCode; switch (op) { case OP.Encrypt: errorCode = secModule.EncryptMessage(context, sdcInOut, sequenceNumber); break; case OP.Decrypt: errorCode = secModule.DecryptMessage(context, sdcInOut, sequenceNumber); break; case OP.MakeSignature: errorCode = secModule.MakeSignature(context, sdcInOut, sequenceNumber); break; case OP.VerifySignature: errorCode = secModule.VerifySignature(context, sdcInOut, sequenceNumber); break; default: GlobalLog.Assert("SSPIWrapper::EncryptDecryptHelper", "Unknown OP: " + op); throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException); } // Marshalling back returned sizes / data. for (int i = 0; i < input.Length; i++) { SecurityBuffer iBuffer = input[i]; iBuffer.size = unmanagedBuffer[i].count; iBuffer.type = unmanagedBuffer[i].type; if (iBuffer.size == 0) { iBuffer.offset = 0; iBuffer.token = null; } else { checked { // Find the buffer this is inside of. Usually they all point inside buffer 0. int j; for (j = 0; j < input.Length; j++) { if (buffers[j] == null) { continue; } byte* bufferAddress = (byte*)Marshal.UnsafeAddrOfPinnedArrayElement(buffers[j], 0); if ((byte*)unmanagedBuffer[i].token >= bufferAddress && (byte*)unmanagedBuffer[i].token + iBuffer.size <= bufferAddress + buffers[j].Length) { iBuffer.offset = (int)((byte*)unmanagedBuffer[i].token - bufferAddress); iBuffer.token = buffers[j]; break; } } if (j >= input.Length) { GlobalLog.Assert("SSPIWrapper::EncryptDecryptHelper", "Output buffer out of range."); iBuffer.size = 0; iBuffer.offset = 0; iBuffer.token = null; } } } // Backup validate the new sizes. GlobalLog.Assert(iBuffer.offset >= 0 && iBuffer.offset <= (iBuffer.token == null ? 0 : iBuffer.token.Length), "SSPIWrapper::EncryptDecryptHelper|'offset' out of range. [{0}]", iBuffer.offset); GlobalLog.Assert(iBuffer.size >= 0 && iBuffer.size <= (iBuffer.token == null ? 0 : iBuffer.token.Length - iBuffer.offset), "SSPIWrapper::EncryptDecryptHelper|'size' out of range. [{0}]", iBuffer.size); } if (errorCode != 0 && Logging.On) { if (errorCode == Interop.Secur32.SEC_I_RENEGOTIATE) { Logging.PrintError(Logging.Web, SR.Format(SR.net_log_operation_returned_something, op, "SEC_I_RENEGOTIATE")); } else { Logging.PrintError(Logging.Web, SR.Format(SR.net_log_operation_failed_with_error, op, String.Format(CultureInfo.CurrentCulture, "0X{0:X}", errorCode))); } } return errorCode; } finally { for (int i = 0; i < pinnedBuffers.Length; ++i) { if (pinnedBuffers[i].IsAllocated) { pinnedBuffers[i].Free(); } } } } } public static SafeFreeContextBufferChannelBinding QueryContextChannelBinding(SSPIInterface secModule, SafeDeleteContext securityContext, Interop.Secur32.ContextAttribute contextAttribute) { GlobalLog.Enter("QueryContextChannelBinding", contextAttribute.ToString()); SafeFreeContextBufferChannelBinding result; int errorCode = secModule.QueryContextChannelBinding(securityContext, contextAttribute, out result); if (errorCode != 0) { GlobalLog.Leave("QueryContextChannelBinding", "ERROR = " + ErrorDescription(errorCode)); return null; } GlobalLog.Leave("QueryContextChannelBinding", Logging.HashString(result)); return result; } public static object QueryContextAttributes(SSPIInterface secModule, SafeDeleteContext securityContext, Interop.Secur32.ContextAttribute contextAttribute) { int errorCode; return QueryContextAttributes(secModule, securityContext, contextAttribute, out errorCode); } public static object QueryContextAttributes(SSPIInterface secModule, SafeDeleteContext securityContext, Interop.Secur32.ContextAttribute contextAttribute, out int errorCode) { GlobalLog.Enter("QueryContextAttributes", contextAttribute.ToString()); int nativeBlockSize = IntPtr.Size; Type handleType = null; switch (contextAttribute) { case Interop.Secur32.ContextAttribute.Sizes: nativeBlockSize = SecSizes.SizeOf; break; case Interop.Secur32.ContextAttribute.StreamSizes: nativeBlockSize = StreamSizes.SizeOf; break; case Interop.Secur32.ContextAttribute.Names: handleType = typeof(SafeFreeContextBuffer); break; case Interop.Secur32.ContextAttribute.PackageInfo: handleType = typeof(SafeFreeContextBuffer); break; case Interop.Secur32.ContextAttribute.NegotiationInfo: handleType = typeof(SafeFreeContextBuffer); nativeBlockSize = Marshal.SizeOf<NegotiationInfo>(); break; case Interop.Secur32.ContextAttribute.ClientSpecifiedSpn: handleType = typeof(SafeFreeContextBuffer); break; case Interop.Secur32.ContextAttribute.RemoteCertificate: handleType = typeof(SafeFreeCertContext); break; case Interop.Secur32.ContextAttribute.LocalCertificate: handleType = typeof(SafeFreeCertContext); break; case Interop.Secur32.ContextAttribute.IssuerListInfoEx: nativeBlockSize = Marshal.SizeOf<Interop.Secur32.IssuerListInfoEx>(); handleType = typeof(SafeFreeContextBuffer); break; case Interop.Secur32.ContextAttribute.ConnectionInfo: nativeBlockSize = Marshal.SizeOf<SslConnectionInfo>(); break; default: throw new ArgumentException(SR.Format(SR.net_invalid_enum, "ContextAttribute"), "contextAttribute"); } SafeHandle sspiHandle = null; object attribute = null; try { byte[] nativeBuffer = new byte[nativeBlockSize]; errorCode = secModule.QueryContextAttributes(securityContext, contextAttribute, nativeBuffer, handleType, out sspiHandle); if (errorCode != 0) { GlobalLog.Leave("Win32:QueryContextAttributes", "ERROR = " + ErrorDescription(errorCode)); return null; } switch (contextAttribute) { case Interop.Secur32.ContextAttribute.Sizes: attribute = new SecSizes(nativeBuffer); break; case Interop.Secur32.ContextAttribute.StreamSizes: attribute = new StreamSizes(nativeBuffer); break; case Interop.Secur32.ContextAttribute.Names: attribute = Marshal.PtrToStringUni(sspiHandle.DangerousGetHandle()); break; case Interop.Secur32.ContextAttribute.PackageInfo: attribute = new SecurityPackageInfoClass(sspiHandle, 0); break; case Interop.Secur32.ContextAttribute.NegotiationInfo: unsafe { fixed (void* ptr = nativeBuffer) { attribute = new NegotiationInfoClass(sspiHandle, Marshal.ReadInt32(new IntPtr(ptr), NegotiationInfo.NegotiationStateOffest)); } } break; case Interop.Secur32.ContextAttribute.ClientSpecifiedSpn: attribute = Marshal.PtrToStringUni(sspiHandle.DangerousGetHandle()); break; case Interop.Secur32.ContextAttribute.LocalCertificate: // Fall-through to RemoteCertificate is intentional. case Interop.Secur32.ContextAttribute.RemoteCertificate: attribute = sspiHandle; sspiHandle = null; break; case Interop.Secur32.ContextAttribute.IssuerListInfoEx: attribute = new Interop.Secur32.IssuerListInfoEx(sspiHandle, nativeBuffer); sspiHandle = null; break; case Interop.Secur32.ContextAttribute.ConnectionInfo: attribute = new SslConnectionInfo(nativeBuffer); break; default: // Will return null. break; } } finally { if (sspiHandle != null) { sspiHandle.Dispose(); } } GlobalLog.Leave("QueryContextAttributes", Logging.ObjectToString(attribute)); return attribute; } public static string ErrorDescription(int errorCode) { if (errorCode == -1) { return "An exception when invoking Win32 API"; } switch ((Interop.SecurityStatus)errorCode) { case Interop.SecurityStatus.InvalidHandle: return "Invalid handle"; case Interop.SecurityStatus.InvalidToken: return "Invalid token"; case Interop.SecurityStatus.ContinueNeeded: return "Continue needed"; case Interop.SecurityStatus.IncompleteMessage: return "Message incomplete"; case Interop.SecurityStatus.WrongPrincipal: return "Wrong principal"; case Interop.SecurityStatus.TargetUnknown: return "Target unknown"; case Interop.SecurityStatus.PackageNotFound: return "Package not found"; case Interop.SecurityStatus.BufferNotEnough: return "Buffer not enough"; case Interop.SecurityStatus.MessageAltered: return "Message altered"; case Interop.SecurityStatus.UntrustedRoot: return "Untrusted root"; default: return "0x" + errorCode.ToString("x", NumberFormatInfo.InvariantInfo); } } } // class SSPIWrapper [StructLayout(LayoutKind.Sequential)] internal class StreamSizes { public int header; public int trailer; public int maximumMessage; public int buffersCount; public int blockSize; internal unsafe StreamSizes(byte[] memory) { fixed (void* voidPtr = memory) { IntPtr unmanagedAddress = new IntPtr(voidPtr); try { header = (int)checked((uint)Marshal.ReadInt32(unmanagedAddress)); trailer = (int)checked((uint)Marshal.ReadInt32(unmanagedAddress, 4)); maximumMessage = (int)checked((uint)Marshal.ReadInt32(unmanagedAddress, 8)); buffersCount = (int)checked((uint)Marshal.ReadInt32(unmanagedAddress, 12)); blockSize = (int)checked((uint)Marshal.ReadInt32(unmanagedAddress, 16)); } catch (OverflowException) { GlobalLog.Assert(false, "StreamSizes::.ctor", "Negative size."); throw; } } } public static readonly int SizeOf = Marshal.SizeOf<StreamSizes>(); } [StructLayout(LayoutKind.Sequential)] internal class SecSizes { public readonly int MaxToken; public readonly int MaxSignature; public readonly int BlockSize; public readonly int SecurityTrailer; internal unsafe SecSizes(byte[] memory) { fixed (void* voidPtr = memory) { IntPtr unmanagedAddress = new IntPtr(voidPtr); try { MaxToken = (int)checked((uint)Marshal.ReadInt32(unmanagedAddress)); MaxSignature = (int)checked((uint)Marshal.ReadInt32(unmanagedAddress, 4)); BlockSize = (int)checked((uint)Marshal.ReadInt32(unmanagedAddress, 8)); SecurityTrailer = (int)checked((uint)Marshal.ReadInt32(unmanagedAddress, 12)); } catch (OverflowException) { GlobalLog.Assert(false, "SecSizes::.ctor", "Negative size."); throw; } } } public static readonly int SizeOf = Marshal.SizeOf<SecSizes>(); } // TODO (Issue #3114): Move to Interop. // Investigate if this can be safely converted to a struct. // From Schannel.h [StructLayout(LayoutKind.Sequential)] internal class SslConnectionInfo { public readonly int Protocol; public readonly int DataCipherAlg; public readonly int DataKeySize; public readonly int DataHashAlg; public readonly int DataHashKeySize; public readonly int KeyExchangeAlg; public readonly int KeyExchKeySize; internal unsafe SslConnectionInfo(byte[] nativeBuffer) { fixed (void* voidPtr = nativeBuffer) { try { // TODO (Issue #3114): replace with Marshal.PtrToStructure. IntPtr unmanagedAddress = new IntPtr(voidPtr); Protocol = Marshal.ReadInt32(unmanagedAddress); DataCipherAlg = Marshal.ReadInt32(unmanagedAddress, 4); DataKeySize = Marshal.ReadInt32(unmanagedAddress, 8); DataHashAlg = Marshal.ReadInt32(unmanagedAddress, 12); DataHashKeySize = Marshal.ReadInt32(unmanagedAddress, 16); KeyExchangeAlg = Marshal.ReadInt32(unmanagedAddress, 20); KeyExchKeySize = Marshal.ReadInt32(unmanagedAddress, 24); } catch (OverflowException) { GlobalLog.Assert(false, "SslConnectionInfo::.ctor", "Negative size."); throw; } } } } [StructLayout(LayoutKind.Sequential)] internal struct NegotiationInfo { // see SecPkgContext_NegotiationInfoW in <sspi.h> // [MarshalAs(UnmanagedType.LPStruct)] internal SecurityPackageInfo PackageInfo; internal IntPtr PackageInfo; internal uint NegotiationState; internal static readonly int Size = Marshal.SizeOf<NegotiationInfo>(); internal static readonly int NegotiationStateOffest = (int)Marshal.OffsetOf<NegotiationInfo>("NegotiationState"); } // we keep it simple since we use this only to know if NTLM or // Kerberos are used in the context of a Negotiate handshake internal class NegotiationInfoClass { internal const string NTLM = "NTLM"; internal const string Kerberos = "Kerberos"; internal const string WDigest = "WDigest"; internal const string Negotiate = "Negotiate"; internal string AuthenticationPackage; internal NegotiationInfoClass(SafeHandle safeHandle, int negotiationState) { if (safeHandle.IsInvalid) { GlobalLog.Print("NegotiationInfoClass::.ctor() the handle is invalid:" + (safeHandle.DangerousGetHandle()).ToString("x")); return; } IntPtr packageInfo = safeHandle.DangerousGetHandle(); GlobalLog.Print("NegotiationInfoClass::.ctor() packageInfo:" + packageInfo.ToString("x8") + " negotiationState:" + negotiationState.ToString("x8")); if (negotiationState == Interop.Secur32.SECPKG_NEGOTIATION_COMPLETE || negotiationState == Interop.Secur32.SECPKG_NEGOTIATION_OPTIMISTIC) { IntPtr unmanagedString = Marshal.ReadIntPtr(packageInfo, SecurityPackageInfo.NameOffest); string name = null; if (unmanagedString != IntPtr.Zero) { name = Marshal.PtrToStringUni(unmanagedString); } GlobalLog.Print("NegotiationInfoClass::.ctor() packageInfo:" + packageInfo.ToString("x8") + " negotiationState:" + negotiationState.ToString("x8") + " name:" + Logging.ObjectToString(name)); // an optimization for future string comparisons if (string.Compare(name, Kerberos, StringComparison.OrdinalIgnoreCase) == 0) { AuthenticationPackage = Kerberos; } else if (string.Compare(name, NTLM, StringComparison.OrdinalIgnoreCase) == 0) { AuthenticationPackage = NTLM; } else if (string.Compare(name, WDigest, StringComparison.OrdinalIgnoreCase) == 0) { AuthenticationPackage = WDigest; } else { AuthenticationPackage = name; } } } } [StructLayout(LayoutKind.Sequential)] internal struct SecurityPackageInfo { // see SecPkgInfoW in <sspi.h> internal int Capabilities; internal short Version; internal short RPCID; internal int MaxToken; internal IntPtr Name; internal IntPtr Comment; internal static readonly int Size = Marshal.SizeOf<SecurityPackageInfo>(); internal static readonly int NameOffest = (int)Marshal.OffsetOf<SecurityPackageInfo>("Name"); } internal class SecurityPackageInfoClass { internal int Capabilities = 0; internal short Version = 0; internal short RPCID = 0; internal int MaxToken = 0; internal string Name = null; internal string Comment = null; /* * This is to support SSL under semi trusted environment. * Note that it is only for SSL with no client cert * * Important: safeHandle should not be Disposed during construction of this object. */ internal SecurityPackageInfoClass(SafeHandle safeHandle, int index) { if (safeHandle.IsInvalid) { GlobalLog.Print("SecurityPackageInfoClass::.ctor() the pointer is invalid: " + (safeHandle.DangerousGetHandle()).ToString("x")); return; } IntPtr unmanagedAddress = IntPtrHelper.Add(safeHandle.DangerousGetHandle(), SecurityPackageInfo.Size * index); GlobalLog.Print("SecurityPackageInfoClass::.ctor() unmanagedPointer: " + ((long)unmanagedAddress).ToString("x")); Capabilities = Marshal.ReadInt32(unmanagedAddress, (int)Marshal.OffsetOf<SecurityPackageInfo>("Capabilities")); Version = Marshal.ReadInt16(unmanagedAddress, (int)Marshal.OffsetOf<SecurityPackageInfo>("Version")); RPCID = Marshal.ReadInt16(unmanagedAddress, (int)Marshal.OffsetOf<SecurityPackageInfo>("RPCID")); MaxToken = Marshal.ReadInt32(unmanagedAddress, (int)Marshal.OffsetOf<SecurityPackageInfo>("MaxToken")); IntPtr unmanagedString; unmanagedString = Marshal.ReadIntPtr(unmanagedAddress, (int)Marshal.OffsetOf<SecurityPackageInfo>("Name")); if (unmanagedString != IntPtr.Zero) { Name = Marshal.PtrToStringUni(unmanagedString); GlobalLog.Print("Name: " + Name); } unmanagedString = Marshal.ReadIntPtr(unmanagedAddress, (int)Marshal.OffsetOf<SecurityPackageInfo>("Comment")); if (unmanagedString != IntPtr.Zero) { Comment = Marshal.PtrToStringUni(unmanagedString); GlobalLog.Print("Comment: " + Comment); } GlobalLog.Print("SecurityPackageInfoClass::.ctor(): " + ToString()); } public override string ToString() { return "Capabilities:" + String.Format(CultureInfo.InvariantCulture, "0x{0:x}", Capabilities) + " Version:" + Version.ToString(NumberFormatInfo.InvariantInfo) + " RPCID:" + RPCID.ToString(NumberFormatInfo.InvariantInfo) + " MaxToken:" + MaxToken.ToString(NumberFormatInfo.InvariantInfo) + " Name:" + ((Name == null) ? "(null)" : Name) + " Comment:" + ((Comment == null) ? "(null)" : Comment ); } } [StructLayout(LayoutKind.Sequential)] internal struct Bindings { // see SecPkgContext_Bindings in <sspi.h> internal int BindingsLength; internal IntPtr pBindings; } }
namespace NEventStore.Persistence.Sql.SqlDialects { using System; using System.Data; using System.Reflection; using System.Transactions; using NEventStore.Persistence.Sql; public class OracleNativeDialect : CommonSqlDialect { private const int UniqueKeyViolation = -2146232008; Action<IConnectionFactory, IDbConnection, IDbStatement, byte[]> _addPayloadParamater; public override string AppendSnapshotToCommit { get { return OracleNativeStatements.AppendSnapshotToCommit; } } public override string CheckpointNumber { get { return MakeOracleParameter(base.CheckpointNumber); } } public override string CommitId { get { return MakeOracleParameter(base.CommitId); } } public override string CommitSequence { get { return MakeOracleParameter(base.CommitSequence); } } public override string CommitStamp { get { return MakeOracleParameter(base.CommitStamp); } } public override string CommitStampEnd { get { return MakeOracleParameter(base.CommitStampEnd); } } public override string CommitStampStart { get { return MakeOracleParameter(CommitStampStart); } } public override string DuplicateCommit { get { return OracleNativeStatements.DuplicateCommit; } } public override string GetSnapshot { get { return OracleNativeStatements.GetSnapshot; } } public override string GetCommitsFromStartingRevision { get { return LimitedQuery(OracleNativeStatements.GetCommitsFromStartingRevision); } } public override string GetCommitsFromInstant { get { return OraclePaging(OracleNativeStatements.GetCommitsFromInstant); } } public override string GetCommitsFromCheckpoint { get { return OraclePaging(OracleNativeStatements.GetCommitsSinceCheckpoint); } } public override string GetCommitsFromBucketAndCheckpoint { get { return OraclePaging(OracleNativeStatements.GetCommitsFromBucketAndCheckpoint); } } public override string GetUndispatchedCommits { get { return OraclePaging(base.GetUndispatchedCommits); } } public override string GetStreamsRequiringSnapshots { get { return LimitedQuery(OracleNativeStatements.GetStreamsRequiringSnapshots); } } public override string InitializeStorage { get { return OracleNativeStatements.InitializeStorage; } } public override string Limit { get { return MakeOracleParameter(base.Limit); } } public override string MarkCommitAsDispatched { get { return OracleNativeStatements.MarkCommitAsDispatched; } } public override string PersistCommit { get { return OracleNativeStatements.PersistCommit; } } public override string PurgeStorage { get { return OracleNativeStatements.PurgeStorage; } } public override string DeleteStream { get { return OracleNativeStatements.DeleteStream; } } public override string Drop { get { return OracleNativeStatements.DropTables; } } public override string Skip { get { return MakeOracleParameter(base.Skip); } } public override string BucketId { get { return MakeOracleParameter(base.BucketId); } } public override string StreamId { get { return MakeOracleParameter(base.StreamId); } } public override string StreamIdOriginal { get { return MakeOracleParameter(base.StreamIdOriginal); } } public override string Threshold { get { return MakeOracleParameter(base.Threshold); } } public override string Payload { get { return MakeOracleParameter(base.Payload); } } public override string StreamRevision { get { return MakeOracleParameter(base.StreamRevision); } } public override string MaxStreamRevision { get { return MakeOracleParameter(base.MaxStreamRevision); } } public override IDbStatement BuildStatement(TransactionScope scope, IDbConnection connection, IDbTransaction transaction) { return new OracleDbStatement(this, scope, connection, transaction); } public override object CoalesceParameterValue(object value) { if (value is Guid) { value = ((Guid) value).ToByteArray(); } return value; } private static string ExtractOrderBy(ref string query) { int orderByIndex = query.IndexOf("ORDER BY", StringComparison.Ordinal); string result = query.Substring(orderByIndex).Replace(";", String.Empty); query = query.Substring(0, orderByIndex); return result; } public override bool IsDuplicate(Exception exception) { return exception.Message.Contains("ORA-00001"); } public override NextPageDelegate NextPageDelegate { get { return (q, r) => { } ; } } public override void AddPayloadParamater(IConnectionFactory connectionFactory, IDbConnection connection, IDbStatement cmd, byte[] payload) { if (_addPayloadParamater == null) { string dbProviderAssemblyName = connectionFactory.GetDbProviderFactoryType().Assembly.GetName().Name; const string oracleManagedDataAcccessAssemblyName = "Oracle.ManagedDataAccess"; const string oracleDataAcccessAssemblyName = "Oracle.DataAccess"; if (dbProviderAssemblyName.Equals(oracleManagedDataAcccessAssemblyName, StringComparison.Ordinal)) { _addPayloadParamater = CreateOraAddPayloadAction(oracleManagedDataAcccessAssemblyName); } else if (dbProviderAssemblyName.Equals(oracleDataAcccessAssemblyName, StringComparison.Ordinal)) { _addPayloadParamater = CreateOraAddPayloadAction(oracleDataAcccessAssemblyName); } else { _addPayloadParamater = (connectionFactory2, connection2, cmd2, payload2) => base.AddPayloadParamater(connectionFactory2, connection2, cmd2, payload2); } } _addPayloadParamater(connectionFactory, connection, cmd, payload); } private Action<IConnectionFactory, IDbConnection, IDbStatement, byte[]> CreateOraAddPayloadAction( string assemblyName) { Assembly assembly = Assembly.Load(assemblyName); var oracleParamaterType = assembly.GetType(assemblyName + ".Client.OracleParameter", true); var oracleParamaterValueProperty = oracleParamaterType.GetProperty("Value"); var oracleBlobType = assembly.GetType(assemblyName + ".Types.OracleBlob", true); var oracleBlobWriteMethod = oracleBlobType.GetMethod("Write", new []{ typeof(Byte[]), typeof(int), typeof(int)}); Type oracleParamapterType = assembly.GetType(assemblyName + ".Client.OracleDbType", true); FieldInfo blobField = oracleParamapterType.GetField("Blob"); var blobDbType = blobField.GetValue(null); return (_, connection2, cmd2, payload2) => { object payloadParam = Activator.CreateInstance(oracleParamaterType, new[] { Payload, blobDbType }); ((OracleDbStatement)cmd2).AddParameter(Payload, payloadParam); object oracleConnection = ((ConnectionScope)connection2).Current; object oracleBlob = Activator.CreateInstance(oracleBlobType, new[] { oracleConnection }); oracleBlobWriteMethod.Invoke(oracleBlob, new object[] { payload2, 0, payload2.Length }); oracleParamaterValueProperty.SetValue(payloadParam, oracleBlob, null); }; } private static string LimitedQuery(string query) { query = RemovePaging(query); if (query.EndsWith(";")) { query = query.TrimEnd(new[] {';'}); } string value = OracleNativeStatements.LimitedQueryFormat.FormatWith(query); return value; } private static string MakeOracleParameter(string parameterName) { return parameterName.Replace('@', ':'); } private static string OraclePaging(string query) { query = RemovePaging(query); string orderBy = ExtractOrderBy(ref query); int fromIndex = query.IndexOf("FROM ", StringComparison.Ordinal); string from = query.Substring(fromIndex); string select = query.Substring(0, fromIndex); string value = OracleNativeStatements.PagedQueryFormat.FormatWith(select, orderBy, from); return value; } private static string RemovePaging(string query) { return query .Replace("\n LIMIT @Limit OFFSET @Skip;", ";") .Replace("\n LIMIT @Limit;", ";") .Replace("WHERE ROWNUM <= :Limit;", ";") .Replace("\r\nWHERE ROWNUM <= (:Skip + 1) AND ROWNUM > :Skip", ";"); } } }
using System; using System.Collections; using System.Globalization; using System.Text; using Lucene.Net.Documents; using Lucene.Net.Support; namespace Lucene.Net.Search { using Lucene.Net.Randomized.Generators; using NUnit.Framework; /* * 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 Analyzer = Lucene.Net.Analysis.Analyzer; using BasicAutomata = Lucene.Net.Util.Automaton.BasicAutomata; using CharacterRunAutomaton = Lucene.Net.Util.Automaton.CharacterRunAutomaton; using Directory = Lucene.Net.Store.Directory; using Document = Documents.Document; using Field = Field; using IndexReader = Lucene.Net.Index.IndexReader; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using MockTokenizer = Lucene.Net.Analysis.MockTokenizer; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using StringField = StringField; using Term = Lucene.Net.Index.Term; using TestUtil = Lucene.Net.Util.TestUtil; using TextField = TextField; /// <summary> /// Simple base class for checking search equivalence. /// Extend it, and write tests that create <seealso cref="#randomTerm()"/>s /// (all terms are single characters a-z), and use /// <seealso cref="#assertSameSet(Query, Query)"/> and /// <seealso cref="#assertSubsetOf(Query, Query)"/> /// </summary> public abstract class SearchEquivalenceTestBase : LuceneTestCase { protected internal static IndexSearcher S1, S2; protected internal static Directory Directory; protected internal static IndexReader Reader; protected internal static Analyzer Analyzer; protected internal static string Stopword; // we always pick a character as a stopword /// <summary> /// LUCENENET specific /// Is non-static because ClassEnvRule is no longer static. /// </summary> [OneTimeSetUp] public override void BeforeClass() { base.BeforeClass(); Random random = Random(); Directory = NewDirectory(); Stopword = "" + RandomChar(); CharacterRunAutomaton stopset = new CharacterRunAutomaton(BasicAutomata.MakeString(Stopword)); Analyzer = new MockAnalyzer(random, MockTokenizer.WHITESPACE, false, stopset); RandomIndexWriter iw = new RandomIndexWriter(random, Directory, Analyzer, ClassEnvRule.similarity, ClassEnvRule.timeZone); Document doc = new Document(); Field id = new StringField("id", "", Field.Store.NO); Field field = new TextField("field", "", Field.Store.NO); doc.Add(id); doc.Add(field); // index some docs int numDocs = AtLeast(1000); for (int i = 0; i < numDocs; i++) { id.SetStringValue(Convert.ToString(i, CultureInfo.InvariantCulture)); field.SetStringValue(RandomFieldContents()); iw.AddDocument(doc); } // delete some docs int numDeletes = numDocs / 20; for (int i = 0; i < numDeletes; i++) { Term toDelete = new Term("id", Convert.ToString(random.Next(numDocs), CultureInfo.InvariantCulture)); if (random.NextBoolean()) { iw.DeleteDocuments(toDelete); } else { iw.DeleteDocuments(new TermQuery(toDelete)); } } Reader = iw.Reader; S1 = NewSearcher(Reader); S2 = NewSearcher(Reader); iw.Dispose(); } [OneTimeTearDown] public override void AfterClass() { Reader.Dispose(); Directory.Dispose(); Analyzer.Dispose(); Reader = null; Directory = null; Analyzer = null; S1 = S2 = null; base.AfterClass(); } /// <summary> /// populate a field with random contents. /// terms should be single characters in lowercase (a-z) /// tokenization can be assumed to be on whitespace. /// </summary> internal static string RandomFieldContents() { // TODO: zipf-like distribution StringBuilder sb = new StringBuilder(); int numTerms = Random().Next(15); for (int i = 0; i < numTerms; i++) { if (sb.Length > 0) { sb.Append(' '); // whitespace } sb.Append(RandomChar()); } return sb.ToString(); } /// <summary> /// returns random character (a-z) /// </summary> internal static char RandomChar() { return (char)TestUtil.NextInt(Random(), 'a', 'z'); } /// <summary> /// returns a term suitable for searching. /// terms are single characters in lowercase (a-z) /// </summary> protected internal virtual Term RandomTerm() { return new Term("field", "" + RandomChar()); } /// <summary> /// Returns a random filter over the document set /// </summary> protected internal virtual Filter RandomFilter() { return new QueryWrapperFilter(TermRangeQuery.NewStringRange("field", "a", "" + RandomChar(), true, true)); } /// <summary> /// Asserts that the documents returned by <code>q1</code> /// are the same as of those returned by <code>q2</code> /// </summary> public virtual void AssertSameSet(Query q1, Query q2) { AssertSubsetOf(q1, q2); AssertSubsetOf(q2, q1); } /// <summary> /// Asserts that the documents returned by <code>q1</code> /// are a subset of those returned by <code>q2</code> /// </summary> public virtual void AssertSubsetOf(Query q1, Query q2) { // test without a filter AssertSubsetOf(q1, q2, null); // test with a filter (this will sometimes cause advance'ing enough to test it) AssertSubsetOf(q1, q2, RandomFilter()); } /// <summary> /// Asserts that the documents returned by <code>q1</code> /// are a subset of those returned by <code>q2</code>. /// /// Both queries will be filtered by <code>filter</code> /// </summary> protected internal virtual void AssertSubsetOf(Query q1, Query q2, Filter filter) { // TRUNK ONLY: test both filter code paths if (filter != null && Random().NextBoolean()) { q1 = new FilteredQuery(q1, filter, TestUtil.RandomFilterStrategy(Random())); q2 = new FilteredQuery(q2, filter, TestUtil.RandomFilterStrategy(Random())); filter = null; } // not efficient, but simple! TopDocs td1 = S1.Search(q1, filter, Reader.MaxDoc); TopDocs td2 = S2.Search(q2, filter, Reader.MaxDoc); Assert.IsTrue(td1.TotalHits <= td2.TotalHits); // fill the superset into a bitset var bitset = new BitArray(td2.ScoreDocs.Length); for (int i = 0; i < td2.ScoreDocs.Length; i++) { bitset.SafeSet(td2.ScoreDocs[i].Doc, true); } // check in the subset, that every bit was set by the super for (int i = 0; i < td1.ScoreDocs.Length; i++) { Assert.IsTrue(bitset.SafeGet(td1.ScoreDocs[i].Doc)); } } } }
using System; using System.Collections.Generic; using System.Data; using System.Web; using System.Linq; using System.Web.Mvc; using System.Web.Routing; using System.Web.Security; using System.Web.UI; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.IO; using Umbraco.Core.Cache; using Umbraco.Core.Logging; using Umbraco.Core.Services; using umbraco.BusinessLogic; using umbraco.DataLayer; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.Security; namespace umbraco.BasePages { /// <summary> /// umbraco.BasePages.BasePage is the default page type for the umbraco backend. /// The basepage keeps track of the current user and the page context. But does not /// Restrict access to the page itself. /// The keep the page secure, the umbracoEnsuredPage class should be used instead /// </summary> [Obsolete("This class has been superceded by Umbraco.Web.UI.Pages.BasePage")] public class BasePage : System.Web.UI.Page { private User _user; private bool _userisValidated = false; private ClientTools _clientTools; /// <summary> /// The path to the umbraco root folder /// </summary> protected string UmbracoPath = SystemDirectories.Umbraco; /// <summary> /// The current user ID /// </summary> protected int uid = 0; /// <summary> /// The page timeout in seconds. /// </summary> protected long timeout = 0; /// <summary> /// Unused, please do not use /// </summary> [Obsolete("Obsolete, For querying the database use the new UmbracoDatabase object ApplicationContext.Current.DatabaseContext.Database", false)] protected static ISqlHelper SqlHelper { get { return BusinessLogic.Application.SqlHelper; } } /// <summary> /// Returns the current ApplicationContext /// </summary> public ApplicationContext ApplicationContext { get { return ApplicationContext.Current; } } /// <summary> /// Returns a ServiceContext /// </summary> public ServiceContext Services { get { return ApplicationContext.Services; } } /// <summary> /// Returns a DatabaseContext /// </summary> public DatabaseContext DatabaseContext { get { return ApplicationContext.DatabaseContext; } } /// <summary> /// Returns the current BasePage for the current request. /// This assumes that the current page is a BasePage, otherwise, returns null; /// </summary> [Obsolete("Should use the Umbraco.Web.UmbracoContext.Current singleton instead to access common methods and properties")] public static BasePage Current { get { var page = HttpContext.Current.CurrentHandler as BasePage; if (page != null) return page; //the current handler is not BasePage but people might be expecting this to be the case if they // are using this singleton accesor... which is legacy code now and shouldn't be used. When people // start using Umbraco.Web.UI.Pages.BasePage then this will not be the case! So, we'll just return a // new instance of BasePage as a hack to make it work. if (HttpContext.Current.Items["umbraco.BasePages.BasePage"] == null) { HttpContext.Current.Items["umbraco.BasePages.BasePage"] = new BasePage(); } return (BasePage)HttpContext.Current.Items["umbraco.BasePages.BasePage"]; } } private UrlHelper _url; /// <summary> /// Returns a UrlHelper /// </summary> /// <remarks> /// This URL helper is created without any route data and an empty request context /// </remarks> public UrlHelper Url { get { return _url ?? (_url = new UrlHelper(Context.Request.RequestContext)); } } /// <summary> /// Returns a refernce of an instance of ClientTools for access to the pages client API /// </summary> public ClientTools ClientTools { get { if (_clientTools == null) _clientTools = new ClientTools(this); return _clientTools; } } [Obsolete("Use ClientTools instead")] public void RefreshPage(int Seconds) { ClientTools.RefreshAdmin(Seconds); } //NOTE: This is basically replicated in WebSecurity because this class exists in a poorly placed assembly. - also why it is obsolete. private void ValidateUser() { var ticket = Context.GetUmbracoAuthTicket(); if (ticket != null) { if (ticket.Expired == false) { _user = BusinessLogic.User.GetUser(GetUserId("")); // Check for console access if (_user.Disabled || (_user.NoConsole && GlobalSettings.RequestIsInUmbracoApplication(Context))) { throw new ArgumentException("You have no priviledges to the umbraco console. Please contact your administrator"); } _userisValidated = true; UpdateLogin(); } else { throw new ArgumentException("User has timed out!!"); } } else { throw new InvalidOperationException("The user has no umbraco contextid - try logging in"); } } /// <summary> /// Gets the user id. /// </summary> /// <param name="umbracoUserContextID">This is not used</param> /// <returns></returns> [Obsolete("This method is no longer used, use the GetUserId() method without parameters instead")] public static int GetUserId(string umbracoUserContextID) { return GetUserId(); } /// <summary> /// Gets the currnet user's id. /// </summary> /// <returns></returns> public static int GetUserId() { var identity = HttpContext.Current.GetCurrentIdentity( //DO NOT AUTO-AUTH UNLESS THE CURRENT HANDLER IS WEBFORMS! // Without this check, anything that is using this legacy API, like ui.Text will // automatically log the back office user in even if it is a front-end request (if there is // a back office user logged in. This can cause problems becaues the identity is changing mid // request. For example: http://issues.umbraco.org/issue/U4-4010 HttpContext.Current.CurrentHandler is Page); if (identity == null) return -1; return Convert.ToInt32(identity.Id); } // Added by NH to use with webservices authentications /// <summary> /// Validates the user context ID. /// </summary> /// <param name="currentUmbracoUserContextID">This doesn't do anything</param> /// <returns></returns> [Obsolete("This method is no longer used, use the ValidateCurrentUser() method instead")] public static bool ValidateUserContextID(string currentUmbracoUserContextID) { return ValidateCurrentUser(); } /// <summary> /// Validates the currently logged in user and ensures they are not timed out /// </summary> /// <returns></returns> public static bool ValidateCurrentUser() { var identity = HttpContext.Current.GetCurrentIdentity( //DO NOT AUTO-AUTH UNLESS THE CURRENT HANDLER IS WEBFORMS! // Without this check, anything that is using this legacy API, like ui.Text will // automatically log the back office user in even if it is a front-end request (if there is // a back office user logged in. This can cause problems becaues the identity is changing mid // request. For example: http://issues.umbraco.org/issue/U4-4010 HttpContext.Current.CurrentHandler is Page); if (identity != null) { return true; } return false; } //[Obsolete("Use Umbraco.Web.Security.WebSecurity.GetTimeout instead")] public static long GetTimeout(bool bypassCache) { var ticket = HttpContext.Current.GetUmbracoAuthTicket(); if (ticket.Expired) return 0; var ticks = ticket.Expiration.Ticks - DateTime.Now.Ticks; return ticks; } // Changed to public by NH to help with webservice authentication /// <summary> /// Gets or sets the umbraco user context ID. /// </summary> /// <value>The umbraco user context ID.</value> [Obsolete("Returns the current user's unique umbraco sesion id - this cannot be set and isn't intended to be used in your code")] public static string umbracoUserContextID { get { var identity = HttpContext.Current.GetCurrentIdentity( //DO NOT AUTO-AUTH UNLESS THE CURRENT HANDLER IS WEBFORMS! // Without this check, anything that is using this legacy API, like ui.Text will // automatically log the back office user in even if it is a front-end request (if there is // a back office user logged in. This can cause problems becaues the identity is changing mid // request. For example: http://issues.umbraco.org/issue/U4-4010 HttpContext.Current.CurrentHandler is Page); return identity == null ? "" : identity.SessionId; } set { } } /// <summary> /// Clears the login. /// </summary> public void ClearLogin() { Context.UmbracoLogout(); } private void UpdateLogin() { Context.RenewUmbracoAuthTicket(); } public static void RenewLoginTimeout() { HttpContext.Current.RenewUmbracoAuthTicket(); } /// <summary> /// Logs a user in. /// </summary> /// <param name="u">The user</param> public static void doLogin(User u) { HttpContext.Current.CreateUmbracoAuthTicket(new UserData(Guid.NewGuid().ToString("N")) { Id = u.Id, AllowedApplications = u.GetApplications().Select(x => x.alias).ToArray(), RealName = u.Name, Roles = u.GetGroups(), StartContentNodes = u.UserEntity.CalculateContentStartNodeIds(ApplicationContext.Current.Services.EntityService), StartMediaNodes = u.UserEntity.CalculateMediaStartNodeIds(ApplicationContext.Current.Services.EntityService), Username = u.LoginName, Culture = ui.Culture(u) }); LogHelper.Info<BasePage>("User {0} (Id: {1}) logged in", () => u.Name, () => u.Id); } /// <summary> /// Gets the user. /// </summary> /// <returns></returns> [Obsolete("Use UmbracoUser property instead.")] public User getUser() { return UmbracoUser; } /// <summary> /// Gets the user. /// </summary> /// <value></value> public User UmbracoUser { get { if (!_userisValidated) ValidateUser(); return _user; } } /// <summary> /// Ensures the page context. /// </summary> public void ensureContext() { ValidateUser(); } [Obsolete("Use ClientTools instead")] public void speechBubble(speechBubbleIcon i, string header, string body) { ClientTools.ShowSpeechBubble(i, header, body); } //[Obsolete("Use ClientTools instead")] //public void reloadParentNode() //{ // ClientTools.ReloadParentNode(true); //} /// <summary> /// a collection of available speechbubble icons /// </summary> [Obsolete("This has been superceded by Umbraco.Web.UI.SpeechBubbleIcon but that requires the use of the Umbraco.Web.UI.Pages.BasePage or Umbraco.Web.UI.Pages.EnsuredPage objects")] public enum speechBubbleIcon { /// <summary> /// Save icon /// </summary> save, /// <summary> /// Info icon /// </summary> info, /// <summary> /// Error icon /// </summary> error, /// <summary> /// Success icon /// </summary> success, /// <summary> /// Warning icon /// </summary> warning } protected override void OnInit(EventArgs e) { base.OnInit(e); //This must be set on each page to mitigate CSRF attacks which ensures that this unique token // is added to the viewstate of each request if (umbracoUserContextID.IsNullOrWhiteSpace() == false) { ViewStateUserKey = umbracoUserContextID; } } /// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Load"></see> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs"></see> object that contains the event data.</param> protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (!Request.IsSecureConnection && GlobalSettings.UseSSL) { string serverName = HttpUtility.UrlEncode(Request.ServerVariables["SERVER_NAME"]); Response.Redirect(string.Format("https://{0}{1}", serverName, Request.FilePath)); } } /// <summary> /// Override client target. /// </summary> [Obsolete("This is no longer supported")] public bool OverrideClientTarget = false; } }
namespace Tests.Surface.Lender.Slos.Dal.Bases { using System; using System.ComponentModel; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Text; using FluentNHibernate.Cfg; using global::Lender.Slos.NHibernate; using NDbUnit.Core; using NDbUnit.Core.SqlClient; using NHibernate; [ExcludeFromCodeCoverage] public abstract class TestContextBase : IDisposable { public const string DefaultConnectionString = @"Data Source=(local)\SQLExpress;Initial Catalog=Lender.Slos;Integrated Security=True"; public const string DefaultProjectPath = @"Tests\Surface\Lender.Slos.Dal\Bases"; public const string DefaultXmlSchemaFilename = @"Lender.Slos.DataSet.xsd"; public const string DefaultDatabaseInitializationSql = "database.initialization.sql"; // Constructor protected TestContextBase() { ProjectPath = DefaultProjectPath; Provider = DatabaseProvider.SqlClient; } protected TestContextBase(Type typeOfClassUnderTest) : this() { ClassUnderTest = typeOfClassUnderTest; } ~TestContextBase() { Dispose(false); } public enum DatabaseProvider { [Description("System.Data.SqlClient")] SqlClient = 1, [Description("System.Data.SqlServerCe")] SqlCe = 2, [Description("System.Data.SQLite")] SqLite = 3, } public DatabaseProvider Provider { get; set; } public string ConnectionString { get; set; } public string ProjectPath { get; set; } public string FolderName { get; set; } public Type ClassUnderTest { get; set; } // NHibernate support public ISessionFactory SessionFactory { get; private set; } // Override in derived class to provide another DataSet filename. public virtual string XmlSchemaFilename { get { return null; } } public string GetRunnerConnectionString() { var connectionString = ConfigurationManager .ConnectionStrings["Tests.Surface.Runner"]; return connectionString != null ? connectionString.ConnectionString : DefaultConnectionString; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } // NHibernate support public void CreateSessionFactory(bool buildSchema = false) { try { SessionFactory = NHibernateModule .CreateSessionFactory(ConnectionString, GetMappings(), buildSchema); } catch (Exception exception) { System.Diagnostics.Trace.TraceError("Exception: {0}", exception.ToString()); throw; } } // NHibernate support public ISession GetSession() { return SessionFactory != null ? SessionFactory.OpenSession() : null; } public void SetupTestDatabase( string xmlDataFilename, bool executeCleanupScript = true, string cleanupScript = null) { var database = InitializeDatabase(cleanupScript); var xmlSchemaFile = GetFilePath( ProjectPath, @"Bases\Data", DefaultXmlSchemaFilename); if (!string.IsNullOrEmpty(XmlSchemaFilename)) { xmlSchemaFile = GetSchemaPath(XmlSchemaFilename); } database.ReadXmlSchema(xmlSchemaFile); var xmlFile = GetDataPath(xmlDataFilename); database.ReadXml(xmlFile); database.PerformDbOperation(DbOperationFlag.CleanInsertIdentity); } internal void Initialize( string projectPath) { InitializeConnection(); InitializeDatabase(projectPath); } internal void InitializeConnection() { switch (Provider) { case DatabaseProvider.SqlClient: if (string.IsNullOrEmpty(ConnectionString)) { ConnectionString = GetRunnerConnectionString(); } break; default: throw new InvalidOperationException( string.Format("Provider '{0}' is not supported.", Provider)); } } // NHibernate support protected virtual Action<MappingConfiguration> GetMappings() { return null; } internal TData Retrieve<TData>( string columnName, string tableName, string whereClause) { if (string.IsNullOrWhiteSpace(columnName)) throw new ArgumentException("IsNullOrWhiteSpace", "whereClause"); if (string.IsNullOrWhiteSpace(tableName)) throw new ArgumentException("IsNullOrWhiteSpace", "tableName"); if (string.IsNullOrWhiteSpace(whereClause)) throw new ArgumentException("IsNullOrWhiteSpace", "whereClause"); using (var sqlConnection = new SqlConnection(GetRunnerConnectionString())) { var dataSet = new DataSet(); var stringBuilder = new StringBuilder(); stringBuilder.AppendFormat( "SELECT [{0}] FROM [dbo].[{1}] WHERE {2}", columnName, tableName, whereClause); var command = sqlConnection.CreateCommand(); command.CommandType = CommandType.Text; command.CommandText = stringBuilder.ToString(); sqlConnection.Open(); var adapter = new SqlDataAdapter(command); adapter.Fill(dataSet); command.Parameters.Clear(); var returnValue = default(TData); if (dataSet.Tables.Count > 0) { var table = dataSet.Tables[0]; if (table.Rows.Count == 0) { throw new InvalidOperationException("Query returned zero records"); } foreach (DataRow row in table.Rows) { returnValue = row.Field<TData>(columnName); } } else { throw new InvalidOperationException("Query returned no results"); } return returnValue; } } protected virtual void Dispose(bool disposing) { if (disposing) { // Clean up all managed resources } // Clean up any unmanaged resources here. // NHibernate support if (SessionFactory != null) { SessionFactory.Dispose(); SessionFactory = null; } } private static string GetFilePath( string projectPath, string relativePath, string filename) { var path = Path.Combine(relativePath, filename); // Running in the ReSharper runner. var relativeToBinPath = Path.Combine(Environment.CurrentDirectory, @"..\..\"); var filePath = Path.Combine(relativeToBinPath, path); if (File.Exists(filePath)) return filePath; filePath = Path.Combine(Environment.CurrentDirectory, path); if (File.Exists(filePath)) return filePath; // Running in the command line test runner. var commandLinePath = Path.Combine( Environment.CurrentDirectory, projectPath); filePath = Path.Combine(commandLinePath, path); return File.Exists(filePath) ? filePath : path; } private INDbUnitTest CreateDbInstance() { switch (Provider) { case DatabaseProvider.SqlClient: return new SqlDbUnitTest(ConnectionString); default: throw new InvalidOperationException( string.Format("Provider '{0}' is not supported.", Provider)); } } private INDbUnitTest InitializeDatabase( string cleanupScript = null) { var database = CreateDbInstance(); var filename = GetFilePath( ProjectPath, @"Bases\Scripts", cleanupScript ?? DefaultDatabaseInitializationSql); if (File.Exists(filename)) { database.Scripts.AddSingle(filename); database.ExecuteScripts(); } database.Scripts.ClearAll(); return database; } private string GetSchemaPath( string filename) { var xmlSchemaPath = string.Format(@"{0}\Data", FolderName); return GetFilePath(ProjectPath, xmlSchemaPath, filename); } private string GetDataPath( string filename) { var xmlDataPath = string.Format(@"{0}\Data", FolderName ?? "."); return GetFilePath(ProjectPath, xmlDataPath, filename); } } }
// 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 0.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Internal.Resources { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for FeaturesOperations. /// </summary> public static partial class FeaturesOperationsExtensions { /// <summary> /// Gets all the preview features that are available through AFEC for the /// subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<FeatureResult> ListAll(this IFeaturesOperations operations) { return Task.Factory.StartNew(s => ((IFeaturesOperations)s).ListAllAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets all the preview features that are available through AFEC for the /// subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<FeatureResult>> ListAllAsync(this IFeaturesOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all the preview features in a provider namespace that are available /// through AFEC for the subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceProviderNamespace'> /// The namespace of the resource provider for getting features. /// </param> public static IPage<FeatureResult> List(this IFeaturesOperations operations, string resourceProviderNamespace) { return Task.Factory.StartNew(s => ((IFeaturesOperations)s).ListAsync(resourceProviderNamespace), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets all the preview features in a provider namespace that are available /// through AFEC for the subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceProviderNamespace'> /// The namespace of the resource provider for getting features. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<FeatureResult>> ListAsync(this IFeaturesOperations operations, string resourceProviderNamespace, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(resourceProviderNamespace, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the preview feature with the specified name. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceProviderNamespace'> /// The resource provider namespace for the feature. /// </param> /// <param name='featureName'> /// The name of the feature to get. /// </param> public static FeatureResult Get(this IFeaturesOperations operations, string resourceProviderNamespace, string featureName) { return Task.Factory.StartNew(s => ((IFeaturesOperations)s).GetAsync(resourceProviderNamespace, featureName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the preview feature with the specified name. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceProviderNamespace'> /// The resource provider namespace for the feature. /// </param> /// <param name='featureName'> /// The name of the feature to get. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<FeatureResult> GetAsync(this IFeaturesOperations operations, string resourceProviderNamespace, string featureName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceProviderNamespace, featureName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Registers the preview feature for the subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceProviderNamespace'> /// The namespace of the resource provider. /// </param> /// <param name='featureName'> /// The name of the feature to register. /// </param> public static FeatureResult Register(this IFeaturesOperations operations, string resourceProviderNamespace, string featureName) { return Task.Factory.StartNew(s => ((IFeaturesOperations)s).RegisterAsync(resourceProviderNamespace, featureName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Registers the preview feature for the subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceProviderNamespace'> /// The namespace of the resource provider. /// </param> /// <param name='featureName'> /// The name of the feature to register. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<FeatureResult> RegisterAsync(this IFeaturesOperations operations, string resourceProviderNamespace, string featureName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.RegisterWithHttpMessagesAsync(resourceProviderNamespace, featureName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all the preview features that are available through AFEC for the /// subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<FeatureResult> ListAllNext(this IFeaturesOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IFeaturesOperations)s).ListAllNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets all the preview features that are available through AFEC for the /// subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<FeatureResult>> ListAllNextAsync(this IFeaturesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all the preview features in a provider namespace that are available /// through AFEC for the subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<FeatureResult> ListNext(this IFeaturesOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IFeaturesOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets all the preview features in a provider namespace that are available /// through AFEC for the subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<FeatureResult>> ListNextAsync(this IFeaturesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Data.Services.Client; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Net; using System.Security.Claims; using System.Threading; using System.Threading.Tasks; using System.Web; using System.Web.Caching; using System.Web.Mvc; using System.Web.Routing; using System.Web.Security.AntiXss; using System.Web.WebPages; using Adxstudio.Xrm; using Adxstudio.Xrm.AspNet.Cms; using Adxstudio.Xrm.AspNet.Identity; using Adxstudio.Xrm.AspNet.Mvc; using Adxstudio.Xrm.Configuration; using Adxstudio.Xrm.Core.Flighting; using Adxstudio.Xrm.Resources; using Adxstudio.Xrm.Services; using Adxstudio.Xrm.Web; using Adxstudio.Xrm.Web.Mvc; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin.Security; using Microsoft.Xrm.Client; using Microsoft.Xrm.Sdk; using Site.Areas.Account.Models; using Site.Areas.Account.ViewModels; using Site.Areas.AccountManagement; namespace Site.Areas.Account.Controllers { [Authorize] [PortalView, UnwrapNotFoundException] [OutputCache(NoStore = true, Duration = 0)] public class LoginController : Controller { public LoginController() { } public LoginController( ApplicationUserManager userManager, ApplicationSignInManager signInManager, ApplicationInvitationManager invitationManager, ApplicationOrganizationManager organizationManager) { UserManager = userManager; SignInManager = signInManager; InvitationManager = invitationManager; OrganizationManager = organizationManager; } private ApplicationUserManager _userManager; public ApplicationUserManager UserManager { get { return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); } private set { _userManager = value; } } private ApplicationInvitationManager _invitationManager; public ApplicationInvitationManager InvitationManager { get { return _invitationManager ?? HttpContext.GetOwinContext().Get<ApplicationInvitationManager>(); } private set { _invitationManager = value; } } private ApplicationOrganizationManager _organizationManager; public ApplicationOrganizationManager OrganizationManager { get { return _organizationManager ?? HttpContext.GetOwinContext().Get<ApplicationOrganizationManager>(); } private set { _organizationManager = value; } } private ApplicationStartupSettingsManager _startupSettingsManager; public ApplicationStartupSettingsManager StartupSettingsManager { get { return _startupSettingsManager ?? HttpContext.GetOwinContext().Get<ApplicationStartupSettingsManager>(); } private set { _startupSettingsManager = value; } } private static Dictionary<string, bool> _validEssLicenses; private static Dictionary<string, bool> ValidEssLicenses { get { if (_validEssLicenses == null) { // get a comma delimited list of license skus from config var licenseConfigValue = PortalSettings.Instance.Ess.ValidLicenseSkus; var licenses = licenseConfigValue.Split(new[] { ',' }); _validEssLicenses = new Dictionary<string, bool>(); // build the dictionary foreach (var license in licenses) { _validEssLicenses[license] = true; // we don't really care about the value. just need a quick lookup of the sku as key } } return _validEssLicenses; } } // the duration in minutes to allow cached ESS graph pieces to stay cached private const int GraphCacheTtlMinutes = 5; // // GET: /Login/Login [HttpGet] [AllowAnonymous] [LanguageActionFilter] [OutputCache(CacheProfile = "UserShared")] public ActionResult Login(string returnUrl, string invitationCode) { if (!string.IsNullOrWhiteSpace(ViewBag.Settings.LoginButtonAuthenticationType)) { return RedirectToAction("ExternalLogin", "Login", new { returnUrl, area = "Account", provider = ViewBag.Settings.LoginButtonAuthenticationType }); } // if the portal is ess, don't use regular local signin (this page shows signin options) if (ViewBag.IsESS) { // this action will redirect to the specified provider's login page return RedirectToAction("ExternalLogin", "Login", new { returnUrl, area = "Account", provider = StartupSettingsManager.AzureAdOptions.AuthenticationType }); } // this seems to be the only easy way to get this setting to the master page this.Request.RequestContext.RouteData.Values["DisableChatWidget"] = true; return View(GetLoginViewModel(null, null, returnUrl, invitationCode)); } private ApplicationSignInManager _signInManager; public ApplicationSignInManager SignInManager { get { return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>(); } private set { _signInManager = value; } } protected override void Initialize(RequestContext requestContext) { base.Initialize(requestContext); var isLocal = requestContext.HttpContext.IsDebuggingEnabled && requestContext.HttpContext.Request.IsLocal; var website = requestContext.HttpContext.GetWebsite(); ViewBag.Settings = website.GetAuthenticationSettings(isLocal); ViewBag.IsESS = PortalSettings.Instance.Ess.IsEss; ViewBag.AzureAdOrExternalLoginEnabled = ViewBag.Settings.ExternalLoginEnabled || StartupSettingsManager.AzureAdOptions != null; ViewBag.ExternalRegistrationEnabled = StartupSettingsManager.ExternalRegistrationEnabled; ViewBag.IdentityErrors = website.GetIdentityErrors(this.HttpContext.GetOwinContext()); } // // POST: /Login/Login [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] [LocalLogin] [Throttle(Name= "LoginThrottle")] public async Task<ActionResult> Login(LoginViewModel model, string returnUrl, string invitationCode) { ViewBag.LoginSuccessful = false; if (ViewBag.Locked == true) { AddErrors(ViewBag.IdentityErrors.TooManyAttempts()); return View(GetLoginViewModel(null, null, returnUrl, invitationCode)); } if (!ModelState.IsValid || (ViewBag.Settings.LocalLoginByEmail && string.IsNullOrWhiteSpace(model.Email)) || (!ViewBag.Settings.LocalLoginByEmail && string.IsNullOrWhiteSpace(model.Username))) { AddErrors(ViewBag.IdentityErrors.InvalidLogin()); return View(GetLoginViewModel(model, null, returnUrl, invitationCode)); } var rememberMe = ViewBag.Settings.RememberMeEnabled && model.RememberMe; // This doen't count login failures towards lockout only two factor authentication // To enable password failures to trigger lockout, change to shouldLockout: true SignInStatus result = ViewBag.Settings.LocalLoginByEmail ? await SignInManager.PasswordSignInByEmailAsync(model.Email, model.Password, rememberMe, ViewBag.Settings.TriggerLockoutOnFailedPassword) : await SignInManager.PasswordSignInAsync(model.Username, model.Password, rememberMe, ViewBag.Settings.TriggerLockoutOnFailedPassword); switch (result) { case SignInStatus.Success: ViewBag.LoginSuccessful = true; return await RedirectOnPostAuthenticate(returnUrl, invitationCode); case SignInStatus.LockedOut: AddErrors(ViewBag.IdentityErrors.UserLocked()); return View(GetLoginViewModel(model, null, returnUrl, invitationCode)); case SignInStatus.RequiresVerification: ViewBag.LoginSuccessful = true; return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, InvitationCode = invitationCode, RememberMe = rememberMe }); case SignInStatus.Failure: default: AddErrors(ViewBag.IdentityErrors.InvalidLogin()); return View(GetLoginViewModel(model, null, returnUrl, invitationCode)); } } // // GET: /Login/VerifyCode [HttpGet] [AllowAnonymous] public async Task<ActionResult> VerifyCode(string provider, string returnUrl, bool rememberMe, string invitationCode) { if (PortalSettings.Instance.Ess.IsEss) { return HttpNotFound(); } // Require that the user has already logged in via username/password or external login if (!await SignInManager.HasBeenVerifiedAsync()) { return HttpNotFound(); } if (ViewBag.Settings.IsDemoMode) { var user = await UserManager.FindByIdAsync(await SignInManager.GetVerifiedUserIdAsync()); if (user != null && user.LogonEnabled) { var code = await UserManager.GenerateTwoFactorTokenAsync(user.Id, provider); ViewBag.DemoModeCode = code; } } return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe, InvitationCode = invitationCode }); } // // POST: /Login/VerifyCode [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> VerifyCode(VerifyCodeViewModel model) { if (PortalSettings.Instance.Ess.IsEss) { return HttpNotFound(); } if (!ModelState.IsValid) { return View(model); } var rememberMe = ViewBag.Settings.RememberMeEnabled && model.RememberMe; var rememberBrowser = ViewBag.Settings.TwoFactorEnabled && ViewBag.Settings.RememberBrowserEnabled && model.RememberBrowser; SignInStatus result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent: rememberMe, rememberBrowser: rememberBrowser); switch (result) { case SignInStatus.Success: return await RedirectOnPostAuthenticate(model.ReturnUrl, model.InvitationCode); case SignInStatus.LockedOut: AddErrors(ViewBag.IdentityErrors.UserLocked()); return View(model); case SignInStatus.Failure: default: AddErrors(ViewBag.IdentityErrors.InvalidTwoFactorCode()); return View(model); } } // // GET: /Login/ForgotPassword [HttpGet] [AllowAnonymous] [LocalLogin] [LanguageActionFilter] public ActionResult ForgotPassword() { if (!ViewBag.Settings.ResetPasswordEnabled) { return HttpNotFound(); } return View(); } // // POST: /Login/ForgotPassword [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] [LocalLogin] public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model) { if (!ViewBag.Settings.ResetPasswordEnabled) { return HttpNotFound(); } if (ModelState.IsValid) { if (string.IsNullOrWhiteSpace(model.Email)) { return HttpNotFound(); } var user = await UserManager.FindByEmailAsync(model.Email); if (user == null || !user.LogonEnabled || (ViewBag.Settings.ResetPasswordRequiresConfirmedEmail && !(await UserManager.IsEmailConfirmedAsync(user.Id)))) { // Don't reveal that the user does not exist or is not confirmed return View("ForgotPasswordConfirmation"); } var code = await UserManager.GeneratePasswordResetTokenAsync(user.Id); var callbackUrl = Url.Action("ResetPassword", "Login", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); var parameters = new Dictionary<string, object> { { "UserId", user.Id }, { "Code", code }, { "UrlCode", AntiXssEncoder.UrlEncode(code) }, { "CallbackUrl", callbackUrl }, { "Email", model.Email } }; try { await OrganizationManager.InvokeProcessAsync("adx_SendPasswordResetToContact", user.ContactId, parameters); } catch (System.ServiceModel.FaultException ex) { var guid = WebEventSource.Log.GenericErrorException(ex); ViewBag.ErrorMessage = string.Format(ResourceManager.GetString("Generic_Error_Message"), guid); return View("ForgotPassword"); } //await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking here: <a href=\"" + callbackUrl + "\">link</a>"); if (ViewBag.Settings.IsDemoMode) { ViewBag.DemoModeLink = callbackUrl; } return View("ForgotPasswordConfirmation"); } // If we got this far, something failed, redisplay form return View(model); } // // GET: /Login/ForgotPasswordConfirmation [HttpGet] [AllowAnonymous] [LocalLogin] public ActionResult ForgotPasswordConfirmation() { if (!ViewBag.Settings.ResetPasswordEnabled) { return HttpNotFound(); } return View(); } // // GET: /Login/ResetPassword [HttpGet] [AllowAnonymous] [LocalLogin] [LanguageActionFilter] public ActionResult ResetPassword(string userId, string code) { if (!ViewBag.Settings.ResetPasswordEnabled) { return HttpNotFound(); } if (userId == null || code == null) { return HttpNotFound(); } return View(); } // // POST: /Login/ResetPassword [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] [LocalLogin] public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model) { if (!ViewBag.Settings.ResetPasswordEnabled) { return HttpNotFound(); } if (!string.Equals(model.Password, model.ConfirmPassword)) { ModelState.AddModelError("Password", ViewBag.IdentityErrors.PasswordConfirmationFailure().Description); } if (!ModelState.IsValid) { return View(model); } var user = await UserManager.FindByIdAsync(model.UserId); if (user == null || !user.LogonEnabled) { // Don't reveal that the user does not exist return RedirectToAction("ResetPasswordConfirmation", "Login"); } var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password); if (result.Succeeded) { return RedirectToAction("ResetPasswordConfirmation", "Login"); } AddErrors(result); return View(); } // // GET: /Login/ResetPasswordConfirmation [HttpGet] [AllowAnonymous] [LocalLogin] public ActionResult ResetPasswordConfirmation() { if (!ViewBag.Settings.ResetPasswordEnabled) { return HttpNotFound(); } return View(); } // // GET: /Login/ConfirmEmail [HttpGet] [AllowAnonymous] public ActionResult ConfirmEmail() { if (User.Identity.IsAuthenticated) { return RedirectToProfile(null); } return View(); } // // POST: /Login/ExternalLogin [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] [ExternalLogin] public ActionResult ExternalLogin(string provider, string returnUrl, string invitationCode) { //StartupSettingsManager.AzureAdOptions.Notifications.AuthorizationCodeReceived // Request a redirect to the external login provider return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Login", new { ReturnUrl = returnUrl, InvitationCode = invitationCode, Provider = provider })); } // // GET: /Login/ExternalLogin [HttpGet] [AllowAnonymous] [ExternalLogin] [ActionName("ExternalLogin")] public ActionResult GetExternalLogin(string provider, string returnUrl, string invitationCode) { return ExternalLogin(provider, returnUrl, invitationCode); } // // GET: /Login/ExternalPasswordReset [HttpGet] [AllowAnonymous] [ExternalLogin] public void ExternalPasswordReset(string passwordResetPolicyId, string provider) { if (string.IsNullOrWhiteSpace(passwordResetPolicyId) || string.IsNullOrWhiteSpace(provider)) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, "External Password Reset could not be invoked. Password Reset Policy ID was not specified or the provider was not defined."); Redirect("~/"); } // Let the middleware know you are trying to use the password reset policy HttpContext.GetOwinContext().Set("Policy", passwordResetPolicyId); var redirectUri = Url.Action("ExternalLogin", "Login", new { area = "Account", provider }); // Set the page to redirect to after password has been successfully changed. var authenticationProperties = new AuthenticationProperties { RedirectUri = redirectUri }; ADXTrace.Instance.TraceInfo(TraceCategory.Application, "External Password Reset invoked."); HttpContext.GetOwinContext().Authentication.Challenge(authenticationProperties, provider); } // // GET: /Login/SendCode [HttpGet] [AllowAnonymous] public async Task<ActionResult> SendCode(string returnUrl, string invitationCode, bool rememberMe = false) { if (PortalSettings.Instance.Ess.IsEss) { return HttpNotFound(); } var userId = await SignInManager.GetVerifiedUserIdAsync(); if (userId == null) { throw new ApplicationException("Account error."); } var userFactors = await UserManager.GetValidTwoFactorProvidersAsync(userId); if (userFactors.Count() == 1) { // Send the code directly for a single option return await SendCode(new SendCodeViewModel { SelectedProvider = userFactors.Single(), ReturnUrl = returnUrl, RememberMe = rememberMe, InvitationCode = invitationCode }); } var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList(); return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe, InvitationCode = invitationCode }); } // // POST: /Login/SendCode [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> SendCode(SendCodeViewModel model) { if (PortalSettings.Instance.Ess.IsEss) { return HttpNotFound(); } if (!ModelState.IsValid) { return View(); } // Generate the token and send it if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider)) { throw new ApplicationException("Account error."); } return RedirectToAction("VerifyCode", new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe, InvitationCode = model.InvitationCode }); } // // GET: /Login/ExternalLoginCallback [HttpGet] [AllowAnonymous] [ExternalLogin] public async Task<ActionResult> ExternalLoginCallback(string returnUrl, string invitationCode, string provider) { var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(); if (loginInfo == null) { return RedirectToAction("Login"); } if (ViewBag.IsESS) { var graphResult = await DoAdditionalEssGraphWork(loginInfo); // will be passed as query parameter to Access Denied - Missing License liquid template // to determine correct error message to display string error = string.Empty; switch (graphResult) { case Enums.AzureADGraphAuthResults.NoValidLicense: error = "missing_license"; break; case Enums.AzureADGraphAuthResults.UserHasNoEmail: break; case Enums.AzureADGraphAuthResults.UserNotFound: break; } if (graphResult != Enums.AzureADGraphAuthResults.NoErrors) { return new RedirectToSiteMarkerResult("Access Denied - Missing License", new NameValueCollection { { "error", error } }); } } // Sign in the user with this external login provider if the user already has a login var result = await SignInManager.ExternalSignInAsync(loginInfo, false, (bool)ViewBag.Settings.TriggerLockoutOnFailedPassword); switch (result) { case SignInStatus.Success: return await RedirectOnPostAuthenticate(returnUrl, invitationCode, loginInfo); case SignInStatus.LockedOut: AddErrors(ViewBag.IdentityErrors.UserLocked()); return View("Login", GetLoginViewModel(null, null, returnUrl, invitationCode)); case SignInStatus.RequiresVerification: return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, InvitationCode = invitationCode }); case SignInStatus.Failure: default: // If the user does not have an account, then prompt the user to create an account ViewBag.ReturnUrl = returnUrl; ViewBag.InvitationCode = invitationCode; var contactId = ToContactId(await FindInvitationByCodeAsync(invitationCode)); var email = (contactId != null ? contactId.Name : null) ?? await ToEmail(loginInfo); var username = loginInfo.Login.ProviderKey; var firstName = loginInfo.ExternalIdentity.FindFirstValue(System.Security.Claims.ClaimTypes.GivenName); var lastName = loginInfo.ExternalIdentity.FindFirstValue(System.Security.Claims.ClaimTypes.Surname); return await ExternalLoginConfirmation(username, email, firstName, lastName, returnUrl, invitationCode, loginInfo); } } private async Task<string> ToEmail(ExternalLoginInfo loginInfo, CancellationToken cancellationToken = default(CancellationToken)) { if (!string.IsNullOrWhiteSpace(loginInfo?.Email)) { return loginInfo.Email; } if (this.StartupSettingsManager.AzureAdOptions != null && !string.IsNullOrWhiteSpace(this.StartupSettingsManager.AzureAdOptions.AuthenticationType) && !string.IsNullOrWhiteSpace(PortalSettings.Instance.Graph.RootUrl)) { var authenticationType = await this.StartupSettingsManager.GetAuthenticationTypeAsync(loginInfo, cancellationToken); if (this.StartupSettingsManager.AzureAdOptions.AuthenticationType == authenticationType) { // this is an Azure AD sign-in Microsoft.Azure.ActiveDirectory.GraphClient.IUser graphUser; try { graphUser = await GetGraphUser(loginInfo); } catch (Exception ex) { var guid = WebEventSource.Log.GenericErrorException(ex); ViewBag.ErrorMessage = string.Format(ResourceManager.GetString("Generic_Error_Message"), guid); graphUser = null; } if (graphUser != null) { return ToEmail(graphUser); } } } var identity = loginInfo?.ExternalIdentity; if (identity != null) { var claim = identity.FindFirst(System.Security.Claims.ClaimTypes.Email) ?? identity.FindFirst("email") ?? identity.FindFirst("emails") ?? identity.FindFirst(System.Security.Claims.ClaimTypes.Upn); if (claim != null) { return claim.Value; } } return null; } private static string ToEmail(Microsoft.Azure.ActiveDirectory.GraphClient.IUser graphUser) { if (!string.IsNullOrWhiteSpace(graphUser.Mail)) return graphUser.Mail; return graphUser.OtherMails != null ? graphUser.OtherMails.FirstOrDefault() : graphUser.UserPrincipalName; } private async Task<Enums.AzureADGraphAuthResults> DoAdditionalEssGraphWork(ExternalLoginInfo loginInfo) { var userCacheKey = $"{loginInfo.Login.ProviderKey}_graphUser"; var userAuthResultCacheKey = $"{loginInfo.Login.ProviderKey}_userAuthResult"; Microsoft.Azure.ActiveDirectory.GraphClient.IUser user = null; // if the user's already gone through the Graph check, this will be set with the error that happened if (HttpContext.Cache[userAuthResultCacheKey] != null) { return OutputGraphError((Enums.AzureADGraphAuthResults)HttpContext.Cache[userAuthResultCacheKey], userAuthResultCacheKey, loginInfo); } // if the cache here is null, we haven't retrieved the Graph user yet. retrieve it if (HttpContext.Cache[userCacheKey] == null) { user = await GetGraphUser(loginInfo, userCacheKey, userAuthResultCacheKey); if (user == null) { // resharper warns that Cache[] here might be null. won't be null since we're calling something that sets this if the return is null return (Enums.AzureADGraphAuthResults)HttpContext.Cache[userAuthResultCacheKey]; } } else { user = (Microsoft.Azure.ActiveDirectory.GraphClient.IUser)HttpContext.Cache[userCacheKey]; } // if the user doesn't have an email address, try to use the UPN if (string.IsNullOrEmpty(user.Mail)) { ADXTrace.Instance.TraceWarning(TraceCategory.Application, "Email was not set on user. Trying UPN."); // if the UPN isn't set, fail if (string.IsNullOrEmpty(user.UserPrincipalName)) { return OutputGraphError(Enums.AzureADGraphAuthResults.UserHasNoEmail, userAuthResultCacheKey, loginInfo); } loginInfo.Email = user.UserPrincipalName; } else { // retrieve email loginInfo.Email = user.Mail; } // do license check foreach (var plan in user.AssignedPlans) { if (ValidEssLicenses.ContainsKey(plan.ServicePlanId.ToString()) && plan.CapabilityStatus.Equals("Enabled", StringComparison.InvariantCultureIgnoreCase)) { return Enums.AzureADGraphAuthResults.NoErrors; } } return OutputGraphError(Enums.AzureADGraphAuthResults.NoValidLicense, userAuthResultCacheKey, loginInfo); } private async Task<Microsoft.Azure.ActiveDirectory.GraphClient.IUser> GetGraphUser(ExternalLoginInfo loginInfo) { var userCacheKey = $"{loginInfo.Login.ProviderKey}_graphUser"; var userAuthResultCacheKey = $"{loginInfo.Login.ProviderKey}_userAuthResult"; // if the user's already gone through the Graph check, this will be set with the error that happened if (HttpContext.Cache[userAuthResultCacheKey] != null) { return null; } // if the cache here is null, we haven't retrieved the Graph user yet. retrieve it if (HttpContext.Cache[userCacheKey] == null) { return await GetGraphUser(loginInfo, userCacheKey, userAuthResultCacheKey); } return (Microsoft.Azure.ActiveDirectory.GraphClient.IUser)HttpContext.Cache[userCacheKey]; } private async Task<Microsoft.Azure.ActiveDirectory.GraphClient.IUser> GetGraphUser(ExternalLoginInfo loginInfo, string userCacheKey, string userAuthResultCacheKey) { const int tokenRetryCount = 3; var client = this.GetGraphClient(loginInfo, PortalSettings.Instance.Graph.RootUrl, PortalSettings.Instance.Authentication.TenantId); Microsoft.Azure.ActiveDirectory.GraphClient.IUser user = null; // retry tokenRetryCount times to retrieve the users. each time it fails, it will nullify the cache and try again for (var x = 0; x < tokenRetryCount; x++) { try { ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Attempting to retrieve user from Graph with UPN "); // when we call this, the client will try to retrieve a token from GetAuthTokenTask() user = await client.Me.ExecuteAsync(); // if we get here then everything is alright. stop looping break; } catch (AggregateException ex) { var handled = false; foreach (var innerEx in ex.InnerExceptions) { if (innerEx.InnerException == null) { break; } var clientException = innerEx.InnerException as DataServiceClientException; if (clientException?.StatusCode == (int)HttpStatusCode.Unauthorized) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Current GraphClient auth token didn't seem to work. Discarding..."); // the token didn't seem to work. throw away cached token to retrieve new one this.TokenManager.Reset(); handled = true; } } if (!handled) { throw; } } } // if user is null here, we have a config problem where we can't get correct auth tokens despite repeated attempts if (user == null) { OutputGraphError(Enums.AzureADGraphAuthResults.AuthConfigProblem, userAuthResultCacheKey, loginInfo); return null; } // add cache entry for graph user object. it will expire in GraphCacheTtlMinutes minutes HttpRuntime.Cache.Add(userCacheKey, user, null, DateTime.MaxValue, TimeSpan.FromMinutes(GraphCacheTtlMinutes), CacheItemPriority.Normal, null); return user; } private Enums.AzureADGraphAuthResults OutputGraphError(Enums.AzureADGraphAuthResults result, string userAuthResultCacheKey, ExternalLoginInfo loginInfo) { // add cache entry for graph check result. it will expire in GraphCacheTtlMinutes minutes HttpRuntime.Cache.Add(userAuthResultCacheKey, result, null, DateTime.MaxValue, TimeSpan.FromMinutes(GraphCacheTtlMinutes), CacheItemPriority.Normal, null); switch (result) { case Enums.AzureADGraphAuthResults.UserNotFound: ADXTrace.Instance.TraceError(TraceCategory.Application, "Azure AD didn't have the user with the specified NameIdentifier"); return Enums.AzureADGraphAuthResults.UserNotFound; case Enums.AzureADGraphAuthResults.UserHasNoEmail: ADXTrace.Instance.TraceError(TraceCategory.Application, "UPN was not set on user."); return Enums.AzureADGraphAuthResults.UserHasNoEmail; case Enums.AzureADGraphAuthResults.NoValidLicense: ADXTrace.Instance.TraceError(TraceCategory.Application, "No valid license was found assigned to the user"); return Enums.AzureADGraphAuthResults.NoValidLicense; case Enums.AzureADGraphAuthResults.AuthConfigProblem: ADXTrace.Instance.TraceError(TraceCategory.Application, "There's a critical problem with retrieving Graph auth tokens."); return Enums.AzureADGraphAuthResults.AuthConfigProblem; } ADXTrace.Instance.TraceError(TraceCategory.Application, "An unknown graph error occurred. Passed through UserNotFound, UserHasNoEmail, and NoValidLicense."); return Enums.AzureADGraphAuthResults.UnknownError; } private readonly Lazy<CrmTokenManager> tokenManager = new Lazy<CrmTokenManager>(CreateCrmTokenManager); private static CrmTokenManager CreateCrmTokenManager() { return new CrmTokenManager(PortalSettings.Instance.Authentication, PortalSettings.Instance.Certificate, PortalSettings.Instance.Graph.RootUrl); } private ICrmTokenManager TokenManager => this.tokenManager.Value; private Microsoft.Azure.ActiveDirectory.GraphClient.ActiveDirectoryClient GetGraphClient(ExternalLoginInfo loginInfo, string graphRoot, string tenantId) { var accessCodeClaim = loginInfo.ExternalIdentity.FindFirst("AccessCode"); var accessCode = accessCodeClaim?.Value; return new Microsoft.Azure.ActiveDirectory.GraphClient.ActiveDirectoryClient( new Uri(graphRoot + "/" + tenantId), async () => await this.TokenManager.GetTokenAsync(accessCode)); } // // POST: /Login/ExternalLoginConfirmation [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] [ExternalLogin] public Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl, string invitationCode, CancellationToken cancellationToken) { return ExternalLoginConfirmation(model.Username ?? model.Email, model.Email, model.FirstName, model.LastName, returnUrl, invitationCode, null, cancellationToken); } protected virtual async Task<ActionResult> ExternalLoginConfirmation(string username, string email, string firstName, string lastName, string returnUrl, string invitationCode, ExternalLoginInfo loginInfo, CancellationToken cancellationToken = default(CancellationToken)) { loginInfo = loginInfo ?? await AuthenticationManager.GetExternalLoginInfoAsync(); if (loginInfo == null) { ADXTrace.Instance.TraceError(TraceCategory.Application, "External Login Failure. Could not get ExternalLoginInfo."); return View("ExternalLoginFailure"); } var options = await this.StartupSettingsManager.GetAuthenticationOptionsExtendedAsync(loginInfo, cancellationToken); var providerRegistrationEnabled = options?.RegistrationEnabled ?? false; if (!ViewBag.Settings.RegistrationEnabled || !providerRegistrationEnabled || (!ViewBag.Settings.OpenRegistrationEnabled && !ViewBag.Settings.InvitationEnabled)) { AddErrors(ViewBag.IdentityErrors.InvalidLogin()); // Registration is disabled ViewBag.ExternalRegistrationFailure = true; ADXTrace.Instance.TraceWarning(TraceCategory.Application, "User Registration Failed. Registration is not enabled."); return View("Login", GetLoginViewModel(null, null, returnUrl, invitationCode)); } if (!ViewBag.Settings.OpenRegistrationEnabled && ViewBag.Settings.InvitationEnabled && string.IsNullOrWhiteSpace(invitationCode)) { // Registration requires an invitation return RedirectToAction("RedeemInvitation", new { ReturnUrl = returnUrl }); } if (User.Identity.IsAuthenticated) { return Redirect(returnUrl ?? "~/"); } if (ModelState.IsValid) { var invitation = await FindInvitationByCodeAsync(invitationCode); var essUserByEmail = await FindEssUserByEmailAsync(email); var associatedUserByEmail = await FindAssociatedUserByEmailAsync(loginInfo, email); var contactId = ToContactId(essUserByEmail) ?? ToContactId(invitation) ?? ToContactId(associatedUserByEmail); if (ModelState.IsValid) { // Validate the username and email var user = contactId != null ? new ApplicationUser { UserName = username, Email = email, FirstName = firstName, LastName = lastName, Id = contactId.Id.ToString() } : new ApplicationUser { UserName = username, Email = email, FirstName = firstName, LastName = lastName }; var validateResult = await UserManager.UserValidator.ValidateAsync(user); if (validateResult.Succeeded) { IdentityResult result; if (contactId == null) { if (!ViewBag.Settings.OpenRegistrationEnabled) { throw new InvalidOperationException("Open registration is not enabled."); } // Create a new user result = await UserManager.CreateAsync(user); } else { // Update the existing invited user user = await UserManager.FindByIdAsync(contactId.Id.ToString()); if (user != null) { result = await UserManager.InitializeUserAsync(user, username, null, !string.IsNullOrWhiteSpace(email) ? email : contactId.Name, ViewBag.Settings.TriggerLockoutOnFailedPassword); } else { // Contact does not exist or login is disabled if (!ViewBag.Settings.OpenRegistrationEnabled) { throw new InvalidOperationException("Open registration is not enabled."); } // Create a new user result = await UserManager.CreateAsync(user); } if (!result.Succeeded) { AddErrors(result); ViewBag.ReturnUrl = returnUrl; ViewBag.InvitationCode = invitationCode; return View("RedeemInvitation", new RedeemInvitationViewModel { InvitationCode = invitationCode }); } } if (result.Succeeded) { var addResult = await UserManager.AddLoginAsync(user.Id, loginInfo.Login); // Treat email as confirmed on external login success var confirmEmailResult = await UserManager.AutoConfirmEmailAsync(user.Id); if (!confirmEmailResult.Succeeded) { AddErrors(confirmEmailResult); } if (addResult.Succeeded) { // AddLoginAsync added related entity adx_externalidentity and we must re-retrieve the user so the related collection ids are loaded, otherwise the adx_externalidentity will be deleted on subsequent user updates. user = await this.UserManager.FindByIdAsync(user.Id); var claimsMapping = options?.RegistrationClaimsMapping; if (!string.IsNullOrWhiteSpace(claimsMapping)) { ApplyClaimsMapping(user, loginInfo, claimsMapping); } if (invitation != null) { var redeemResult = await InvitationManager.RedeemAsync(invitation, user, Request.UserHostAddress); if (redeemResult.Succeeded) { return await SignInAsync(user, returnUrl, loginInfo); } else { AddErrors(redeemResult); } } else { return await SignInAsync(user, returnUrl, loginInfo); } } else { AddErrors(addResult); } } else { AddErrors(result); } } else { AddErrors(validateResult); } } } ViewBag.ReturnUrl = returnUrl; ViewBag.InvitationCode = invitationCode; return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email, FirstName = firstName, LastName = lastName, Username = username }); } // // GET: /Login/LogOff [HttpGet] public async Task<ActionResult> LogOff(string returnUrl, CancellationToken cancellationToken) { if (ViewBag.Settings.SignOutEverywhereEnabled) { UserManager.UpdateSecurityStamp(User.Identity.GetUserId()); } var authenticationTypes = ViewBag.IsESS ? GetSignOutAuthenticationTypes(StartupSettingsManager.AzureAdOptions.AuthenticationType) : await this.GetSignOutAuthenticationTypes(cancellationToken); if (authenticationTypes != null) { AuthenticationManager.SignOut(authenticationTypes); } else { AuthenticationManager.SignOut(new AuthenticationProperties { RedirectUri = returnUrl }); } AuthenticationManager.AuthenticationResponseGrant = null; try { if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage)) { PortalFeatureTrace.TraceInstance.LogAuthentication(FeatureTraceCategory.Authentication, this.HttpContext, "logOut", "authentication"); } } catch (Exception e) { WebEventSource.Log.GenericErrorException(e); } return Redirect(!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl) ? returnUrl : "~/"); } private static string[] GetSignOutAuthenticationTypes(params string[] authenticationTypes) { var defaultAuthenticationTypes = new[] { DefaultAuthenticationTypes.ApplicationCookie, DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.TwoFactorCookie, }; return defaultAuthenticationTypes.Concat(authenticationTypes).ToArray(); } private async Task<string[]> GetSignOutAuthenticationTypes(CancellationToken cancellationToken) { var provider = ((ClaimsIdentity)User.Identity).Claims .FirstOrDefault(c => c.Type == "http://schemas.adxstudio.com/xrm/2014/02/identity/claims/loginprovider") ?.Value; if (provider != null) { var options = await this.StartupSettingsManager.GetAuthenticationOptionsExtendedAsync(provider, cancellationToken); if (options != null && options.ExternalLogoutEnabled) { return GetSignOutAuthenticationTypes(options.AuthenticationType); } } return null; } // // GET: /Login/ExternalLoginFailure [HttpGet] [AllowAnonymous] [ExternalLogin] public ActionResult ExternalLoginFailure() { return View(); } // OWINAuthenticationFailedAccessDeniedMsg = "access_denied"; private const string OwinAuthenticationFailedAccessDeniedMsg = "access_denied"; private const string MessageQueryStringParameter = "message"; // // GET: /Login/ExternalAuthenticationFailed [HttpGet] [AllowAnonymous] [ExternalLogin] public ActionResult ExternalAuthenticationFailed() { if ((this.Request?.QueryString.GetValues(MessageQueryStringParameter) ?? new string[] { }) .Any(m => m == OwinAuthenticationFailedAccessDeniedMsg)) { ViewBag.AccessDeniedError = true; } // Because AuthenticationFailedNotification doesn't pass an initial returnUrl from which user might tried to SignIn, // and when having redidected to this view makes SignIn link become "SignIn?returnUrl=/Account/Login/ExternalAuthenticationFailed?message=access_denied" // which makes an infinite redirect loop - just set returnUrl to root ViewBag.ReturnUrl = "/"; return View(); } // // GET: /Login/RedeemInvitation [HttpGet] [AllowAnonymous] [LanguageActionFilter] public ActionResult RedeemInvitation(string returnUrl, [Bind(Prefix="invitation")]string invitationCode = "", bool invalid = false) { if (!ViewBag.Settings.RegistrationEnabled || !ViewBag.Settings.InvitationEnabled) { return HttpNotFound(); } if (invalid) { ModelState.AddModelError("InvitationCode", ViewBag.IdentityErrors.InvalidInvitationCode().Description); } ViewBag.ReturnUrl = returnUrl; // Decoding invitation code invitationCode = HttpUtility.HtmlDecode(invitationCode).Trim(); ViewBag.InvitationCode = invitationCode; return View(new RedeemInvitationViewModel { InvitationCode = invitationCode }); } // // POST: /Login/RedeemInvitation [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> RedeemInvitation(RedeemInvitationViewModel model, string returnUrl) { if (!ViewBag.Settings.RegistrationEnabled || !ViewBag.Settings.InvitationEnabled) { return HttpNotFound(); } if (ModelState.IsValid) { var applicationInvitation = await FindInvitationByCodeAsync(model.InvitationCode); var contactId = ToContactId(applicationInvitation); ViewBag.ReturnUrl = returnUrl; ViewBag.InvitationCode = model.InvitationCode; if (contactId != null || applicationInvitation != null) { if (!string.IsNullOrWhiteSpace(ViewBag.Settings.LoginButtonAuthenticationType)) { return RedirectToAction("ExternalLogin", "Login", new { returnUrl, area = "Account", invitationCode = model.InvitationCode, provider = ViewBag.Settings.LoginButtonAuthenticationType }); } if (model.RedeemByLogin) { return View("Login", GetLoginViewModel(null, null, returnUrl, model.InvitationCode)); } return Redirect(Site.Helpers.UrlHelpers.SecureRegistrationUrl(this.Url, returnUrl, model.InvitationCode)); } ModelState.AddModelError("InvitationCode", ViewBag.IdentityErrors.InvalidInvitationCode().Description); } ViewBag.ReturnUrl = returnUrl; return View(model); } [HttpGet] [AllowAnonymous] [ExternalLogin] public Task<ActionResult> FacebookExternalLogin() { Response.SuppressFormsAuthenticationRedirect = true; var website = HttpContext.GetWebsite(); var authenticationType = website.GetFacebookAuthenticationType(); var returnUrl = Url.Action("FacebookReloadParent", "Login"); var redirectUri = Url.Action("ExternalLoginCallback", "Login", new { ReturnUrl = returnUrl }); var result = new ChallengeResult(authenticationType.LoginProvider, redirectUri); return Task.FromResult(result as ActionResult); } [HttpGet] [AllowAnonymous] [ExternalLogin] public ActionResult FacebookReloadParent() { return View("LoginReloadParent"); } [HttpPost] [AllowAnonymous] [ExternalLogin, SuppressMessage("ASP.NET.MVC.Security", "CA5332:MarkVerbHandlersWithValidateAntiforgeryToken", Justification = "External caller cannot provide anti-forgery token, signed_request value is validated.")] public async Task<ActionResult> FacebookExternalLoginCallback(string signed_request, string returnUrl, CancellationToken cancellationToken) { if (string.IsNullOrWhiteSpace(signed_request)) { return HttpNotFound(); } var website = HttpContext.GetWebsite(); var loginInfo = website.GetFacebookLoginInfo(signed_request); if (loginInfo == null) { return RedirectToLocal(returnUrl); } // Sign in the user with this external login provider if the user already has a login var result = await SignInManager.ExternalSignInAsync(loginInfo, false, (bool)ViewBag.Settings.TriggerLockoutOnFailedPassword); switch (result) { case SignInStatus.Success: case SignInStatus.LockedOut: return RedirectToLocal(returnUrl); case SignInStatus.RequiresVerification: return RedirectToAction("SendCode", new { ReturnUrl = returnUrl }); case SignInStatus.Failure: default: // If the user does not have an account, then prompt the user to create an account ViewBag.ReturnUrl = returnUrl; var email = loginInfo.Email; var username = loginInfo.Login.ProviderKey; var firstName = loginInfo.ExternalIdentity.FindFirstValue(System.Security.Claims.ClaimTypes.GivenName); var lastName = loginInfo.ExternalIdentity.FindFirstValue(System.Security.Claims.ClaimTypes.Surname); return await ExternalLoginConfirmation(username, email, firstName, lastName, returnUrl, null, loginInfo, cancellationToken); } } #region Helpers // Used for XSRF protection when adding external logins private const string XsrfKey = "XsrfId"; private IAuthenticationManager AuthenticationManager { get { return HttpContext.GetOwinContext().Authentication; } } private void AddErrors(IdentityError error) { AddErrors(IdentityResult.Failed(error.Description)); } private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error); } } private async Task<ActionResult> RedirectOnPostAuthenticate(string returnUrl, string invitationCode, ExternalLoginInfo loginInfo = null, CancellationToken cancellationToken = default(CancellationToken)) { var identity = this.AuthenticationManager.AuthenticationResponseGrant.Identity; var userId = identity.GetUserId(); var user = await this.UserManager.FindByIdAsync(userId); if (user != null && loginInfo != null) { var options = await this.StartupSettingsManager.GetAuthenticationOptionsExtendedAsync(loginInfo, cancellationToken); var claimsMapping = options?.LoginClaimsMapping; if (!string.IsNullOrWhiteSpace(claimsMapping)) { ApplyClaimsMapping(user, loginInfo, claimsMapping); } } return await this.RedirectOnPostAuthenticate(user, returnUrl, invitationCode, loginInfo, cancellationToken); } private async Task<ActionResult> RedirectOnPostAuthenticate(ApplicationUser user, string returnUrl, string invitationCode, ExternalLoginInfo loginInfo = null, CancellationToken cancellationToken = default(CancellationToken)) { if (user != null) { this.UpdateCurrentLanguage(user, ref returnUrl); this.UpdateLastSuccessfulLogin(user); await this.ApplyGraphUser(user, loginInfo, cancellationToken); if (user.IsDirty) { await UserManager.UpdateAsync(user); user.IsDirty = false; } IdentityResult redeemResult; var invitation = await FindInvitationByCodeAsync(invitationCode); if (invitation != null) { // Redeem invitation for the existing/registered contact redeemResult = await InvitationManager.RedeemAsync(invitation, user, Request.UserHostAddress); } else if (!string.IsNullOrWhiteSpace(invitationCode)) { redeemResult = IdentityResult.Failed(ViewBag.IdentityErrors.InvalidInvitationCode().Description); } else { redeemResult = IdentityResult.Success; } if (!redeemResult.Succeeded) { return RedirectToAction("RedeemInvitation", new { ReturnUrl = returnUrl, invitation = invitationCode, invalid = true }); } if (!DisplayModeIsActive() && (user.HasProfileAlert || user.ProfileModifiedOn == null) && ViewBag.Settings.ProfileRedirectEnabled) { return RedirectToProfile(returnUrl); } } return RedirectToLocal(returnUrl); } /// <summary> /// Updates the current request language based on user preferences. If needed, updates the return URL as well. /// </summary> /// <param name="user">Application User that is currently being logged in.</param> /// <param name="returnUrl">Return URL to be updated if needed.</param> private void UpdateCurrentLanguage(ApplicationUser user, ref string returnUrl) { var languageContext = this.HttpContext.GetContextLanguageInfo(); if (languageContext.IsCrmMultiLanguageEnabled) { var preferredLanguage = user.Entity.GetAttributeValue<EntityReference>("adx_preferredlanguageid"); if (preferredLanguage != null) { var websiteLangauges = languageContext.ActiveWebsiteLanguages.ToArray(); // Only consider published website languages for users var newLanguage = languageContext.GetWebsiteLanguageByPortalLanguageId(preferredLanguage.Id, websiteLangauges, true); if (newLanguage != null) { if (ContextLanguageInfo.DisplayLanguageCodeInUrl) { returnUrl = languageContext.FormatUrlWithLanguage(false, newLanguage.Code, (returnUrl ?? string.Empty).AsAbsoluteUri(Request.Url)); } } } } } /// <summary> /// Updates date and time of last successful login /// </summary> /// <param name="user">Application User that is currently being logged in.</param> private void UpdateLastSuccessfulLogin(ApplicationUser user) { if (!ViewBag.Settings.LoginTrackingEnabled) { return; } user.Entity.SetAttributeValue("adx_identity_lastsuccessfullogin", DateTime.UtcNow); user.IsDirty = true; } private static void ApplyClaimsMapping(ApplicationUser user, ExternalLoginInfo loginInfo, string claimsMapping) { try { if (user != null && !string.IsNullOrWhiteSpace(claimsMapping)) { foreach (var pair in claimsMapping.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { var pieces = pair.Split('='); var claimValue = loginInfo.ExternalIdentity.Claims.FirstOrDefault(c => c.Type == pieces[1]); if (pieces.Length == 2 && claimValue != null) { user.Entity.SetAttributeValue(pieces[0], claimValue.Value); user.IsDirty = true; } } } } catch (Exception ex) { WebEventSource.Log.GenericErrorException(ex); } } private async Task ApplyGraphUser(ApplicationUser user, ExternalLoginInfo loginInfo, CancellationToken cancellationToken) { if (loginInfo != null && this.StartupSettingsManager.AzureAdOptions != null && !string.IsNullOrWhiteSpace(this.StartupSettingsManager.AzureAdOptions.AuthenticationType) && !string.IsNullOrWhiteSpace(PortalSettings.Instance.Graph.RootUrl) && string.IsNullOrWhiteSpace(user.FirstName) && string.IsNullOrWhiteSpace(user.LastName) && string.IsNullOrWhiteSpace(user.Email)) { var authenticationType = await this.StartupSettingsManager.GetAuthenticationTypeAsync(loginInfo, cancellationToken); if (this.StartupSettingsManager.AzureAdOptions.AuthenticationType == authenticationType) { // update the contact using Graph try { var graphUser = await this.GetGraphUser(loginInfo); user.FirstName = graphUser.GivenName; user.LastName = graphUser.Surname; user.Email = ToEmail(graphUser); user.IsDirty = true; } catch (Exception ex) { var guid = WebEventSource.Log.GenericErrorException(ex); this.ViewBag.ErrorMessage = string.Format(ResourceManager.GetString("Generic_Error_Message"), guid); } } } } private bool DisplayModeIsActive() { return DisplayModeProvider.Instance .GetAvailableDisplayModesForContext(HttpContext, null) .OfType<HostNameSettingDisplayMode>() .Any(); } private static ActionResult RedirectToProfile(string returnUrl) { var query = !string.IsNullOrWhiteSpace(returnUrl) ? new NameValueCollection { { "ReturnUrl", returnUrl } } : null; return new RedirectToSiteMarkerResult("Profile", query); } private ActionResult RedirectToLocal(string returnUrl) { if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } return Redirect("~/"); } internal class ChallengeResult : HttpUnauthorizedResult { public ChallengeResult(string provider, string redirectUri) : this(provider, redirectUri, null) { } public ChallengeResult(string provider, string redirectUri, string userId) { LoginProvider = provider; RedirectUri = redirectUri; UserId = userId; } public string LoginProvider { get; set; } public string RedirectUri { get; set; } public string UserId { get; set; } public override void ExecuteResult(ControllerContext context) { var properties = new AuthenticationProperties { RedirectUri = RedirectUri }; if (UserId != null) { properties.Dictionary[XsrfKey] = UserId; } context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider); } } private object GetLoginViewModel(LoginViewModel local, IEnumerable<AuthenticationDescription> external, string returnUrl, string invitationCode) { ViewData["local"] = local ?? new LoginViewModel(); ViewData["external"] = external ?? GetExternalAuthenticationTypes(); ViewBag.ReturnUrl = returnUrl; ViewBag.InvitationCode = invitationCode; return ViewData; } private IEnumerable<AuthenticationDescription> GetExternalAuthenticationTypes() { var authTypes = this.HttpContext.GetOwinContext().Authentication .GetExternalAuthenticationTypes() .OrderBy(type => type.AuthenticationType) .ToList(); foreach (var authType in authTypes) { if (!authType.Properties.ContainsKey("RegistrationEnabled")) { var options = this.StartupSettingsManager.GetAuthenticationOptionsExtended(authType.AuthenticationType); authType.Properties["RegistrationEnabled"] = options.RegistrationEnabled; } } return authTypes; } private async Task<ApplicationInvitation> FindInvitationByCodeAsync(string invitationCode) { if (string.IsNullOrWhiteSpace(invitationCode)) return null; if (!ViewBag.Settings.InvitationEnabled) return null; return await InvitationManager.FindByCodeAsync(invitationCode); } private async Task<ApplicationUser> FindEssUserByEmailAsync(string email) { return ViewBag.IsEss ? await UserManager.FindByEmailAsync(email) : null; } /// <summary> /// If AllowContactMappingWithEmail property on the appropriate authentication options class for the provider /// is true - finds a single unique contact where emailaddress1 equals email on the ExternalLoginInfo /// </summary> /// <param name="loginInfo">ExternalLoginIfo to find if AllowContactMappingWithEmail is true</param> /// <param name="email">Email to match againts emailaddress1 from portal contacts</param> /// <returns>ApplicationUser with unique email same as in external login, otherwise null.</returns> private async Task<ApplicationUser> FindAssociatedUserByEmailAsync(ExternalLoginInfo loginInfo, string email) { return GetLoginProviderSetting<bool>(loginInfo, "AllowContactMappingWithEmail", false) ? await UserManager.FindByEmailAsync(email) : null; } private static EntityReference ToContactId(ApplicationInvitation invitation) { return invitation != null && invitation.InvitedContact != null ? new EntityReference(invitation.InvitedContact.LogicalName, invitation.InvitedContact.Id) { Name = invitation.Email } : null; } private static EntityReference ToContactId(ApplicationUser user) { return user != null ? user.ContactId : null; } private async Task<ActionResult> SignInAsync(ApplicationUser user, string returnUrl, ExternalLoginInfo loginInfo = null, bool isPersistent = false, bool rememberBrowser = false) { await this.SignInManager.SignInAsync(user, isPersistent, rememberBrowser); return await this.RedirectOnPostAuthenticate(user, returnUrl, null, loginInfo); } /// <summary> /// Finds setting from the appropriate authentication options class of LoginProvider /// </summary> /// <typeparam name="T">Type of setting</typeparam> /// <param name="loginInfo">Defines LoginProvider</param> /// <param name="name">Name of a property in authentication options class</param> /// <param name="defaultValue">Will be returned on any exception</param> /// <returns>Value if exists. Otherwise - defaultValue</returns> private T GetLoginProviderSetting<T>(ExternalLoginInfo loginInfo, string name, T defaultValue) { if (loginInfo == null) { return defaultValue; } T result = defaultValue; string loginProvider = loginInfo.Login.LoginProvider; try { // Getting the correct provider options switch (loginProvider) { // OAuth case "Twitter": result = (T)StartupSettingsManager.Twitter?.GetType() .GetProperty(name)?.GetValue(StartupSettingsManager.Twitter); break; case "Google": result = (T)StartupSettingsManager.Google?.GetType() .GetProperty(name)?.GetValue(StartupSettingsManager.Google); break; case "Facebook": result = (T)StartupSettingsManager.Facebook?.GetType() .GetProperty(name)?.GetValue(StartupSettingsManager.Facebook); break; case "LinkedIn": result = (T)StartupSettingsManager.LinkedIn?.GetType() .GetProperty(name)?.GetValue(StartupSettingsManager.LinkedIn); break; case "Yahoo": result = (T)StartupSettingsManager.Yahoo?.GetType() .GetProperty(name)?.GetValue(StartupSettingsManager.Yahoo); break; case "MicrosoftAccount": result = (T)StartupSettingsManager.MicrosoftAccount?.GetType() .GetProperty(name)?.GetValue(StartupSettingsManager.MicrosoftAccount); break; default: // OpenIdConnect - checking Authority var options = StartupSettingsManager.OpenIdConnectOptions?.FirstOrDefault(o => string.Equals(o.Authority, loginProvider, StringComparison.InvariantCultureIgnoreCase)); if (options != null) { result = (T)options.GetType().GetProperty(name)?.GetValue(options); } else { // wsFed - checking Caption var wsFedOptions = StartupSettingsManager.WsFederationOptions?.FirstOrDefault(o => string.Equals(o.Caption, loginProvider, StringComparison.InvariantCultureIgnoreCase)); if (wsFedOptions != null) { result = (T)wsFedOptions.GetType().GetProperty(name)?.GetValue(wsFedOptions); } else { // saml2 - checking Caption var saml2options = StartupSettingsManager.Saml2Options?.FirstOrDefault(o => string.Equals(o.Caption, loginProvider, StringComparison.InvariantCultureIgnoreCase)); if (saml2options != null) { result = (T)saml2options.GetType().GetProperty(name)?.GetValue(saml2options); } } } break; } } catch (Exception) { return defaultValue; } return result; } #endregion } }
using BotBits.Shop; // ReSharper disable MemberHidesStaticFromOuterClass namespace BotBits { public static class Foreground { public enum Id : ushort { } public const Id Empty = 0; public static class Gravity { public const Id Left = (Id)1, Up = (Id)2, Right = (Id)3, Dot = (Id)4, InvisibleLeft = (Id)411, InvisibleUp = (Id)412, InvisibleRight = (Id)413, InvisibleDot = (Id)414; [Pack("brickslowdot")] public const Id SlowDot = (Id)459, InvisibleSlowDot = (Id)460; } public static class Key { public const Id Red = (Id)6, Green = (Id)7, Blue = (Id)8, Cyan = (Id)408, Magenta = (Id)409, Yellow = (Id)410; } public static class Basic { public const Id Gray = (Id)9, Blue = (Id)10, Purple = (Id)11, Red = (Id)12, Orange = (Id)1018, Yellow = (Id)13, Green = (Id)14, Cyan = (Id)15, Black = (Id)182; } public static class Brick { public const Id Gray = (Id)1022, Orange = (Id)16, Blue = (Id)1023, Teal = (Id)17, Purple = (Id)18, Green = (Id)19, Red = (Id)20, Tan = (Id)21, Black = (Id)1024; } public static class Generic { public const Id StripedYellow = (Id)22, Yellow = (Id)1057, Face = (Id)32, Black = (Id)33, StripedBlack = (Id)1058; } public static class Door { public const Id Red = (Id)23, Green = (Id)24, Blue = (Id)25, Cyan = (Id)1005, Magenta = (Id)1006, Yellow = (Id)1007; } public static class Gate { public const Id Red = (Id)26, Green = (Id)27, Blue = (Id)28, Cyan = (Id)1008, Magenta = (Id)1009, Yellow = (Id)1010; } public static class BuildersClub { [Pack("-", BuildersClubOnly = true)] public const Id Door = (Id)200, Gate = (Id)201; } public static class Team { [Pack("brickeffectteam", ForegroundType = ForegroundType.Team)] public const Id Effect = (Id)423; [Pack("brickeffectteam", ForegroundType = ForegroundType.Team)] public const Id Door = (Id)1027; [Pack("brickeffectteam", ForegroundType = ForegroundType.Team)] public const Id Gate = (Id)1028; } public static class Death { [Pack("brickdeathdoor", ForegroundType = ForegroundType.Goal)] public const Id Door = (Id)1011; [Pack("brickdeathdoor", ForegroundType = ForegroundType.Goal)] public const Id Gate = (Id)1012; } public static class Metal { public const Id White = (Id)29, Red = (Id)30, Yellow = (Id)31; } public static class Grass { public const Id Left = (Id)34, Middle = (Id)35, Right = (Id)36; } public static class Beta { [Pack("pro")] public const Id Pink = (Id)37, Green = (Id)38, Cyan = (Id)1019, Blue = (Id)39, Red = (Id)40, Orange = (Id)1020, Yellow = (Id)41, Gray = (Id)42, Black = (Id)1021; } public static class Factory { [Pack("brickfactorypack")] public const Id TanCross = (Id)45, Planks = (Id)46, Sandpaper = (Id)47, BrownCross = (Id)48, Fishscales = (Id)49; } public static class Secret { [Pack("bricksecret")] public const Id Unpassable = (Id)50, InvisibleUnpassable = (Id)136, Passable = (Id)243; [Pack("brickblackblock")] public const Id Black = (Id)44; } public static class Glass { [Pack("brickglass")] public const Id Red = (Id)51, Pink = (Id)52, Indigo = (Id)53, Blue = (Id)54, Cyan = (Id)55, Green = (Id)56, Yellow = (Id)57, Orange = (Id)58; } public static class Summer2011 { [Pack("bricksummer2012")] public const Id Sand = (Id)59, Sunshade = (Id)228, RightCornerSand = (Id)229, LeftCornerSand = (Id)230, Rock = (Id)231; } public static class Candy { [Pack("brickcandy")] public const Id Pink = (Id)60, OneWayPink = (Id)61, OneWayRed = (Id)62, OneWayCyan = (Id)63, OneWayGreen = (Id)64, CandyCane = (Id)65, CandyCorn = (Id)66, Chocolate = (Id)67, ToppingSmall = (Id)227, ToppingBig = (Id)431, PuddingRed = (Id)432, PuddingGreen = (Id)433, PuddingPurple = (Id)434; } public static class Halloween2011 { [Pack("brickhw2011")] public const Id Blood = (Id)68, FullBrick = (Id)69, Tombstone = (Id)224, LeftCornerWeb = (Id)225, RightCornerWeb = (Id)226; } public static class Mineral { [Pack("brickminiral")] public const Id Red = (Id)70, Pink = (Id)71, Blue = (Id)72, Cyan = (Id)73, Green = (Id)74, Yellow = (Id)75, Orange = (Id)76; } public static class Music { [Pack("bricknode", ForegroundType = ForegroundType.Note)] public const Id Piano = (Id)77; [Pack("brickdrums", ForegroundType = ForegroundType.Note)] public const Id Drum = (Id)83; } public static class Christmas2011 { [Pack("brickxmas2011")] public const Id YellowBox = (Id)78, WhiteBox = (Id)79, RedBox = (Id)80, BlueBox = (Id)81, GreenBox = (Id)82, SphereBlue = (Id)218, SphereGreen = (Id)219, SphereRed = (Id)220, Wreath = (Id)221, Star = (Id)222; } public static class SciFi { [Pack("brickscifi")] public const Id Red = (Id)84, Blue = (Id)85, Gray = (Id)86, White = (Id)87, Brown = (Id)88, OneWayRed = (Id)89, OneWayBlue = (Id)90, OneWayGreen = (Id)91, OneWayYellow = (Id)1051; [Pack("brickscifi", ForegroundType = ForegroundType.Morphable)] public const Id BlueSlope = (Id)375, BlueStraight = (Id)376, GreenSlope = (Id)379, GreenStraight = (Id)380, YellowSlope = (Id)377, YellowStraight = (Id)378, RedSlope = (Id)438, RedStraight = (Id)439; } public static class Prison { [Pack("brickprison")] public const Id Wall = (Id)92, Bars = (Id)261; } public static class Pirate { [Pack("brickpirate")] public const Id Planks = (Id)93, Chest = (Id)94, Canoncover = (Id)271, Skull = (Id)272, Canon = (Id)435, Window = (Id)436, OneWay = (Id)154; } public static class Stone { [Pack("brickstone")] public const Id Gray = (Id)95, Teal = (Id)1044, Brown = (Id)1045, Blue = (Id)1046; } public static class Dojo { [Pack("brickninja")] public const Id White = (Id)96, Gray = (Id)97, BrightWindow = (Id)278, DarkWindow = (Id)281, LadderShape = (Id)282, AntennaShape = (Id)283, YinYang = (Id)284; [Pack("brickninja", ForegroundType = ForegroundType.Morphable)] public const Id LeftRooftop = (Id)276, RightRooftop = (Id)277, LeftDarkRooftop = (Id)279, RightDarkRooftop = (Id)280; } public static class Ladder { [Pack("brickmedieval")] public const Id Chain = (Id)118; [Pack("brickninja")] public const Id Wood = (Id)120; [Pack("brickjungle")] public const Id VineVertical = (Id)98, VineHorizontal = (Id)99; [Pack("brickcowboy")] public const Id Rope = (Id)424; } public static class Coin { public const Id Gold = (Id)100, Blue = (Id)101; [Pack("brickcoindoor", ForegroundType = ForegroundType.Goal)] public const Id GoldDoor = (Id)43; [Pack("brickcoindoor", ForegroundType = ForegroundType.Goal)] public const Id GoldGate = (Id)165; [Pack("brickbluecoindoor", ForegroundType = ForegroundType.Goal)] public const Id BlueDoor = (Id)213; [Pack("brickbluecoindoor", ForegroundType = ForegroundType.Goal)] public const Id BlueGate = (Id)214; } public static class Switch { [Pack("brickswitchpurple", ForegroundType = ForegroundType.Goal)] public const Id Purple = (Id)113; [Pack("brickswitchpurple", ForegroundType = ForegroundType.Goal)] public const Id PurpleDoor = (Id)184; [Pack("brickswitchpurple", ForegroundType = ForegroundType.Goal)] public const Id PurpleGate = (Id)185; } public static class Boost { [Pack("brickboost")] public const Id Left = (Id)114, Right = (Id)115, Up = (Id)116, Down = (Id)117; } public static class Water { [Pack("brickwater")] public const Id Waves = (Id)300; } public static class Tool { public const Id Crown = (Id)5; [Pack("brickcomplete")] public const Id Trophy = (Id)121; [Pack("brickspawn")] public const Id Spawnpoint = (Id)255; [Pack("brickcheckpoint")] public const Id Checkpoint = (Id)360; [Pack("brickresetpoint")] public const Id Resetpoint = (Id)466; } public static class WildWest { [Pack("brickcowboy")] public const Id BrownLit = (Id)122, RedLit = (Id)123, BlueLit = (Id)124, BrownDark = (Id)125, RedDark = (Id)126, BlueDark = (Id)127, PoleLit = (Id)285, PoleDark = (Id)286, DoorBrownLeft = (Id)287, DoorBrownRight = (Id)288, DoorRedLeft = (Id)289, DoorRedRight = (Id)290, DoorBlueLeft = (Id)291, DoorBlueRight = (Id)292, Window = (Id)293, TableBrownLit = (Id)294, TableBrownDark = (Id)295, TableRedLit = (Id)296, TableRedDark = (Id)297, TableBlueLit = (Id)298, TableBlueDark = (Id)299; } public static class Plastic { [Pack("brickplastic")] public const Id LightGreen = (Id)128, Red = (Id)129, Yellow = (Id)130, Cyan = (Id)131, Blue = (Id)132, Pink = (Id)133, Green = (Id)134, Orange = (Id)135; } public static class Sand { [Pack("bricksand")] public const Id White = (Id)137, Gray = (Id)138, Yellow = (Id)139, Orange = (Id)140, Tan = (Id)141, Brown = (Id)142, DuneWhite = (Id)301, DuneGray = (Id)302, DuneYellow = (Id)303, DuneOrange = (Id)304, DuneTan = (Id)305, DuneBrown = (Id)306; } public static class Cloud { [Pack("brickcloud")] public const Id White = (Id)143, Bottom = (Id)311, Top = (Id)312, Right = (Id)313, Left = (Id)314, BottomLeftCorner = (Id)315, BottomRightCorner = (Id)316, TopRightCorner = (Id)317, TopLeftCorner = (Id)318; } public static class Industrial { [Pack("brickindustrial")] public const Id Iron = (Id)144, Wires = (Id)145, OneWay = (Id)146, CrossSupport = (Id)147, Elevator = (Id)148, Support = (Id)149, LeftConveyor = (Id)150, SupportedMiddleConveyor = (Id)151, MiddleConveyor = (Id)152, RightConveyor = (Id)153, SignFire = (Id)319, SignSkull = (Id)320, SignLightning = (Id)321, SignCross = (Id)322, HorizontalLine = (Id)323, VerticalLine = (Id)324; } public static class Timed { [Pack("bricktimeddoor")] public const Id Door = (Id)156; [Pack("bricktimeddoor")] public const Id Gate = (Id)157; } public static class Medieval { [Pack("brickmedieval")] public const Id CastleOneWay = (Id)158, CastleWall = (Id)159, CastleWindow = (Id)160, Anvil = (Id)162, Barrel = (Id)163, CastleSupport = (Id)325, Tombstone = (Id)326, Shield = (Id)330, ClosedDoor = (Id)437; [Pack("brickmedieval", ForegroundType = ForegroundType.Morphable)] public const Id Timber = (Id)440, Axe = (Id)275, Sword = (Id)329, Circle = (Id)273, CoatOfArms = (Id)328, Banner = (Id)327; } public static class Pipe { [Pack("brickpipe")] public const Id Left = (Id)166, Horizontal = (Id)167, Right = (Id)168, Up = (Id)169, Vertical = (Id)170, Down = (Id)171; } public static class OuterSpace { [Pack("brickrocket")] public const Id White = (Id)172, Blue = (Id)173, Green = (Id)174, Red = (Id)175, Dust = (Id)176, SilverTexture = (Id)1029, GreenSign = (Id)332, RedLight = (Id)333, BlueLight = (Id)334, Computer = (Id)335, BigStar = (Id)428, MediumStar = (Id)429, LittleStar = (Id)430, Stone = (Id)331; } public static class Desert { // TODO find better names for Patterns [Pack("brickdesert")] public const Id Pattern1 = (Id)177, Pattern2 = (Id)178, Pattern3 = (Id)179, Pattern4 = (Id)180, Pattern5 = (Id)181, Rock = (Id)336, Cactus = (Id)425, Shrub = (Id)426, Tree = (Id)427; } public static class Checker { [Pack("brickchecker")] public const Id Gray = (Id)186, DarkBlue = (Id)187, Purple = (Id)188, Red = (Id)189, Yellow = (Id)190, Green = (Id)191, LightBlue = (Id)192, Orange = (Id)1025, Black = (Id)1026; } public static class Jungle { [Pack("brickjungle")] public const Id Tiki = (Id)193, OneWay = (Id)194, Gray = (Id)195, Red = (Id)196, Blue = (Id)197, Yellow = (Id)198, Vase = (Id)199, Undergrowth = (Id)357, Log = (Id)358, Idol = (Id)359; } public static class Lava { [Pack("bricklava")] public const Id Yellow = (Id)202, Orange = (Id)203, Red = (Id)204, Waves = (Id)415; } public static class Marble { [Pack("bricksparta")] public const Id Gray = (Id)208, Green = (Id)209, Red = (Id)210, OneWay = (Id)211, PillarTop = (Id)382, PillarMiddle = (Id)383, PillarBottom = (Id)384; } public static class Farm { [Pack("brickfarm")] public const Id Hay = (Id)212, Crop = (Id)386, Plants = (Id)387, FenceLeftEnded = (Id)388, FenceRightEnded = (Id)389; } public static class Autumn2014 { [Pack("brickautumn2014")] public const Id RightCornerLeaves = (Id)390, LeftCornerLeaves = (Id)391, LeftGrass = (Id)392, MiddleGrass = (Id)393, RightGrass = (Id)394, Acorn = (Id)395, Pumpkin = (Id)396; } public static class Christmas2014 { [Pack("brickchristmas2014")] public const Id Ice = (Id)215, OneWay = (Id)216, LeftSnow = (Id)398, MiddleSnow = (Id)399, RightSnow = (Id)400, CandyCane = (Id)401, Wreath = (Id)402, Stocking = (Id)403, Bow = (Id)404; } public static class Zombie { [Pack("brickeffectzombie", ForegroundType = ForegroundType.ToggleGoal)] public const Id Effect = (Id)422; [Pack("brickzombiedoor")] // TODO: effect zombie also gives you 10 public const Id Door = (Id)207; [Pack("brickzombiedoor")] public const Id Gate = (Id)206; } public static class Hologram { [Pack("brickhologram")] public const Id Block = (Id)397; } public static class Prize { [Pack("brickhwtrophy")] public const Id Trophy = (Id)223; } public static class Spring2011 { [Pack("brickspring2011")] public const Id LeftGrass = (Id)233, MiddleGrass = (Id)234, RightGrass = (Id)235, LeftBush = (Id)236, MiddleBush = (Id)237, RightBush = (Id)238, Flower = (Id)239, Shrub = (Id)240; } public static class Diamond { [Pack("brickdiamond")] public const Id Block = (Id)241; } public static class Portal { [Pack("brickportal", ForegroundType = ForegroundType.Portal)] public const Id Normal = (Id)242; [Pack("brickinvisibleportal", ForegroundType = ForegroundType.Portal)] public const Id Invisible = (Id)381; [Pack("brickworldportal", ForegroundType = ForegroundType.WorldPortal)] public const Id World = (Id)374; } public static class NewYear2010 { [Pack("mixednewyear2010")] public const Id Purple = (Id)244, Yellow = (Id)245, Blue = (Id)246, Red = (Id)247, Green = (Id)248; } public static class Christmas2010 { [Pack("brickchristmas2010")] public const Id RightCornerSnow = (Id)249, LeftCornerSnow = (Id)250, Tree = (Id)251, DecoratedTree = (Id)252, SnowyFence = (Id)253, Fence = (Id)254; } public static class Easter2012 { [Pack("brickeaster2012")] public const Id BlueEgg = (Id)256, PinkEgg = (Id)257, YellowEgg = (Id)258, RedEgg = (Id)259, GreenEgg = (Id)260; } public static class Window { [Pack("brickwindow")] public const Id Clear = (Id)262, Green = (Id)263, Teal = (Id)264, Blue = (Id)265, Purple = (Id)266, Pink = (Id)267, Red = (Id)268, Orange = (Id)269, Yellow = (Id)270; } public static class Summer2012 { [Pack("bricksummer2012")] public const Id Ball = (Id)307, Bucket = (Id)308, Grubber = (Id)309, Cocktail = (Id)310; } public static class Cake { [Pack("brickcake")] public const Id Block = (Id)337; } public static class Monster { [Pack("brickmonster", ForegroundType = ForegroundType.Morphable)] public const Id BigTooth = (Id)338, SmallTooth = (Id)339, TripleTooth = (Id)340; [Pack("brickmonster")] public const Id PurpleEye = (Id)274, OrangeEye = (Id)341, BlueEye = (Id)342; } public static class Fog { [Pack("brickfog")] public const Id Full = (Id)343, Bottom = (Id)344, Top = (Id)345, Right = (Id)346, Left = (Id)347, BottomLeftCorner = (Id)348, BottomRightCorner = (Id)349, TopRightCorner = (Id)350, TopLeftCorner = (Id)351; } public static class Halloween2012 { [Pack("brickhw2012")] public const Id TeslaCap = (Id)352, TeslaCoil = (Id)353, WiresVertical = (Id)354, WiresHorizontal = (Id)355, Electricity = (Id)356; } public static class Hazard { [Pack("brickspike", ForegroundType = ForegroundType.Morphable)] public const Id Spike = (Id)361; [Pack("brickfire")] public const Id Fire = (Id)368; } public static class Swamp { [Pack("brickswamp")] public const Id MudBubbles = (Id)370, Grass = (Id)371, Log = (Id)372, Radioactive = (Id)373; } public static class Christmas2012 { [Pack("brickxmas2012")] public const Id BlueVertical = (Id)362, BlueHorizontal = (Id)363, BlueCross = (Id)364, RedVertical = (Id)365, RedHorizontal = (Id)366, RedCross = (Id)367; } public static class Sign { [Pack("bricksign", ForegroundType = ForegroundType.Text)] public const Id Block = (Id)385; } public static class Admin { [Pack("admin", ForegroundType = ForegroundType.Label)] public const Id Text = (Id)1000; } public static class OneWay { [Pack("brickoneway", ForegroundType = ForegroundType.Morphable)] public const Id Cyan = (Id)1001, Orange = (Id)1002, Yellow = (Id)1003, Pink = (Id)1004, Gray = (Id)1052, Blue = (Id)1053, Red = (Id)1054, Green = (Id)1055, Black = (Id)1056; } public static class Valentines2015 { [Pack("brickvalentines2015")] public const Id RedHeart = (Id)405, PurpleHeart = (Id)406, PinkHeart = (Id)407; } public static class Magic { [Pack("brickmagic")] public const Id Green = (Id)1013; [Pack("brickmagic2")] public const Id Purple = (Id)1014; [Pack("brickmagic3")] public const Id Orange = (Id)1015; [Pack("brickmagic4")] public const Id Blue = (Id)1016; [Pack("brickmagic5")] public const Id Red = (Id)1017; } public static class Effect { [Pack("brickeffectjump", ForegroundType = ForegroundType.Toggle)] public const Id Jump = (Id)417; [Pack("brickeffectfly", ForegroundType = ForegroundType.Toggle)] public const Id Fly = (Id)418; [Pack("brickeffectspeed", ForegroundType = ForegroundType.Toggle)] public const Id Speed = (Id)419; [Pack("brickeffectprotection", ForegroundType = ForegroundType.Toggle)] public const Id Protection = (Id)420; [Pack("brickeffectcurse", ForegroundType = ForegroundType.ToggleGoal)] public const Id Curse = (Id)421; [Pack("brickeffectlowgravity", ForegroundType = ForegroundType.Toggle)] public const Id LowGravity = (Id)453; [Pack("brickeffectmultijump", ForegroundType = ForegroundType.Morphable)] public const Id MultiJump = (Id)461; } public static class Liquid { [Pack("brickswamp")] public const Id Swamp = (Id)369; [Pack("brickwater")] public const Id Water = (Id)119; [Pack("bricklava")] public const Id Lava = (Id)416; } public static class Summer2015 { [Pack("bricksummer2015")] public const Id Lifesaver = (Id)441, Anchor = (Id)442, RopeLeftEnded = (Id)443, RopeRightEnded = (Id)444, PalmTree = (Id)445; } public static class Environment { [Pack("brickenvironment")] public const Id Tree = (Id)1030, Grass = (Id)1031, Bamboo = (Id)1032, Rock = (Id)1033, Lava = (Id)1034; } public static class Domestic { [Pack("brickdomestic")] public const Id Tile = (Id)1035, Wood = (Id)1036, CarpetRed = (Id)1037, CarpetBlue = (Id)1038, CarpetGreen = (Id)1039, WoodenPanel = (Id)1040, Lamp = (Id)446; [Pack("brickdomestic", ForegroundType = ForegroundType.Morphable)] public const Id BeigeHalfBlock = (Id)1041, WoodHalfBlock = (Id)1042, WhiteHalfBlock = (Id)1043, LightBulb = (Id)447, Pipe = (Id)448, Painting = (Id)449, Vase = (Id)450, Television = (Id)451, Window = (Id)452; } public static class Halloween2015 { [Pack("brickhalloween2015")] public const Id MossyBrick = (Id)1047, Siding = (Id)1048, Rooftop = (Id)1049, OneWay = (Id)1050, DeadShrub = (Id)454, IronFence = (Id)455; [Pack("brickhalloween2015", ForegroundType = ForegroundType.Morphable)] public const Id Window = (Id)456, WoodHalfBlock = (Id)457, Lantern = (Id)458; } public static class Ice { [Pack("brickice2")] public const Id Block = (Id)1064; } public static class Arctic { [Pack("brickarctic")] public const Id Ice = (Id)1059, Snow = (Id)1060, SnowyLeft = (Id)1061, SnowyMiddle = (Id)1062, SnowyRight = (Id)1063; } public static class NewYear2015 { [Pack("bricknewyear2015")] public const Id WineGlass = (Id)462, Bottle = (Id)463; [Pack("bricknewyear2015", ForegroundType = ForegroundType.Morphable)] public const Id Balloon = (Id)464, Streamer = (Id)465; } } }
// 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.EventHub { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// NamespacesOperations operations. /// </summary> public partial interface INamespacesOperations { /// <summary> /// Check the give Namespace name availability. /// </summary> /// <param name='parameters'> /// Parameters to check availability of the given Namespace name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<CheckNameAvailabilityResult>> CheckNameAvailabilityWithHttpMessagesAsync(CheckNameAvailabilityParameter parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all the available Namespaces within a subscription, /// irrespective of the resource groups. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<EHNamespace>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists the available Namespaces within a resource group. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<EHNamespace>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a namespace. Once created, this namespace's /// resource manifest is immutable. This operation is idempotent. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='parameters'> /// Parameters for creating a namespace resource. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<EHNamespace>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, EHNamespace parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes an existing namespace. This operation also removes all /// associated resources under the namespace. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the description of the specified namespace. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<EHNamespace>> GetWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a namespace. Once created, this namespace's /// resource manifest is immutable. This operation is idempotent. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='parameters'> /// Parameters for updating a namespace resource. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<EHNamespace>> UpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, EHNamespace parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a list of authorization rules for a Namespace. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<AuthorizationRule>>> ListAuthorizationRulesWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates an AuthorizationRule for a Namespace. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> /// <param name='parameters'> /// The shared access AuthorizationRule. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<AuthorizationRule>> CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, AuthorizationRule parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes an AuthorizationRule for a Namespace. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets an AuthorizationRule for a Namespace by rule name. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<AuthorizationRule>> GetAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the primary and secondary connection strings for the /// Namespace. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<AccessKeys>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Regenerates the primary or secondary connection strings for the /// specified Namespace. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> /// <param name='parameters'> /// Parameters required to regenerate the connection string. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<AccessKeys>> RegenerateKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, RegenerateAccessKeyParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a namespace. Once created, this namespace's /// resource manifest is immutable. This operation is idempotent. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='parameters'> /// Parameters for creating a namespace resource. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<EHNamespace>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, EHNamespace parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes an existing namespace. This operation also removes all /// associated resources under the namespace. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all the available Namespaces within a subscription, /// irrespective of the resource groups. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<EHNamespace>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists the available Namespaces within a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<EHNamespace>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a list of authorization rules for a Namespace. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<AuthorizationRule>>> ListAuthorizationRulesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// 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.CognitiveServices.Vision.Face { using Microsoft.Azure; using Microsoft.Azure.CognitiveServices; using Microsoft.Azure.CognitiveServices.Vision; using Microsoft.Rest; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// PersonGroup operations. /// </summary> public partial class PersonGroup : IServiceOperations<FaceAPI>, IPersonGroup { /// <summary> /// Initializes a new instance of the PersonGroup class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public PersonGroup(FaceAPI client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the FaceAPI /// </summary> public FaceAPI Client { get; private set; } /// <summary> /// Create a new person group with specified personGroupId, name and /// user-provided userData. /// </summary> /// <param name='personGroupId'> /// User-provided personGroupId as a string. /// </param> /// <param name='name'> /// Name of the face list, maximum length is 128. /// </param> /// <param name='userData'> /// Optional user defined data for the face list. Length should not exceed /// 16KB. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="APIErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse> CreateWithHttpMessagesAsync(string personGroupId, string name = default(string), string userData = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (personGroupId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "personGroupId"); } if (personGroupId != null) { if (personGroupId.Length > 64) { throw new ValidationException(ValidationRules.MaxLength, "personGroupId", 64); } if (!System.Text.RegularExpressions.Regex.IsMatch(personGroupId, "^[a-z0-9-_]+$")) { throw new ValidationException(ValidationRules.Pattern, "personGroupId", "^[a-z0-9-_]+$"); } } if (Client.SubscriptionKey == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionKey"); } if (name != null) { if (name.Length > 128) { throw new ValidationException(ValidationRules.MaxLength, "name", 128); } } if (userData != null) { if (userData.Length > 16384) { throw new ValidationException(ValidationRules.MaxLength, "userData", 16384); } } CreatePersonGroupRequest body = new CreatePersonGroupRequest(); if (name != null || userData != null) { body.Name = name; body.UserData = userData; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("personGroupId", personGroupId); tracingParameters.Add("body", body); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri; var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "persongroups/{personGroupId}"; _url = _url.Replace("{AzureRegion}", Rest.Serialization.SafeJsonConvert.SerializeObject(Client.AzureRegion, Client.SerializationSettings).Trim('"')); _url = _url.Replace("{personGroupId}", System.Uri.EscapeDataString(personGroupId)); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.SubscriptionKey != null) { if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key")) { _httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key"); } _httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", Client.SubscriptionKey); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(body != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new APIErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); APIError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<APIError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Delete an existing person group. Persisted face images of all people in the /// person group will also be deleted. /// </summary> /// <param name='personGroupId'> /// The personGroupId of the person group to be deleted. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="APIErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse> DeleteWithHttpMessagesAsync(string personGroupId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (personGroupId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "personGroupId"); } if (Client.SubscriptionKey == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionKey"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("personGroupId", personGroupId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri; var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "persongroups/{personGroupId}"; _url = _url.Replace("{AzureRegion}", Rest.Serialization.SafeJsonConvert.SerializeObject(Client.AzureRegion, Client.SerializationSettings).Trim('"')); _url = _url.Replace("{personGroupId}", System.Uri.EscapeDataString(personGroupId)); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.SubscriptionKey != null) { if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key")) { _httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key"); } _httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", Client.SubscriptionKey); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new APIErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); APIError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<APIError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Retrieve the information of a person group, including its name and /// userData. /// </summary> /// <param name='personGroupId'> /// personGroupId of the target person group. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="APIErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<PersonGroupResult>> GetWithHttpMessagesAsync(string personGroupId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (personGroupId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "personGroupId"); } if (Client.SubscriptionKey == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionKey"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("personGroupId", personGroupId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri; var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "persongroups/{personGroupId}"; _url = _url.Replace("{AzureRegion}", Rest.Serialization.SafeJsonConvert.SerializeObject(Client.AzureRegion, Client.SerializationSettings).Trim('"')); _url = _url.Replace("{personGroupId}", System.Uri.EscapeDataString(personGroupId)); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.SubscriptionKey != null) { if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key")) { _httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key"); } _httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", Client.SubscriptionKey); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new APIErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); APIError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<APIError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<PersonGroupResult>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<PersonGroupResult>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Update an existing person group's display name and userData. The properties /// which does not appear in request body will not be updated. /// </summary> /// <param name='personGroupId'> /// personGroupId of the person group to be updated. /// </param> /// <param name='name'> /// Name of the face list, maximum length is 128. /// </param> /// <param name='userData'> /// Optional user defined data for the face list. Length should not exceed /// 16KB. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="APIErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse> UpdateWithHttpMessagesAsync(string personGroupId, string name = default(string), string userData = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (personGroupId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "personGroupId"); } if (Client.SubscriptionKey == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionKey"); } if (name != null) { if (name.Length > 128) { throw new ValidationException(ValidationRules.MaxLength, "name", 128); } } if (userData != null) { if (userData.Length > 16384) { throw new ValidationException(ValidationRules.MaxLength, "userData", 16384); } } CreatePersonGroupRequest body = new CreatePersonGroupRequest(); if (name != null || userData != null) { body.Name = name; body.UserData = userData; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("personGroupId", personGroupId); tracingParameters.Add("body", body); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri; var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "persongroups/{personGroupId}"; _url = _url.Replace("{AzureRegion}", Rest.Serialization.SafeJsonConvert.SerializeObject(Client.AzureRegion, Client.SerializationSettings).Trim('"')); _url = _url.Replace("{personGroupId}", System.Uri.EscapeDataString(personGroupId)); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.SubscriptionKey != null) { if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key")) { _httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key"); } _httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", Client.SubscriptionKey); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(body != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new APIErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); APIError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<APIError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Retrieve the training status of a person group (completed or ongoing). /// </summary> /// <param name='personGroupId'> /// personGroupId of target person group. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="APIErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<TrainingStatus>> GetTrainingStatusWithHttpMessagesAsync(string personGroupId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (personGroupId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "personGroupId"); } if (Client.SubscriptionKey == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionKey"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("personGroupId", personGroupId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetTrainingStatus", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri; var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "persongroups/{personGroupId}/training"; _url = _url.Replace("{AzureRegion}", Rest.Serialization.SafeJsonConvert.SerializeObject(Client.AzureRegion, Client.SerializationSettings).Trim('"')); _url = _url.Replace("{personGroupId}", System.Uri.EscapeDataString(personGroupId)); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.SubscriptionKey != null) { if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key")) { _httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key"); } _httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", Client.SubscriptionKey); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new APIErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); APIError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<APIError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<TrainingStatus>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<TrainingStatus>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// List person groups and their information. /// </summary> /// <param name='start'> /// List person groups from the least personGroupId greater than the "start". /// </param> /// <param name='top'> /// The number of person groups to list. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="APIErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<IList<PersonGroupResult>>> ListWithHttpMessagesAsync(string start = default(string), int? top = 1000, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (start != null) { if (start.Length > 64) { throw new ValidationException(ValidationRules.MaxLength, "start", 64); } } if (top > 1000) { throw new ValidationException(ValidationRules.InclusiveMaximum, "top", 1000); } if (top < 1) { throw new ValidationException(ValidationRules.InclusiveMinimum, "top", 1); } if (Client.SubscriptionKey == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionKey"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("start", start); tracingParameters.Add("top", top); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri; var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "persongroups"; _url = _url.Replace("{AzureRegion}", Rest.Serialization.SafeJsonConvert.SerializeObject(Client.AzureRegion, Client.SerializationSettings).Trim('"')); List<string> _queryParameters = new List<string>(); if (start != null) { _queryParameters.Add(string.Format("start={0}", System.Uri.EscapeDataString(start))); } if (top != null) { _queryParameters.Add(string.Format("top={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(top, Client.SerializationSettings).Trim('"')))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.SubscriptionKey != null) { if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key")) { _httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key"); } _httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", Client.SubscriptionKey); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new APIErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); APIError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<APIError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<IList<PersonGroupResult>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<IList<PersonGroupResult>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Queue a person group training task, the training task may not be started /// immediately. /// </summary> /// <param name='personGroupId'> /// Target person group to be trained. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="APIErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse> TrainWithHttpMessagesAsync(string personGroupId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (personGroupId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "personGroupId"); } if (Client.SubscriptionKey == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionKey"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("personGroupId", personGroupId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Train", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri; var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "persongroups/{personGroupId}/train"; _url = _url.Replace("{AzureRegion}", Rest.Serialization.SafeJsonConvert.SerializeObject(Client.AzureRegion, Client.SerializationSettings).Trim('"')); _url = _url.Replace("{personGroupId}", System.Uri.EscapeDataString(personGroupId)); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.SubscriptionKey != null) { if (_httpRequest.Headers.Contains("Ocp-Apim-Subscription-Key")) { _httpRequest.Headers.Remove("Ocp-Apim-Subscription-Key"); } _httpRequest.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", Client.SubscriptionKey); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 202) { var ex = new APIErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); APIError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<APIError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using Microsoft.Extensions.Logging; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using YesSql.Indexes; using YesSql.Serialization; namespace YesSql.Commands { public abstract class IndexCommand : IIndexCommand { protected const string ParameterSuffix = "_$$$"; protected readonly IStore _store; private static readonly ConcurrentDictionary<PropertyInfo, PropertyInfoAccessor> PropertyAccessors = new ConcurrentDictionary<PropertyInfo, PropertyInfoAccessor>(); private static readonly ConcurrentDictionary<string, PropertyInfo[]> TypeProperties = new ConcurrentDictionary<string, PropertyInfo[]>(); private static readonly ConcurrentDictionary<CompoundKey, string> InsertsList = new ConcurrentDictionary<CompoundKey, string>(); private static readonly ConcurrentDictionary<CompoundKey, string> UpdatesList = new ConcurrentDictionary<CompoundKey, string>(); protected static PropertyInfo[] KeysProperties = new[] { typeof(IIndex).GetProperty("Id") }; public abstract int ExecutionOrder { get; } public IndexCommand(IIndex index, IStore store, string collection) { Index = index; _store = store; Collection = collection; } public IIndex Index { get; } public Document Document { get; } public string Collection { get; } public abstract Task ExecuteAsync(DbConnection connection, DbTransaction transaction, ISqlDialect dialect, ILogger logger); public static void ResetQueryCache() { InsertsList.Clear(); UpdatesList.Clear(); } protected static void GetProperties(DbCommand command, object item, string suffix, ISqlDialect dialect) { var type = item.GetType(); foreach (var property in TypePropertiesCache(type)) { var accessor = PropertyAccessors.GetOrAdd(property, p => new PropertyInfoAccessor(p)); var value = accessor.Get(item); var parameter = command.CreateParameter(); parameter.ParameterName = property.Name + suffix; parameter.Value = dialect.TryConvert(value) ?? DBNull.Value; parameter.DbType = dialect.ToDbType(property.PropertyType); command.Parameters.Add(parameter); } } protected static PropertyInfo[] TypePropertiesCache(Type type) { if (TypeProperties.TryGetValue(type.FullName, out var pis)) { return pis; } var properties = type.GetProperties().Where(IsWriteable).ToArray(); TypeProperties[type.FullName] = properties; return properties; } protected string Inserts(Type type, ISqlDialect dialect) { var key = new CompoundKey(dialect.Name, type.FullName, _store.Configuration.TablePrefix, Collection); if (!InsertsList.TryGetValue(key, out var result)) { string values; var allProperties = TypePropertiesCache(type); if (allProperties.Any()) { var sbColumnList = new StringBuilder(null); for (var i = 0; i < allProperties.Count(); i++) { var property = allProperties.ElementAt(i); sbColumnList.Append(dialect.QuoteForColumnName(property.Name)); if (i < allProperties.Count() - 1) { sbColumnList.Append(", "); } } var sbParameterList = new StringBuilder(null); for (var i = 0; i < allProperties.Count(); i++) { var property = allProperties.ElementAt(i); sbParameterList.Append("@").Append(property.Name).Append(ParameterSuffix); if (i < allProperties.Count() - 1) { sbParameterList.Append(", "); } } if (typeof(MapIndex).IsAssignableFrom(type)) { // We can set the document id sbColumnList.Append(", ").Append(dialect.QuoteForColumnName("DocumentId")); sbParameterList.Append(", @DocumentId").Append(ParameterSuffix); } values = $"({sbColumnList}) values ({sbParameterList})"; } else { if (typeof(MapIndex).IsAssignableFrom(type)) { values = $"({dialect.QuoteForColumnName("DocumentId")}) values (@DocumentId{ParameterSuffix})"; } else { values = dialect.DefaultValuesInsert; } } InsertsList[key] = result = $"insert into {dialect.QuoteForTableName(_store.Configuration.TablePrefix + _store.Configuration.TableNameConvention.GetIndexTable(type, Collection))} {values} {dialect.IdentitySelectString} {dialect.QuoteForColumnName("Id")};"; } return result; } protected string Updates(Type type, ISqlDialect dialect) { var key = new CompoundKey(dialect.Name, type.FullName, _store.Configuration.TablePrefix, Collection); if (!UpdatesList.TryGetValue(key, out var result)) { var allProperties = TypePropertiesCache(type); var values = new StringBuilder(null); for (var i = 0; i < allProperties.Length; i++) { var property = allProperties[i]; values.Append(dialect.QuoteForColumnName(property.Name) + " = @" + property.Name + ParameterSuffix); if (i < allProperties.Length - 1) { values.Append(", "); } } UpdatesList[key] = result = $"update {dialect.QuoteForTableName(_store.Configuration.TablePrefix + _store.Configuration.TableNameConvention.GetIndexTable(type, Collection))} set {values} where {dialect.QuoteForColumnName("Id")} = @Id{ParameterSuffix};"; } return result; } private static bool IsWriteable(PropertyInfo pi) { return pi.Name != nameof(IIndex.Id) && // don't read DocumentId when on a MapIndex as it might be used to // read the DocumentId directly from an Index query pi.Name != "DocumentId" ; } public abstract bool AddToBatch(ISqlDialect dialect, List<string> queries, DbCommand batchCommand, List<Action<DbDataReader>> actions, int index); public struct CompoundKey : IEquatable<CompoundKey> { private readonly string _key1; private readonly string _key2; private readonly string _key3; private readonly string _key4; public CompoundKey(string key1, string key2, string key3, string key4) { _key1 = key1; _key2 = key2; _key3 = key3; _key4 = key4; } /// <inheritdoc /> public override bool Equals(object obj) { if (obj is CompoundKey other) { return Equals(other); } return false; } /// <inheritdoc /> public bool Equals(CompoundKey other) { return String.Equals(_key1, other._key1) && String.Equals(_key2, other._key2) && String.Equals(_key3, other._key3) && String.Equals(_key4, other._key4) ; } /// <inheritdoc /> public override int GetHashCode() { unchecked { var hashCode = 13; hashCode = (hashCode * 397) ^ (!string.IsNullOrEmpty(_key1) ? _key1.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (!string.IsNullOrEmpty(_key2) ? _key2.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (!string.IsNullOrEmpty(_key3) ? _key3.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (!string.IsNullOrEmpty(_key4) ? _key4.GetHashCode() : 0); return hashCode; } } } } }
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) using System; using System.Diagnostics; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Utilities; namespace Org.BouncyCastle.Crypto.Engines { /** * an implementation of the AES (Rijndael), from FIPS-197. * <p> * For further details see: <a href="http://csrc.nist.gov/encryption/aes/">http://csrc.nist.gov/encryption/aes/</a>. * * This implementation is based on optimizations from Dr. Brian Gladman's paper and C code at * <a href="http://fp.gladman.plus.com/cryptography_technology/rijndael/">http://fp.gladman.plus.com/cryptography_technology/rijndael/</a> * * There are three levels of tradeoff of speed vs memory * Because java has no preprocessor, they are written as three separate classes from which to choose * * The fastest uses 8Kbytes of static tables to precompute round calculations, 4 256 word tables for encryption * and 4 for decryption. * * The middle performance version uses only one 256 word table for each, for a total of 2Kbytes, * adding 12 rotate operations per round to compute the values contained in the other tables from * the contents of the first. * * The slowest version uses no static tables at all and computes the values in each round. * </p> * <p> * This file contains the middle performance version with 2Kbytes of static tables for round precomputation. * </p> */ public class AesEngine : IBlockCipher { // The S box private static readonly byte[] S = { 99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117, 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132, 83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207, 208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168, 81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210, 205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115, 96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219, 224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, 231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, 186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, 112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, 225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223, 140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22, }; // The inverse S-box private static readonly byte[] Si = { 82, 9, 106, 213, 48, 54, 165, 56, 191, 64, 163, 158, 129, 243, 215, 251, 124, 227, 57, 130, 155, 47, 255, 135, 52, 142, 67, 68, 196, 222, 233, 203, 84, 123, 148, 50, 166, 194, 35, 61, 238, 76, 149, 11, 66, 250, 195, 78, 8, 46, 161, 102, 40, 217, 36, 178, 118, 91, 162, 73, 109, 139, 209, 37, 114, 248, 246, 100, 134, 104, 152, 22, 212, 164, 92, 204, 93, 101, 182, 146, 108, 112, 72, 80, 253, 237, 185, 218, 94, 21, 70, 87, 167, 141, 157, 132, 144, 216, 171, 0, 140, 188, 211, 10, 247, 228, 88, 5, 184, 179, 69, 6, 208, 44, 30, 143, 202, 63, 15, 2, 193, 175, 189, 3, 1, 19, 138, 107, 58, 145, 17, 65, 79, 103, 220, 234, 151, 242, 207, 206, 240, 180, 230, 115, 150, 172, 116, 34, 231, 173, 53, 133, 226, 249, 55, 232, 28, 117, 223, 110, 71, 241, 26, 113, 29, 41, 197, 137, 111, 183, 98, 14, 170, 24, 190, 27, 252, 86, 62, 75, 198, 210, 121, 32, 154, 219, 192, 254, 120, 205, 90, 244, 31, 221, 168, 51, 136, 7, 199, 49, 177, 18, 16, 89, 39, 128, 236, 95, 96, 81, 127, 169, 25, 181, 74, 13, 45, 229, 122, 159, 147, 201, 156, 239, 160, 224, 59, 77, 174, 42, 245, 176, 200, 235, 187, 60, 131, 83, 153, 97, 23, 43, 4, 126, 186, 119, 214, 38, 225, 105, 20, 99, 85, 33, 12, 125, }; // vector used in calculating key schedule (powers of x in GF(256)) private static readonly byte[] rcon = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91 }; // precomputation tables of calculations for rounds private static readonly uint[] T0 = { 0xa56363c6, 0x847c7cf8, 0x997777ee, 0x8d7b7bf6, 0x0df2f2ff, 0xbd6b6bd6, 0xb16f6fde, 0x54c5c591, 0x50303060, 0x03010102, 0xa96767ce, 0x7d2b2b56, 0x19fefee7, 0x62d7d7b5, 0xe6abab4d, 0x9a7676ec, 0x45caca8f, 0x9d82821f, 0x40c9c989, 0x877d7dfa, 0x15fafaef, 0xeb5959b2, 0xc947478e, 0x0bf0f0fb, 0xecadad41, 0x67d4d4b3, 0xfda2a25f, 0xeaafaf45, 0xbf9c9c23, 0xf7a4a453, 0x967272e4, 0x5bc0c09b, 0xc2b7b775, 0x1cfdfde1, 0xae93933d, 0x6a26264c, 0x5a36366c, 0x413f3f7e, 0x02f7f7f5, 0x4fcccc83, 0x5c343468, 0xf4a5a551, 0x34e5e5d1, 0x08f1f1f9, 0x937171e2, 0x73d8d8ab, 0x53313162, 0x3f15152a, 0x0c040408, 0x52c7c795, 0x65232346, 0x5ec3c39d, 0x28181830, 0xa1969637, 0x0f05050a, 0xb59a9a2f, 0x0907070e, 0x36121224, 0x9b80801b, 0x3de2e2df, 0x26ebebcd, 0x6927274e, 0xcdb2b27f, 0x9f7575ea, 0x1b090912, 0x9e83831d, 0x742c2c58, 0x2e1a1a34, 0x2d1b1b36, 0xb26e6edc, 0xee5a5ab4, 0xfba0a05b, 0xf65252a4, 0x4d3b3b76, 0x61d6d6b7, 0xceb3b37d, 0x7b292952, 0x3ee3e3dd, 0x712f2f5e, 0x97848413, 0xf55353a6, 0x68d1d1b9, 0x00000000, 0x2cededc1, 0x60202040, 0x1ffcfce3, 0xc8b1b179, 0xed5b5bb6, 0xbe6a6ad4, 0x46cbcb8d, 0xd9bebe67, 0x4b393972, 0xde4a4a94, 0xd44c4c98, 0xe85858b0, 0x4acfcf85, 0x6bd0d0bb, 0x2aefefc5, 0xe5aaaa4f, 0x16fbfbed, 0xc5434386, 0xd74d4d9a, 0x55333366, 0x94858511, 0xcf45458a, 0x10f9f9e9, 0x06020204, 0x817f7ffe, 0xf05050a0, 0x443c3c78, 0xba9f9f25, 0xe3a8a84b, 0xf35151a2, 0xfea3a35d, 0xc0404080, 0x8a8f8f05, 0xad92923f, 0xbc9d9d21, 0x48383870, 0x04f5f5f1, 0xdfbcbc63, 0xc1b6b677, 0x75dadaaf, 0x63212142, 0x30101020, 0x1affffe5, 0x0ef3f3fd, 0x6dd2d2bf, 0x4ccdcd81, 0x140c0c18, 0x35131326, 0x2fececc3, 0xe15f5fbe, 0xa2979735, 0xcc444488, 0x3917172e, 0x57c4c493, 0xf2a7a755, 0x827e7efc, 0x473d3d7a, 0xac6464c8, 0xe75d5dba, 0x2b191932, 0x957373e6, 0xa06060c0, 0x98818119, 0xd14f4f9e, 0x7fdcdca3, 0x66222244, 0x7e2a2a54, 0xab90903b, 0x8388880b, 0xca46468c, 0x29eeeec7, 0xd3b8b86b, 0x3c141428, 0x79dedea7, 0xe25e5ebc, 0x1d0b0b16, 0x76dbdbad, 0x3be0e0db, 0x56323264, 0x4e3a3a74, 0x1e0a0a14, 0xdb494992, 0x0a06060c, 0x6c242448, 0xe45c5cb8, 0x5dc2c29f, 0x6ed3d3bd, 0xefacac43, 0xa66262c4, 0xa8919139, 0xa4959531, 0x37e4e4d3, 0x8b7979f2, 0x32e7e7d5, 0x43c8c88b, 0x5937376e, 0xb76d6dda, 0x8c8d8d01, 0x64d5d5b1, 0xd24e4e9c, 0xe0a9a949, 0xb46c6cd8, 0xfa5656ac, 0x07f4f4f3, 0x25eaeacf, 0xaf6565ca, 0x8e7a7af4, 0xe9aeae47, 0x18080810, 0xd5baba6f, 0x887878f0, 0x6f25254a, 0x722e2e5c, 0x241c1c38, 0xf1a6a657, 0xc7b4b473, 0x51c6c697, 0x23e8e8cb, 0x7cdddda1, 0x9c7474e8, 0x211f1f3e, 0xdd4b4b96, 0xdcbdbd61, 0x868b8b0d, 0x858a8a0f, 0x907070e0, 0x423e3e7c, 0xc4b5b571, 0xaa6666cc, 0xd8484890, 0x05030306, 0x01f6f6f7, 0x120e0e1c, 0xa36161c2, 0x5f35356a, 0xf95757ae, 0xd0b9b969, 0x91868617, 0x58c1c199, 0x271d1d3a, 0xb99e9e27, 0x38e1e1d9, 0x13f8f8eb, 0xb398982b, 0x33111122, 0xbb6969d2, 0x70d9d9a9, 0x898e8e07, 0xa7949433, 0xb69b9b2d, 0x221e1e3c, 0x92878715, 0x20e9e9c9, 0x49cece87, 0xff5555aa, 0x78282850, 0x7adfdfa5, 0x8f8c8c03, 0xf8a1a159, 0x80898909, 0x170d0d1a, 0xdabfbf65, 0x31e6e6d7, 0xc6424284, 0xb86868d0, 0xc3414182, 0xb0999929, 0x772d2d5a, 0x110f0f1e, 0xcbb0b07b, 0xfc5454a8, 0xd6bbbb6d, 0x3a16162c }; private static readonly uint[] Tinv0 = { 0x50a7f451, 0x5365417e, 0xc3a4171a, 0x965e273a, 0xcb6bab3b, 0xf1459d1f, 0xab58faac, 0x9303e34b, 0x55fa3020, 0xf66d76ad, 0x9176cc88, 0x254c02f5, 0xfcd7e54f, 0xd7cb2ac5, 0x80443526, 0x8fa362b5, 0x495ab1de, 0x671bba25, 0x980eea45, 0xe1c0fe5d, 0x02752fc3, 0x12f04c81, 0xa397468d, 0xc6f9d36b, 0xe75f8f03, 0x959c9215, 0xeb7a6dbf, 0xda595295, 0x2d83bed4, 0xd3217458, 0x2969e049, 0x44c8c98e, 0x6a89c275, 0x78798ef4, 0x6b3e5899, 0xdd71b927, 0xb64fe1be, 0x17ad88f0, 0x66ac20c9, 0xb43ace7d, 0x184adf63, 0x82311ae5, 0x60335197, 0x457f5362, 0xe07764b1, 0x84ae6bbb, 0x1ca081fe, 0x942b08f9, 0x58684870, 0x19fd458f, 0x876cde94, 0xb7f87b52, 0x23d373ab, 0xe2024b72, 0x578f1fe3, 0x2aab5566, 0x0728ebb2, 0x03c2b52f, 0x9a7bc586, 0xa50837d3, 0xf2872830, 0xb2a5bf23, 0xba6a0302, 0x5c8216ed, 0x2b1ccf8a, 0x92b479a7, 0xf0f207f3, 0xa1e2694e, 0xcdf4da65, 0xd5be0506, 0x1f6234d1, 0x8afea6c4, 0x9d532e34, 0xa055f3a2, 0x32e18a05, 0x75ebf6a4, 0x39ec830b, 0xaaef6040, 0x069f715e, 0x51106ebd, 0xf98a213e, 0x3d06dd96, 0xae053edd, 0x46bde64d, 0xb58d5491, 0x055dc471, 0x6fd40604, 0xff155060, 0x24fb9819, 0x97e9bdd6, 0xcc434089, 0x779ed967, 0xbd42e8b0, 0x888b8907, 0x385b19e7, 0xdbeec879, 0x470a7ca1, 0xe90f427c, 0xc91e84f8, 0x00000000, 0x83868009, 0x48ed2b32, 0xac70111e, 0x4e725a6c, 0xfbff0efd, 0x5638850f, 0x1ed5ae3d, 0x27392d36, 0x64d90f0a, 0x21a65c68, 0xd1545b9b, 0x3a2e3624, 0xb1670a0c, 0x0fe75793, 0xd296eeb4, 0x9e919b1b, 0x4fc5c080, 0xa220dc61, 0x694b775a, 0x161a121c, 0x0aba93e2, 0xe52aa0c0, 0x43e0223c, 0x1d171b12, 0x0b0d090e, 0xadc78bf2, 0xb9a8b62d, 0xc8a91e14, 0x8519f157, 0x4c0775af, 0xbbdd99ee, 0xfd607fa3, 0x9f2601f7, 0xbcf5725c, 0xc53b6644, 0x347efb5b, 0x7629438b, 0xdcc623cb, 0x68fcedb6, 0x63f1e4b8, 0xcadc31d7, 0x10856342, 0x40229713, 0x2011c684, 0x7d244a85, 0xf83dbbd2, 0x1132f9ae, 0x6da129c7, 0x4b2f9e1d, 0xf330b2dc, 0xec52860d, 0xd0e3c177, 0x6c16b32b, 0x99b970a9, 0xfa489411, 0x2264e947, 0xc48cfca8, 0x1a3ff0a0, 0xd82c7d56, 0xef903322, 0xc74e4987, 0xc1d138d9, 0xfea2ca8c, 0x360bd498, 0xcf81f5a6, 0x28de7aa5, 0x268eb7da, 0xa4bfad3f, 0xe49d3a2c, 0x0d927850, 0x9bcc5f6a, 0x62467e54, 0xc2138df6, 0xe8b8d890, 0x5ef7392e, 0xf5afc382, 0xbe805d9f, 0x7c93d069, 0xa92dd56f, 0xb31225cf, 0x3b99acc8, 0xa77d1810, 0x6e639ce8, 0x7bbb3bdb, 0x097826cd, 0xf418596e, 0x01b79aec, 0xa89a4f83, 0x656e95e6, 0x7ee6ffaa, 0x08cfbc21, 0xe6e815ef, 0xd99be7ba, 0xce366f4a, 0xd4099fea, 0xd67cb029, 0xafb2a431, 0x31233f2a, 0x3094a5c6, 0xc066a235, 0x37bc4e74, 0xa6ca82fc, 0xb0d090e0, 0x15d8a733, 0x4a9804f1, 0xf7daec41, 0x0e50cd7f, 0x2ff69117, 0x8dd64d76, 0x4db0ef43, 0x544daacc, 0xdf0496e4, 0xe3b5d19e, 0x1b886a4c, 0xb81f2cc1, 0x7f516546, 0x04ea5e9d, 0x5d358c01, 0x737487fa, 0x2e410bfb, 0x5a1d67b3, 0x52d2db92, 0x335610e9, 0x1347d66d, 0x8c61d79a, 0x7a0ca137, 0x8e14f859, 0x893c13eb, 0xee27a9ce, 0x35c961b7, 0xede51ce1, 0x3cb1477a, 0x59dfd29c, 0x3f73f255, 0x79ce1418, 0xbf37c773, 0xeacdf753, 0x5baafd5f, 0x146f3ddf, 0x86db4478, 0x81f3afca, 0x3ec468b9, 0x2c342438, 0x5f40a3c2, 0x72c31d16, 0x0c25e2bc, 0x8b493c28, 0x41950dff, 0x7101a839, 0xdeb30c08, 0x9ce4b4d8, 0x90c15664, 0x6184cb7b, 0x70b632d5, 0x745c6c48, 0x4257b8d0 }; private static uint Shift(uint r, int shift) { return (r >> shift) | (r << (32 - shift)); } /* multiply four bytes in GF(2^8) by 'x' {02} in parallel */ private const uint m1 = 0x80808080; private const uint m2 = 0x7f7f7f7f; private const uint m3 = 0x0000001b; private static uint FFmulX(uint x) { return ((x & m2) << 1) ^ (((x & m1) >> 7) * m3); } /* The following defines provide alternative definitions of FFmulX that might give improved performance if a fast 32-bit multiply is not available. private int FFmulX(int x) { int u = x & m1; u |= (u >> 1); return ((x & m2) << 1) ^ ((u >>> 3) | (u >>> 6)); } private static final int m4 = 0x1b1b1b1b; private int FFmulX(int x) { int u = x & m1; return ((x & m2) << 1) ^ ((u - (u >>> 7)) & m4); } */ private static uint Inv_Mcol(uint x) { uint f2 = FFmulX(x); uint f4 = FFmulX(f2); uint f8 = FFmulX(f4); uint f9 = x ^ f8; return f2 ^ f4 ^ f8 ^ Shift(f2 ^ f9, 8) ^ Shift(f4 ^ f9, 16) ^ Shift(f9, 24); } private static uint SubWord(uint x) { return (uint)S[x&255] | (((uint)S[(x>>8)&255]) << 8) | (((uint)S[(x>>16)&255]) << 16) | (((uint)S[(x>>24)&255]) << 24); } /** * Calculate the necessary round keys * The number of calculations depends on key size and block size * AES specified a fixed block size of 128 bits and key sizes 128/192/256 bits * This code is written assuming those are the only possible values */ private uint[][] GenerateWorkingKey( byte[] key, bool forEncryption) { int KC = key.Length / 4; // key length in words int t; if ((KC != 4) && (KC != 6) && (KC != 8)) throw new ArgumentException("Key length not 128/192/256 bits."); ROUNDS = KC + 6; // This is not always true for the generalized Rijndael that allows larger block sizes uint[][] W = new uint[ROUNDS + 1][]; // 4 words in a block for (int i = 0; i <= ROUNDS; ++i) { W[i] = new uint[4]; } // // copy the key into the round key array // t = 0; for (int i = 0; i < key.Length; t++) { W[t >> 2][t & 3] = Pack.LE_To_UInt32(key, i); i+=4; } // // while not enough round key material calculated // calculate new values // int k = (ROUNDS + 1) << 2; for (int i = KC; (i < k); i++) { uint temp = W[(i-1)>>2][(i-1)&3]; if ((i % KC) == 0) { temp = SubWord(Shift(temp, 8)) ^ rcon[(i / KC)-1]; } else if ((KC > 6) && ((i % KC) == 4)) { temp = SubWord(temp); } W[i>>2][i&3] = W[(i - KC)>>2][(i-KC)&3] ^ temp; } if (!forEncryption) { for (int j = 1; j < ROUNDS; j++) { uint[] w = W[j]; for (int i = 0; i < 4; i++) { w[i] = Inv_Mcol(w[i]); } } } return W; } private int ROUNDS; private uint[][] WorkingKey; private uint C0, C1, C2, C3; private bool forEncryption; private const int BLOCK_SIZE = 16; /** * default constructor - 128 bit block size. */ public AesEngine() { } /** * initialise an AES cipher. * * @param forEncryption whether or not we are for encryption. * @param parameters the parameters required to set up the cipher. * @exception ArgumentException if the parameters argument is * inappropriate. */ public virtual void Init( bool forEncryption, ICipherParameters parameters) { KeyParameter keyParameter = parameters as KeyParameter; if (keyParameter == null) throw new ArgumentException("invalid parameter passed to AES init - " + parameters.GetType().Name); WorkingKey = GenerateWorkingKey(keyParameter.GetKey(), forEncryption); this.forEncryption = forEncryption; } public virtual string AlgorithmName { get { return "AES"; } } public virtual bool IsPartialBlockOkay { get { return false; } } public virtual int GetBlockSize() { return BLOCK_SIZE; } public virtual int ProcessBlock( byte[] input, int inOff, byte[] output, int outOff) { if (WorkingKey == null) throw new InvalidOperationException("AES engine not initialised"); Check.DataLength(input, inOff, 16, "input buffer too short"); Check.OutputLength(output, outOff, 16, "output buffer too short"); UnPackBlock(input, inOff); if (forEncryption) { EncryptBlock(WorkingKey); } else { DecryptBlock(WorkingKey); } PackBlock(output, outOff); return BLOCK_SIZE; } public virtual void Reset() { } private void UnPackBlock( byte[] bytes, int off) { C0 = Pack.LE_To_UInt32(bytes, off); C1 = Pack.LE_To_UInt32(bytes, off + 4); C2 = Pack.LE_To_UInt32(bytes, off + 8); C3 = Pack.LE_To_UInt32(bytes, off + 12); } private void PackBlock( byte[] bytes, int off) { Pack.UInt32_To_LE(C0, bytes, off); Pack.UInt32_To_LE(C1, bytes, off + 4); Pack.UInt32_To_LE(C2, bytes, off + 8); Pack.UInt32_To_LE(C3, bytes, off + 12); } private void EncryptBlock(uint[][] KW) { uint[] kw = KW[0]; uint t0 = this.C0 ^ kw[0]; uint t1 = this.C1 ^ kw[1]; uint t2 = this.C2 ^ kw[2]; uint r0, r1, r2, r3 = this.C3 ^ kw[3]; int r = 1; while (r < ROUNDS - 1) { kw = KW[r++]; r0 = T0[t0 & 255] ^ Shift(T0[(t1 >> 8) & 255], 24) ^ Shift(T0[(t2 >> 16) & 255], 16) ^ Shift(T0[(r3 >> 24) & 255], 8) ^ kw[0]; r1 = T0[t1 & 255] ^ Shift(T0[(t2 >> 8) & 255], 24) ^ Shift(T0[(r3 >> 16) & 255], 16) ^ Shift(T0[(t0 >> 24) & 255], 8) ^ kw[1]; r2 = T0[t2 & 255] ^ Shift(T0[(r3 >> 8) & 255], 24) ^ Shift(T0[(t0 >> 16) & 255], 16) ^ Shift(T0[(t1 >> 24) & 255], 8) ^ kw[2]; r3 = T0[r3 & 255] ^ Shift(T0[(t0 >> 8) & 255], 24) ^ Shift(T0[(t1 >> 16) & 255], 16) ^ Shift(T0[(t2 >> 24) & 255], 8) ^ kw[3]; kw = KW[r++]; t0 = T0[r0 & 255] ^ Shift(T0[(r1 >> 8) & 255], 24) ^ Shift(T0[(r2 >> 16) & 255], 16) ^ Shift(T0[(r3 >> 24) & 255], 8) ^ kw[0]; t1 = T0[r1 & 255] ^ Shift(T0[(r2 >> 8) & 255], 24) ^ Shift(T0[(r3 >> 16) & 255], 16) ^ Shift(T0[(r0 >> 24) & 255], 8) ^ kw[1]; t2 = T0[r2 & 255] ^ Shift(T0[(r3 >> 8) & 255], 24) ^ Shift(T0[(r0 >> 16) & 255], 16) ^ Shift(T0[(r1 >> 24) & 255], 8) ^ kw[2]; r3 = T0[r3 & 255] ^ Shift(T0[(r0 >> 8) & 255], 24) ^ Shift(T0[(r1 >> 16) & 255], 16) ^ Shift(T0[(r2 >> 24) & 255], 8) ^ kw[3]; } kw = KW[r++]; r0 = T0[t0 & 255] ^ Shift(T0[(t1 >> 8) & 255], 24) ^ Shift(T0[(t2 >> 16) & 255], 16) ^ Shift(T0[(r3 >> 24) & 255], 8) ^ kw[0]; r1 = T0[t1 & 255] ^ Shift(T0[(t2 >> 8) & 255], 24) ^ Shift(T0[(r3 >> 16) & 255], 16) ^ Shift(T0[(t0 >> 24) & 255], 8) ^ kw[1]; r2 = T0[t2 & 255] ^ Shift(T0[(r3 >> 8) & 255], 24) ^ Shift(T0[(t0 >> 16) & 255], 16) ^ Shift(T0[(t1 >> 24) & 255], 8) ^ kw[2]; r3 = T0[r3 & 255] ^ Shift(T0[(t0 >> 8) & 255], 24) ^ Shift(T0[(t1 >> 16) & 255], 16) ^ Shift(T0[(t2 >> 24) & 255], 8) ^ kw[3]; // the final round's table is a simple function of S so we don't use a whole other four tables for it kw = KW[r]; this.C0 = (uint)S[r0 & 255] ^ (((uint)S[(r1 >> 8) & 255]) << 8) ^ (((uint)S[(r2 >> 16) & 255]) << 16) ^ (((uint)S[(r3 >> 24) & 255]) << 24) ^ kw[0]; this.C1 = (uint)S[r1 & 255] ^ (((uint)S[(r2 >> 8) & 255]) << 8) ^ (((uint)S[(r3 >> 16) & 255]) << 16) ^ (((uint)S[(r0 >> 24) & 255]) << 24) ^ kw[1]; this.C2 = (uint)S[r2 & 255] ^ (((uint)S[(r3 >> 8) & 255]) << 8) ^ (((uint)S[(r0 >> 16) & 255]) << 16) ^ (((uint)S[(r1 >> 24) & 255]) << 24) ^ kw[2]; this.C3 = (uint)S[r3 & 255] ^ (((uint)S[(r0 >> 8) & 255]) << 8) ^ (((uint)S[(r1 >> 16) & 255]) << 16) ^ (((uint)S[(r2 >> 24) & 255]) << 24) ^ kw[3]; } private void DecryptBlock(uint[][] KW) { uint[] kw = KW[ROUNDS]; uint t0 = this.C0 ^ kw[0]; uint t1 = this.C1 ^ kw[1]; uint t2 = this.C2 ^ kw[2]; uint r0, r1, r2, r3 = this.C3 ^ kw[3]; int r = ROUNDS - 1; while (r > 1) { kw = KW[r--]; r0 = Tinv0[t0 & 255] ^ Shift(Tinv0[(r3 >> 8) & 255], 24) ^ Shift(Tinv0[(t2 >> 16) & 255], 16) ^ Shift(Tinv0[(t1 >> 24) & 255], 8) ^ kw[0]; r1 = Tinv0[t1 & 255] ^ Shift(Tinv0[(t0 >> 8) & 255], 24) ^ Shift(Tinv0[(r3 >> 16) & 255], 16) ^ Shift(Tinv0[(t2 >> 24) & 255], 8) ^ kw[1]; r2 = Tinv0[t2 & 255] ^ Shift(Tinv0[(t1 >> 8) & 255], 24) ^ Shift(Tinv0[(t0 >> 16) & 255], 16) ^ Shift(Tinv0[(r3 >> 24) & 255], 8) ^ kw[2]; r3 = Tinv0[r3 & 255] ^ Shift(Tinv0[(t2 >> 8) & 255], 24) ^ Shift(Tinv0[(t1 >> 16) & 255], 16) ^ Shift(Tinv0[(t0 >> 24) & 255], 8) ^ kw[3]; kw = KW[r--]; t0 = Tinv0[r0 & 255] ^ Shift(Tinv0[(r3 >> 8) & 255], 24) ^ Shift(Tinv0[(r2 >> 16) & 255], 16) ^ Shift(Tinv0[(r1 >> 24) & 255], 8) ^ kw[0]; t1 = Tinv0[r1 & 255] ^ Shift(Tinv0[(r0 >> 8) & 255], 24) ^ Shift(Tinv0[(r3 >> 16) & 255], 16) ^ Shift(Tinv0[(r2 >> 24) & 255], 8) ^ kw[1]; t2 = Tinv0[r2 & 255] ^ Shift(Tinv0[(r1 >> 8) & 255], 24) ^ Shift(Tinv0[(r0 >> 16) & 255], 16) ^ Shift(Tinv0[(r3 >> 24) & 255], 8) ^ kw[2]; r3 = Tinv0[r3 & 255] ^ Shift(Tinv0[(r2 >> 8) & 255], 24) ^ Shift(Tinv0[(r1 >> 16) & 255], 16) ^ Shift(Tinv0[(r0 >> 24) & 255], 8) ^ kw[3]; } kw = KW[1]; r0 = Tinv0[t0 & 255] ^ Shift(Tinv0[(r3 >> 8) & 255], 24) ^ Shift(Tinv0[(t2 >> 16) & 255], 16) ^ Shift(Tinv0[(t1 >> 24) & 255], 8) ^ kw[0]; r1 = Tinv0[t1 & 255] ^ Shift(Tinv0[(t0 >> 8) & 255], 24) ^ Shift(Tinv0[(r3 >> 16) & 255], 16) ^ Shift(Tinv0[(t2 >> 24) & 255], 8) ^ kw[1]; r2 = Tinv0[t2 & 255] ^ Shift(Tinv0[(t1 >> 8) & 255], 24) ^ Shift(Tinv0[(t0 >> 16) & 255], 16) ^ Shift(Tinv0[(r3 >> 24) & 255], 8) ^ kw[2]; r3 = Tinv0[r3 & 255] ^ Shift(Tinv0[(t2 >> 8) & 255], 24) ^ Shift(Tinv0[(t1 >> 16) & 255], 16) ^ Shift(Tinv0[(t0 >> 24) & 255], 8) ^ kw[3]; // the final round's table is a simple function of Si so we don't use a whole other four tables for it kw = KW[0]; this.C0 = (uint)Si[r0 & 255] ^ (((uint)Si[(r3 >> 8) & 255]) << 8) ^ (((uint)Si[(r2 >> 16) & 255]) << 16) ^ (((uint)Si[(r1 >> 24) & 255]) << 24) ^ kw[0]; this.C1 = (uint)Si[r1 & 255] ^ (((uint)Si[(r0 >> 8) & 255]) << 8) ^ (((uint)Si[(r3 >> 16) & 255]) << 16) ^ (((uint)Si[(r2 >> 24) & 255]) << 24) ^ kw[1]; this.C2 = (uint)Si[r2 & 255] ^ (((uint)Si[(r1 >> 8) & 255]) << 8) ^ (((uint)Si[(r0 >> 16) & 255]) << 16) ^ (((uint)Si[(r3 >> 24) & 255]) << 24) ^ kw[2]; this.C3 = (uint)Si[r3 & 255] ^ (((uint)Si[(r2 >> 8) & 255]) << 8) ^ (((uint)Si[(r1 >> 16) & 255]) << 16) ^ (((uint)Si[(r0 >> 24) & 255]) << 24) ^ kw[3]; } } } #endif
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Text; using System.Threading; using System.Timers; using Timer = System.Timers.Timer; using Nini.Config; using NUnit.Framework; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.ClientStack.Linden; using OpenSim.Region.CoreModules.Framework.EntityTransfer; using OpenSim.Region.CoreModules.World.Serialiser; using OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation; using OpenSim.Tests.Common; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenSim.Services.Interfaces; namespace OpenSim.Region.Framework.Scenes.Tests { /// <summary> /// Scene presence tests /// </summary> [TestFixture] public class ScenePresenceAgentTests : OpenSimTestCase { // public Scene scene, scene2, scene3; // public UUID agent1, agent2, agent3; // public static Random random; // public ulong region1, region2, region3; // public AgentCircuitData acd1; // public TestClient testclient; // [TestFixtureSetUp] // public void Init() // { //// TestHelpers.InMethod(); //// //// SceneHelpers sh = new SceneHelpers(); //// //// scene = sh.SetupScene("Neighbour x", UUID.Random(), 1000, 1000); //// scene2 = sh.SetupScene("Neighbour x+1", UUID.Random(), 1001, 1000); //// scene3 = sh.SetupScene("Neighbour x-1", UUID.Random(), 999, 1000); //// //// ISharedRegionModule interregionComms = new LocalSimulationConnectorModule(); //// interregionComms.Initialise(new IniConfigSource()); //// interregionComms.PostInitialise(); //// SceneHelpers.SetupSceneModules(scene, new IniConfigSource(), interregionComms); //// SceneHelpers.SetupSceneModules(scene2, new IniConfigSource(), interregionComms); //// SceneHelpers.SetupSceneModules(scene3, new IniConfigSource(), interregionComms); // //// agent1 = UUID.Random(); //// agent2 = UUID.Random(); //// agent3 = UUID.Random(); // //// region1 = scene.RegionInfo.RegionHandle; //// region2 = scene2.RegionInfo.RegionHandle; //// region3 = scene3.RegionInfo.RegionHandle; // } [Test] public void TestCreateRootScenePresence() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); UUID spUuid = TestHelpers.ParseTail(0x1); TestScene scene = new SceneHelpers().SetupScene(); SceneHelpers.AddScenePresence(scene, spUuid); Assert.That(scene.AuthenticateHandler.GetAgentCircuitData(spUuid), Is.Not.Null); Assert.That(scene.AuthenticateHandler.GetAgentCircuits().Count, Is.EqualTo(1)); ScenePresence sp = scene.GetScenePresence(spUuid); Assert.That(sp, Is.Not.Null); Assert.That(sp.IsChildAgent, Is.False); Assert.That(sp.UUID, Is.EqualTo(spUuid)); Assert.That(scene.GetScenePresences().Count, Is.EqualTo(1)); } /// <summary> /// Test that duplicate complete movement calls are ignored. /// </summary> /// <remarks> /// If duplicate calls are not ignored then there is a risk of race conditions or other unexpected effects. /// </remarks> [Test] public void TestDupeCompleteMovementCalls() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); UUID spUuid = TestHelpers.ParseTail(0x1); TestScene scene = new SceneHelpers().SetupScene(); int makeRootAgentEvents = 0; scene.EventManager.OnMakeRootAgent += spi => makeRootAgentEvents++; ScenePresence sp = SceneHelpers.AddScenePresence(scene, spUuid); Assert.That(makeRootAgentEvents, Is.EqualTo(1)); // Normally these would be invoked by a CompleteMovement message coming in to the UDP stack. But for // convenience, here we will invoke it manually. sp.CompleteMovement(sp.ControllingClient, true); Assert.That(makeRootAgentEvents, Is.EqualTo(1)); // Check rest of exepcted parameters. Assert.That(scene.AuthenticateHandler.GetAgentCircuitData(spUuid), Is.Not.Null); Assert.That(scene.AuthenticateHandler.GetAgentCircuits().Count, Is.EqualTo(1)); Assert.That(sp.IsChildAgent, Is.False); Assert.That(sp.UUID, Is.EqualTo(spUuid)); Assert.That(scene.GetScenePresences().Count, Is.EqualTo(1)); } [Test] public void TestCreateDuplicateRootScenePresence() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); UUID spUuid = TestHelpers.ParseTail(0x1); // The etm is only invoked by this test to check whether an agent is still in transit if there is a dupe EntityTransferModule etm = new EntityTransferModule(); IConfigSource config = new IniConfigSource(); IConfig modulesConfig = config.AddConfig("Modules"); modulesConfig.Set("EntityTransferModule", etm.Name); IConfig entityTransferConfig = config.AddConfig("EntityTransfer"); // In order to run a single threaded regression test we do not want the entity transfer module waiting // for a callback from the destination scene before removing its avatar data. entityTransferConfig.Set("wait_for_callback", false); TestScene scene = new SceneHelpers().SetupScene(); SceneHelpers.SetupSceneModules(scene, config, etm); SceneHelpers.AddScenePresence(scene, spUuid); SceneHelpers.AddScenePresence(scene, spUuid); Assert.That(scene.AuthenticateHandler.GetAgentCircuitData(spUuid), Is.Not.Null); Assert.That(scene.AuthenticateHandler.GetAgentCircuits().Count, Is.EqualTo(1)); ScenePresence sp = scene.GetScenePresence(spUuid); Assert.That(sp, Is.Not.Null); Assert.That(sp.IsChildAgent, Is.False); Assert.That(sp.UUID, Is.EqualTo(spUuid)); } [Test] public void TestCloseClient() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); TestScene scene = new SceneHelpers().SetupScene(); ScenePresence sp = SceneHelpers.AddScenePresence(scene, TestHelpers.ParseTail(0x1)); scene.CloseAgent(sp.UUID, false); Assert.That(scene.GetScenePresence(sp.UUID), Is.Null); Assert.That(scene.AuthenticateHandler.GetAgentCircuitData(sp.UUID), Is.Null); Assert.That(scene.AuthenticateHandler.GetAgentCircuits().Count, Is.EqualTo(0)); // TestHelpers.DisableLogging(); } [Test] public void TestCreateChildScenePresence() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); LocalSimulationConnectorModule lsc = new LocalSimulationConnectorModule(); IConfigSource configSource = new IniConfigSource(); IConfig config = configSource.AddConfig("Modules"); config.Set("SimulationServices", "LocalSimulationConnectorModule"); SceneHelpers sceneHelpers = new SceneHelpers(); TestScene scene = sceneHelpers.SetupScene(); SceneHelpers.SetupSceneModules(scene, configSource, lsc); UUID agentId = TestHelpers.ParseTail(0x01); AgentCircuitData acd = SceneHelpers.GenerateAgentData(agentId); acd.child = true; GridRegion region = scene.GridService.GetRegionByName(UUID.Zero, scene.RegionInfo.RegionName); string reason; // *** This is the first stage, when a neighbouring region is told that a viewer is about to try and // establish a child scene presence. We pass in the circuit code that the client has to connect with *** // XXX: ViaLogin may not be correct here. EntityTransferContext ctx = new EntityTransferContext(); scene.SimulationService.CreateAgent(null, region, acd, (uint)TeleportFlags.ViaLogin, ctx, out reason); Assert.That(scene.AuthenticateHandler.GetAgentCircuitData(agentId), Is.Not.Null); Assert.That(scene.AuthenticateHandler.GetAgentCircuits().Count, Is.EqualTo(1)); // There's no scene presence yet since only an agent circuit has been established. Assert.That(scene.GetScenePresence(agentId), Is.Null); // *** This is the second stage, where the client established a child agent/scene presence using the // circuit code given to the scene in stage 1 *** TestClient client = new TestClient(acd, scene); scene.AddNewAgent(client, PresenceType.User); Assert.That(scene.AuthenticateHandler.GetAgentCircuitData(agentId), Is.Not.Null); Assert.That(scene.AuthenticateHandler.GetAgentCircuits().Count, Is.EqualTo(1)); ScenePresence sp = scene.GetScenePresence(agentId); Assert.That(sp, Is.Not.Null); Assert.That(sp.UUID, Is.EqualTo(agentId)); Assert.That(sp.IsChildAgent, Is.True); } /// <summary> /// Test that if a root agent logs into a region, a child agent is also established in the neighbouring region /// </summary> /// <remarks> /// Please note that unlike the other tests here, this doesn't rely on anything set up in the instance fields. /// INCOMPLETE /// </remarks> [Test] public void TestChildAgentEstablishedInNeighbour() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); // UUID agent1Id = UUID.Parse("00000000-0000-0000-0000-000000000001"); TestScene myScene1 = new SceneHelpers().SetupScene("Neighbour y", UUID.Random(), 1000, 1000); TestScene myScene2 = new SceneHelpers().SetupScene("Neighbour y + 1", UUID.Random(), 1001, 1000); IConfigSource configSource = new IniConfigSource(); IConfig config = configSource.AddConfig("Startup"); config.Set("serverside_object_permissions", true); config.Set("EventQueue", true); EntityTransferModule etm = new EntityTransferModule(); EventQueueGetModule eqgm1 = new EventQueueGetModule(); SceneHelpers.SetupSceneModules(myScene1, configSource, etm, eqgm1); EventQueueGetModule eqgm2 = new EventQueueGetModule(); SceneHelpers.SetupSceneModules(myScene2, configSource, etm, eqgm2); // SceneHelpers.AddScenePresence(myScene1, agent1Id); // ScenePresence childPresence = myScene2.GetScenePresence(agent1); // // // TODO: Need to do a fair amount of work to allow synchronous establishment of child agents // Assert.That(childPresence, Is.Not.Null); // Assert.That(childPresence.IsChildAgent, Is.True); } } }
using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; namespace Elasticsearch.Net.Integration.Yaml.IndicesGetMapping1 { public partial class IndicesGetMapping1YamlTests { public class IndicesGetMapping110BasicYamlBase : YamlTestsBase { public IndicesGetMapping110BasicYamlBase() : base() { //do indices.create _body = new { mappings= new { type_1= new {}, type_2= new {} } }; this.Do(()=> _client.IndicesCreate("test_1", _body)); //do indices.create _body = new { mappings= new { type_2= new {}, type_3= new {} } }; this.Do(()=> _client.IndicesCreate("test_2", _body)); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetMapping2Tests : IndicesGetMapping110BasicYamlBase { [Test] public void GetMapping2Test() { //do indices.get_mapping this.Do(()=> _client.IndicesGetMappingForAll()); //match _response.test_1.mappings.type_1.properties: this.IsMatch(_response.test_1.mappings.type_1.properties, new {}); //match _response.test_1.mappings.type_2.properties: this.IsMatch(_response.test_1.mappings.type_2.properties, new {}); //match _response.test_2.mappings.type_2.properties: this.IsMatch(_response.test_2.mappings.type_2.properties, new {}); //match _response.test_2.mappings.type_3.properties: this.IsMatch(_response.test_2.mappings.type_3.properties, new {}); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetIndexMapping3Tests : IndicesGetMapping110BasicYamlBase { [Test] public void GetIndexMapping3Test() { //do indices.get_mapping this.Do(()=> _client.IndicesGetMapping("test_1")); //match _response.test_1.mappings.type_1.properties: this.IsMatch(_response.test_1.mappings.type_1.properties, new {}); //match _response.test_1.mappings.type_2.properties: this.IsMatch(_response.test_1.mappings.type_2.properties, new {}); //is_false _response.test_2; this.IsFalse(_response.test_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetIndexMappingAll4Tests : IndicesGetMapping110BasicYamlBase { [Test] public void GetIndexMappingAll4Test() { //do indices.get_mapping this.Do(()=> _client.IndicesGetMapping("test_1", "_all")); //match _response.test_1.mappings.type_1.properties: this.IsMatch(_response.test_1.mappings.type_1.properties, new {}); //match _response.test_1.mappings.type_2.properties: this.IsMatch(_response.test_1.mappings.type_2.properties, new {}); //is_false _response.test_2; this.IsFalse(_response.test_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetIndexMapping5Tests : IndicesGetMapping110BasicYamlBase { [Test] public void GetIndexMapping5Test() { //do indices.get_mapping this.Do(()=> _client.IndicesGetMapping("test_1", "*")); //match _response.test_1.mappings.type_1.properties: this.IsMatch(_response.test_1.mappings.type_1.properties, new {}); //match _response.test_1.mappings.type_2.properties: this.IsMatch(_response.test_1.mappings.type_2.properties, new {}); //is_false _response.test_2; this.IsFalse(_response.test_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetIndexMappingType6Tests : IndicesGetMapping110BasicYamlBase { [Test] public void GetIndexMappingType6Test() { //do indices.get_mapping this.Do(()=> _client.IndicesGetMapping("test_1", "type_1")); //match _response.test_1.mappings.type_1.properties: this.IsMatch(_response.test_1.mappings.type_1.properties, new {}); //is_false _response.test_1.mappings.type_2; this.IsFalse(_response.test_1.mappings.type_2); //is_false _response.test_2; this.IsFalse(_response.test_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetIndexMappingTypeType7Tests : IndicesGetMapping110BasicYamlBase { [Test] public void GetIndexMappingTypeType7Test() { //do indices.get_mapping this.Do(()=> _client.IndicesGetMapping("test_1", "type_1,type_2")); //match _response.test_1.mappings.type_1.properties: this.IsMatch(_response.test_1.mappings.type_1.properties, new {}); //match _response.test_1.mappings.type_2.properties: this.IsMatch(_response.test_1.mappings.type_2.properties, new {}); //is_false _response.test_2; this.IsFalse(_response.test_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetIndexMappingType8Tests : IndicesGetMapping110BasicYamlBase { [Test] public void GetIndexMappingType8Test() { //do indices.get_mapping this.Do(()=> _client.IndicesGetMapping("test_1", "*2")); //match _response.test_1.mappings.type_2.properties: this.IsMatch(_response.test_1.mappings.type_2.properties, new {}); //is_false _response.test_1.mappings.type_1; this.IsFalse(_response.test_1.mappings.type_1); //is_false _response.test_2; this.IsFalse(_response.test_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetMappingType9Tests : IndicesGetMapping110BasicYamlBase { [Test] public void GetMappingType9Test() { //do indices.get_mapping this.Do(()=> _client.IndicesGetMappingForAll("type_2")); //match _response.test_1.mappings.type_2.properties: this.IsMatch(_response.test_1.mappings.type_2.properties, new {}); //match _response.test_2.mappings.type_2.properties: this.IsMatch(_response.test_2.mappings.type_2.properties, new {}); //is_false _response.test_1.mappings.type_1; this.IsFalse(_response.test_1.mappings.type_1); //is_false _response.test_2.mappings.type_3; this.IsFalse(_response.test_2.mappings.type_3); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetAllMappingType10Tests : IndicesGetMapping110BasicYamlBase { [Test] public void GetAllMappingType10Test() { //do indices.get_mapping this.Do(()=> _client.IndicesGetMapping("_all", "type_2")); //match _response.test_1.mappings.type_2.properties: this.IsMatch(_response.test_1.mappings.type_2.properties, new {}); //match _response.test_2.mappings.type_2.properties: this.IsMatch(_response.test_2.mappings.type_2.properties, new {}); //is_false _response.test_1.mappings.type_1; this.IsFalse(_response.test_1.mappings.type_1); //is_false _response.test_2.mappings.type_3; this.IsFalse(_response.test_2.mappings.type_3); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetMappingType11Tests : IndicesGetMapping110BasicYamlBase { [Test] public void GetMappingType11Test() { //do indices.get_mapping this.Do(()=> _client.IndicesGetMapping("*", "type_2")); //match _response.test_1.mappings.type_2.properties: this.IsMatch(_response.test_1.mappings.type_2.properties, new {}); //match _response.test_2.mappings.type_2.properties: this.IsMatch(_response.test_2.mappings.type_2.properties, new {}); //is_false _response.test_1.mappings.type_1; this.IsFalse(_response.test_1.mappings.type_1); //is_false _response.test_2.mappings.type_3; this.IsFalse(_response.test_2.mappings.type_3); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetIndexIndexMappingType12Tests : IndicesGetMapping110BasicYamlBase { [Test] public void GetIndexIndexMappingType12Test() { //do indices.get_mapping this.Do(()=> _client.IndicesGetMapping("test_1,test_2", "type_2")); //match _response.test_1.mappings.type_2.properties: this.IsMatch(_response.test_1.mappings.type_2.properties, new {}); //match _response.test_2.mappings.type_2.properties: this.IsMatch(_response.test_2.mappings.type_2.properties, new {}); //is_false _response.test_2.mappings.type_3; this.IsFalse(_response.test_2.mappings.type_3); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetIndexMappingType13Tests : IndicesGetMapping110BasicYamlBase { [Test] public void GetIndexMappingType13Test() { //do indices.get_mapping this.Do(()=> _client.IndicesGetMapping("*2", "type_2")); //match _response.test_2.mappings.type_2.properties: this.IsMatch(_response.test_2.mappings.type_2.properties, new {}); //is_false _response.test_1; this.IsFalse(_response.test_1); //is_false _response.test_2.mappings.type_3; this.IsFalse(_response.test_2.mappings.type_3); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using JCG = J2N.Collections.Generic; namespace Lucene.Net.Search.Spans { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using IBits = Lucene.Net.Util.IBits; using IndexReader = Lucene.Net.Index.IndexReader; using Term = Lucene.Net.Index.Term; using TermContext = Lucene.Net.Index.TermContext; using ToStringUtils = Lucene.Net.Util.ToStringUtils; /// <summary> /// Matches spans which are near one another. One can specify <i>slop</i>, the /// maximum number of intervening unmatched positions, as well as whether /// matches are required to be in-order. /// </summary> public class SpanNearQuery : SpanQuery #if FEATURE_CLONEABLE , System.ICloneable #endif { protected readonly IList<SpanQuery> m_clauses; protected int m_slop; protected bool m_inOrder; protected string m_field; private bool collectPayloads; /// <summary> /// Construct a <see cref="SpanNearQuery"/>. Matches spans matching a span from each /// clause, with up to <paramref name="slop"/> total unmatched positions between /// them. * When <paramref name="inOrder"/> is <c>true</c>, the spans from each clause /// must be * ordered as in <paramref name="clauses"/>. </summary> /// <param name="clauses"> The clauses to find near each other </param> /// <param name="slop"> The slop value </param> /// <param name="inOrder"> <c>true</c> if order is important</param> public SpanNearQuery(SpanQuery[] clauses, int slop, bool inOrder) : this(clauses, slop, inOrder, true) { } public SpanNearQuery(SpanQuery[] clauses, int slop, bool inOrder, bool collectPayloads) { // copy clauses array into an ArrayList this.m_clauses = new List<SpanQuery>(clauses.Length); for (int i = 0; i < clauses.Length; i++) { SpanQuery clause = clauses[i]; if (m_field == null) // check field { m_field = clause.Field; } else if (clause.Field != null && !clause.Field.Equals(m_field, StringComparison.Ordinal)) { throw new ArgumentException("Clauses must have same field."); } this.m_clauses.Add(clause); } this.collectPayloads = collectPayloads; this.m_slop = slop; this.m_inOrder = inOrder; } /// <summary> /// Return the clauses whose spans are matched. </summary> public virtual SpanQuery[] GetClauses() { return m_clauses.ToArray(); } /// <summary> /// Return the maximum number of intervening unmatched positions permitted. </summary> public virtual int Slop => m_slop; /// <summary> /// Return <c>true</c> if matches are required to be in-order. </summary> public virtual bool IsInOrder => m_inOrder; public override string Field => m_field; public override void ExtractTerms(ISet<Term> terms) { foreach (SpanQuery clause in m_clauses) { clause.ExtractTerms(terms); } } public override string ToString(string field) { StringBuilder buffer = new StringBuilder(); buffer.Append("SpanNear(["); bool isFirst = true; foreach (SpanQuery clause in m_clauses) { if (!isFirst) { buffer.Append(", "); } buffer.Append(clause.ToString(field)); isFirst = false; } buffer.Append("], "); buffer.Append(m_slop); buffer.Append(", "); buffer.Append(m_inOrder); buffer.Append(")"); buffer.Append(ToStringUtils.Boost(Boost)); return buffer.ToString(); } public override Spans GetSpans(AtomicReaderContext context, IBits acceptDocs, IDictionary<Term, TermContext> termContexts) { if (m_clauses.Count == 0) // optimize 0-clause case { return (new SpanOrQuery(GetClauses())).GetSpans(context, acceptDocs, termContexts); } if (m_clauses.Count == 1) // optimize 1-clause case { return m_clauses[0].GetSpans(context, acceptDocs, termContexts); } return m_inOrder ? (Spans)new NearSpansOrdered(this, context, acceptDocs, termContexts, collectPayloads) : (Spans)new NearSpansUnordered(this, context, acceptDocs, termContexts); } public override Query Rewrite(IndexReader reader) { SpanNearQuery clone = null; for (int i = 0; i < m_clauses.Count; i++) { SpanQuery c = m_clauses[i]; SpanQuery query = (SpanQuery)c.Rewrite(reader); if (query != c) // clause rewrote: must clone { if (clone == null) { clone = (SpanNearQuery)this.Clone(); } clone.m_clauses[i] = query; } } if (clone != null) { return clone; // some clauses rewrote } else { return this; // no clauses rewrote } } public override object Clone() { int sz = m_clauses.Count; SpanQuery[] newClauses = new SpanQuery[sz]; for (int i = 0; i < sz; i++) { newClauses[i] = (SpanQuery)m_clauses[i].Clone(); } SpanNearQuery spanNearQuery = new SpanNearQuery(newClauses, m_slop, m_inOrder); spanNearQuery.Boost = Boost; return spanNearQuery; } /// <summary> /// Returns true iff <code>o</code> is equal to this. </summary> public override bool Equals(object o) { if (this == o) { return true; } if (!(o is SpanNearQuery spanNearQuery)) { return false; } if (m_inOrder != spanNearQuery.m_inOrder) { return false; } if (m_slop != spanNearQuery.m_slop) { return false; } if (!JCG.ListEqualityComparer<SpanQuery>.Default.Equals(m_clauses, spanNearQuery.m_clauses)) { return false; } return Boost == spanNearQuery.Boost; } public override int GetHashCode() { int result; result = JCG.ListEqualityComparer<SpanQuery>.Default.GetHashCode(m_clauses); // Mix bits before folding in things like boost, since it could cancel the // last element of clauses. this particular mix also serves to // differentiate SpanNearQuery hashcodes from others. result ^= (result << 14) | ((int)((uint)result >> 19)); // reversible result += J2N.BitConversion.SingleToRawInt32Bits(Boost); result += m_slop; result ^= (m_inOrder ? unchecked((int)0x99AFD3BD) : 0); return result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class Http { [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyCreate")] public static extern SafeCurlHandle EasyCreate(); [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyDestroy")] private static extern void EasyDestroy(IntPtr handle); [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasySetOptionString", CharSet = CharSet.Ansi)] public static extern CURLcode EasySetOptionString(SafeCurlHandle curl, CURLoption option, string value); [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasySetOptionLong")] public static extern CURLcode EasySetOptionLong(SafeCurlHandle curl, CURLoption option, long value); [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasySetOptionPointer")] public static extern CURLcode EasySetOptionPointer(SafeCurlHandle curl, CURLoption option, IntPtr value); [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasySetOptionPointer")] public static extern CURLcode EasySetOptionPointer(SafeCurlHandle curl, CURLoption option, SafeHandle value); [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyGetErrorString")] public static extern IntPtr EasyGetErrorString(int code); [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyGetInfoPointer")] public static extern CURLcode EasyGetInfoPointer(IntPtr handle, CURLINFO info, out IntPtr value); [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyGetInfoLong")] public static extern CURLcode EasyGetInfoLong(SafeCurlHandle handle, CURLINFO info, out long value); [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyPerform")] public static extern CURLcode EasyPerform(SafeCurlHandle curl); [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_EasyUnpause")] public static extern CURLcode EasyUnpause(SafeCurlHandle easy); public delegate CurlSeekResult SeekCallback(IntPtr userPointer, long offset, int origin); public delegate ulong ReadWriteCallback(IntPtr buffer, ulong bufferSize, ulong nitems, IntPtr userPointer); public delegate CURLcode SslCtxCallback(IntPtr curl, IntPtr sslCtx, IntPtr userPointer); public delegate void DebugCallback(IntPtr curl, CurlInfoType type, IntPtr data, ulong size, IntPtr userPointer); [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_RegisterSeekCallback")] public static extern void RegisterSeekCallback( SafeCurlHandle curl, SeekCallback callback, IntPtr userPointer, ref SafeCallbackHandle callbackHandle); [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_RegisterReadWriteCallback")] public static extern void RegisterReadWriteCallback( SafeCurlHandle curl, ReadWriteFunction functionType, ReadWriteCallback callback, IntPtr userPointer, ref SafeCallbackHandle callbackHandle); [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_RegisterSslCtxCallback")] public static extern CURLcode RegisterSslCtxCallback( SafeCurlHandle curl, SslCtxCallback callback, IntPtr userPointer, ref SafeCallbackHandle callbackHandle); [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_RegisterDebugCallback")] public static extern CURLcode RegisterDebugCallback( SafeCurlHandle curl, DebugCallback callback, IntPtr userPointer, ref SafeCallbackHandle callbackHandle); [DllImport(Libraries.HttpNative, EntryPoint = "HttpNative_FreeCallbackHandle")] private static extern void FreeCallbackHandle(IntPtr handle); // Curl options are of the format <type base> + <n> private const int CurlOptionLongBase = 0; private const int CurlOptionObjectPointBase = 10000; // Enum for constants defined for the enum CURLoption in curl.h internal enum CURLoption { CURLOPT_INFILESIZE = CurlOptionLongBase + 14, CURLOPT_SSLVERSION = CurlOptionLongBase + 32, CURLOPT_VERBOSE = CurlOptionLongBase + 41, CURLOPT_NOBODY = CurlOptionLongBase + 44, CURLOPT_UPLOAD = CurlOptionLongBase + 46, CURLOPT_POST = CurlOptionLongBase + 47, CURLOPT_FOLLOWLOCATION = CurlOptionLongBase + 52, CURLOPT_PROXYPORT = CurlOptionLongBase + 59, CURLOPT_POSTFIELDSIZE = CurlOptionLongBase + 60, CURLOPT_MAXREDIRS = CurlOptionLongBase + 68, CURLOPT_HTTP_VERSION = CurlOptionLongBase + 84, CURLOPT_NOSIGNAL = CurlOptionLongBase + 99, CURLOPT_PROXYTYPE = CurlOptionLongBase + 101, CURLOPT_HTTPAUTH = CurlOptionLongBase + 107, CURLOPT_PROTOCOLS = CurlOptionLongBase + 181, CURLOPT_REDIR_PROTOCOLS = CurlOptionLongBase + 182, CURLOPT_URL = CurlOptionObjectPointBase + 2, CURLOPT_PROXY = CurlOptionObjectPointBase + 4, CURLOPT_PROXYUSERPWD = CurlOptionObjectPointBase + 6, CURLOPT_COOKIE = CurlOptionObjectPointBase + 22, CURLOPT_HTTPHEADER = CurlOptionObjectPointBase + 23, CURLOPT_CUSTOMREQUEST = CurlOptionObjectPointBase + 36, CURLOPT_ACCEPT_ENCODING = CurlOptionObjectPointBase + 102, CURLOPT_PRIVATE = CurlOptionObjectPointBase + 103, CURLOPT_COPYPOSTFIELDS = CurlOptionObjectPointBase + 165, CURLOPT_USERNAME = CurlOptionObjectPointBase + 173, CURLOPT_PASSWORD = CurlOptionObjectPointBase + 174, } internal enum ReadWriteFunction { Write = 0, Read = 1, Header = 2, } // Curl info are of the format <type base> + <n> private const int CurlInfoStringBase = 0x100000; private const int CurlInfoLongBase = 0x200000; // Enum for constants defined for CURL_HTTP_VERSION internal enum CurlHttpVersion { CURL_HTTP_VERSION_NONE = 0, CURL_HTTP_VERSION_1_0 = 1, CURL_HTTP_VERSION_1_1 = 2, CURL_HTTP_VERSION_2_0 = 3, }; // Enum for constants defined for CURL_SSLVERSION internal enum CurlSslVersion { CURL_SSLVERSION_TLSv1 = 1, /* TLS 1.x */ }; // Enum for constants defined for the enum CURLINFO in curl.h internal enum CURLINFO { CURLINFO_PRIVATE = CurlInfoStringBase + 21, CURLINFO_HTTPAUTH_AVAIL = CurlInfoLongBase + 23, } // AUTH related constants [Flags] internal enum CURLAUTH { None = 0, Basic = 1 << 0, Digest = 1 << 1, Negotiate = 1 << 2, NTLM = 1 << 3, } // Enum for constants defined for the enum curl_proxytype in curl.h internal enum curl_proxytype { CURLPROXY_HTTP = 0, } [Flags] internal enum CurlProtocols { CURLPROTO_HTTP = (1 << 0), CURLPROTO_HTTPS = (1 << 1), } // Enum for constants defined for the results of CURL_SEEKFUNCTION internal enum CurlSeekResult : int { CURL_SEEKFUNC_OK = 0, CURL_SEEKFUNC_FAIL = 1, CURL_SEEKFUNC_CANTSEEK = 2, } internal enum CurlInfoType : int { CURLINFO_TEXT = 0, CURLINFO_HEADER_IN = 1, CURLINFO_HEADER_OUT = 2, CURLINFO_DATA_IN = 3, CURLINFO_DATA_OUT = 4, CURLINFO_SSL_DATA_IN = 5, CURLINFO_SSL_DATA_OUT = 6, }; // constants defined for the results of a CURL_READ or CURL_WRITE function internal const ulong CURL_READFUNC_ABORT = 0x10000000; internal const ulong CURL_READFUNC_PAUSE = 0x10000001; internal const ulong CURL_WRITEFUNC_PAUSE = 0x10000001; internal const ulong CURL_MAX_HTTP_HEADER = 100 * 1024; internal sealed class SafeCurlHandle : SafeHandle { public SafeCurlHandle() : base(IntPtr.Zero, true) { } public override bool IsInvalid { get { return handle == IntPtr.Zero; } } protected override bool ReleaseHandle() { EasyDestroy(handle); SetHandle(IntPtr.Zero); return true; } } internal sealed class SafeCallbackHandle : SafeHandle { public SafeCallbackHandle() : base(IntPtr.Zero, true) { } public override bool IsInvalid { get { return handle == IntPtr.Zero; } } protected override bool ReleaseHandle() { FreeCallbackHandle(handle); SetHandle(IntPtr.Zero); return true; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using FluentNHibernate.Testing.Values; using FluentNHibernate.Utils; using System.Collections; using FluentNHibernate.Utils.Reflection; namespace FluentNHibernate.Testing { public static class PersistenceSpecificationExtensions { public static PersistenceSpecification<T> CheckProperty<T>(this PersistenceSpecification<T> spec, Expression<Func<T, object>> expression, object propertyValue) { return spec.CheckProperty(expression, propertyValue, (IEqualityComparer)null); } public static PersistenceSpecification<T> CheckProperty<T>(this PersistenceSpecification<T> spec, Expression<Func<T, object>> expression, object propertyValue, IEqualityComparer propertyComparer) { Accessor property = ReflectionHelper.GetAccessor(expression); return spec.RegisterCheckedProperty(new Property<T, object>(property, propertyValue), propertyComparer); } public static PersistenceSpecification<T> CheckProperty<T, TListElement>(this PersistenceSpecification<T> spec, Expression<Func<T, Array>> expression, IEnumerable<TListElement> propertyValue) { return spec.CheckProperty(expression, propertyValue, null); } public static PersistenceSpecification<T> CheckProperty<T, TListElement>(this PersistenceSpecification<T> spec, Expression<Func<T, Array>> expression, IEnumerable<TListElement> propertyValue, IEqualityComparer elementComparer) { Accessor property = ReflectionHelper.GetAccessor(expression); return spec.RegisterCheckedProperty(new List<T, TListElement>(property, propertyValue), elementComparer); } public static PersistenceSpecification<T> CheckProperty<T, TProperty>(this PersistenceSpecification<T> spec, Expression<Func<T, TProperty>> expression, TProperty propertyValue, Action<T, TProperty> propertySetter) { return spec.CheckProperty(expression, propertyValue, null, propertySetter); } public static PersistenceSpecification<T> CheckProperty<T, TProperty>(this PersistenceSpecification<T> spec, Expression<Func<T, TProperty>> expression, TProperty propertyValue, IEqualityComparer propertyComparer, Action<T, TProperty> propertySetter) { Accessor propertyInfoFromExpression = ReflectionHelper.GetAccessor(expression); var property = new Property<T, TProperty>(propertyInfoFromExpression, propertyValue); property.ValueSetter = (target, propertyInfo, value) => propertySetter(target, value); return spec.RegisterCheckedProperty(property, propertyComparer); } public static PersistenceSpecification<T> CheckReference<T>(this PersistenceSpecification<T> spec, Expression<Func<T, object>> expression, object propertyValue) { return spec.CheckReference(expression, propertyValue, (IEqualityComparer)null); } public static PersistenceSpecification<T> CheckReference<T>(this PersistenceSpecification<T> spec, Expression<Func<T, object>> expression, object propertyValue, IEqualityComparer propertyComparer) { Accessor property = ReflectionHelper.GetAccessor(expression); return spec.RegisterCheckedProperty(new ReferenceProperty<T, object>(property, propertyValue), propertyComparer); } public static PersistenceSpecification<T> CheckReference<T, TReference>(this PersistenceSpecification<T> spec, Expression<Func<T, object>> expression, TReference propertyValue, params Func<TReference, object>[] propertiesToCompare) { // Because of the params keyword, the compiler will select this overload // instead of the one above, even when no funcs are supplied in the method call. if (propertiesToCompare == null || propertiesToCompare.Length == 0) return spec.CheckReference(expression, propertyValue, (IEqualityComparer)null); return spec.CheckReference(expression, propertyValue, new FuncEqualityComparer<TReference>(propertiesToCompare)); } public static PersistenceSpecification<T> CheckReference<T, TProperty>(this PersistenceSpecification<T> spec, Expression<Func<T, TProperty>> expression, TProperty propertyValue, Action<T, TProperty> propertySetter) { return spec.CheckReference(expression, propertyValue, null, propertySetter); } public static PersistenceSpecification<T> CheckReference<T, TProperty>(this PersistenceSpecification<T> spec, Expression<Func<T, TProperty>> expression, TProperty propertyValue, IEqualityComparer propertyComparer, Action<T, TProperty> propertySetter) { Accessor propertyInfoFromExpression = ReflectionHelper.GetAccessor(expression); var property = new ReferenceProperty<T, TProperty>(propertyInfoFromExpression, propertyValue); property.ValueSetter = (target, propertyInfo, value) => propertySetter(target, value); return spec.RegisterCheckedProperty(property, propertyComparer); } public static PersistenceSpecification<T> CheckList<T, TListElement>(this PersistenceSpecification<T> spec, Expression<Func<T, IEnumerable<TListElement>>> expression, IEnumerable<TListElement> propertyValue) { return spec.CheckList(expression, propertyValue, (IEqualityComparer)null); } public static PersistenceSpecification<T> CheckList<T, TListElement>(this PersistenceSpecification<T> spec, Expression<Func<T, IEnumerable<TListElement>>> expression, IEnumerable<TListElement> propertyValue, IEqualityComparer elementComparer) { Accessor property = ReflectionHelper.GetAccessor(expression); return spec.RegisterCheckedProperty(new ReferenceList<T, TListElement>(property, propertyValue), elementComparer); } public static PersistenceSpecification<T> CheckList<T, TListElement>(this PersistenceSpecification<T> spec, Expression<Func<T, IEnumerable<TListElement>>> expression, IEnumerable<TListElement> propertyValue, params Func<TListElement, object>[] propertiesToCompare) { // Because of the params keyword, the compiler can select this overload // instead of the one above, even when no funcs are supplied in the method call. if (propertiesToCompare == null || propertiesToCompare.Length == 0) return spec.CheckList(expression, propertyValue, (IEqualityComparer)null); return spec.CheckList(expression, propertyValue, new FuncEqualityComparer<TListElement>(propertiesToCompare)); } public static PersistenceSpecification<T> CheckList<T, TListElement>(this PersistenceSpecification<T> spec, Expression<Func<T, IEnumerable<TListElement>>> expression, IEnumerable<TListElement> propertyValue, Action<T, TListElement> listItemSetter) { return spec.CheckList(expression, propertyValue, null, listItemSetter); } public static PersistenceSpecification<T> CheckList<T, TListElement>(this PersistenceSpecification<T> spec, Expression<Func<T, IEnumerable<TListElement>>> expression, IEnumerable<TListElement> propertyValue, IEqualityComparer elementComparer, Action<T, TListElement> listItemSetter) { Accessor property = ReflectionHelper.GetAccessor(expression); var list = new ReferenceList<T, TListElement>(property, propertyValue); list.ValueSetter = (target, propertyInfo, value) => { foreach(var item in value) { listItemSetter(target, item); } }; return spec.RegisterCheckedProperty(list, elementComparer); } public static PersistenceSpecification<T> CheckList<T, TListElement>(this PersistenceSpecification<T> spec, Expression<Func<T, IEnumerable<TListElement>>> expression, IEnumerable<TListElement> propertyValue, Action<T, IEnumerable<TListElement>> listSetter) { return spec.CheckList(expression, propertyValue, null, listSetter); } public static PersistenceSpecification<T> CheckList<T, TListElement>(this PersistenceSpecification<T> spec, Expression<Func<T, IEnumerable<TListElement>>> expression, IEnumerable<TListElement> propertyValue, IEqualityComparer elementComparer, Action<T, IEnumerable<TListElement>> listSetter) { Accessor property = ReflectionHelper.GetAccessor(expression); var list = new ReferenceList<T, TListElement>(property, propertyValue); list.ValueSetter = (target, propertyInfo, value) => listSetter(target, value); return spec.RegisterCheckedProperty(list, elementComparer); } public static PersistenceSpecification<T> CheckComponentList<T, TListElement>(this PersistenceSpecification<T> spec, Expression<Func<T, object>> expression, IEnumerable<TListElement> propertyValue) { return spec.CheckComponentList(expression, propertyValue, null); } /// <summary> /// Checks a list of components for validity. /// </summary> /// <typeparam name="T">Entity type</typeparam> /// <typeparam name="TListElement">Type of list element</typeparam> /// <param name="spec">Persistence specification</param> /// <param name="expression">Property</param> /// <param name="propertyValue">Value to save</param> /// <param name="elementComparer">Equality comparer</param> public static PersistenceSpecification<T> CheckComponentList<T, TListElement>(this PersistenceSpecification<T> spec, Expression<Func<T, object>> expression, IEnumerable<TListElement> propertyValue, IEqualityComparer elementComparer) { Accessor property = ReflectionHelper.GetAccessor(expression); return spec.RegisterCheckedProperty(new List<T, TListElement>(property, propertyValue), elementComparer); } public static PersistenceSpecification<T> CheckComponentList<T, TListElement>(this PersistenceSpecification<T> spec, Expression<Func<T, IEnumerable<TListElement>>> expression, IEnumerable<TListElement> propertyValue, Action<T, TListElement> listItemSetter) { return spec.CheckComponentList(expression, propertyValue, null, listItemSetter); } public static PersistenceSpecification<T> CheckComponentList<T, TListElement>(this PersistenceSpecification<T> spec, Expression<Func<T, IEnumerable<TListElement>>> expression, IEnumerable<TListElement> propertyValue, IEqualityComparer elementComparer, Action<T, TListElement> listItemSetter) { Accessor property = ReflectionHelper.GetAccessor(expression); var list = new List<T, TListElement>(property, propertyValue); list.ValueSetter = (target, propertyInfo, value) => { foreach(var item in value) { listItemSetter(target, item); } }; return spec.RegisterCheckedProperty(list, elementComparer); } public static PersistenceSpecification<T> CheckComponentList<T, TListElement>(this PersistenceSpecification<T> spec, Expression<Func<T, IEnumerable<TListElement>>> expression, IEnumerable<TListElement> propertyValue, Action<T, IEnumerable<TListElement>> listSetter) { return spec.CheckComponentList(expression, propertyValue, null, listSetter); } public static PersistenceSpecification<T> CheckComponentList<T, TListElement>(this PersistenceSpecification<T> spec, Expression<Func<T, IEnumerable<TListElement>>> expression, IEnumerable<TListElement> propertyValue, IEqualityComparer elementComparer, Action<T, IEnumerable<TListElement>> listSetter) { Accessor property = ReflectionHelper.GetAccessor(expression); var list = new List<T, TListElement>(property, propertyValue); list.ValueSetter = (target, propertyInfo, value) => listSetter(target, value); return spec.RegisterCheckedProperty(list, elementComparer); } [Obsolete("CheckEnumerable has been replaced with CheckList")] public static PersistenceSpecification<T> CheckEnumerable<T, TItem>(this PersistenceSpecification<T> spec, Expression<Func<T, IEnumerable<TItem>>> expression, Action<T, TItem> addAction, IEnumerable<TItem> itemsToAdd) { return spec.CheckList(expression, itemsToAdd, addAction); } private class FuncEqualityComparer<T> : EqualityComparer<T> { readonly IEnumerable<Func<T, object>> comparisons; public FuncEqualityComparer(IEnumerable<Func<T, object>> comparisons) { this.comparisons = comparisons; } public override bool Equals(T x, T y) { return comparisons.All(func => object.Equals(func(x), func(y))); } public override int GetHashCode(T obj) { throw new NotSupportedException(); } } } }
/* ==================================================================== */ using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using System.Xml; using System.Text; using System.IO; using Oranikle.Report.Engine; namespace Oranikle.ReportDesigner { /// <summary> /// Filters specification: used for DataRegions (List, Chart, Table, Matrix), DataSets, group instances /// </summary> internal class SubreportCtl : Oranikle.ReportDesigner.Base.BaseControl, IProperty { private DesignXmlDraw _Draw; private XmlNode _Subreport; private DataTable _DataTable; private DataGridTextBoxColumn dgtbName; private DataGridTextBoxColumn dgtbValue; private System.Windows.Forms.DataGridTableStyle dgTableStyle; private System.Windows.Forms.Label label1; private Oranikle.Studio.Controls.StyledButton bFile; private Oranikle.Studio.Controls.CustomTextControl tbReportFile; private Oranikle.Studio.Controls.CustomTextControl tbNoRows; private System.Windows.Forms.Label label2; private Oranikle.Studio.Controls.StyledCheckBox chkMergeTrans; private System.Windows.Forms.DataGrid dgParms; private Oranikle.Studio.Controls.StyledButton bRefreshParms; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; internal SubreportCtl(DesignXmlDraw dxDraw, XmlNode subReport) { _Draw = dxDraw; _Subreport =subReport; // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // Initialize form using the style node values InitValues(); } private void InitValues() { this.tbReportFile.Text = _Draw.GetElementValue(_Subreport, "ReportName", ""); this.tbNoRows.Text = _Draw.GetElementValue(_Subreport, "NoRows", ""); this.chkMergeTrans.Checked = _Draw.GetElementValue(_Subreport, "MergeTransactions", "false").ToLower() == "true"; // Initialize the DataGrid columns dgtbName = new DataGridTextBoxColumn(); dgtbValue = new DataGridTextBoxColumn(); this.dgTableStyle.GridColumnStyles.AddRange(new DataGridColumnStyle[] { this.dgtbName, this.dgtbValue}); // // dgtbFE // dgtbName.HeaderText = "Parameter Name"; dgtbName.MappingName = "ParameterName"; dgtbName.Width = 75; // Get the parent's dataset name // string dataSetName = _Draw.GetDataSetNameValue(_FilterParent); // // string[] fields = _Draw.GetFields(dataSetName, true); // if (fields != null) // dgtbFE.CB.Items.AddRange(fields); // // dgtbValue // this.dgtbValue.HeaderText = "Value"; this.dgtbValue.MappingName = "Value"; this.dgtbValue.Width = 75; // string[] parms = _Draw.GetReportParameters(true); // if (parms != null) // dgtbFV.CB.Items.AddRange(parms); // Initialize the DataTable _DataTable = new DataTable(); _DataTable.Columns.Add(new DataColumn("ParameterName", typeof(string))); _DataTable.Columns.Add(new DataColumn("Value", typeof(string))); string[] rowValues = new string[2]; XmlNode parameters = _Draw.GetNamedChildNode(_Subreport, "Parameters"); if (parameters != null) foreach (XmlNode pNode in parameters.ChildNodes) { if (pNode.NodeType != XmlNodeType.Element || pNode.Name != "Parameter") continue; rowValues[0] = _Draw.GetElementAttribute(pNode, "Name", ""); rowValues[1] = _Draw.GetElementValue(pNode, "Value", ""); _DataTable.Rows.Add(rowValues); } // Don't allow users to add their own rows // DataView dv = new DataView(_DataTable); // bad side effect // dv.AllowNew = false; this.dgParms.DataSource = _DataTable; DataGridTableStyle ts = dgParms.TableStyles[0]; ts.GridColumnStyles[0].Width = 140; ts.GridColumnStyles[0].ReadOnly = true; ts.GridColumnStyles[1].Width = 140; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.dgParms = new System.Windows.Forms.DataGrid(); this.dgTableStyle = new System.Windows.Forms.DataGridTableStyle(); this.label1 = new System.Windows.Forms.Label(); this.tbReportFile = new Oranikle.Studio.Controls.CustomTextControl(); this.bFile = new Oranikle.Studio.Controls.StyledButton(); this.tbNoRows = new Oranikle.Studio.Controls.CustomTextControl(); this.label2 = new System.Windows.Forms.Label(); this.chkMergeTrans = new Oranikle.Studio.Controls.StyledCheckBox(); this.bRefreshParms = new Oranikle.Studio.Controls.StyledButton(); ((System.ComponentModel.ISupportInitialize)(this.dgParms)).BeginInit(); this.SuspendLayout(); // // dgParms // this.dgParms.BackgroundColor = System.Drawing.Color.White; this.dgParms.CaptionVisible = false; this.dgParms.DataMember = ""; this.dgParms.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.dgParms.Location = new System.Drawing.Point(8, 112); this.dgParms.Name = "dgParms"; this.dgParms.Size = new System.Drawing.Size(384, 168); this.dgParms.TabIndex = 2; this.dgParms.TableStyles.AddRange(new System.Windows.Forms.DataGridTableStyle[] { this.dgTableStyle}); // // dgTableStyle // this.dgTableStyle.AllowSorting = false; this.dgTableStyle.DataGrid = this.dgParms; this.dgTableStyle.HeaderForeColor = System.Drawing.SystemColors.ControlText; // // label1 // this.label1.Location = new System.Drawing.Point(8, 7); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(88, 23); this.label1.TabIndex = 3; this.label1.Text = "Subreport name"; // // tbReportFile // this.tbReportFile.AddX = 0; this.tbReportFile.AddY = 0; this.tbReportFile.AllowSpace = false; this.tbReportFile.BorderColor = System.Drawing.Color.LightGray; this.tbReportFile.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.tbReportFile.ChangeVisibility = false; this.tbReportFile.ChildControl = null; this.tbReportFile.ConvertEnterToTab = true; this.tbReportFile.ConvertEnterToTabForDialogs = false; this.tbReportFile.Decimals = 0; this.tbReportFile.DisplayList = new object[0]; this.tbReportFile.HitText = Oranikle.Studio.Controls.HitText.String; this.tbReportFile.Location = new System.Drawing.Point(104, 8); this.tbReportFile.Name = "tbReportFile"; this.tbReportFile.OnDropDownCloseFocus = true; this.tbReportFile.SelectType = 0; this.tbReportFile.Size = new System.Drawing.Size(312, 20); this.tbReportFile.TabIndex = 4; this.tbReportFile.UseValueForChildsVisibilty = false; this.tbReportFile.Value = true; // // bFile // this.bFile.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245))))); this.bFile.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225))))); this.bFile.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.bFile.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200))))); this.bFile.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.bFile.Font = new System.Drawing.Font("Arial", 9F); this.bFile.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90))))); this.bFile.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bFile.Location = new System.Drawing.Point(424, 8); this.bFile.Name = "bFile"; this.bFile.OverriddenSize = null; this.bFile.Size = new System.Drawing.Size(24, 21); this.bFile.TabIndex = 5; this.bFile.Text = "..."; this.bFile.UseVisualStyleBackColor = true; this.bFile.Click += new System.EventHandler(this.bFile_Click); // // tbNoRows // this.tbNoRows.AddX = 0; this.tbNoRows.AddY = 0; this.tbNoRows.AllowSpace = false; this.tbNoRows.BorderColor = System.Drawing.Color.LightGray; this.tbNoRows.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.tbNoRows.ChangeVisibility = false; this.tbNoRows.ChildControl = null; this.tbNoRows.ConvertEnterToTab = true; this.tbNoRows.ConvertEnterToTabForDialogs = false; this.tbNoRows.Decimals = 0; this.tbNoRows.DisplayList = new object[0]; this.tbNoRows.HitText = Oranikle.Studio.Controls.HitText.String; this.tbNoRows.Location = new System.Drawing.Point(104, 40); this.tbNoRows.Name = "tbNoRows"; this.tbNoRows.OnDropDownCloseFocus = true; this.tbNoRows.SelectType = 0; this.tbNoRows.Size = new System.Drawing.Size(312, 20); this.tbNoRows.TabIndex = 7; this.tbNoRows.UseValueForChildsVisibilty = false; this.tbNoRows.Value = true; // // label2 // this.label2.Location = new System.Drawing.Point(8, 39); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(96, 23); this.label2.TabIndex = 8; this.label2.Text = "No rows message"; // // chkMergeTrans // this.chkMergeTrans.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.chkMergeTrans.ForeColor = System.Drawing.Color.Black; this.chkMergeTrans.Location = new System.Drawing.Point(8, 72); this.chkMergeTrans.Name = "chkMergeTrans"; this.chkMergeTrans.Size = new System.Drawing.Size(376, 24); this.chkMergeTrans.TabIndex = 9; this.chkMergeTrans.Text = "Use same Data Source connections as parent report when possible"; // // bRefreshParms // this.bRefreshParms.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245))))); this.bRefreshParms.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225))))); this.bRefreshParms.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.bRefreshParms.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200))))); this.bRefreshParms.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.bRefreshParms.Font = new System.Drawing.Font("Arial", 9F); this.bRefreshParms.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90))))); this.bRefreshParms.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bRefreshParms.Location = new System.Drawing.Point(399, 116); this.bRefreshParms.Name = "bRefreshParms"; this.bRefreshParms.OverriddenSize = null; this.bRefreshParms.Size = new System.Drawing.Size(56, 21); this.bRefreshParms.TabIndex = 10; this.bRefreshParms.Text = "Refresh"; this.bRefreshParms.UseVisualStyleBackColor = true; this.bRefreshParms.Click += new System.EventHandler(this.bRefreshParms_Click); // // SubreportCtl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.Controls.Add(this.bRefreshParms); this.Controls.Add(this.chkMergeTrans); this.Controls.Add(this.tbNoRows); this.Controls.Add(this.label2); this.Controls.Add(this.bFile); this.Controls.Add(this.tbReportFile); this.Controls.Add(this.label1); this.Controls.Add(this.dgParms); this.Name = "SubreportCtl"; this.Size = new System.Drawing.Size(464, 304); ((System.ComponentModel.ISupportInitialize)(this.dgParms)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion public bool IsValid() { if (this.tbReportFile.Text.Length > 0) return true; MessageBox.Show("Subreport file must be specified.", "Subreport"); return false; } public void Apply() { _Draw.SetElement(_Subreport, "ReportName", this.tbReportFile.Text); if (this.tbNoRows.Text.Trim().Length == 0) _Draw.RemoveElement(_Subreport, "NoRows"); else _Draw.SetElement(_Subreport, "NoRows", tbNoRows.Text); _Draw.SetElement(_Subreport, "MergeTransactions", this.chkMergeTrans.Checked? "true": "false"); // Remove the old filters XmlNode parms = _Draw.GetCreateNamedChildNode(_Subreport, "Parameters"); while (parms.FirstChild != null) { parms.RemoveChild(parms.FirstChild); } // Loop thru and add all the filters foreach (DataRow dr in _DataTable.Rows) { if (dr[0] == DBNull.Value || dr[1] == DBNull.Value) continue; string name = (string) dr[0]; string val = (string) dr[1]; if (name.Length <= 0 || val.Length <= 0) continue; XmlNode pNode = _Draw.CreateElement(parms, "Parameter", null); _Draw.SetElementAttribute(pNode, "Name", name); _Draw.SetElement(pNode, "Value", val); } if (!parms.HasChildNodes) _Subreport.RemoveChild(parms); } private void bFile_Click(object sender, System.EventArgs e) { using (OpenFileDialog ofd = new OpenFileDialog()) { ofd.Filter = "Report files (*.rdlc)|*.rdlc" + "|All files (*.*)|*.*"; ofd.FilterIndex = 1; ofd.FileName = "*.rdlc"; ofd.Title = "Specify Report File Name"; ofd.DefaultExt = "rdl"; ofd.AddExtension = true; if (ofd.ShowDialog() == DialogResult.OK) { string file = Path.GetFileNameWithoutExtension(ofd.FileName); tbReportFile.Text = file; } } } private void bRefreshParms_Click(object sender, System.EventArgs e) { // Obtain the source string filename=""; if (tbReportFile.Text.Length > 0) filename = tbReportFile.Text + ".rdlc"; string source = this.GetSource(filename); if (source == null) return; // error: message already displayed // Compile the report Oranikle.Report.Engine.Report report = this.GetReport(source, filename); if (report == null) return; // error: message already displayed ICollection rps = report.UserReportParameters; string[] rowValues = new string[2]; _DataTable.Rows.Clear(); foreach (UserReportParameter rp in rps) { rowValues[0] = rp.Name; rowValues[1] = ""; _DataTable.Rows.Add(rowValues); } this.dgParms.Refresh(); } private string GetSource(string file) { StreamReader fs=null; string prog=null; try { fs = new StreamReader(file); prog = fs.ReadToEnd(); } catch(Exception e) { prog = null; MessageBox.Show(e.Message, "Error reading report file"); } finally { if (fs != null) fs.Close(); } return prog; } private Oranikle.Report.Engine.Report GetReport(string prog, string file) { // Now parse the file RDLParser rdlp; Oranikle.Report.Engine.Report r; try { rdlp = new RDLParser(prog); string folder = Path.GetDirectoryName(file); if (folder == "") folder = Environment.CurrentDirectory; rdlp.Folder = folder; r = rdlp.Parse(); if (r.ErrorMaxSeverity > 4) { MessageBox.Show(string.Format("Report {0} has errors and cannot be processed.", "Report")); r = null; // don't return when severe errors } } catch(Exception e) { r = null; MessageBox.Show(e.Message, "Report load failed"); } return r; } } }
using ICSharpCode.NRefactory.CSharp; using ICSharpCode.NRefactory.TypeSystem; using Mono.Cecil; using System; using System.Collections.Generic; namespace Bridge.Contract { public interface IEmitter : ILog, IAstVisitor { string Tag { get; set; } IAssemblyInfo AssemblyInfo { get; set; } ICSharpCode.NRefactory.CSharp.AssignmentOperatorType AssignmentType { get; set; } ICSharpCode.NRefactory.CSharp.UnaryOperatorType UnaryOperatorType { get; set; } bool IsUnaryAccessor { get; set; } IAsyncBlock AsyncBlock { get; set; } bool AsyncExpressionHandling { get; set; } ICSharpCode.NRefactory.CSharp.SwitchStatement AsyncSwitch { get; set; } System.Collections.Generic.List<string> AsyncVariables { get; set; } bool Comma { get; set; } int CompareTypeInfosByName(ITypeInfo x, ITypeInfo y); int CompareTypeInfosByPriority(ITypeInfo x, ITypeInfo y); bool IsInheritedFrom(ITypeInfo x, ITypeInfo y); void SortTypesByInheritance(); System.Collections.Generic.List<IPluginDependency> CurrentDependencies { get; set; } List<TranslatorOutputItem> Emit(); bool EnableSemicolon { get; set; } ICSharpCode.NRefactory.TypeSystem.IAttribute GetAttribute(System.Collections.Generic.IEnumerable<ICSharpCode.NRefactory.TypeSystem.IAttribute> attributes, string name); Mono.Cecil.CustomAttribute GetAttribute(System.Collections.Generic.IEnumerable<Mono.Cecil.CustomAttribute> attributes, string name); Mono.Cecil.TypeDefinition GetBaseMethodOwnerTypeDefinition(string methodName, int genericParamCount); Mono.Cecil.TypeDefinition GetBaseTypeDefinition(); Mono.Cecil.TypeDefinition GetBaseTypeDefinition(Mono.Cecil.TypeDefinition type); string GetEntityName(ICSharpCode.NRefactory.CSharp.EntityDeclaration entity); string GetParameterName(ICSharpCode.NRefactory.CSharp.ParameterDeclaration entity); NameSemantic GetNameSemantic(IEntity member); string GetEntityName(ICSharpCode.NRefactory.TypeSystem.IEntity member); string GetTypeName(ICSharpCode.NRefactory.TypeSystem.ITypeDefinition type, TypeDefinition typeDefinition); string GetLiteralEntityName(ICSharpCode.NRefactory.TypeSystem.IEntity member); string GetInline(ICSharpCode.NRefactory.CSharp.EntityDeclaration method); string GetInline(ICSharpCode.NRefactory.TypeSystem.IEntity entity); Tuple<bool, bool, string> GetInlineCode(ICSharpCode.NRefactory.CSharp.InvocationExpression node); Tuple<bool, bool, string> GetInlineCode(ICSharpCode.NRefactory.CSharp.MemberReferenceExpression node); bool IsForbiddenInvocation(InvocationExpression node); System.Collections.Generic.IEnumerable<string> GetScript(ICSharpCode.NRefactory.CSharp.EntityDeclaration method); int GetPriority(Mono.Cecil.TypeDefinition type); Mono.Cecil.TypeDefinition GetTypeDefinition(); Mono.Cecil.TypeDefinition GetTypeDefinition(ICSharpCode.NRefactory.CSharp.AstType reference, bool safe = false); Mono.Cecil.TypeDefinition GetTypeDefinition(IType type); string GetTypeHierarchy(); ICSharpCode.NRefactory.CSharp.AstNode IgnoreBlock { get; set; } bool IsAssignment { get; set; } bool IsAsync { get; set; } bool IsYield { get; set; } bool IsInlineConst(ICSharpCode.NRefactory.TypeSystem.IMember member); bool IsMemberConst(ICSharpCode.NRefactory.TypeSystem.IMember member); bool IsNativeMember(string fullName); bool IsNewLine { get; set; } int IteratorCount { get; set; } System.Collections.Generic.List<IJumpInfo> JumpStatements { get; set; } IWriterInfo LastSavedWriter { get; set; } int Level { get; } int InitialLevel { get; } int ResetLevel(int? level = null); InitPosition? InitPosition { get; set; } System.Collections.Generic.Dictionary<string, ICSharpCode.NRefactory.CSharp.AstType> Locals { get; set; } System.Collections.Generic.Dictionary<IVariable, string> LocalsMap { get; set; } System.Collections.Generic.Dictionary<string, string> LocalsNamesMap { get; set; } System.Collections.Generic.Stack<System.Collections.Generic.Dictionary<string, ICSharpCode.NRefactory.CSharp.AstType>> LocalsStack { get; set; } ILogger Log { get; set; } System.Collections.Generic.IEnumerable<Mono.Cecil.MethodDefinition> MethodsGroup { get; set; } System.Collections.Generic.Dictionary<int, System.Text.StringBuilder> MethodsGroupBuilder { get; set; } ICSharpCode.NRefactory.CSharp.AstNode NoBraceBlock { get; set; } Action BeforeBlock { get; set; } System.Text.StringBuilder Output { get; set; } string SourceFileName { get; set; } int SourceFileNameIndex { get; set; } string LastSequencePoint { get; set; } IEmitterOutputs Outputs { get; set; } IEmitterOutput EmitterOutput { get; set; } System.Collections.Generic.IEnumerable<Mono.Cecil.AssemblyDefinition> References { get; set; } bool ReplaceAwaiterByVar { get; set; } IMemberResolver Resolver { get; set; } bool SkipSemiColon { get; set; } System.Collections.Generic.IList<string> SourceFiles { get; set; } int ThisRefCounter { get; set; } string ToJavaScript(object value); System.Collections.Generic.IDictionary<string, Mono.Cecil.TypeDefinition> TypeDefinitions { get; } ITypeInfo TypeInfo { get; set; } System.Collections.Generic.Dictionary<string, ITypeInfo> TypeInfoDefinitions { get; set; } System.Collections.Generic.List<ITypeInfo> Types { get; set; } IValidator Validator { get; } System.Collections.Generic.Stack<IWriter> Writers { get; set; } IVisitorException CreateException(AstNode node); IVisitorException CreateException(AstNode node, string message); IPlugins Plugins { get; set; } EmitterCache Cache { get; } string GetFieldName(FieldDeclaration field); string GetEventName(EventDeclaration evt); Dictionary<string, bool> TempVariables { get; set; } Dictionary<string, string> NamedTempVariables { get; set; } Dictionary<string, bool> ParentTempVariables { get; set; } Tuple<bool, string> IsGlobalTarget(IMember member); BridgeTypes BridgeTypes { get; set; } ITranslator Translator { get; set; } void InitEmitter(); IJsDoc JsDoc { get; set; } IType ReturnType { get; set; } string GetEntityNameFromAttr(IEntity member, bool setter = false); bool ReplaceJump { get; set; } string CatchBlockVariable { get; set; } Dictionary<string, string> NamedFunctions { get; set; } Dictionary<IType, Dictionary<string, string>> NamedBoxedFunctions { get; set; } bool StaticBlock { get; set; } bool IsJavaScriptOverflowMode { get; } bool IsRefArg { get; set; } Dictionary<AnonymousType, IAnonymousTypeConfig> AnonymousTypes { get; set; } List<string> AutoStartupMethods { get; set; } bool IsAnonymousReflectable { get; set; } string MetaDataOutputName { get; set; } IType[] ReflectableTypes { get; set; } Dictionary<string, int> NamespacesCache { get; set; } bool DisableDependencyTracking { get; set; } void WriteIndented(string s, int? position = null); string GetReflectionName(IType type); bool ForbidLifting { get; set; } Dictionary<IAssembly, NameRule[]> AssemblyNameRuleCache { get; } Dictionary<ITypeDefinition, NameRule[]> ClassNameRuleCache { get; } Dictionary<IAssembly, CompilerRule[]> AssemblyCompilerRuleCache { get; } Dictionary<ITypeDefinition, CompilerRule[]> ClassCompilerRuleCache { get; } bool InConstructor { get; set; } CompilerRule Rules { get; set; } bool HasModules { get; set; } string TemplateModifier { get; set; } int WrapRestCounter { get; set; } } }
using System; using System.Windows.Forms; using SharpFlame.Collections.Specialized; using SharpFlame.Core.Extensions; using SharpFlame.Domain; using SharpFlame.FileIO; using SharpFlame.Mapping.Tiles; using SharpFlame.Collections.Specialized; using SharpFlame.Core; using SharpFlame.Core.Domain; using SharpFlame.FileIO; using SharpFlame.Generators; using SharpFlame.Mapping; using SharpFlame.Mapping.Tiles; using SharpFlame.Mapping.Tools; using SharpFlame.Maths; namespace SharpFlame { public partial class frmGenerator { private readonly clsGenerateMap Generator = new clsGenerateMap(); private readonly frmMain _Owner; private int PlayerCount = 4; private bool StopTrying; public frmGenerator(frmMain Owner) { InitializeComponent(); _Owner = Owner; } private int ValidateTextbox(TextBox TextBoxToValidate, double Min, double Max, double Multiplier) { double dblTemp = 0; var Result = 0; if ( !IOUtil.InvariantParse(TextBoxToValidate.Text, ref dblTemp) ) { return 0; } Result = Math.Floor(MathUtil.ClampDbl(dblTemp, Min, Max) * Multiplier).ToInt(); TextBoxToValidate.Text = ((float)(Result / Multiplier)).ToStringInvariant(); return Result; } public void btnGenerateLayout_Click(Object sender, EventArgs e) { lstResult.Items.Clear(); btnGenerateLayout.Enabled = false; lstResult_AddText("Generating layout."); Application.DoEvents(); StopTrying = false; var LoopCount = 0; Generator.ClearLayout(); Generator.GenerateTileset = null; Generator.Map = null; Generator.TopLeftPlayerCount = PlayerCount; switch ( cboSymmetry.SelectedIndex ) { case 0: //none Generator.SymmetryBlockCountXY.X = 1; Generator.SymmetryBlockCountXY.Y = 1; Generator.SymmetryBlockCount = 1; Generator.SymmetryBlocks = new clsGenerateMap.sSymmetryBlock[Generator.SymmetryBlockCount - 1]; Generator.SymmetryBlocks[0].XYNum = new XYInt(0, 0); Generator.SymmetryBlocks[0].Orientation = new TileOrientation(false, false, false); Generator.SymmetryIsRotational = false; break; case 1: //h rotation Generator.SymmetryBlockCountXY.X = 2; Generator.SymmetryBlockCountXY.Y = 1; Generator.SymmetryBlockCount = 2; Generator.SymmetryBlocks = new clsGenerateMap.sSymmetryBlock[Generator.SymmetryBlockCount - 1]; Generator.SymmetryBlocks[0].XYNum = new XYInt(0, 0); Generator.SymmetryBlocks[0].Orientation = new TileOrientation(false, false, false); Generator.SymmetryBlocks[0].ReflectToNum = new int[((double)Generator.SymmetryBlockCount / 2).ToInt() - 1]; Generator.SymmetryBlocks[0].ReflectToNum[0] = 1; Generator.SymmetryBlocks[1].XYNum = new XYInt(1, 0); Generator.SymmetryBlocks[1].Orientation = new TileOrientation(true, true, false); Generator.SymmetryBlocks[1].ReflectToNum = new int[((double)Generator.SymmetryBlockCount / 2).ToInt() - 1]; Generator.SymmetryBlocks[1].ReflectToNum[0] = 0; Generator.SymmetryIsRotational = true; break; case 2: //v rotation Generator.SymmetryBlockCountXY.X = 1; Generator.SymmetryBlockCountXY.Y = 2; Generator.SymmetryBlockCount = 2; Generator.SymmetryBlocks = new clsGenerateMap.sSymmetryBlock[Generator.SymmetryBlockCount - 1]; Generator.SymmetryBlocks[0].XYNum = new XYInt(0, 0); Generator.SymmetryBlocks[0].Orientation = new TileOrientation(false, false, false); Generator.SymmetryBlocks[0].ReflectToNum = new int[( (double)Generator.SymmetryBlockCount / 2 ).ToInt() - 1]; Generator.SymmetryBlocks[0].ReflectToNum[0] = 1; Generator.SymmetryBlocks[1].XYNum = new XYInt(0, 1); Generator.SymmetryBlocks[1].Orientation = new TileOrientation(true, true, false); Generator.SymmetryBlocks[1].ReflectToNum = new int[( (double)Generator.SymmetryBlockCount / 2 ).ToInt() - 1]; Generator.SymmetryBlocks[1].ReflectToNum[0] = 0; Generator.SymmetryIsRotational = true; break; case 3: //h flip Generator.SymmetryBlockCountXY.X = 2; Generator.SymmetryBlockCountXY.Y = 1; Generator.SymmetryBlockCount = 2; Generator.SymmetryBlocks = new clsGenerateMap.sSymmetryBlock[Generator.SymmetryBlockCount - 1]; Generator.SymmetryBlocks[0].XYNum = new XYInt(0, 0); Generator.SymmetryBlocks[0].Orientation = new TileOrientation(false, false, false); Generator.SymmetryBlocks[0].ReflectToNum = new int[( (double)Generator.SymmetryBlockCount / 2 ).ToInt() - 1]; Generator.SymmetryBlocks[0].ReflectToNum[0] = 1; Generator.SymmetryBlocks[1].XYNum = new XYInt(1, 0); Generator.SymmetryBlocks[1].Orientation = new TileOrientation(true, false, false); Generator.SymmetryBlocks[1].ReflectToNum = new int[( (double)Generator.SymmetryBlockCount / 2 ).ToInt() - 1]; Generator.SymmetryBlocks[1].ReflectToNum[0] = 0; Generator.SymmetryIsRotational = false; break; case 4: //v flip Generator.SymmetryBlockCountXY.X = 1; Generator.SymmetryBlockCountXY.Y = 2; Generator.SymmetryBlockCount = 2; Generator.SymmetryBlocks = new clsGenerateMap.sSymmetryBlock[(Generator.SymmetryBlockCount - 1) + 1]; Generator.SymmetryBlocks[0].XYNum = new XYInt(0, 0); Generator.SymmetryBlocks[0].Orientation = new TileOrientation(false, false, false); Generator.SymmetryBlocks[0].ReflectToNum = new int[( (double)Generator.SymmetryBlockCount / 2 ).ToInt() - 1]; Generator.SymmetryBlocks[0].ReflectToNum[0] = 1; Generator.SymmetryBlocks[1].XYNum = new XYInt(0, 1); Generator.SymmetryBlocks[1].Orientation = new TileOrientation(false, true, false); Generator.SymmetryBlocks[1].ReflectToNum = new int[( (double)Generator.SymmetryBlockCount / 2 ).ToInt() - 1]; Generator.SymmetryBlocks[1].ReflectToNum[0] = 0; Generator.SymmetryIsRotational = false; Generator.SymmetryIsRotational = false; break; case 5: //4x rotation Generator.SymmetryBlockCountXY.X = 2; Generator.SymmetryBlockCountXY.Y = 2; Generator.SymmetryBlockCount = 4; Generator.SymmetryBlocks = new clsGenerateMap.sSymmetryBlock[Generator.SymmetryBlockCount - 1]; Generator.SymmetryBlocks[0].XYNum = new XYInt(0, 0); Generator.SymmetryBlocks[0].Orientation = new TileOrientation(false, false, false); Generator.SymmetryBlocks[0].ReflectToNum = new int[( (double)Generator.SymmetryBlockCount / 2 ).ToInt() - 1]; Generator.SymmetryBlocks[0].ReflectToNum[0] = 1; Generator.SymmetryBlocks[0].ReflectToNum[1] = 2; Generator.SymmetryBlocks[1].XYNum = new XYInt(1, 0); Generator.SymmetryBlocks[1].Orientation = new TileOrientation(true, false, true); Generator.SymmetryBlocks[1].ReflectToNum = new int[( (double)Generator.SymmetryBlockCount / 2 ).ToInt() - 1]; Generator.SymmetryBlocks[1].ReflectToNum[0] = 3; Generator.SymmetryBlocks[1].ReflectToNum[1] = 0; Generator.SymmetryBlocks[2].XYNum = new XYInt(0, 1); Generator.SymmetryBlocks[2].Orientation = new TileOrientation(false, true, true); Generator.SymmetryBlocks[2].ReflectToNum = new int[( (double)Generator.SymmetryBlockCount / 2 ).ToInt() - 1]; Generator.SymmetryBlocks[2].ReflectToNum[0] = 0; Generator.SymmetryBlocks[2].ReflectToNum[1] = 3; Generator.SymmetryBlocks[3].XYNum = new XYInt(1, 1); Generator.SymmetryBlocks[3].Orientation = new TileOrientation(true, true, false); Generator.SymmetryBlocks[3].ReflectToNum = new int[( (double)Generator.SymmetryBlockCount / 2 ).ToInt() - 1]; Generator.SymmetryBlocks[3].ReflectToNum[0] = 2; Generator.SymmetryBlocks[3].ReflectToNum[1] = 1; Generator.SymmetryIsRotational = true; break; case 6: //hv flip Generator.SymmetryBlockCountXY.X = 2; Generator.SymmetryBlockCountXY.Y = 2; Generator.SymmetryBlockCount = 4; Generator.SymmetryBlocks = new clsGenerateMap.sSymmetryBlock[Generator.SymmetryBlockCount - 1]; Generator.SymmetryBlocks[0].XYNum = new XYInt(0, 0); Generator.SymmetryBlocks[0].Orientation = new TileOrientation(false, false, false); Generator.SymmetryBlocks[0].ReflectToNum = new int[( (double)Generator.SymmetryBlockCount / 2 ).ToInt() - 1]; Generator.SymmetryBlocks[0].ReflectToNum[0] = 1; Generator.SymmetryBlocks[0].ReflectToNum[1] = 2; Generator.SymmetryBlocks[1].XYNum = new XYInt(1, 0); Generator.SymmetryBlocks[1].Orientation = new TileOrientation(true, false, false); Generator.SymmetryBlocks[1].ReflectToNum = new int[( (double)Generator.SymmetryBlockCount / 2 ).ToInt() - 1]; Generator.SymmetryBlocks[1].ReflectToNum[0] = 0; Generator.SymmetryBlocks[1].ReflectToNum[1] = 3; Generator.SymmetryBlocks[2].XYNum = new XYInt(0, 1); Generator.SymmetryBlocks[2].Orientation = new TileOrientation(false, true, false); Generator.SymmetryBlocks[2].ReflectToNum = new int[( (double)Generator.SymmetryBlockCount / 2 ).ToInt() - 1]; Generator.SymmetryBlocks[2].ReflectToNum[0] = 3; Generator.SymmetryBlocks[2].ReflectToNum[1] = 0; Generator.SymmetryBlocks[3].XYNum = new XYInt(1, 1); Generator.SymmetryBlocks[3].Orientation = new TileOrientation(true, true, false); Generator.SymmetryBlocks[3].ReflectToNum = new int[( (double)Generator.SymmetryBlockCount / 2 ).ToInt() - 1]; Generator.SymmetryBlocks[3].ReflectToNum[0] = 2; Generator.SymmetryBlocks[3].ReflectToNum[1] = 1; Generator.SymmetryIsRotational = false; break; default: MessageBox.Show("Select symmetry"); btnGenerateLayout.Enabled = true; return; } if ( Generator.TopLeftPlayerCount * Generator.SymmetryBlockCount < 2 ) { MessageBox.Show("That configuration only produces 1 player."); btnGenerateLayout.Enabled = true; return; } if ( Generator.TopLeftPlayerCount * Generator.SymmetryBlockCount > 10 ) { MessageBox.Show("That configuration produces more than 10 players."); btnGenerateLayout.Enabled = true; return; } Generator.TileSize.X = ValidateTextbox(txtWidth, 48.0D, 250.0D, 1.0D); Generator.TileSize.Y = ValidateTextbox(txtHeight, 48.0D, 250.0D, 1.0D); if ( Generator.SymmetryBlockCount == 4 ) { if ( Generator.TileSize.X != Generator.TileSize.Y && Generator.SymmetryIsRotational ) { MessageBox.Show("Width and height must be equal if map is rotated on two axes."); btnGenerateLayout.Enabled = true; return; } } Generator.PlayerBasePos = new XYInt[Generator.TopLeftPlayerCount]; var BaseMin = 12.0D; var BaseMax = new XYDouble(Math.Min((double)Generator.TileSize.X / Generator.SymmetryBlockCountXY.X, Generator.TileSize.X - 12.0D), Math.Min((double)Generator.TileSize.Y / Generator.SymmetryBlockCountXY.Y, Generator.TileSize.Y - 12.0D)); Generator.PlayerBasePos[0] = new XYInt(ValidateTextbox(txt1x, BaseMin, BaseMax.X, Constants.TerrainGridSpacing), ValidateTextbox(txt1y, BaseMin, BaseMax.X, Constants.TerrainGridSpacing)); if ( Generator.TopLeftPlayerCount >= 2 ) { Generator.PlayerBasePos[1] = new XYInt(ValidateTextbox(txt2x, BaseMin, BaseMax.X, Constants.TerrainGridSpacing), ValidateTextbox(txt2y, BaseMin, BaseMax.Y, Constants.TerrainGridSpacing)); if ( Generator.TopLeftPlayerCount >= 3 ) { Generator.PlayerBasePos[2] = new XYInt(ValidateTextbox(txt3x, BaseMin, BaseMax.X, Constants.TerrainGridSpacing), ValidateTextbox(txt3y, BaseMin, BaseMax.Y, Constants.TerrainGridSpacing)); if ( Generator.TopLeftPlayerCount >= 4 ) { Generator.PlayerBasePos[3] = new XYInt(ValidateTextbox(txt4x, BaseMin, BaseMax.X, Constants.TerrainGridSpacing), ValidateTextbox(txt4y, BaseMin, BaseMax.Y, Constants.TerrainGridSpacing)); if ( Generator.TopLeftPlayerCount >= 5 ) { Generator.PlayerBasePos[4] = new XYInt(ValidateTextbox(txt5x, BaseMin, BaseMax.X, Constants.TerrainGridSpacing), ValidateTextbox(txt5y, BaseMin, BaseMax.Y, Constants.TerrainGridSpacing)); if ( Generator.TopLeftPlayerCount >= 6 ) { Generator.PlayerBasePos[5] = new XYInt(ValidateTextbox(txt6x, BaseMin, BaseMax.X, Constants.TerrainGridSpacing), ValidateTextbox(txt6y, BaseMin, BaseMax.Y, Constants.TerrainGridSpacing)); if ( Generator.TopLeftPlayerCount >= 7 ) { Generator.PlayerBasePos[6] = new XYInt(ValidateTextbox(txt7x, BaseMin, BaseMax.X, Constants.TerrainGridSpacing), ValidateTextbox(txt7y, BaseMin, BaseMax.Y, Constants.TerrainGridSpacing)); if ( Generator.TopLeftPlayerCount >= 8 ) { Generator.PlayerBasePos[7] = new XYInt(ValidateTextbox(txt8x, BaseMin, BaseMax.X, Constants.TerrainGridSpacing), ValidateTextbox(txt8y, BaseMin, BaseMax.Y, Constants.TerrainGridSpacing)); if ( Generator.TopLeftPlayerCount >= 9 ) { Generator.PlayerBasePos[8] = new XYInt( ValidateTextbox(txt9x, BaseMin, BaseMax.X, Constants.TerrainGridSpacing), ValidateTextbox(txt9y, BaseMin, BaseMax.Y, Constants.TerrainGridSpacing)); if ( Generator.TopLeftPlayerCount >= 10 ) { Generator.PlayerBasePos[9] = new XYInt(ValidateTextbox(txt10x, BaseMin, BaseMax.X, Constants.TerrainGridSpacing), ValidateTextbox(txt10y, BaseMin, BaseMax.Y, Constants.TerrainGridSpacing)); } } } } } } } } } Generator.LevelCount = ValidateTextbox(txtLevels, 3.0D, 5.0D, 1.0D); Generator.BaseLevel = ValidateTextbox(txtBaseLevel, -1.0D, Generator.LevelCount - 1, 1.0D); Generator.JitterScale = 1; Generator.MaxLevelTransition = 2; Generator.PassagesChance = ValidateTextbox(txtLevelFrequency, 0.0D, 100.0D, 1.0D); Generator.VariationChance = ValidateTextbox(txtVariation, 0.0D, 100.0D, 1.0D); Generator.FlatsChance = ValidateTextbox(txtFlatness, 0.0D, 100.0D, 1.0D); Generator.BaseFlatArea = ValidateTextbox(txtBaseArea, 1.0D, 16.0D, 1.0D); Generator.NodeScale = 4.0F; Generator.WaterSpawnQuantity = ValidateTextbox(txtWaterQuantity, 0.0D, 9999.0D, 1.0D); Generator.TotalWaterQuantity = ValidateTextbox(txtConnectedWater, 0.0D, 9999.0D, 1.0D); Application.DoEvents(); LoopCount = 0; var Result = default(Result); do { Result = new Result("", false); Result = Generator.GenerateLayout(); if ( !Result.HasProblems ) { var HeightsResult = FinishHeights(); Result.Add(HeightsResult); if ( !HeightsResult.HasProblems ) { lstResult_AddResult(Result); lstResult_AddText("Done."); btnGenerateLayout.Enabled = true; break; } } LoopCount++; lstResult_AddText("Attempt " + Convert.ToString(LoopCount) + " failed."); Application.DoEvents(); if ( StopTrying ) { Generator.Map = null; lstResult_AddResult(Result); lstResult_AddText("Stopped."); btnGenerateLayout.Enabled = true; return; } lstResult_AddResult(Result); lstResult_AddText("Retrying..."); Application.DoEvents(); Generator.ClearLayout(); } while ( true ); lstResult_AddResult(Result); } private Result FinishHeights() { var ReturnResult = new Result("", false); ReturnResult.Take(Generator.GenerateLayoutTerrain()); if ( ReturnResult.HasProblems ) { return ReturnResult; } Generator.Map.RandomizeHeights(Generator.LevelCount); Generator.Map.InterfaceOptions = new InterfaceOptions(); Generator.Map.InterfaceOptions.CompileMultiPlayers = Generator.GetTotalPlayerCount; _Owner.NewMainMap(Generator.Map); return ReturnResult; } private Result FinishTextures() { var ReturnResult = new Result("", false); if ( cbxMasterTexture.Checked ) { switch ( cboTileset.SelectedIndex ) { case 0: Generator.GenerateTileset = DefaultGenerator.Generator_TilesetArizona; DefaultGenerator.TerrainStyle_Arizona.Watermap = Generator.GetWaterMap(); DefaultGenerator.TerrainStyle_Arizona.LevelCount = Generator.LevelCount; Generator.Map.GenerateMasterTerrain(ref DefaultGenerator.TerrainStyle_Arizona); DefaultGenerator.TerrainStyle_Arizona.Watermap = null; break; case 1: Generator.GenerateTileset = DefaultGenerator.Generator_TilesetUrban; DefaultGenerator.TerrainStyle_Urban.Watermap = Generator.GetWaterMap(); DefaultGenerator.TerrainStyle_Urban.LevelCount = Generator.LevelCount; Generator.Map.GenerateMasterTerrain(ref DefaultGenerator.TerrainStyle_Urban); DefaultGenerator.TerrainStyle_Urban.Watermap = null; break; case 2: Generator.GenerateTileset = DefaultGenerator.Generator_TilesetRockies; DefaultGenerator.TerrainStyle_Rockies.Watermap = Generator.GetWaterMap(); DefaultGenerator.TerrainStyle_Rockies.LevelCount = Generator.LevelCount; Generator.Map.GenerateMasterTerrain(ref DefaultGenerator.TerrainStyle_Rockies); DefaultGenerator.TerrainStyle_Rockies.Watermap = null; break; default: ReturnResult.ProblemAdd("Error: bad tileset selection."); btnGenerateLayout.Enabled = true; return ReturnResult; } Generator.Map.TileType_Reset(); Generator.Map.SetPainterToDefaults(); } else { switch ( cboTileset.SelectedIndex ) { case 0: Generator.Map.Tileset = App.Tileset_Arizona; Generator.GenerateTileset = DefaultGenerator.Generator_TilesetArizona; break; case 1: Generator.Map.Tileset = App.Tileset_Urban; Generator.GenerateTileset = DefaultGenerator.Generator_TilesetUrban; break; case 2: Generator.Map.Tileset = App.Tileset_Rockies; Generator.GenerateTileset = DefaultGenerator.Generator_TilesetRockies; break; default: ReturnResult.ProblemAdd("Error: bad tileset selection."); btnGenerateLayout.Enabled = true; return ReturnResult; } Generator.Map.TileType_Reset(); Generator.Map.SetPainterToDefaults(); var CliffAngle = Math.Atan(255.0D * Generator.Map.HeightMultiplier / (2.0D * (Generator.LevelCount - 1.0D) * Constants.TerrainGridSpacing)) - MathUtil.RadOf1Deg; var tmpBrush = new clsBrush((Math.Max(Generator.Map.Terrain.TileSize.X, Generator.Map.Terrain.TileSize.Y)) * 1.1D, ShapeType.Square); var ApplyCliff = new clsApplyCliff(); ApplyCliff.Map = Generator.Map; ApplyCliff.Angle = CliffAngle; ApplyCliff.SetTris = true; var Alignments = new clsBrush.sPosNum(); Alignments.Normal = new XYInt(Math.Floor(Generator.Map.Terrain.TileSize.X / 2.0D).ToInt(), Math.Floor(Generator.Map.Terrain.TileSize.Y / 2.0D).ToInt()); Alignments.Alignment = Alignments.Normal; tmpBrush.PerformActionMapTiles(ApplyCliff, Alignments); bool[] RevertSlope = null; bool[] RevertHeight = null; var WaterMap = new BooleanMap(); var bmTemp = new BooleanMap(); var A = 0; WaterMap = Generator.GetWaterMap(); RevertSlope = new bool[Generator.GenerateTileset.OldTextureLayers.LayerCount]; RevertHeight = new bool[Generator.GenerateTileset.OldTextureLayers.LayerCount]; for ( A = 0; A <= Generator.GenerateTileset.OldTextureLayers.LayerCount - 1; A++ ) { var with_2 = Generator.GenerateTileset.OldTextureLayers.Layers[A]; with_2.Terrainmap = Generator.Map.GenerateTerrainMap(with_2.Scale, with_2.Density); if ( with_2.SlopeMax < 0.0F ) { with_2.SlopeMax = (float)(CliffAngle - MathUtil.RadOf1Deg); if ( with_2.HeightMax < 0.0F ) { with_2.HeightMax = 255.0F; bmTemp.Within(with_2.Terrainmap, WaterMap); with_2.Terrainmap.ValueData = bmTemp.ValueData; bmTemp.ValueData = new BooleanMapDataValue(); RevertHeight[A] = true; } RevertSlope[A] = true; } } Generator.Map.MapTexturer(ref Generator.GenerateTileset.OldTextureLayers); for ( A = 0; A <= Generator.GenerateTileset.OldTextureLayers.LayerCount - 1; A++ ) { var with_3 = Generator.GenerateTileset.OldTextureLayers.Layers[A]; with_3.Terrainmap = null; if ( RevertSlope[A] ) { with_3.SlopeMax = -1.0F; } if ( RevertHeight[A] ) { with_3.HeightMax = -1.0F; } } } Generator.Map.LevelWater(); Generator.Map.WaterTriCorrection(); Generator.Map.SectorGraphicsChanges.SetAllChanged(); Generator.Map.SectorUnitHeightsChanges.SetAllChanged(); Generator.Map.Update(null); Generator.Map.UndoStepCreate("Generated Textures"); if ( Generator.Map == _Owner.MainMap ) { Program.frmMainInstance.PainterTerrains_Refresh(-1, -1); Program.frmMainInstance.MainMapTilesetChanged(); } return ReturnResult; } public void btnGenerateObjects_Click(Object sender, EventArgs e) { if ( Generator.Map == null || Generator.GenerateTileset == null ) { return; } Generator.BaseOilCount = ValidateTextbox(txtBaseOil, 0.0D, 16.0D, 1.0D); Generator.ExtraOilCount = ValidateTextbox(txtOilElsewhere, 0.0D, 9999.0D, 1.0D); Generator.ExtraOilClusterSizeMax = ValidateTextbox(txtOilClusterMax, 0.0D, 99.0D, 1.0D); Generator.ExtraOilClusterSizeMin = ValidateTextbox(txtOilClusterMin, 0.0D, Generator.ExtraOilClusterSizeMax, 1.0D); Generator.OilDispersion = ValidateTextbox(txtOilDispersion, 0.0D, 9999.0D, 1.0D) / 100.0F; Generator.OilAtATime = ValidateTextbox(txtOilAtATime, 1.0D, 2.0D, 1.0D); Generator.FeatureClusterChance = ValidateTextbox(txtFClusterChance, 0.0D, 100.0D, 1.0D) / 100.0F; Generator.FeatureClusterMaxUnits = ValidateTextbox(txtFClusterMax, 0.0D, 99.0D, 1.0D); Generator.FeatureClusterMinUnits = ValidateTextbox(txtFClusterMin, 0.0D, Generator.FeatureClusterMaxUnits, 1.0D); Generator.FeatureScatterCount = ValidateTextbox(txtFScatterChance, 0.0D, 99999.0D, 1.0D); Generator.FeatureScatterGap = ValidateTextbox(txtFScatterGap, 0.0D, 99999.0D, 1.0D); Generator.BaseTruckCount = ValidateTextbox(txtTrucks, 0.0D, 15.0D, 1.0D); Generator.GenerateTilePathMap(); Generator.TerrainBlockPaths(); Generator.BlockEdgeTiles(); Generator.GenerateGateways(); lstResult_AddText("Generating objects."); var Result = new Result("", false); Result.Take(Generator.GenerateOil()); Result.Take(Generator.GenerateUnits()); lstResult_AddResult(Result); if ( Result.HasProblems ) { lstResult_AddText("Failed."); } else { lstResult_AddText("Done."); } Generator.Map.SectorGraphicsChanges.SetAllChanged(); Generator.Map.Update(null); Generator.Map.UndoStepCreate("Generator objects"); } public void btnGenerateRamps_Click(Object sender, EventArgs e) { if ( Generator.Map == null ) { return; } Generator.MaxDisconnectionDist = ValidateTextbox(txtRampDistance, 0.0D, 99999.0D, Constants.TerrainGridSpacing); Generator.RampBase = ValidateTextbox(txtRampBase, 10.0D, 1000.0D, 10.0D) / 1000.0D; var Result = new Result("", false); lstResult_AddText("Generating ramps."); Result = Generator.GenerateRamps(); if ( !Result.HasProblems ) { Result.Add(FinishHeights()); } lstResult_AddResult(Result); if ( Result.HasProblems ) { lstResult_AddText("Failed."); } lstResult_AddText("Done."); } public void btnGenerateTextures_Click(Object sender, EventArgs e) { if ( Generator.Map == null ) { return; } lstResult_AddResult(FinishTextures()); Program.frmMainInstance.View_DrawViewLater(); } public void frmGenerator_FormClosing(object sender, FormClosingEventArgs e) { Hide(); e.Cancel = true; } public void frmWZMapGen_Load(object sender, EventArgs e) { cboTileset.SelectedIndex = 0; cboSymmetry.SelectedIndex = 0; } public void rdoPlayer2_CheckedChanged(Object sender, EventArgs e) { if ( rdoPlayer2.Checked ) { PlayerCount = 2; rdoPlayer1.Checked = false; rdoPlayer3.Checked = false; rdoPlayer4.Checked = false; rdoPlayer5.Checked = false; rdoPlayer6.Checked = false; rdoPlayer7.Checked = false; rdoPlayer8.Checked = false; rdoPlayer9.Checked = false; rdoPlayer10.Checked = false; } } public void rdoPlayer3_CheckedChanged(Object sender, EventArgs e) { if ( rdoPlayer3.Checked ) { PlayerCount = 3; rdoPlayer1.Checked = false; rdoPlayer2.Checked = false; rdoPlayer4.Checked = false; rdoPlayer5.Checked = false; rdoPlayer6.Checked = false; rdoPlayer7.Checked = false; rdoPlayer8.Checked = false; rdoPlayer9.Checked = false; rdoPlayer10.Checked = false; } } public void rdoPlayer4_CheckedChanged(Object sender, EventArgs e) { if ( rdoPlayer4.Checked ) { PlayerCount = 4; rdoPlayer1.Checked = false; rdoPlayer2.Checked = false; rdoPlayer3.Checked = false; rdoPlayer5.Checked = false; rdoPlayer6.Checked = false; rdoPlayer7.Checked = false; rdoPlayer8.Checked = false; rdoPlayer9.Checked = false; rdoPlayer10.Checked = false; } } public void rdoPlayer5_CheckedChanged(Object sender, EventArgs e) { if ( rdoPlayer5.Checked ) { PlayerCount = 5; rdoPlayer1.Checked = false; rdoPlayer2.Checked = false; rdoPlayer3.Checked = false; rdoPlayer4.Checked = false; rdoPlayer6.Checked = false; rdoPlayer7.Checked = false; rdoPlayer8.Checked = false; rdoPlayer9.Checked = false; rdoPlayer10.Checked = false; } } public void rdoPlayer6_CheckedChanged(Object sender, EventArgs e) { if ( rdoPlayer6.Checked ) { PlayerCount = 6; rdoPlayer1.Checked = false; rdoPlayer2.Checked = false; rdoPlayer3.Checked = false; rdoPlayer4.Checked = false; rdoPlayer5.Checked = false; rdoPlayer7.Checked = false; rdoPlayer8.Checked = false; rdoPlayer9.Checked = false; rdoPlayer10.Checked = false; } } public void rdoPlayer7_CheckedChanged(Object sender, EventArgs e) { if ( rdoPlayer7.Checked ) { PlayerCount = 7; rdoPlayer1.Checked = false; rdoPlayer2.Checked = false; rdoPlayer3.Checked = false; rdoPlayer4.Checked = false; rdoPlayer5.Checked = false; rdoPlayer6.Checked = false; rdoPlayer8.Checked = false; rdoPlayer9.Checked = false; rdoPlayer10.Checked = false; } } public void rdoPlayer8_CheckedChanged(Object sender, EventArgs e) { if ( rdoPlayer8.Checked ) { PlayerCount = 8; rdoPlayer1.Checked = false; rdoPlayer2.Checked = false; rdoPlayer3.Checked = false; rdoPlayer4.Checked = false; rdoPlayer5.Checked = false; rdoPlayer6.Checked = false; rdoPlayer7.Checked = false; rdoPlayer9.Checked = false; rdoPlayer10.Checked = false; } } public void btnStop_Click(Object sender, EventArgs e) { StopTrying = true; } public void rdoPlayer1_CheckedChanged(Object sender, EventArgs e) { if ( rdoPlayer1.Checked ) { PlayerCount = 1; rdoPlayer2.Checked = false; rdoPlayer3.Checked = false; rdoPlayer4.Checked = false; rdoPlayer5.Checked = false; rdoPlayer6.Checked = false; rdoPlayer7.Checked = false; rdoPlayer8.Checked = false; rdoPlayer9.Checked = false; rdoPlayer10.Checked = false; } } public void rdoPlayer9_CheckedChanged(Object sender, EventArgs e) { if ( rdoPlayer9.Checked ) { PlayerCount = 9; rdoPlayer1.Checked = false; rdoPlayer2.Checked = false; rdoPlayer3.Checked = false; rdoPlayer4.Checked = false; rdoPlayer5.Checked = false; rdoPlayer6.Checked = false; rdoPlayer7.Checked = false; rdoPlayer8.Checked = false; rdoPlayer10.Checked = false; } } public void rdoPlayer10_CheckedChanged(Object sender, EventArgs e) { if ( rdoPlayer10.Checked ) { PlayerCount = 10; rdoPlayer1.Checked = false; rdoPlayer2.Checked = false; rdoPlayer3.Checked = false; rdoPlayer4.Checked = false; rdoPlayer5.Checked = false; rdoPlayer6.Checked = false; rdoPlayer7.Checked = false; rdoPlayer8.Checked = false; rdoPlayer9.Checked = false; } } private void lstResult_AddResult(Result result) { lstResult.SelectedIndex = lstResult.Items.Count - 1; } private void lstResult_AddText(string Text) { lstResult.Items.Add(Text); lstResult.SelectedIndex = lstResult.Items.Count - 1; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests.Client.Cache { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Transactions; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Client; using Apache.Ignite.Core.Client.Cache; using Apache.Ignite.Core.Client.Transactions; using Apache.Ignite.Core.Impl.Client.Transactions; using Apache.Ignite.Core.Transactions; using NUnit.Framework; using NUnit.Framework.Constraints; /// <summary> /// Transactional cache client tests. /// </summary> public abstract class CacheClientAbstractTxTest : ClientTestBase { /** All concurrency controls. */ private static readonly TransactionConcurrency[] AllConcurrencyControls = { TransactionConcurrency.Optimistic, TransactionConcurrency.Pessimistic }; /** All isolation levels*/ private static readonly TransactionIsolation[] AllIsolationLevels = { TransactionIsolation.Serializable, TransactionIsolation.ReadCommitted, TransactionIsolation.RepeatableRead }; /// <summary> /// Initializes a new instance of the <see cref="CacheClientAbstractTxTest"/> class. /// </summary> protected CacheClientAbstractTxTest(int serverCount, bool enablePartitionAwareness) : base(serverCount, enablePartitionAwareness: enablePartitionAwareness) { // No-op. } /// <summary> /// Tests that custom client transactions configuration is applied. /// </summary> [Test] public void TestClientTransactionConfiguration() { var timeout = TransactionClientConfiguration.DefaultDefaultTimeout.Add(TimeSpan.FromMilliseconds(1000)); var cfg = GetClientConfiguration(); cfg.TransactionConfiguration = new TransactionClientConfiguration { DefaultTimeout = timeout }; foreach (var concurrency in AllConcurrencyControls) { foreach (var isolation in AllIsolationLevels) { cfg.TransactionConfiguration.DefaultTransactionConcurrency = concurrency; cfg.TransactionConfiguration.DefaultTransactionIsolation = isolation; using (var client = Ignition.StartClient(cfg)) { var transactions = client.GetTransactions(); Assert.AreEqual(concurrency, transactions.DefaultTransactionConcurrency); Assert.AreEqual(isolation, transactions.DefaultTransactionIsolation); Assert.AreEqual(timeout, transactions.DefaultTimeout); ITransaction igniteTx; using (var tx = transactions.TxStart()) { Assert.AreEqual(tx, transactions.Tx); Assert.AreEqual(concurrency, tx.Concurrency); Assert.AreEqual(isolation, tx.Isolation); Assert.AreEqual(timeout, tx.Timeout); igniteTx = GetSingleLocalTransaction(); Assert.AreEqual(concurrency, igniteTx.Concurrency); Assert.AreEqual(isolation, igniteTx.Isolation); Assert.AreEqual(timeout, igniteTx.Timeout); } igniteTx.Dispose(); } } } } /// <summary> /// Tests that parameters passed to TxStart are applied. /// </summary> [Test] public void TestTxStartPassesParameters() { var timeout = TransactionClientConfiguration.DefaultDefaultTimeout.Add(TimeSpan.FromMilliseconds(1000)); var acts = new List<Func<ITransactionsClient>> { () => Client.GetTransactions(), () => Client.GetTransactions().WithLabel("label"), }; foreach (var concurrency in AllConcurrencyControls) { foreach (var isolation in AllIsolationLevels) { foreach (var act in acts) { var client = act(); ITransaction igniteTx; using (var tx = client.TxStart(concurrency, isolation)) { Assert.AreEqual(tx, client.Tx); Assert.AreEqual(concurrency, tx.Concurrency); Assert.AreEqual(isolation, tx.Isolation); igniteTx = GetSingleLocalTransaction(); Assert.AreEqual(concurrency, igniteTx.Concurrency); Assert.AreEqual(isolation, igniteTx.Isolation); } igniteTx.Dispose(); using (var tx = client.TxStart(concurrency, isolation, timeout)) { Assert.AreEqual(concurrency, tx.Concurrency); Assert.AreEqual(isolation, tx.Isolation); Assert.AreEqual(timeout, tx.Timeout); igniteTx = GetSingleLocalTransaction(); Assert.AreEqual(concurrency, igniteTx.Concurrency); Assert.AreEqual(isolation, igniteTx.Isolation); Assert.AreEqual(timeout, igniteTx.Timeout); } igniteTx.Dispose(); } } } } /// <summary> /// Tests that transaction can't be committed/rollback after being already completed. /// </summary> [Test] public void TestThrowsIfEndAlreadyCompletedTransaction() { var tx = Client.GetTransactions().TxStart(); tx.Commit(); var constraint = new ReusableConstraint(Is.TypeOf<InvalidOperationException>() .And.Message.Contains("Transaction") .And.Message.Contains("is closed")); Assert.Throws(constraint, () => tx.Commit()); Assert.Throws(constraint, () => tx.Rollback()); using (tx = Client.GetTransactions().TxStart()) { } Assert.Throws(constraint, () => tx.Commit()); Assert.Throws(constraint, () => tx.Rollback()); } /// <summary> /// Tests that transaction throws if timeout elapsed. /// </summary> [Test] public void TestTimeout() { var timeout = TimeSpan.FromMilliseconds(200); var cache = GetTransactionalCache(); cache.Put(1, 1); using (var tx = Client.GetTransactions().TxStart(TransactionConcurrency.Pessimistic, TransactionIsolation.ReadCommitted, timeout)) { Thread.Sleep(TimeSpan.FromMilliseconds(300)); var constraint = new ReusableConstraint(Is.TypeOf<IgniteClientException>() .And.Message.Contains("Cache transaction timed out")); Assert.Throws(constraint, () => cache.Put(1, 10)); Assert.Throws(constraint, () => tx.Commit()); } Assert.AreEqual(1, cache.Get(1)); } /// <summary> /// Tests that commit applies cache changes. /// </summary> [Test] public void TestTxCommit() { var cache = GetTransactionalCache(); cache.Put(1, 1); cache.Put(2, 2); using (var tx = Client.GetTransactions().TxStart()) { cache.Put(1, 10); cache.Put(2, 20); tx.Commit(); } Assert.AreEqual(10, cache.Get(1)); Assert.AreEqual(20, cache.Get(2)); } /// <summary> /// Tests that rollback reverts cache changes. /// </summary> [Test] public void TestTxRollback() { var cache = GetTransactionalCache(); cache.Put(1, 1); cache.Put(2, 2); using (var tx = Client.GetTransactions().TxStart()) { cache.Put(1, 10); cache.Put(2, 20); Assert.AreEqual(10, cache.Get(1)); Assert.AreEqual(20, cache.Get(2)); tx.Rollback(); } Assert.AreEqual(1, cache.Get(1)); Assert.AreEqual(2, cache.Get(2)); } /// <summary> /// Tests that closing transaction without commit reverts cache changes. /// </summary> [Test] public void TestTxClose() { var cache = GetTransactionalCache(); cache.Put(1, 1); cache.Put(2, 2); using (Client.GetTransactions().TxStart()) { cache.Put(1, 10); cache.Put(2, 20); } Assert.AreEqual(1, cache.Get(1)); Assert.AreEqual(2, cache.Get(2)); } /// <summary> /// Tests that client can't start multiple transactions in one thread. /// </summary> [Test] public void TestThrowsIfMultipleStarted() { TestThrowsIfMultipleStarted( () => Client.GetTransactions().TxStart(), () => Client.GetTransactions().TxStart()); } /// <summary> /// Tests that different clients can start transactions in one thread. /// </summary> [Test] public void TestDifferentClientsCanStartTransactions() { var client = Client; var cache = GetTransactionalCache(client); cache[1] = 1; cache[2] = 2; var anotherClient = GetClient(); var anotherCache = GetTransactionalCache(anotherClient); var concurrency = TransactionConcurrency.Optimistic; var isolation = TransactionIsolation.ReadCommitted; using (var tx = client.GetTransactions().TxStart(concurrency, isolation)) { cache[1] = 10; using (var anotherTx = anotherClient.GetTransactions().TxStart(concurrency, isolation)) { Assert.AreNotSame(tx, anotherTx); Assert.AreSame(tx, client.GetTransactions().Tx); Assert.AreSame(anotherTx, anotherClient.GetTransactions().Tx); Assert.AreEqual(10, cache[1]); Assert.AreEqual(1, anotherCache[1]); anotherCache[2] = 20; Assert.AreEqual(2, cache[2]); Assert.AreEqual(20, anotherCache[2]); anotherTx.Commit(); Assert.AreEqual(20, cache[2]); } } Assert.AreEqual(1, cache[1]); Assert.AreEqual(20, cache[2]); Assert.AreEqual(1, anotherCache[1]); Assert.AreEqual(20, anotherCache[2]); } /// <summary> /// Test Ignite thin client transaction with label. /// </summary> [Test] public void TestWithLabel() { const string label1 = "label1"; const string label2 = "label2"; var cache = GetTransactionalCache(); cache.Put(1, 1); cache.Put(2, 2); ITransaction igniteTx; using (Client.GetTransactions().WithLabel(label1).TxStart()) { igniteTx = GetSingleLocalTransaction(); Assert.AreEqual(igniteTx.Label, label1); cache.Put(1, 10); cache.Put(2, 20); } igniteTx.Dispose(); Assert.AreEqual(1, cache.Get(1)); Assert.AreEqual(2, cache.Get(2)); using (var tx = Client.GetTransactions().WithLabel(label1).TxStart()) { igniteTx = GetSingleLocalTransaction(); Assert.AreEqual(label1, igniteTx.Label); Assert.AreEqual(label1, tx.Label); cache.Put(1, 10); cache.Put(2, 20); tx.Commit(); } igniteTx.Dispose(); Assert.AreEqual(10, cache.Get(1)); Assert.AreEqual(20, cache.Get(2)); using (var tx = Client.GetTransactions().WithLabel(label1).WithLabel(label2).TxStart()) { igniteTx = GetSingleLocalTransaction(); Assert.AreEqual(label2, igniteTx.Label); Assert.AreEqual(label2, tx.Label); } igniteTx.Dispose(); TestThrowsIfMultipleStarted( () => Client.GetTransactions().WithLabel(label1).TxStart(), () => Client.GetTransactions().TxStart()); TestThrowsIfMultipleStarted( () => Client.GetTransactions().TxStart(), () => Client.GetTransactions().WithLabel(label1).TxStart()); TestThrowsIfMultipleStarted( () => Client.GetTransactions().WithLabel(label1).TxStart(), () => Client.GetTransactions().WithLabel(label2).TxStart()); } /// <summary> /// Tests that unfinished transaction does not prevent <see cref="IIgniteClient"/>> /// from being garbage collected. /// </summary> [Test] public void TestFinalizesAfterClientIsDisposed() { ConcurrentBag<WeakReference> weakRef = new ConcurrentBag<WeakReference>(); Action<Action<IIgniteClient>> act = startTx => { var client = GetClient(); weakRef.Add(new WeakReference(client)); var cache = GetTransactionalCache(client); startTx(client); cache[42] = 42; client.Dispose(); }; Action<IIgniteClient>[] txStarts = { // ReSharper disable once ObjectCreationAsStatement client => new TransactionScope(), client => client.GetTransactions().TxStart() }; foreach (var txStart in txStarts) { // ReSharper disable once AccessToForEachVariableInClosure var tasks = Enumerable.Range(0, 3) .Select(i => Task.Factory.StartNew(() => act(txStart),TaskCreationOptions.LongRunning)) .ToArray(); Task.WaitAll(tasks); GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); GC.WaitForPendingFinalizers(); Assert.IsFalse(weakRef.All(wr => wr.IsAlive)); } } /// <summary> /// Test that GC does not close <see cref="TransactionScope"/>'s underlying transaction. /// </summary> [Test] public void TestGcDoesNotCloseAmbientTx() { WeakReference weakRef = null; Func<TransactionScope> act = () => { var innerScope = new TransactionScope(); GetTransactionalCache()[42] = 42; weakRef = new WeakReference(Client.GetTransactions().Tx); return innerScope; }; using (act()) { GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); GC.WaitForPendingFinalizers(); Assert.IsTrue(weakRef.IsAlive); var tx = (ITransactionClient) weakRef.Target; Assert.IsNotNull(Client.GetTransactions().Tx); Assert.AreSame(tx, Client.GetTransactions().Tx); } } /// <summary> /// Test Ignite thin client transaction enlistment in ambient <see cref="TransactionScope"/>. /// </summary> [Test] public void TestTransactionScopeSingleCache() { var cache = GetTransactionalCache(); cache[1] = 1; cache[2] = 2; // Commit. using (var ts = new TransactionScope()) { cache[1] = 10; cache[2] = 20; ts.Complete(); } Assert.AreEqual(10, cache[1]); Assert.AreEqual(20, cache[2]); // Rollback. using (new TransactionScope()) { cache[1] = 100; cache[2] = 200; } Assert.AreEqual(10, cache[1]); Assert.AreEqual(20, cache[2]); } /// <summary> /// Test Ignite thin client transaction enlistment in ambient <see cref="TransactionScope"/> /// with multiple participating caches. /// </summary> [Test] public void TestTransactionScopeMultiCache() { var cache1 = GetTransactionalCache(); var cache2 = GetTransactionalCache(cache1.Name + "1"); cache1[1] = 1; cache2[1] = 2; // Commit. using (var ts = new TransactionScope()) { cache1.Put(1, 10); cache2.Put(1, 20); ts.Complete(); } Assert.AreEqual(10, cache1[1]); Assert.AreEqual(20, cache2[1]); // Rollback. using (new TransactionScope()) { cache1.Put(1, 100); cache2.Put(1, 200); } Assert.AreEqual(10, cache1[1]); Assert.AreEqual(20, cache2[1]); } /// <summary> /// Test Ignite thin client transaction enlistment in ambient <see cref="TransactionScope"/> /// when Ignite tx is started manually. /// </summary> [Test] public void TestTransactionScopeWithManualIgniteTx() { var cache = GetTransactionalCache(); var transactions = Client.GetTransactions(); cache[1] = 1; // When Ignite tx is started manually, it won't be enlisted in TransactionScope. using (var tx = transactions.TxStart()) { using (new TransactionScope()) { cache[1] = 2; } // Revert transaction scope. tx.Commit(); // Commit manual tx. } Assert.AreEqual(2, cache[1]); } /// <summary> /// Test Ignite transaction with <see cref="TransactionScopeOption.Suppress"/> option. /// </summary> [Test] public void TestSuppressedTransactionScope() { var cache = GetTransactionalCache(); cache[1] = 1; using (new TransactionScope(TransactionScopeOption.Suppress)) { cache[1] = 2; } // Even though transaction is not completed, the value is updated, because tx is suppressed. Assert.AreEqual(2, cache[1]); } /// <summary> /// Test Ignite thin client transaction enlistment in ambient <see cref="TransactionScope"/> with nested scopes. /// </summary> [Test] public void TestNestedTransactionScope() { var cache = GetTransactionalCache(); cache[1] = 1; foreach (var option in new[] {TransactionScopeOption.Required, TransactionScopeOption.RequiresNew}) { // Commit. using (var ts1 = new TransactionScope()) { using (var ts2 = new TransactionScope(option)) { cache[1] = 2; ts2.Complete(); } cache[1] = 3; ts1.Complete(); } Assert.AreEqual(3, cache[1]); // Rollback. using (new TransactionScope()) { using (new TransactionScope(option)) cache[1] = 4; cache[1] = 5; } // In case with Required option there is a single tx // that gets aborted, second put executes outside the tx. Assert.AreEqual(option == TransactionScopeOption.Required ? 5 : 3, cache[1], option.ToString()); } } /// <summary> /// Test that ambient <see cref="TransactionScope"/> options propagate to Ignite transaction. /// </summary> [Test] public void TestTransactionScopeOptions() { var cache = GetTransactionalCache(); var transactions = (TransactionsClient) Client.GetTransactions(); var modes = new[] { Tuple.Create(IsolationLevel.Serializable, TransactionIsolation.Serializable), Tuple.Create(IsolationLevel.RepeatableRead, TransactionIsolation.RepeatableRead), Tuple.Create(IsolationLevel.ReadCommitted, TransactionIsolation.ReadCommitted), Tuple.Create(IsolationLevel.ReadUncommitted, TransactionIsolation.ReadCommitted), Tuple.Create(IsolationLevel.Snapshot, TransactionIsolation.ReadCommitted), Tuple.Create(IsolationLevel.Chaos, TransactionIsolation.ReadCommitted), }; foreach (var mode in modes) { ITransaction tx; using (new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = mode.Item1 })) { cache[1] = 1; tx = GetSingleLocalTransaction(); Assert.AreEqual(mode.Item2, tx.Isolation); Assert.AreEqual(transactions.DefaultTransactionConcurrency, tx.Concurrency); } tx.Dispose(); } } /// <summary> /// Tests all synchronous transactional operations with <see cref="TransactionScope"/>. /// </summary> [Test] public void TestTransactionScopeAllOperationsSync() { CheckTxOp((cache, key) => cache.Put(key, -5)); CheckTxOp((cache, key) => cache.PutAll(new Dictionary<int, int> {{key, -7}})); CheckTxOp((cache, key) => { cache.Remove(key); cache.PutIfAbsent(key, -10); }); CheckTxOp((cache, key) => cache.GetAndPut(key, -9)); CheckTxOp((cache, key) => { cache.Remove(key); cache.GetAndPutIfAbsent(key, -10); }); CheckTxOp((cache, key) => cache.GetAndRemove(key)); CheckTxOp((cache, key) => cache.GetAndReplace(key, -11)); CheckTxOp((cache, key) => cache.Remove(key)); CheckTxOp((cache, key) => cache.RemoveAll(new[] {key})); CheckTxOp((cache, key) => cache.Replace(key, 100)); CheckTxOp((cache, key) => cache.Replace(key, cache[key], 100)); } /// <summary> /// Tests all transactional async operations with <see cref="TransactionScope"/>. /// </summary> [Test] [Ignore("Async thin client transactional operations not supported.")] public void TestTransactionScopeAllOperationsAsync() { CheckTxOp((cache, key) => cache.PutAsync(key, -5)); CheckTxOp((cache, key) => cache.PutAllAsync(new Dictionary<int, int> {{key, -7}})); CheckTxOp((cache, key) => { cache.Remove(key); cache.PutIfAbsentAsync(key, -10); }); CheckTxOp((cache, key) => cache.GetAndPutAsync(key, -9)); CheckTxOp((cache, key) => { cache.Remove(key); cache.GetAndPutIfAbsentAsync(key, -10); }); CheckTxOp((cache, key) => cache.GetAndRemoveAsync(key)); CheckTxOp((cache, key) => cache.GetAndReplaceAsync(key, -11)); CheckTxOp((cache, key) => cache.RemoveAsync(key)); CheckTxOp((cache, key) => cache.RemoveAllAsync(new[] {key})); CheckTxOp((cache, key) => cache.ReplaceAsync(key, 100)); CheckTxOp((cache, key) => cache.ReplaceAsync(key, cache[key], 100)); } /// <summary> /// Tests that read operations lock keys in Serializable mode. /// </summary> [Test] public void TestTransactionScopeWithSerializableIsolationLocksKeysOnRead() { Action<Func<ICacheClient<int, int>, int, int>> test = TestTransactionScopeWithSerializableIsolationLocksKeysOnRead; test((cache, key) => cache[key]); test((cache, key) => cache.Get(key)); test((cache, key) => { int val; return cache.TryGet(key, out val) ? val : 0; }); test((cache, key) => cache.GetAll(new[] {key}).Single().Value); } /// <summary> /// Tests that async read operations lock keys in Serializable mode. /// </summary> [Test] [Ignore("Async thin client transactional operations not supported.")] public void TestTransactionScopeWithSerializableIsolationLocksKeysOnReadAsync() { Action<Func<ICacheClient<int, int>, int, int>> test = TestTransactionScopeWithSerializableIsolationLocksKeysOnRead; test((cache, key) => cache.GetAsync(key).Result); test((cache, key) => cache.TryGetAsync(key).Result.Value); test((cache, key) => cache.GetAll(new[] {key}).Single().Value); } /// <summary> /// Tests that read operations lock keys in Serializable mode. /// </summary> private void TestTransactionScopeWithSerializableIsolationLocksKeysOnRead( Func<ICacheClient<int, int>, int, int> readOp) { var cache = GetTransactionalCache(); cache.Put(1, 1); var options = new TransactionOptions {IsolationLevel = IsolationLevel.Serializable}; using (var scope = new TransactionScope(TransactionScopeOption.Required, options)) { Assert.AreEqual(1, readOp(cache, 1)); Assert.IsNotNull(Client.GetTransactions().Tx); var evt = new ManualResetEventSlim(); var task = Task.Factory.StartNew(() => { cache.PutAsync(1, 2); evt.Set(); }); evt.Wait(); Assert.AreEqual(1, readOp(cache, 1)); scope.Complete(); task.Wait(); } TestUtils.WaitForTrueCondition(() => 2 == readOp(cache, 1)); } /// <summary> /// Checks that cache operation behaves transactionally. /// </summary> private void CheckTxOp(Action<ICacheClient<int, int>, int> act) { var isolationLevels = new[] { IsolationLevel.Serializable, IsolationLevel.RepeatableRead, IsolationLevel.ReadCommitted, IsolationLevel.ReadUncommitted, IsolationLevel.Snapshot, IsolationLevel.Chaos }; foreach (var isolationLevel in isolationLevels) { var txOpts = new TransactionOptions {IsolationLevel = isolationLevel}; const TransactionScopeOption scope = TransactionScopeOption.Required; var cache = GetTransactionalCache(); cache[1] = 1; cache[2] = 2; // Rollback. using (new TransactionScope(scope, txOpts)) { act(cache, 1); Assert.IsNotNull(Client.GetTransactions().Tx, "Transaction has not started."); } Assert.AreEqual(1, cache[1]); Assert.AreEqual(2, cache[2]); using (new TransactionScope(scope, txOpts)) { act(cache, 1); act(cache, 2); } Assert.AreEqual(1, cache[1]); Assert.AreEqual(2, cache[2]); // Commit. using (var ts = new TransactionScope(scope, txOpts)) { act(cache, 1); ts.Complete(); } Assert.IsTrue(!cache.ContainsKey(1) || cache[1] != 1); Assert.AreEqual(2, cache[2]); using (var ts = new TransactionScope(scope, txOpts)) { act(cache, 1); act(cache, 2); ts.Complete(); } Assert.IsTrue(!cache.ContainsKey(1) || cache[1] != 1); Assert.IsTrue(!cache.ContainsKey(2) || cache[2] != 2); } } /// <summary> /// Gets single transaction from Ignite. /// </summary> private static ITransaction GetSingleLocalTransaction() { return GetIgnite() .GetTransactions() .GetLocalActiveTransactions() .Single(); } /// <summary> /// Tests that client can't start multiple transactions in one thread. /// </summary> private void TestThrowsIfMultipleStarted(Func<IDisposable> outer, Func<IDisposable> inner) { Assert.Throws( Is.TypeOf<IgniteClientException>() .And.Message.Contains("A transaction has already been started by the current thread."), () => { using (outer()) using (inner()) { // No-op. } }); } /// <summary> /// Gets cache name. /// </summary> protected virtual string GetCacheName() { return "client_transactional"; } /// <summary> /// Gets or creates transactional cache /// </summary> protected ICacheClient<int, int> GetTransactionalCache(string cacheName = null) { return GetTransactionalCache(Client, cacheName); } /// <summary> /// Gets or creates transactional cache /// </summary> private ICacheClient<int, int> GetTransactionalCache(IIgniteClient client, string cacheName = null) { return client.GetOrCreateCache<int, int>(new CacheClientConfiguration { Name = cacheName ?? GetCacheName(), AtomicityMode = CacheAtomicityMode.Transactional }); } } }
// 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.Collections.ObjectModel; using Cake.Common.Solution.Project.Properties; using Cake.Common.Tests.Fixtures; using Cake.Core; using Cake.Core.Diagnostics; using Cake.Core.IO; using NSubstitute; using Xunit; namespace Cake.Common.Tests.Unit.Solution.Project.Properties { public sealed class AssemblyInfoCreatorTests { public sealed class TheConstructor { [Fact] public void Should_Throw_If_File_System_Is_Null() { // Given var environment = Substitute.For<ICakeEnvironment>(); var log = Substitute.For<ICakeLog>(); // When var result = Record.Exception(() => new AssemblyInfoCreator(null, environment, log)); // Then AssertEx.IsArgumentNullException(result, "fileSystem"); } [Fact] public void Should_Throw_If_Environment_Is_Null() { // Given var fileSystem = Substitute.For<IFileSystem>(); var log = Substitute.For<ICakeLog>(); // When var result = Record.Exception(() => new AssemblyInfoCreator(fileSystem, null, log)); // Then AssertEx.IsArgumentNullException(result, "environment"); } [Fact] public void Should_Throw_If_Log_Is_Null() { // Given var fileSystem = Substitute.For<IFileSystem>(); var environment = Substitute.For<ICakeEnvironment>(); // When var result = Record.Exception(() => new AssemblyInfoCreator(fileSystem, environment, null)); // Then AssertEx.IsArgumentNullException(result, "log"); } } public sealed class TheCreateMethod { [Fact] public void Should_Throw_If_Output_Path_Is_Null() { // Given var fixture = new AssemblyInfoFixture(); var creator = new AssemblyInfoCreator(fixture.FileSystem, fixture.Environment, fixture.Log); // When var result = Record.Exception(() => creator.Create(null, new AssemblyInfoSettings())); // Then AssertEx.IsArgumentNullException(result, "outputPath"); } [Fact] public void Should_Throw_If_Settings_Are_Null() { // Given var fixture = new AssemblyInfoFixture(); var creator = new AssemblyInfoCreator(fixture.FileSystem, fixture.Environment, fixture.Log); // When var result = Record.Exception(() => creator.Create("A.cs", null)); // Then AssertEx.IsArgumentNullException(result, "settings"); } [Fact] public void Should_Make_Relative_Output_Path_Absolute() { // Given var fixture = new AssemblyInfoFixture(); var creator = new AssemblyInfoCreator(fixture.FileSystem, fixture.Environment, fixture.Log); // When creator.Create("AssemblyInfo.cs", new AssemblyInfoSettings()); // Then Assert.True(fixture.FileSystem.Exist((FilePath)"/Working/AssemblyInfo.cs")); } [Fact] public void Should_Add_Title_Attribute_If_Set() { // Given var fixture = new AssemblyInfoFixture(); fixture.Settings.Title = "TheTitle"; // When var result = fixture.CreateAndReturnContent(); // Then Assert.Contains("using System.Reflection;", result); Assert.Contains("[assembly: AssemblyTitle(\"TheTitle\")]", result); } [Fact] public void Should_Add_Description_Attribute_If_Set() { // Given var fixture = new AssemblyInfoFixture(); fixture.Settings.Description = "TheDescription"; // When var result = fixture.CreateAndReturnContent(); // Then Assert.Contains("using System.Reflection;", result); Assert.Contains("[assembly: AssemblyDescription(\"TheDescription\")]", result); } [Fact] public void Should_Add_Guid_Attribute_If_Set() { // Given var fixture = new AssemblyInfoFixture(); fixture.Settings.Guid = "TheGuid"; // When var result = fixture.CreateAndReturnContent(); // Then Assert.Contains("using System.Runtime.InteropServices;", result); Assert.Contains("[assembly: Guid(\"TheGuid\")]", result); } [Fact] public void Should_Add_Company_Attribute_If_Set() { // Given var fixture = new AssemblyInfoFixture(); fixture.Settings.Company = "TheCompany"; // When var result = fixture.CreateAndReturnContent(); // Then Assert.Contains("using System.Reflection;", result); Assert.Contains("[assembly: AssemblyCompany(\"TheCompany\")]", result); } [Fact] public void Should_Add_Product_Attribute_If_Set() { // Given var fixture = new AssemblyInfoFixture(); fixture.Settings.Product = "TheProduct"; // When var result = fixture.CreateAndReturnContent(); // Then Assert.Contains("using System.Reflection;", result); Assert.Contains("[assembly: AssemblyProduct(\"TheProduct\")]", result); } [Fact] public void Should_Add_Copyright_Attribute_If_Set() { // Given var fixture = new AssemblyInfoFixture(); fixture.Settings.Copyright = "TheCopyright"; // When var result = fixture.CreateAndReturnContent(); // Then Assert.Contains("using System.Reflection;", result); Assert.Contains("[assembly: AssemblyCopyright(\"TheCopyright\")]", result); } [Fact] public void Should_Add_Trademark_Attribute_If_Set() { // Given var fixture = new AssemblyInfoFixture(); fixture.Settings.Trademark = "TheTrademark"; // When var result = fixture.CreateAndReturnContent(); // Then Assert.Contains("using System.Reflection;", result); Assert.Contains("[assembly: AssemblyTrademark(\"TheTrademark\")]", result); } [Fact] public void Should_Add_Version_Attribute_If_Set() { // Given var fixture = new AssemblyInfoFixture(); fixture.Settings.Version = "TheVersion"; // When var result = fixture.CreateAndReturnContent(); // Then Assert.Contains("using System.Reflection;", result); Assert.Contains("[assembly: AssemblyVersion(\"TheVersion\")]", result); } [Fact] public void Should_Add_FileVersion_Attribute_If_Set() { // Given var fixture = new AssemblyInfoFixture(); fixture.Settings.FileVersion = "TheFileVersion"; // When var result = fixture.CreateAndReturnContent(); // Then Assert.Contains("using System.Reflection;", result); Assert.Contains("[assembly: AssemblyFileVersion(\"TheFileVersion\")]", result); } [Fact] public void Should_Add_InformationalVersion_Attribute_If_Set() { // Given var fixture = new AssemblyInfoFixture(); fixture.Settings.InformationalVersion = "TheInformationalVersion"; // When var result = fixture.CreateAndReturnContent(); // Then Assert.Contains("using System.Reflection;", result); Assert.Contains("[assembly: AssemblyInformationalVersion(\"TheInformationalVersion\")]", result); } [Fact] public void Should_Add_ComVisible_Attribute_If_Set() { // Given var fixture = new AssemblyInfoFixture(); fixture.Settings.ComVisible = true; // When var result = fixture.CreateAndReturnContent(); // Then Assert.Contains("using System.Runtime.InteropServices;", result); Assert.Contains("[assembly: ComVisible(true)]", result); } [Fact] public void Should_Add_CLSCompliant_Attribute_If_Set() { // Given var fixture = new AssemblyInfoFixture(); fixture.Settings.CLSCompliant = true; // When var result = fixture.CreateAndReturnContent(); // Then Assert.Contains("using System;", result); Assert.Contains("[assembly: CLSCompliant(true)]", result); } [Fact] public void Should_Add_InternalsVisibleTo_Attribute_If_Set() { // Given var fixture = new AssemblyInfoFixture(); fixture.Settings.InternalsVisibleTo = new List<string> { "Assembly1.Tests" }; // When var result = fixture.CreateAndReturnContent(); // Then Assert.Contains("using System.Runtime.CompilerServices;", result); Assert.Contains("[assembly: InternalsVisibleTo(\"Assembly1.Tests\")]", result); } [Fact] public void Should_Add_Multiple_InternalsVisibleTo_Attribute_If_Set() { // Given var fixture = new AssemblyInfoFixture(); fixture.Settings.InternalsVisibleTo = new Collection<string> { "Assembly1.Tests", "Assembly2.Tests", "Assembly3.Tests" }; // When var result = fixture.CreateAndReturnContent(); // Then Assert.Contains("using System.Runtime.CompilerServices;", result); Assert.Contains("[assembly: InternalsVisibleTo(\"Assembly1.Tests\")]", result); Assert.Contains("[assembly: InternalsVisibleTo(\"Assembly2.Tests\")]", result); Assert.Contains("[assembly: InternalsVisibleTo(\"Assembly3.Tests\")]", result); } [Fact] public void Should_Add_Configuration_Attribute_If_Set() { // Given var fixture = new AssemblyInfoFixture(); fixture.Settings.Configuration = "TheConfiguration"; // When var result = fixture.CreateAndReturnContent(); // Then Assert.Contains("using System.Reflection;", result); Assert.Contains("[assembly: AssemblyConfiguration(\"TheConfiguration\")]", result); } [Fact] public void Should_Add_CustomAttributes_If_Set_With_Raw_Value() { // Given var fixture = new AssemblyInfoFixture(); fixture.Settings.CustomAttributes = new Collection<AssemblyInfoCustomAttribute> { new AssemblyInfoCustomAttribute { Name = "TestAttribute", NameSpace = "Test.NameSpace", Value = "RawTestValue", UseRawValue = true } }; // When var result = fixture.CreateAndReturnContent(); // Then Assert.Contains("using Test.NameSpace;", result); Assert.Contains("[assembly: TestAttribute(RawTestValue)]", result); } [Fact] public void Should_Add_CustomAttributes_If_Set() { // Given var fixture = new AssemblyInfoFixture(); fixture.Settings.CustomAttributes = new Collection<AssemblyInfoCustomAttribute> { new AssemblyInfoCustomAttribute { Name = "TestAttribute", NameSpace = "Test.NameSpace", Value = "TestValue" } }; // When var result = fixture.CreateAndReturnContent(); // Then Assert.Contains("using Test.NameSpace;", result); Assert.Contains("[assembly: TestAttribute(\"TestValue\")]", result); } [Fact] public void Should_Add_CustomAttributes_If_Set_With_Boolean_Value() { // Given var fixture = new AssemblyInfoFixture(); fixture.Settings.CustomAttributes = new Collection<AssemblyInfoCustomAttribute> { new AssemblyInfoCustomAttribute { Name = "TestAttribute", NameSpace = "Test.NameSpace", Value = true } }; // When var result = fixture.CreateAndReturnContent(); // Then Assert.Contains("using Test.NameSpace;", result); Assert.Contains("[assembly: TestAttribute(true)]", result); } [Fact] public void Should_Add_CustomAttributes_If_Set_With_Null_Value() { // Given var fixture = new AssemblyInfoFixture(); fixture.Settings.CustomAttributes = new Collection<AssemblyInfoCustomAttribute> { new AssemblyInfoCustomAttribute { Name = "TestAttribute", NameSpace = "Test.NameSpace", Value = null } }; // When var result = fixture.CreateAndReturnContent(); // Then Assert.Contains("using Test.NameSpace;", result); Assert.Contains("[assembly: TestAttribute()]", result); } [Fact] public void Should_Add_CustomAttributes_If_Set_With_Empty_Value() { // Given var fixture = new AssemblyInfoFixture(); fixture.Settings.CustomAttributes = new Collection<AssemblyInfoCustomAttribute> { new AssemblyInfoCustomAttribute { Name = "TestAttribute", NameSpace = "Test.NameSpace", Value = string.Empty } }; // When var result = fixture.CreateAndReturnContent(); // Then Assert.Contains("using Test.NameSpace;", result); Assert.Contains("[assembly: TestAttribute()]", result); } [Fact] public void Should_Add_MetadataAttributes_If_Set() { // Given var fixture = new AssemblyInfoFixture(); fixture.Settings.MetaDataAttributes = new Collection<AssemblyInfoMetadataAttribute> { new AssemblyInfoMetadataAttribute { Key = "Key1", Value = "TestValue1" }, new AssemblyInfoMetadataAttribute { Key = "Key2", Value = "TestValue2" }, new AssemblyInfoMetadataAttribute { Key = "Key1", Value = "TestValue3" } }; // When var result = fixture.CreateAndReturnContent(); // Then Assert.Contains("using System.Reflection;", result); Assert.Contains("[assembly: AssemblyMetadata(\"Key1\", \"TestValue3\")]", result); Assert.Contains("[assembly: AssemblyMetadata(\"Key2\", \"TestValue2\")]", result); Assert.DoesNotContain("[assembly: AssemblyMetadata(\"Key1\", \"TestValue1\")]", result); } } } }
namespace Microsoft.Protocols.TestSuites.MS_ASAIRS { using System.Xml; using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestSuites.Common.Response; using Microsoft.Protocols.TestTools; using Microsoft.VisualStudio.TestTools.UnitTesting; using DataStructures = Microsoft.Protocols.TestSuites.Common.DataStructures; using Request = Microsoft.Protocols.TestSuites.Common.Request; /// <summary> /// This scenario is designed to test the BodyPartPreference element and BodyPart element in the AirSyncBase namespace, which is used by the Sync command, Search command and ItemOperations command to identify the data sent by and returned to client. /// </summary> [TestClass] public class S01_BodyPartPreference : TestSuiteBase { #region Class initialize and cleanup /// <summary> /// Initialize the class. /// </summary> /// <param name="testContext">VSTS test context.</param> [ClassInitialize] public static void ClassInitialize(TestContext testContext) { TestClassBase.Initialize(testContext); } /// <summary> /// Clear the class. /// </summary> [ClassCleanup] public static void ClassCleanUp() { TestClassBase.Cleanup(); } #endregion #region MSASAIRS_S01_TC01_BodyPartPreference_AllOrNoneTrue_AllContentReturned /// <summary> /// This case is designed to test when the value of the AllOrNone (BodyPartPreference) element is set to 1 (TRUE) and the content has not been truncated, all of the content is synchronized, searched or retrieved. /// </summary> [TestCategory("MSASAIRS"), TestMethod()] public void MSASAIRS_S01_TC01_BodyPartPreference_AllOrNoneTrue_AllContentReturned() { Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The BodyPartPreference element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); Site.Assume.AreNotEqual<string>("14.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The BodyPartPreference element is not supported when the MS-ASProtocolVersion header is set to 14.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); #region Send an html email and get the non-truncated data string subject = Common.GenerateResourceName(Site, "Subject"); string body = Common.GenerateResourceName(Site, "Body"); this.SendEmail(EmailType.HTML, subject, body); DataStructures.Sync allContentItem = this.GetAllContentItem(subject, this.User2Information.InboxCollectionId); #endregion #region Set BodyPartPreference element Request.BodyPartPreference[] bodyPartPreference = new Request.BodyPartPreference[] { new Request.BodyPartPreference() { Type = 2, TruncationSize = 100, TruncationSizeSpecified = true, AllOrNone = true, AllOrNoneSpecified = true } }; #endregion #region Verify Sync command related elements DataStructures.Sync syncItem = this.GetSyncResult(subject, this.User2Information.InboxCollectionId, null, null, bodyPartPreference); this.VerifyBodyPartElements(syncItem.Email.BodyPart, true, false, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R373"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R373 Site.CaptureRequirementIfAreEqual<string>( allContentItem.Email.BodyPart.Data, syncItem.Email.BodyPart.Data, 373, @"[In AllOrNone] When the value [of the AllOrNone element] is set to 1 (TRUE) and the content has not been truncated, all of the content is synchronized."); #endregion #region Verify ItemOperations command related elements DataStructures.ItemOperations itemOperationsItem = this.GetItemOperationsResult(this.User2Information.InboxCollectionId, syncItem.ServerId, null, null, bodyPartPreference, null); this.VerifyBodyPartElements(itemOperationsItem.Email.BodyPart, true, false, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R54"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R54 Site.CaptureRequirementIfAreEqual<string>( allContentItem.Email.BodyPart.Data, itemOperationsItem.Email.BodyPart.Data, 54, @"[In AllOrNone] When the value [of the AllOrNone element] is set to 1 (TRUE) and the content has not been truncated, all of the content is retrieved."); #endregion if (Common.IsRequirementEnabled(53, this.Site)) { #region Verify Search command related elements DataStructures.Search searchItem = this.GetSearchResult(subject, this.User2Information.InboxCollectionId, itemOperationsItem.Email.ConversationId, null, bodyPartPreference); this.VerifyBodyPartElements(searchItem.Email.BodyPart, true, false, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R53"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R53 Site.CaptureRequirementIfAreEqual<string>( allContentItem.Email.BodyPart.Data, searchItem.Email.BodyPart.Data, 53, @"[In AllOrNone] When the value [of the AllOrNone element] is set to 1 (TRUE) and the content has not been truncated, all of the content is searched."); #endregion } #region Verify common requirements // According to above steps, requirements MS-ASAIRS_R120 and MS-ASAIRS_R271 can be covered directly. // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R120"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R120 Site.CaptureRequirement( 120, @"[In BodyPart] The BodyPart element MUST be included in a command response when the BodyPartPreference element (section 2.2.2.11) is specified in a request."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R271"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R271 Site.CaptureRequirement( 271, @"[In Status] [The value] 1 [of Status element] means Success."); #endregion } #endregion #region MSASAIRS_S01_TC02_BodyPartPreference_AllOrNoneTrue_AllContentNotReturned /// <summary> /// This case is designed to test when the value of the AllOrNone (BodyPartPreference) element is set to 1 (TRUE) and the content has been truncated, the content is not synchronized, searched or retrieved. /// </summary> [TestCategory("MSASAIRS"), TestMethod()] public void MSASAIRS_S01_TC02_BodyPartPreference_AllOrNoneTrue_AllContentNotReturned() { Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The BodyPartPreference element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); Site.Assume.AreNotEqual<string>("14.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The BodyPartPreference element is not supported when the MS-ASProtocolVersion header is set to 14.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); #region Send an html email string subject = Common.GenerateResourceName(Site, "Subject"); string body = Common.GenerateResourceName(Site, "Body"); this.SendEmail(EmailType.HTML, subject, body); #endregion #region Set BodyPartPreference element Request.BodyPartPreference[] bodyPartPreference = new Request.BodyPartPreference[] { new Request.BodyPartPreference() { Type = 2, TruncationSize = 2, TruncationSizeSpecified = true, AllOrNone = true, AllOrNoneSpecified = true } }; #endregion #region Verify Sync command related elements DataStructures.Sync syncItem = this.GetSyncResult(subject, this.User2Information.InboxCollectionId, null, null, bodyPartPreference); this.VerifyBodyPartElements(syncItem.Email.BodyPart, true, true, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R376"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R376 Site.CaptureRequirementIfIsNull( syncItem.Email.BodyPart.Data, 376, @"[In AllOrNone] When the value is set to 1 (TRUE) and the content has been truncated, the content is not synchronized. "); #endregion #region Verify ItemOperations command related elements DataStructures.ItemOperations itemOperationsItem = this.GetItemOperationsResult(this.User2Information.InboxCollectionId, syncItem.ServerId, null, null, bodyPartPreference, null); this.VerifyBodyPartElements(itemOperationsItem.Email.BodyPart, true, true, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R377"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R377 Site.CaptureRequirementIfIsNull( itemOperationsItem.Email.BodyPart.Data, 377, @"[In AllOrNone] When the value is set to 1 (TRUE) and the content has been truncated, the content is not retrieved. "); #endregion if (Common.IsRequirementEnabled(53, this.Site)) { #region Verify Search command related elements DataStructures.Search searchItem = this.GetSearchResult(subject, this.User2Information.InboxCollectionId, itemOperationsItem.Email.ConversationId, null, bodyPartPreference); this.VerifyBodyPartElements(searchItem.Email.BodyPart, true, true, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R375"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R375 Site.CaptureRequirementIfIsNull( searchItem.Email.BodyPart.Data, 375, @"[In AllOrNone] When the value is set to 1 (TRUE) and the content has been truncated, the content is not searched. "); #endregion } #region Verify common requirements // According to above steps, requirement MS-ASAIRS_R63 can be covered directly // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R63"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R63 Site.CaptureRequirement( 63, @"[In AllOrNone (BodyPartPreference)] But, if the client also includes the AllOrNone element with a value of 1 (TRUE) along with the TruncationSize element, it is instructing the server not to return a truncated response for that type when the size (in bytes) of the available data exceeds the value of the TruncationSize element."); #endregion } #endregion #region MSASAIRS_S01_TC03_BodyPartPreference_AllOrNoneFalse_TruncatedContentReturned /// <summary> /// This case is designed to test when the value of the AllOrNone (BodyPartPreference) element is set to 0 (FALSE) and the available data exceeds the value of the TruncationSize element, the truncated content is synchronized, searched or retrieved. /// </summary> [TestCategory("MSASAIRS"), TestMethod()] public void MSASAIRS_S01_TC03_BodyPartPreference_AllOrNoneFalse_TruncatedContentReturned() { Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The BodyPartPreference element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); Site.Assume.AreNotEqual<string>("14.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The BodyPartPreference element is not supported when the MS-ASProtocolVersion header is set to 14.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); #region Send an html email and get the non-truncated data string subject = Common.GenerateResourceName(Site, "Subject"); string body = Common.GenerateResourceName(Site, "Body"); this.SendEmail(EmailType.HTML, subject, body); this.GetAllContentItem(subject, this.User2Information.InboxCollectionId); XmlElement lastRawResponse = (XmlElement)this.ASAIRSAdapter.LastRawResponseXml; string allData = TestSuiteHelper.GetDataInnerText(lastRawResponse, "BodyPart", "Data", subject); #endregion #region Set BodyPartPreference element Request.BodyPartPreference[] bodyPartPreference = new Request.BodyPartPreference[] { new Request.BodyPartPreference() { Type = 2, TruncationSize = 8, TruncationSizeSpecified = true, AllOrNone = false, AllOrNoneSpecified = true } }; #endregion #region Verify Sync command related elements DataStructures.Sync syncItem = this.GetSyncResult(subject, this.User2Information.InboxCollectionId, null, null, bodyPartPreference); lastRawResponse = (XmlElement)this.ASAIRSAdapter.LastRawResponseXml; this.VerifyBodyPartElements(syncItem.Email.BodyPart, false, true, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R378"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R378 Site.CaptureRequirementIfAreEqual<string>( TestSuiteHelper.TruncateData(allData, (int)bodyPartPreference[0].TruncationSize), TestSuiteHelper.GetDataInnerText(lastRawResponse, "BodyPart", "Data", subject), 378, @"[In AllOrNone] When the value is set to 0 (FALSE), the truncated is synchronized. "); #endregion #region Verify ItemOperations command related elements DataStructures.ItemOperations itemOperationsItem = this.GetItemOperationsResult(this.User2Information.InboxCollectionId, syncItem.ServerId, null, null, bodyPartPreference, null); lastRawResponse = (XmlElement)this.ASAIRSAdapter.LastRawResponseXml; this.VerifyBodyPartElements(itemOperationsItem.Email.BodyPart, false, true, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R379"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R379 Site.CaptureRequirementIfAreEqual<string>( TestSuiteHelper.TruncateData(allData, (int)bodyPartPreference[0].TruncationSize), TestSuiteHelper.GetDataInnerText(lastRawResponse, "BodyPart", "Data", subject), 379, @"[In AllOrNone] When the value is set to 0 (FALSE), the truncated is retrieved. "); #endregion if (Common.IsRequirementEnabled(53, this.Site)) { #region Verify Search command related elements DataStructures.Search searchItem = this.GetSearchResult(subject, this.User2Information.InboxCollectionId, itemOperationsItem.Email.ConversationId, null, bodyPartPreference); lastRawResponse = (XmlElement)this.ASAIRSAdapter.LastRawResponseXml; this.VerifyBodyPartElements(searchItem.Email.BodyPart, false, true, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R55"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R55 Site.CaptureRequirementIfAreEqual<string>( TestSuiteHelper.TruncateData(allData, (int)bodyPartPreference[0].TruncationSize), TestSuiteHelper.GetDataInnerText(lastRawResponse, "BodyPart", "Data", subject), 55, @"[In AllOrNone] When the value is set to 0 (FALSE), the truncated is searched. "); #endregion } #region Verify requirement // According to above steps, requirement MS-ASAIRS_R188 can be captured directly // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R188"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R188 Site.CaptureRequirement( 188, @"[In Data (BodyPart)] If the Truncated element (section 2.2.2.39.2) is included in the response, then the data in the Data element is truncated."); #endregion } #endregion #region MSASAIRS_S01_TC04_BodyPartPreference_AllOrNoneFalse_NonTruncatedContentReturned /// <summary> /// This case is designed to test when the value of the AllOrNone (BodyPartPreference) element is set to 0 (FALSE) and the available data doesn't exceed the value of the TruncationSize element, the non-truncated content will be synchronized, searched or retrieved. /// </summary> [TestCategory("MSASAIRS"), TestMethod()] public void MSASAIRS_S01_TC04_BodyPartPreference_AllOrNoneFalse_NonTruncatedContentReturned() { Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The BodyPartPreference element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); Site.Assume.AreNotEqual<string>("14.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The BodyPartPreference element is not supported when the MS-ASProtocolVersion header is set to 14.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); #region Send an html email and get the non-truncated data string subject = Common.GenerateResourceName(Site, "Subject"); string body = Common.GenerateResourceName(Site, "Body"); this.SendEmail(EmailType.HTML, subject, body); DataStructures.Sync allContentItem = this.GetAllContentItem(subject, this.User2Information.InboxCollectionId); #endregion #region Set BodyPartPreference element Request.BodyPartPreference[] bodyPartPreference = new Request.BodyPartPreference[] { new Request.BodyPartPreference() { Type = 2, TruncationSize = 100, TruncationSizeSpecified = true, AllOrNone = false, AllOrNoneSpecified = true } }; #endregion #region Verify Sync command related elements DataStructures.Sync syncItem = this.GetSyncResult(subject, this.User2Information.InboxCollectionId, null, null, bodyPartPreference); this.VerifyBodyPartElements(syncItem.Email.BodyPart, false, false, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R381"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R381 Site.CaptureRequirementIfAreEqual<string>( allContentItem.Email.BodyPart.Data, syncItem.Email.BodyPart.Data, 381, @"[In AllOrNone] When the value is set to 0 (FALSE), the nontruncated content is synchronized. "); #endregion #region Verify ItemOperations command related elements DataStructures.ItemOperations itemOperationsItem = this.GetItemOperationsResult(this.User2Information.InboxCollectionId, syncItem.ServerId, null, null, bodyPartPreference, null); this.VerifyBodyPartElements(itemOperationsItem.Email.BodyPart, false, false, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R382"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R382 Site.CaptureRequirementIfAreEqual<string>( allContentItem.Email.BodyPart.Data, itemOperationsItem.Email.BodyPart.Data, 382, @"[In AllOrNone] When the value is set to 0 (FALSE), the nontruncated content is retrieved. "); #endregion if (Common.IsRequirementEnabled(53, this.Site)) { #region Verify Search command related elements DataStructures.Search searchItem = this.GetSearchResult(subject, this.User2Information.InboxCollectionId, itemOperationsItem.Email.ConversationId, null, bodyPartPreference); this.VerifyBodyPartElements(searchItem.Email.BodyPart, false, false, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R380"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R380 Site.CaptureRequirementIfAreEqual<string>( allContentItem.Email.BodyPart.Data, searchItem.Email.BodyPart.Data, 380, @"[In AllOrNone] When the value is set to 0 (FALSE), the nontruncated content is searched. "); #endregion } } #endregion #region MSASAIRS_S01_TC05_BodyPartPreference_NoAllOrNone_TruncatedContentReturned /// <summary> /// This case is designed to test if the AllOrNone (BodyPartPreference) element is not included in the request and the available data exceeds the value of the TruncationSize element, the truncated content synchronized, searched or retrieved as if the value was set to 0 (FALSE). /// </summary> [TestCategory("MSASAIRS"), TestMethod()] public void MSASAIRS_S01_TC05_BodyPartPreference_NoAllOrNone_TruncatedContentReturned() { Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The BodyPartPreference element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); Site.Assume.AreNotEqual<string>("14.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The BodyPartPreference element is not supported when the MS-ASProtocolVersion header is set to 14.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); #region Send an html email and get the non-truncated data string subject = Common.GenerateResourceName(Site, "Subject"); string body = Common.GenerateResourceName(Site, "Body"); this.SendEmail(EmailType.HTML, subject, body); this.GetAllContentItem(subject, this.User2Information.InboxCollectionId); XmlElement lastRawResponse = (XmlElement)this.ASAIRSAdapter.LastRawResponseXml; string allData = TestSuiteHelper.GetDataInnerText(lastRawResponse, "BodyPart", "Data", subject); #endregion #region Set BodyPreference element Request.BodyPartPreference[] bodyPartPreference = new Request.BodyPartPreference[] { new Request.BodyPartPreference() { Type = 2, TruncationSize = 8, TruncationSizeSpecified = true } }; #endregion #region Verify Sync command related elements DataStructures.Sync syncItem = this.GetSyncResult(subject, this.User2Information.InboxCollectionId, null, null, bodyPartPreference); lastRawResponse = (XmlElement)this.ASAIRSAdapter.LastRawResponseXml; this.VerifyBodyPartElements(syncItem.Email.BodyPart, null, true, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R407"); // Verify MS-ASAIRS requirement: Verify MS-ASAIRS_R407 Site.CaptureRequirementIfAreEqual<string>( TestSuiteHelper.TruncateData(allData, (int)bodyPartPreference[0].TruncationSize), TestSuiteHelper.GetDataInnerText(lastRawResponse, "BodyPart", "Data", subject), 407, @"[In AllOrNone (BodyPartPreference)] If the AllOrNone element is not included in the request, the truncated synchronized as if the value was set to 0 (FALSE)."); #endregion #region Verify ItemOperations command related elements DataStructures.ItemOperations itemOperationsItem = this.GetItemOperationsResult(this.User2Information.InboxCollectionId, syncItem.ServerId, null, null, bodyPartPreference, null); lastRawResponse = (XmlElement)this.ASAIRSAdapter.LastRawResponseXml; this.VerifyBodyPartElements(itemOperationsItem.Email.BodyPart, null, true, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R408"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R408 Site.CaptureRequirementIfAreEqual<string>( TestSuiteHelper.TruncateData(allData, (int)bodyPartPreference[0].TruncationSize), TestSuiteHelper.GetDataInnerText(lastRawResponse, "BodyPart", "Data", subject), 408, @"[In AllOrNone (BodyPartPreference)] If the AllOrNone element is not included in the request, the truncated retrieved as if the value was set to 0 (FALSE)."); #endregion if (Common.IsRequirementEnabled(53, this.Site)) { #region Verify Search command related elements DataStructures.Search searchItem = this.GetSearchResult(subject, this.User2Information.InboxCollectionId, itemOperationsItem.Email.ConversationId, null, bodyPartPreference); lastRawResponse = (XmlElement)this.ASAIRSAdapter.LastRawResponseXml; this.VerifyBodyPartElements(searchItem.Email.BodyPart, null, true, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R392"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R392 Site.CaptureRequirementIfAreEqual<string>( TestSuiteHelper.TruncateData(allData, (int)bodyPartPreference[0].TruncationSize), TestSuiteHelper.GetDataInnerText(lastRawResponse, "BodyPart", "Data", subject), 392, @"[In AllOrNone (BodyPartPreference)] If the AllOrNone element is not included in the request, the truncated searched as if the value was set to 0 (FALSE)."); #endregion } #region Verify common requirements // According to above steps, requirements MS-ASAIRS_R62 and MS-ASAIRS_R282 can be captured directly // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R62"); // Verify MS-ASAIRS requirement: Verify MS-ASAIRS_R62 Site.CaptureRequirement( 62, @"[In AllOrNone (BodyPartPreference)] [A client can include multiple BodyPartPreference elements in a command request with different values for the Type element] By default, the server returns the data truncated to the size requested by TruncationSize for the Type element that matches the native storage format of the item's Body element (section 2.2.2.9)."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R282"); // Verify MS-ASAIRS requirement: Verify MS-ASAIRS_R282 Site.CaptureRequirement( 282, @"[In Truncated (BodyPart)] If the value [of the Truncated element] is TRUE, then the body of the item has been truncated."); #endregion } #endregion #region MSASAIRS_S01_TC06_BodyPartPreference_NoAllOrNone_NonTruncatedContentReturned /// <summary> /// This case is designed to test if the AllOrNone (BodyPartPreference) element is not included in the request and the available data doesn't exceed the value of the TruncationSize element, the non-truncated content will be synchronized, searched or retrieved as if the value was set to 0 (FALSE). /// </summary> [TestCategory("MSASAIRS"), TestMethod()] public void MSASAIRS_S01_TC06_BodyPartPreference_NoAllOrNone_NonTruncatedContentReturned() { Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The BodyPartPreference element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); Site.Assume.AreNotEqual<string>("14.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The BodyPartPreference element is not supported when the MS-ASProtocolVersion header is set to 14.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); #region Send an html email and get the non-truncated data string subject = Common.GenerateResourceName(Site, "Subject"); string body = Common.GenerateResourceName(Site, "Body"); this.SendEmail(EmailType.HTML, subject, body); DataStructures.Sync allContentItem = this.GetAllContentItem(subject, this.User2Information.InboxCollectionId); #endregion #region Set BodyPartPreference element Request.BodyPartPreference[] bodyPartPreference = new Request.BodyPartPreference[] { new Request.BodyPartPreference() { Type = 2, TruncationSize = 100, TruncationSizeSpecified = true } }; #endregion #region Verify Sync command related elements DataStructures.Sync syncItem = this.GetSyncResult(subject, this.User2Information.InboxCollectionId, null, null, bodyPartPreference); this.VerifyBodyPartElements(syncItem.Email.BodyPart, null, false, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R410"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R410 Site.CaptureRequirementIfAreEqual<string>( allContentItem.Email.BodyPart.Data, syncItem.Email.BodyPart.Data, 410, @"[In AllOrNone (BodyPartPreference)] If the AllOrNone element is not included in the request, the nontruncated content is synchronized as if the value was set to 0 (FALSE)."); #endregion #region Verify ItemOperations command related elements DataStructures.ItemOperations itemOperationsItem = this.GetItemOperationsResult(this.User2Information.InboxCollectionId, syncItem.ServerId, null, null, bodyPartPreference, null); this.VerifyBodyPartElements(itemOperationsItem.Email.BodyPart, null, false, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R411"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R411 Site.CaptureRequirementIfAreEqual<string>( allContentItem.Email.BodyPart.Data, itemOperationsItem.Email.BodyPart.Data, 411, @"[In AllOrNone (BodyPartPreference)] If the AllOrNone element is not included in the request, the nontruncated content is retrieved as if the value was set to 0 (FALSE)."); #endregion if (Common.IsRequirementEnabled(53, this.Site)) { #region Verify Search command related elements DataStructures.Search searchItem = this.GetSearchResult(subject, this.User2Information.InboxCollectionId, itemOperationsItem.Email.ConversationId, null, bodyPartPreference); this.VerifyBodyPartElements(searchItem.Email.BodyPart, null, false, true); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R409"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R409 Site.CaptureRequirementIfAreEqual<string>( allContentItem.Email.BodyPart.Data, searchItem.Email.BodyPart.Data, 409, @"[In AllOrNone (BodyPartPreference)] If the AllOrNone element is not included in the request, the nontruncated content is searched as if the value was set to 0 (FALSE)."); #endregion } #region Verify common requirements // According to above steps, requirement MS-ASAIRS_R283 can be captured directly // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R283"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R283 Site.CaptureRequirement( 283, @"[In Truncated (BodyPart)] If the value [of the Truncated element] is FALSE, or there is no Truncated element, then the body of the item has not been truncated."); #endregion } #endregion #region MSASAIRS_S01_TC07_BodyPartPreference_NotIncludedTruncationSize /// <summary> /// This case is designed to test if the TruncationSize (BodyPartPreference) element is not included, the server will return the same response no matter whether AllOrNone is true or false. /// </summary> [TestCategory("MSASAIRS"), TestMethod()] public void MSASAIRS_S01_TC07_BodyPartPreference_NotIncludedTruncationSize() { Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The BodyPartPreference element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); Site.Assume.AreNotEqual<string>("14.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The BodyPartPreference element is not supported when the MS-ASProtocolVersion header is set to 14.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); #region Send an html email and get the non-truncated data string subject = Common.GenerateResourceName(Site, "Subject"); string body = Common.GenerateResourceName(Site, "Body"); this.SendEmail(EmailType.HTML, subject, body); DataStructures.Sync allContentItem = this.GetAllContentItem(subject, this.User2Information.InboxCollectionId); #endregion #region Set BodyPartPreference element Request.BodyPartPreference[] bodyPartPreferenceAllOrNoneTrue = new Request.BodyPartPreference[] { new Request.BodyPartPreference() { Type = 2, AllOrNone = true, AllOrNoneSpecified = true } }; Request.BodyPartPreference[] bodyPartPreferenceAllOrNoneFalse = new Request.BodyPartPreference[] { new Request.BodyPartPreference() { Type = 2, AllOrNone = false, AllOrNoneSpecified = true } }; #endregion #region Verify Sync command related elements // Call Sync command with AllOrNone setting to TRUE DataStructures.Sync syncItemAllOrNoneTrue = this.GetSyncResult(subject, this.User2Information.InboxCollectionId, null, null, bodyPartPreferenceAllOrNoneTrue); this.VerifyBodyPartElements(syncItemAllOrNoneTrue.Email.BodyPart, true, false, false); // Call Sync command with AllOrNone setting to FALSE DataStructures.Sync syncItemAllOrNoneFalse = this.GetSyncResult(subject, this.User2Information.InboxCollectionId, null, null, bodyPartPreferenceAllOrNoneFalse); this.VerifyBodyPartElements(syncItemAllOrNoneFalse.Email.BodyPart, false, false, false); Site.Log.Add( LogEntryKind.Debug, "Entire content: {0}, content for AllOrNone TRUE: {1}, content for AllOrNone FALSE: {2}.", allContentItem.Email.BodyPart.Data, syncItemAllOrNoneTrue.Email.BodyPart.Data, syncItemAllOrNoneFalse.Email.BodyPart.Data); Site.Assert.IsTrue( allContentItem.Email.BodyPart.Data == syncItemAllOrNoneTrue.Email.BodyPart.Data && syncItemAllOrNoneTrue.Email.BodyPart.Data == syncItemAllOrNoneFalse.Email.BodyPart.Data, "Server should return the entire content for the request and same response no matter AllOrNone is true or false if the TruncationSize element is absent in Sync command request."); #endregion #region Verify ItemOperations command related elements // Call ItemOperations command with AllOrNone setting to true DataStructures.ItemOperations itemOperationsItemAllOrNoneTrue = this.GetItemOperationsResult(this.User2Information.InboxCollectionId, syncItemAllOrNoneTrue.ServerId, null, null, bodyPartPreferenceAllOrNoneTrue, null); this.VerifyBodyPartElements(itemOperationsItemAllOrNoneTrue.Email.BodyPart, true, false, false); // Call ItemOperations command with AllOrNone setting to false DataStructures.ItemOperations itemOperationsItemAllOrNoneFalse = this.GetItemOperationsResult(this.User2Information.InboxCollectionId, syncItemAllOrNoneTrue.ServerId, null, null, bodyPartPreferenceAllOrNoneFalse, null); this.VerifyBodyPartElements(itemOperationsItemAllOrNoneFalse.Email.BodyPart, false, false, false); Site.Log.Add( LogEntryKind.Debug, "Entire content: {0}, content for AllOrNone TRUE: {1}, content for AllOrNone FALSE: {2}.", allContentItem.Email.BodyPart.Data, itemOperationsItemAllOrNoneTrue.Email.BodyPart.Data, itemOperationsItemAllOrNoneFalse.Email.BodyPart.Data); Site.Assert.IsTrue( allContentItem.Email.BodyPart.Data == itemOperationsItemAllOrNoneTrue.Email.BodyPart.Data && itemOperationsItemAllOrNoneTrue.Email.BodyPart.Data == itemOperationsItemAllOrNoneFalse.Email.BodyPart.Data, "Server should return the entire content for the request and same response no matter AllOrNone is true or false if the TruncationSize element is absent in ItemOperations command request."); #endregion if (Common.IsRequirementEnabled(53, this.Site)) { #region Verify Search command related elements // Call Search command with AllOrNone setting to true DataStructures.Search searchItemAllNoneTrue = this.GetSearchResult(subject, this.User2Information.InboxCollectionId, itemOperationsItemAllOrNoneTrue.Email.ConversationId, null, bodyPartPreferenceAllOrNoneTrue); this.VerifyBodyPartElements(searchItemAllNoneTrue.Email.BodyPart, true, false, false); // Call Search command with AllOrNone setting to false DataStructures.Search searchItemAllNoneFalse = this.GetSearchResult(subject, this.User2Information.InboxCollectionId, itemOperationsItemAllOrNoneTrue.Email.ConversationId, null, bodyPartPreferenceAllOrNoneFalse); this.VerifyBodyPartElements(searchItemAllNoneFalse.Email.BodyPart, false, false, false); Site.Log.Add( LogEntryKind.Debug, "Entire content: {0}, content for AllOrNone TRUE: {1}, content for AllOrNone FALSE: {2}.", allContentItem.Email.BodyPart.Data, searchItemAllNoneTrue.Email.BodyPart.Data, searchItemAllNoneFalse.Email.BodyPart.Data); Site.Assert.IsTrue( allContentItem.Email.BodyPart.Data == searchItemAllNoneTrue.Email.BodyPart.Data && searchItemAllNoneTrue.Email.BodyPart.Data == searchItemAllNoneFalse.Email.BodyPart.Data, "Server should return the entire content for the request and same response no matter AllOrNone is true or false if the TruncationSize element is absent in Search command request."); #endregion } #region Verify requirements // According to above steps, requirements MS-ASAIRS_R294 and MS-ASAIRS_R400 can be captured directly // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R294"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R294 Site.CaptureRequirement( 294, @"[In TruncationSize (BodyPartPreference)] If the TruncationSize element is absent, the entire content is used for the request."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R400"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R400 Site.CaptureRequirement( 400, @"[In AllOrNone (BodyPartPreference)] If the TruncationSize element is not included, the server will return the same response no matter whether AllOrNone is true or false."); #endregion } #endregion #region MSASAIRS_S01_TC08_BodyPart_Preview /// <summary> /// This case is designed to test the Preview (BodyPart) element which contains the Unicode plain text message or message part preview returned to the client. /// </summary> [TestCategory("MSASAIRS"), TestMethod()] public void MSASAIRS_S01_TC08_BodyPart_Preview() { Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The BodyPartPreference element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); Site.Assume.AreNotEqual<string>("14.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The BodyPartPreference element is not supported when the MS-ASProtocolVersion header is set to 14.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); #region Send an html email and get the none truncated data string subject = Common.GenerateResourceName(Site, "Subject"); string body = Common.GenerateResourceName(Site, "Body"); this.SendEmail(EmailType.HTML, subject, body); DataStructures.Sync allContentItem = this.GetAllContentItem(subject, this.User2Information.InboxCollectionId); #endregion #region Set BodyPartPreference element Request.BodyPartPreference[] bodyPartPreference = new Request.BodyPartPreference[] { new Request.BodyPartPreference() { Type = 2, Preview = 18, PreviewSpecified = true } }; #endregion #region Verify Sync command related elements DataStructures.Sync syncItem = this.GetSyncResult(subject, this.User2Information.InboxCollectionId, null, null, bodyPartPreference); this.VerifyBodyPartPreview(syncItem.Email, allContentItem.Email, bodyPartPreference); #endregion #region Verify ItemOperations command related elements DataStructures.ItemOperations itemOperationsItem = this.GetItemOperationsResult(this.User2Information.InboxCollectionId, syncItem.ServerId, null, null, bodyPartPreference, null); this.VerifyBodyPartPreview(itemOperationsItem.Email, allContentItem.Email, bodyPartPreference); #endregion if (Common.IsRequirementEnabled(53, this.Site)) { #region Verify Search command related elements DataStructures.Search searchItem = this.GetSearchResult(subject, this.User2Information.InboxCollectionId, itemOperationsItem.Email.ConversationId, null, bodyPartPreference); this.VerifyBodyPartPreview(searchItem.Email, allContentItem.Email, bodyPartPreference); #endregion } #region Verify requirements // According to above steps, the following requirements can be captured directly // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R256"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R256 Site.CaptureRequirement( 256, @"[In Preview (BodyPart)] The Preview element MUST be present in a command response if a BodyPartPreference element (section 2.2.2.11) in the request included a Preview element and the server can honor the request."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R253"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R253 Site.CaptureRequirement( 253, @"[In Preview (BodyPart)] The Preview element is an optional child element of the BodyPart element (section 2.2.2.10) that contains the Unicode plain text message or message part preview returned to the client."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R255"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R255 Site.CaptureRequirement( 255, @"[In Preview (BodyPart)] The Preview element in a response MUST contain no more than the number of characters specified in the request."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R2599"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R2599 Site.CaptureRequirement( 2599, @"[In Preview (BodyPartPreference)] [The Preview element] specifies the maximum length of the Unicode plain text message or message part preview to be returned to the client."); #endregion } #endregion #region Private methods /// <summary> /// Verify elements in BodyPart element. /// </summary> /// <param name="bodyPart">The body part of item.</param> /// <param name="allOrNone">The value of AllOrNone element, "null" means the AllOrNone element is not present in request.</param> /// <param name="truncated">Whether the content is truncated.</param> /// <param name="includedTruncationSize">Whether includes the TruncationSize element.</param> private void VerifyBodyPartElements(BodyPart bodyPart, bool? allOrNone, bool truncated, bool includedTruncationSize) { Site.Assert.IsNotNull( bodyPart, "The BodyPart element should be included in response when the BodyPartPreference element is specified in request."); Site.Assert.AreEqual<byte>( 1, bodyPart.Status, "The Status should be 1 to indicate the success of the response in returning Data element content given the BodyPartPreference element settings in the request."); // Verify elements when TruncationSize element is absent if (!includedTruncationSize) { Site.Assert.IsTrue( !bodyPart.TruncatedSpecified || (bodyPart.TruncatedSpecified && !bodyPart.Truncated), "The data should not be truncated when the TruncationSize element is absent."); // Since the AllOrNone will be ignored when TruncationSize is not included in request, return if includedTruncationSize is false return; } if (truncated) { Site.Assert.IsTrue( bodyPart.Truncated, "The data should be truncated when the AllOrNone element value is {0} in the request and the available data exceeds the truncation size.", allOrNone); } else { Site.Assert.IsTrue( !bodyPart.TruncatedSpecified || (bodyPart.TruncatedSpecified && !bodyPart.Truncated), "The data should not be truncated when the AllOrNone element value is {0} in the request and the truncation size exceeds the available data.", allOrNone); } if (bodyPart.Truncated) { if (Common.IsRequirementEnabled(403, this.Site)) { // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R403"); // Since the EstimatedDataSize element provides an informational estimate of the size of the data associated with the parent element and the body is not null, if the Truncated value is true, the EstimatedDataSize value should not be 0, then requirement MS-ASAIRS_R403 can be captured. // Verify MS-ASAIRS requirement: MS-ASAIRS_R403 Site.CaptureRequirementIfAreNotEqual<uint>( 0, bodyPart.EstimatedDataSize, 403, @"[In Appendix B: Product Behavior] Implementation does include the EstimatedDataSize (BodyPart) element in a response message whenever the Truncated element is set to TRUE. (Exchange Server 2007 SP1 and above follow this behavior.)"); } } } /// <summary> /// Verify the Preview element in BodyPart element. /// </summary> /// <param name="email">The email item got from server.</param> /// <param name="allContentEmail">The email item which has full content.</param> /// <param name="bodyPartPreference">A BodyPartPreference object.</param> private void VerifyBodyPartPreview(DataStructures.Email email, DataStructures.Email allContentEmail, Request.BodyPartPreference[] bodyPartPreference) { Site.Assert.IsNotNull( email.BodyPart, "The BodyPart element should be included in command response when the BodyPartPreference element is specified in command request."); Site.Assert.AreEqual<byte>( 1, email.BodyPart.Status, "The Status should be 1 to indicate the success of the command response in returning Data element content given the BodyPartPreference element settings in the command request."); Site.Assert.IsNotNull( email.BodyPart.Preview, "The Preview element should be present in response if a BodyPartPreference element in the request included a Preview element and the server can honor the request."); Site.Assert.IsTrue( email.BodyPart.Preview.Length <= bodyPartPreference[0].Preview, "The Preview element in a response should contain no more than the number of characters specified in the request. The length of Preview element in response is: {0}.", email.BodyPart.Preview.Length); Site.Assert.IsTrue( allContentEmail.BodyPart.Data.Contains(email.BodyPart.Preview), "The Preview element in a response should contain the message part preview returned to the client."); } #endregion } }
// 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. - [email protected]) 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> /// Section 5.3.12.10: issued in response to a data query R or set dataR pdu. Needs manual intervention to fix padding on variable datums. UNFINSIHED /// </summary> [Serializable] [XmlRoot] [XmlInclude(typeof(FixedDatum))] [XmlInclude(typeof(VariableDatum))] public partial class DataReliablePdu : SimulationManagementWithReliabilityFamilyPdu, IEquatable<DataReliablePdu> { /// <summary> /// Request ID /// </summary> private uint _requestID; /// <summary> /// level of reliability service used for this transaction /// </summary> private byte _requiredReliabilityService; /// <summary> /// padding /// </summary> private ushort _pad1; /// <summary> /// padding /// </summary> private byte _pad2; /// <summary> /// Fixed datum record count /// </summary> private uint _numberOfFixedDatumRecords; /// <summary> /// variable datum record count /// </summary> private uint _numberOfVariableDatumRecords; /// <summary> /// Fixed datum records /// </summary> private List<FixedDatum> _fixedDatumRecords = new List<FixedDatum>(); /// <summary> /// Variable datum records /// </summary> private List<VariableDatum> _variableDatumRecords = new List<VariableDatum>(); /// <summary> /// Initializes a new instance of the <see cref="DataReliablePdu"/> class. /// </summary> public DataReliablePdu() { PduType = (byte)60; } /// <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 !=(DataReliablePdu left, DataReliablePdu 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 ==(DataReliablePdu left, DataReliablePdu right) { if (object.ReferenceEquals(left, right)) { return true; } if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } public override int GetMarshalledSize() { int marshalSize = 0; marshalSize = base.GetMarshalledSize(); marshalSize += 4; // this._requestID marshalSize += 1; // this._requiredReliabilityService marshalSize += 2; // this._pad1 marshalSize += 1; // this._pad2 marshalSize += 4; // this._numberOfFixedDatumRecords marshalSize += 4; // this._numberOfVariableDatumRecords for (int idx = 0; idx < this._fixedDatumRecords.Count; idx++) { FixedDatum listElement = (FixedDatum)this._fixedDatumRecords[idx]; marshalSize += listElement.GetMarshalledSize(); } for (int idx = 0; idx < this._variableDatumRecords.Count; idx++) { VariableDatum listElement = (VariableDatum)this._variableDatumRecords[idx]; marshalSize += listElement.GetMarshalledSize(); } return marshalSize; } /// <summary> /// Gets or sets the Request ID /// </summary> [XmlElement(Type = typeof(uint), ElementName = "requestID")] public uint RequestID { get { return this._requestID; } set { this._requestID = value; } } /// <summary> /// Gets or sets the level of reliability service used for this transaction /// </summary> [XmlElement(Type = typeof(byte), ElementName = "requiredReliabilityService")] public byte RequiredReliabilityService { get { return this._requiredReliabilityService; } set { this._requiredReliabilityService = value; } } /// <summary> /// Gets or sets the padding /// </summary> [XmlElement(Type = typeof(ushort), ElementName = "pad1")] public ushort Pad1 { get { return this._pad1; } set { this._pad1 = value; } } /// <summary> /// Gets or sets the padding /// </summary> [XmlElement(Type = typeof(byte), ElementName = "pad2")] public byte Pad2 { get { return this._pad2; } set { this._pad2 = value; } } /// <summary> /// Gets or sets the Fixed datum record count /// </summary> /// <remarks> /// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose. /// The getnumberOfFixedDatumRecords method will also be based on the actual list length rather than this value. /// The method is simply here for completeness and should not be used for any computations. /// </remarks> [XmlElement(Type = typeof(uint), ElementName = "numberOfFixedDatumRecords")] public uint NumberOfFixedDatumRecords { get { return this._numberOfFixedDatumRecords; } set { this._numberOfFixedDatumRecords = value; } } /// <summary> /// Gets or sets the variable datum record count /// </summary> /// <remarks> /// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose. /// The getnumberOfVariableDatumRecords method will also be based on the actual list length rather than this value. /// The method is simply here for completeness and should not be used for any computations. /// </remarks> [XmlElement(Type = typeof(uint), ElementName = "numberOfVariableDatumRecords")] public uint NumberOfVariableDatumRecords { get { return this._numberOfVariableDatumRecords; } set { this._numberOfVariableDatumRecords = value; } } /// <summary> /// Gets the Fixed datum records /// </summary> [XmlElement(ElementName = "fixedDatumRecordsList", Type = typeof(List<FixedDatum>))] public List<FixedDatum> FixedDatumRecords { get { return this._fixedDatumRecords; } } /// <summary> /// Gets the Variable datum records /// </summary> [XmlElement(ElementName = "variableDatumRecordsList", Type = typeof(List<VariableDatum>))] public List<VariableDatum> VariableDatumRecords { get { return this._variableDatumRecords; } } /// <summary> /// Automatically sets the length of the marshalled data, then calls the marshal method. /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> public override void MarshalAutoLengthSet(DataOutputStream dos) { // Set the length prior to marshalling data this.Length = (ushort)this.GetMarshalledSize(); this.Marshal(dos); } /// <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 override void Marshal(DataOutputStream dos) { base.Marshal(dos); if (dos != null) { try { dos.WriteUnsignedInt((uint)this._requestID); dos.WriteUnsignedByte((byte)this._requiredReliabilityService); dos.WriteUnsignedShort((ushort)this._pad1); dos.WriteUnsignedByte((byte)this._pad2); dos.WriteUnsignedInt((uint)this._fixedDatumRecords.Count); dos.WriteUnsignedInt((uint)this._variableDatumRecords.Count); for (int idx = 0; idx < this._fixedDatumRecords.Count; idx++) { FixedDatum aFixedDatum = (FixedDatum)this._fixedDatumRecords[idx]; aFixedDatum.Marshal(dos); } for (int idx = 0; idx < this._variableDatumRecords.Count; idx++) { VariableDatum aVariableDatum = (VariableDatum)this._variableDatumRecords[idx]; aVariableDatum.Marshal(dos); } } 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 override void Unmarshal(DataInputStream dis) { base.Unmarshal(dis); if (dis != null) { try { this._requestID = dis.ReadUnsignedInt(); this._requiredReliabilityService = dis.ReadUnsignedByte(); this._pad1 = dis.ReadUnsignedShort(); this._pad2 = dis.ReadUnsignedByte(); this._numberOfFixedDatumRecords = dis.ReadUnsignedInt(); this._numberOfVariableDatumRecords = dis.ReadUnsignedInt(); for (int idx = 0; idx < this.NumberOfFixedDatumRecords; idx++) { FixedDatum anX = new FixedDatum(); anX.Unmarshal(dis); this._fixedDatumRecords.Add(anX); } for (int idx = 0; idx < this.NumberOfVariableDatumRecords; idx++) { VariableDatum anX = new VariableDatum(); anX.Unmarshal(dis); this._variableDatumRecords.Add(anX); } } 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 override void Reflection(StringBuilder sb) { sb.AppendLine("<DataReliablePdu>"); base.Reflection(sb); try { sb.AppendLine("<requestID type=\"uint\">" + this._requestID.ToString(CultureInfo.InvariantCulture) + "</requestID>"); sb.AppendLine("<requiredReliabilityService type=\"byte\">" + this._requiredReliabilityService.ToString(CultureInfo.InvariantCulture) + "</requiredReliabilityService>"); sb.AppendLine("<pad1 type=\"ushort\">" + this._pad1.ToString(CultureInfo.InvariantCulture) + "</pad1>"); sb.AppendLine("<pad2 type=\"byte\">" + this._pad2.ToString(CultureInfo.InvariantCulture) + "</pad2>"); sb.AppendLine("<fixedDatumRecords type=\"uint\">" + this._fixedDatumRecords.Count.ToString(CultureInfo.InvariantCulture) + "</fixedDatumRecords>"); sb.AppendLine("<variableDatumRecords type=\"uint\">" + this._variableDatumRecords.Count.ToString(CultureInfo.InvariantCulture) + "</variableDatumRecords>"); for (int idx = 0; idx < this._fixedDatumRecords.Count; idx++) { sb.AppendLine("<fixedDatumRecords" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"FixedDatum\">"); FixedDatum aFixedDatum = (FixedDatum)this._fixedDatumRecords[idx]; aFixedDatum.Reflection(sb); sb.AppendLine("</fixedDatumRecords" + idx.ToString(CultureInfo.InvariantCulture) + ">"); } for (int idx = 0; idx < this._variableDatumRecords.Count; idx++) { sb.AppendLine("<variableDatumRecords" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"VariableDatum\">"); VariableDatum aVariableDatum = (VariableDatum)this._variableDatumRecords[idx]; aVariableDatum.Reflection(sb); sb.AppendLine("</variableDatumRecords" + idx.ToString(CultureInfo.InvariantCulture) + ">"); } sb.AppendLine("</DataReliablePdu>"); } 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 DataReliablePdu; } /// <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(DataReliablePdu obj) { bool ivarsEqual = true; if (obj.GetType() != this.GetType()) { return false; } ivarsEqual = base.Equals(obj); if (this._requestID != obj._requestID) { ivarsEqual = false; } if (this._requiredReliabilityService != obj._requiredReliabilityService) { ivarsEqual = false; } if (this._pad1 != obj._pad1) { ivarsEqual = false; } if (this._pad2 != obj._pad2) { ivarsEqual = false; } if (this._numberOfFixedDatumRecords != obj._numberOfFixedDatumRecords) { ivarsEqual = false; } if (this._numberOfVariableDatumRecords != obj._numberOfVariableDatumRecords) { ivarsEqual = false; } if (this._fixedDatumRecords.Count != obj._fixedDatumRecords.Count) { ivarsEqual = false; } if (ivarsEqual) { for (int idx = 0; idx < this._fixedDatumRecords.Count; idx++) { if (!this._fixedDatumRecords[idx].Equals(obj._fixedDatumRecords[idx])) { ivarsEqual = false; } } } if (this._variableDatumRecords.Count != obj._variableDatumRecords.Count) { ivarsEqual = false; } if (ivarsEqual) { for (int idx = 0; idx < this._variableDatumRecords.Count; idx++) { if (!this._variableDatumRecords[idx].Equals(obj._variableDatumRecords[idx])) { 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) ^ base.GetHashCode(); result = GenerateHash(result) ^ this._requestID.GetHashCode(); result = GenerateHash(result) ^ this._requiredReliabilityService.GetHashCode(); result = GenerateHash(result) ^ this._pad1.GetHashCode(); result = GenerateHash(result) ^ this._pad2.GetHashCode(); result = GenerateHash(result) ^ this._numberOfFixedDatumRecords.GetHashCode(); result = GenerateHash(result) ^ this._numberOfVariableDatumRecords.GetHashCode(); if (this._fixedDatumRecords.Count > 0) { for (int idx = 0; idx < this._fixedDatumRecords.Count; idx++) { result = GenerateHash(result) ^ this._fixedDatumRecords[idx].GetHashCode(); } } if (this._variableDatumRecords.Count > 0) { for (int idx = 0; idx < this._variableDatumRecords.Count; idx++) { result = GenerateHash(result) ^ this._variableDatumRecords[idx].GetHashCode(); } } return result; } } }
/* FluorineFx open source library Copyright (C) 2007 Zoltan Csibi, [email protected], FluorineFx.com This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; using System.Collections; namespace FluorineFx.Collections { /// <summary> /// Red-black tree, an almost balanced binary tree. /// </summary> /// <remarks>Red-black tree remains "almost balanced" when nodes /// are added or removed. See "Introduction to Algorithms" by T. Cormen at al. /// (ISBN 0262032937) or your favorite computer science text book for details.</remarks> public class RbTree { private RbTreeNode _root; // sentinel, not a real root; real root is _root.Left private IComparer _comparer; /// <summary> /// Logical root node of the tree. /// </summary> /// <remarks> /// RbTreeNode.Nil if the tree is empty. /// </remarks> public RbTreeNode Root { get { return _root.Left; } } /// <summary> /// Comparer used in comparisons between nodes. /// </summary> public IComparer Comparer { get { return _comparer; } } /// <summary> /// Result of insertion into a red-black tree. /// </summary> public struct InsertResult { /// <summary> /// true if new node was inserted, false if old node was used. /// </summary> public bool NewNode; /// <summary> /// Value of inserted or replaced node. /// </summary> public RbTreeNode Node; /// <summary> /// Creates new instance of InsertResult. /// </summary> public InsertResult(bool newNode, RbTreeNode node) { NewNode = newNode; Node = node; } } /// <summary> /// Creates a new instance of a red-black tree. /// </summary> public RbTree(IComparer comparer) { _root = new RbTreeNode(null); _root.IsRed = false; _comparer = comparer; } /// <summary> /// Inserts item based only on its value, probably violating Left/Right property. /// </summary> /// <param name="z">Node to insert.</param> /// /// <param name="allowDuplicates">If true, will insert the node even if equal node /// already exists in the tree. If false, behavior depends on replaceIfDuplicate. /// </param> /// /// <param name="replaceIfDuplicate">Matters only if node equal to z exists in the /// tree and allowDuplicates is false. If replaceIfDuplicate is true, z replaces /// existing node. Otherwise, tree does not change. /// </param> /// <returns> /// result.NewNode is true if new node was inserted to the tree' /// result.Node contains newly inserted node if any, or node equal to z /// </returns> /// private InsertResult BinaryInsert(RbTreeNode z, bool allowDuplicates, bool replaceIfDuplicate) { z.Left = RbTreeNode.Nil; z.Right = RbTreeNode.Nil; RbTreeNode y = _root; RbTreeNode x = _root.Left; while (x != RbTreeNode.Nil) { y = x; int result = _comparer.Compare(x.Value, z.Value); if (!allowDuplicates && (result == 0)) { if (replaceIfDuplicate) { x.Value = z.Value; } return new InsertResult(false, x); } if (result > 0) // x.Value > z.Value { x = x.Left; } else { x = x.Right; } } z.Parent = y; if ((y == _root) || (_comparer.Compare(y.Value, z.Value) > 0)) { y.Left = z; } else { y.Right = z; } z.Parent = y; return new InsertResult(true, z); } /// <summary> /// Left rotation of the tree around x. /// </summary> private void LeftRotate(RbTreeNode x) { RbTreeNode y = x.Right; x.Right = y.Left; if (y.Left != RbTreeNode.Nil) y.Left.Parent = x; y.Parent = x.Parent; if (x == x.Parent.Left) { x.Parent.Left = y; } else { x.Parent.Right = y; } y.Left = x; x.Parent = y; } /// <summary> /// Right rotation of the tree around y. /// </summary> static private void RightRotate(RbTreeNode y) { RbTreeNode x = y.Left; y.Left = x.Right; if (x.Right != RbTreeNode.Nil) { x.Right.Parent = y; } x.Parent = y.Parent; if (y == y.Parent.Left) { y.Parent.Left = x; } else { y.Parent.Right = x; } x.Right = y; y.Parent = x; } /// <summary> /// Inserts object into the tree. /// </summary> /// <param name="val">Value to insert.</param> /// /// <param name="allowDuplicates">If true, will create a new node even if equal node /// already exists in the tree. If false, behavior depends on replaceIfDuplicate. /// </param> /// /// <param name="replaceIfDuplicate">Matters only if node equal to val exists in the /// tree and allowDuplicates is false. If replaceIfDuplicate is true, val replaces /// value of existing node. Otherwise, tree does not change. /// </param> /// <returns> /// <list type="table"> /// <item><term>result.NewNode</term><description>true if new node was inserted to the tree</description></item> /// <item><term>result.Node</term><description>contains newly inserted node if any, or node equal to val</description> </item> /// </list> /// </returns> public InsertResult Insert(object val, bool allowDuplicates, bool replaceIfDuplicate) { RbTreeNode newNode = new RbTreeNode(val); InsertResult result = BinaryInsert(newNode, allowDuplicates, replaceIfDuplicate); if (!result.NewNode) return result; RbTreeNode x = newNode; x.IsRed = true; while (x.Parent.IsRed) { if (x.Parent == x.Parent.Parent.Left) { RbTreeNode y = x.Parent.Parent.Right; if (y.IsRed) { x.Parent.IsRed = false; y.IsRed = false; x.Parent.Parent.IsRed = true; x = x.Parent.Parent; } else { if (x == x.Parent.Right) { x = x.Parent; LeftRotate(x); } x.Parent.IsRed = false; x.Parent.Parent.IsRed = true; RightRotate(x.Parent.Parent); } } else { /* case for x.Parent == x.Parent.Parent.Right */ RbTreeNode y = x.Parent.Parent.Left; if (y.IsRed) { x.Parent.IsRed = false; y.IsRed = false; x.Parent.Parent.IsRed = true; x = x.Parent.Parent; } else { if (x == x.Parent.Left) { x = x.Parent; RightRotate(x); } x.Parent.IsRed = false; x.Parent.Parent.IsRed = true; LeftRotate(x.Parent.Parent); } } } _root.Left.IsRed = false; return new InsertResult(true, newNode); } private void DeleteFixUp(RbTreeNode x) { RbTreeNode root = _root.Left; while ((!x.IsRed) && (root != x)) { if (x == x.Parent.Left) { RbTreeNode w = x.Parent.Right; if (w.IsRed) { w.IsRed = false; x.Parent.IsRed = true; LeftRotate(x.Parent); w = x.Parent.Right; } if ((!w.Right.IsRed) && (!w.Left.IsRed)) { w.IsRed = true; x = x.Parent; } else { if (!w.Right.IsRed) { w.Left.IsRed = false; w.IsRed = true; RightRotate(w); w = x.Parent.Right; } w.IsRed = x.Parent.IsRed; x.Parent.IsRed = false; w.Right.IsRed = false; LeftRotate(x.Parent); x = root; /* this is to exit while loop */ } } else { /* the code below is has Left and Right switched from above */ RbTreeNode w = x.Parent.Left; if (w.IsRed) { w.IsRed = false; x.Parent.IsRed = true; RightRotate(x.Parent); w = x.Parent.Left; } if ((!w.Right.IsRed) && (!w.Left.IsRed)) { w.IsRed = true; x = x.Parent; } else { if (!w.Left.IsRed) { w.Right.IsRed = false; w.IsRed = true; LeftRotate(w); w = x.Parent.Left; } w.IsRed = x.Parent.IsRed; x.Parent.IsRed = false; w.Left.IsRed = false; RightRotate(x.Parent); x = root; /* this is to exit while loop */ } } } x.IsRed = false; } /// <summary> /// Logically first node in the tree. /// </summary> /// <remarks> /// RbTreeNode.Nil if the tree is empty. /// </remarks> public RbTreeNode First { get { RbTreeNode x = Root; while (x.Left != RbTreeNode.Nil) { x = x.Left; } return x; } } /// <summary> /// Logically last node in the tree. /// </summary> /// <remarks> /// RbTreeNode.Nil if the tree is empty. /// </remarks> public RbTreeNode Last { get { RbTreeNode x = Root; while (x.Right != RbTreeNode.Nil) { x = x.Right; } return x; } } /// <summary> /// Node in the tree that follows given node. /// </summary> /// <remarks> /// If x is logically last node in the tree, returns RbTreeNode.Nil. /// </remarks> public RbTreeNode Next(RbTreeNode x) { RbTreeNode root = _root; RbTreeNode y = x.Right; if (y != RbTreeNode.Nil) { while (y.Left != RbTreeNode.Nil) { /* returns the minimum of the right subtree of x */ y = y.Left; } return (y); } else { y = x.Parent; while (x == y.Right) { /* sentinel used instead of checking for nil */ x = y; y = y.Parent; } if (y == root) return (RbTreeNode.Nil); return (y); } } /// <summary> /// Node in the tree that precedes given node. /// </summary> /// <remarks> /// If x is logically fisrt node, returns RbTreeNode.Nil. /// </remarks> public RbTreeNode Prev(RbTreeNode x) { RbTreeNode root = _root; RbTreeNode y = x.Left; if (y != RbTreeNode.Nil) { while (y.Right != RbTreeNode.Nil) { /* returns the maximum of the left subtree of x */ y = y.Right; } return (y); } else { y = x.Parent; while (x == y.Left) { if (y == root) return RbTreeNode.Nil; x = y; y = y.Parent; } return (y); } } /// <summary> /// Returns fisrt node whose value is not less than parameter. /// </summary> /// <param name="val">The value to look for.</param> /// <returns>The node, if found, or RbTreeNode.Nil.</returns> public RbTreeNode LowerBound(object val) { RbTreeNode x = Root; RbTreeNode y = RbTreeNode.Nil; // previous value of x while (x != RbTreeNode.Nil) { if (_comparer.Compare(val, x.Value) <= 0) // val <= x.Value { y = x; x = x.Left; } else { x = x.Right; } } return y; } /// <summary> /// Returns first node whose value is strictly greater than parameter. /// </summary> /// <param name="val">The value to look for.</param> /// <returns>The node, if found, or RbTreeNode.Nil.</returns> public RbTreeNode UpperBound(object val) { RbTreeNode x = Root; RbTreeNode y = RbTreeNode.Nil; while (x != RbTreeNode.Nil) { if (_comparer.Compare(val, x.Value) < 0) // val < x.Value { y = x; x = x.Left; } else { x = x.Right; } } return y; } /// <summary> /// Removes node from the tree, re-arranging red-black structure as needed. /// </summary> public void Erase(RbTreeNode z) { RbTreeNode y; RbTreeNode x; RbTreeNode root = _root; if ((z.Left == RbTreeNode.Nil) || (z.Right == RbTreeNode.Nil)) { y = z; } else { y = Next(z); } x = (y.Left == RbTreeNode.Nil) ? y.Right : y.Left; if (_root == (x.Parent = y.Parent)) /* assignment of y.p to x.p is intentional */ { _root.Left = x; } else { if (y == y.Parent.Left) { y.Parent.Left = x; } else { y.Parent.Right = x; } } if (!(y.IsRed)) DeleteFixUp(x); if (y != z) { y.Left = z.Left; y.Right = z.Right; y.Parent = z.Parent; y.IsRed = z.IsRed; z.Left.Parent = z.Right.Parent = y; if (z == z.Parent.Left) { z.Parent.Left = y; } else { z.Parent.Right = y; } } IDisposable zVal = z.Value as IDisposable; if (zVal != null) zVal.Dispose(); } /// <summary> /// Removes object(s) from the tree. /// </summary> /// <param name="val">Object to remove.</param> /// <returns>Number of nodes removed.</returns> /// <remarks> /// Finds and removes all nodes in the tree whose values compare equal to val. /// Returns number of removed nodes (possibly zero). /// </remarks> public int Erase(object val) { RbTreeNode first = LowerBound(val); RbTreeNode last = UpperBound(val); int nDeleted = 0; while (first != last) { RbTreeNode temp = first; first = Next(first); Erase(temp); ++nDeleted; } return nDeleted; } } }
using System; using System.IO; using Jessica.Configuration; using Jessica.Responses; using Jessica.Specs.Fakes.Models; using Machine.Specifications; namespace Jessica.Specs.Responses { public class when_constructing_a_response { Because of = () => _response = new Response(); It should_contain_the_default_status_code = () => _response.StatusCode.ShouldEqual(200); It should_contain_the_default_content_type = () => _response.ContentType.ShouldEqual("text/html"); It should_contain_empty_contents = () => { using (var stream = new MemoryStream()) { _response.Contents.Invoke(stream); stream.Position = 0; var reader = new StreamReader(stream); var contents = reader.ReadToEnd(); contents.ShouldBeEmpty(); } }; It should_contain_an_empty_header_collection = () => _response.Headers.ShouldBeEmpty(); static Response _response; } public class when_constructing_a_response_with_implicit_integer { Because of = () => _response = 304; It should_contain_the_correct_status_code = () => _response.StatusCode.ShouldEqual(304); It should_contain_the_default_content_type = () => _response.ContentType.ShouldEqual("text/html"); It should_contain_empty_contents = () => { using (var stream = new MemoryStream()) { _response.Contents.Invoke(stream); stream.Position = 0; var reader = new StreamReader(stream); var contents = reader.ReadToEnd(); contents.ShouldBeEmpty(); } }; It should_contain_an_empty_header_collection = () => _response.Headers.ShouldBeEmpty(); static Response _response; } public class when_constructing_a_response_with_implicit_string { Because of = () => _response = "Hello, world!"; It should_contain_the_default_status_code = () => _response.StatusCode.ShouldEqual(200); It should_contain_the_default_content_type = () => _response.ContentType.ShouldEqual("text/html"); It should_contain_the_correct_contents = () => { using (var stream = new MemoryStream()) { _response.Contents.Invoke(stream); stream.Position = 0; var reader = new StreamReader(stream); var contents = reader.ReadToEnd(); contents.ShouldContain("Hello, world!"); } }; It should_contain_an_empty_header_collection = () => _response.Headers.ShouldBeEmpty(); static Response _response; } public class when_constructing_a_response_with_implicit_action { Because of = () => _response = _action; It should_contain_the_default_status_code = () => _response.StatusCode.ShouldEqual(200); It should_contain_the_default_content_type = () => _response.ContentType.ShouldEqual("text/html"); It should_contain_the_correct_contents = () => { using (var stream = new MemoryStream()) { _response.Contents.Invoke(stream); stream.Position = 0; var reader = new StreamReader(stream); var contents = reader.ReadToEnd(); contents.ShouldContain("Hello, world!"); } }; It should_contain_an_empty_header_collection = () => _response.Headers.ShouldBeEmpty(); static Action<Stream> _action = stream => { var writer = new StreamWriter(stream); writer.Write("Hello, world!"); writer.Flush(); }; static Response _response; } public class when_constructing_a_response_with_as_file_method { Because of = () => { Jess.Configuration = new JessicaConfiguration(); _response = Response.AsFile("../../../Fakes/Files/Download.txt"); }; It should_contain_the_correct_status_code = () => _response.StatusCode.ShouldEqual(200); It should_contain_the_correct_content_type = () => _response.ContentType.ShouldEqual("application/octet-stream"); It should_contain_the_correct_contents = () => { using (var stream = new MemoryStream()) { _response.Contents.Invoke(stream); stream.Position = 0; var reader = new StreamReader(stream); var contents = reader.ReadToEnd(); contents.ShouldContain("Hello, world! This is a download."); } }; It should_contain_an_empty_header_collection = () => _response.Headers.ShouldBeEmpty(); static Response _response; } public class when_constructing_a_response_with_as_json_method { Because of = () => { Jess.Configuration = new JessicaConfiguration(); _response = Response.AsJson(new SimpleModel { Message = "Hello, world!", Count = 2 }); }; It should_contain_the_correct_status_code = () => _response.StatusCode.ShouldEqual(200); It should_contain_the_correct_content_type = () => _response.ContentType.ShouldEqual("application/json"); It should_contain_the_correct_contents = () => { using (var stream = new MemoryStream()) { _response.Contents.Invoke(stream); stream.Position = 0; var reader = new StreamReader(stream); var contents = reader.ReadToEnd(); contents.ShouldContain("{\"Message\":\"Hello, world!\",\"Count\":2,\"Price\":0}"); } }; It should_contain_an_empty_header_collection = () => _response.Headers.ShouldBeEmpty(); static Response _response; } public class when_constructing_a_response_with_as_redirect_method { Because of = () => { Jess.Configuration = new JessicaConfiguration(); _response = Response.AsRedirect("http://google.com"); }; It should_contain_the_correct_status_code = () => _response.StatusCode.ShouldEqual(303); It should_contain_the_correct_location_header_key = () => _response.Headers.Keys.ShouldContain("Location"); It should_contain_the_correct_location_header_value = () => _response.Headers["Location"].ShouldEqual("http://google.com"); static Response _response; } public class when_constructing_a_response_with_as_html_method { Because of = () => { Jess.Configuration = new JessicaConfiguration(); _response = Response.AsHtml("../../../Fakes/Files/Index.html"); }; It should_contain_the_correct_status_code = () => _response.StatusCode.ShouldEqual(200); It should_contain_the_correct_content_type = () => _response.ContentType.ShouldEqual("text/html"); It should_contain_the_correct_contents = () => { using (var stream = new MemoryStream()) { _response.Contents.Invoke(stream); stream.Position = 0; var reader = new StreamReader(stream); var contents = reader.ReadToEnd(); contents.ShouldContain("<title>My Fake HTML</title>"); contents.ShouldContain("<h1>Hello, from Jessica!</h1>"); } }; It should_contain_an_empty_header_collection = () => _response.Headers.ShouldBeEmpty(); static Response _response; } public class when_constructing_a_response_with_as_css_method { Because of = () => { Jess.Configuration = new JessicaConfiguration(); _response = Response.AsCss("../../../Fakes/Files/Stylesheet.css"); }; It should_contain_the_correct_status_code = () => _response.StatusCode.ShouldEqual(200); It should_contain_the_correct_content_type = () => _response.ContentType.ShouldEqual("text/css"); It should_contain_the_correct_contents = () => { using (var stream = new MemoryStream()) { _response.Contents.Invoke(stream); stream.Position = 0; var reader = new StreamReader(stream); var contents = reader.ReadToEnd(); contents.ShouldContain("* { margin:0; }"); contents.ShouldContain("body { background:#ccc; }"); } }; It should_contain_an_empty_header_collection = () => _response.Headers.ShouldBeEmpty(); static Response _response; } public class when_constructing_a_response_with_as_js_method { Because of = () => { Jess.Configuration = new JessicaConfiguration(); _response = Response.AsJs("../../../Fakes/Files/SimpleJs.js"); }; It should_contain_the_correct_status_code = () => _response.StatusCode.ShouldEqual(200); It should_contain_the_correct_content_type = () => _response.ContentType.ShouldEqual("text/javascript"); It should_contain_the_correct_contents = () => { using (var stream = new MemoryStream()) { _response.Contents.Invoke(stream); stream.Position = 0; var reader = new StreamReader(stream); var contents = reader.ReadToEnd(); contents.ShouldContain("var myAlert = function (a) { alert(a); }"); } }; It should_contain_an_empty_header_collection = () => _response.Headers.ShouldBeEmpty(); static Response _response; } public class when_constructing_a_response_with_as_text_method_and_value { Because of = () => { Jess.Configuration = new JessicaConfiguration(); _response = Response.AsText("Hello, world!"); }; It should_contain_the_correct_status_code = () => _response.StatusCode.ShouldEqual(200); It should_contain_the_correct_content_type = () => _response.ContentType.ShouldEqual("text/plain"); It should_contain_the_correct_contents = () => { using (var stream = new MemoryStream()) { _response.Contents.Invoke(stream); stream.Position = 0; var reader = new StreamReader(stream); var contents = reader.ReadToEnd(); contents.ShouldContain("Hello, world!"); } }; It should_contain_an_empty_header_collection = () => _response.Headers.ShouldBeEmpty(); static Response _response; } public class when_constructing_a_response_with_as_text_method_with_format_and_arguments { Because of = () => { Jess.Configuration = new JessicaConfiguration(); _response = Response.AsText("Hello, {0} the number is {1}!", "Tom", 100); }; It should_contain_the_correct_status_code = () => _response.StatusCode.ShouldEqual(200); It should_contain_the_correct_content_type = () => _response.ContentType.ShouldEqual("text/plain"); It should_contain_the_correct_contents = () => { using (var stream = new MemoryStream()) { _response.Contents.Invoke(stream); stream.Position = 0; var reader = new StreamReader(stream); var contents = reader.ReadToEnd(); contents.ShouldContain("Hello, Tom the number is 100!"); } }; It should_contain_an_empty_header_collection = () => _response.Headers.ShouldBeEmpty(); static Response _response; } public class when_constructing_a_response_with_as_xml_method { Because of = () => { Jess.Configuration = new JessicaConfiguration(); _response = Response.AsXml(new SimpleModel { Message = "Hello, world!", Count = 2 }); }; It should_contain_the_correct_status_code = () => _response.StatusCode.ShouldEqual(200); It should_contain_the_correct_content_type = () => _response.ContentType.ShouldEqual("application/xml"); It should_contain_the_correct_json_contents = () => { using (var stream = new MemoryStream()) { _response.Contents.Invoke(stream); stream.Position = 0; var reader = new StreamReader(stream); var contents = reader.ReadToEnd(); contents.ShouldContain("<Message>Hello, world!</Message>"); contents.ShouldContain("<Count>2</Count>"); contents.ShouldContain("<Price>0</Price>"); } }; It should_contain_an_empty_header_collection = () => _response.Headers.ShouldBeEmpty(); static Response _response; } }
using System; using System.Collections; namespace Edustructures.Metadata { /// <summary> /// Summary description for SchemaComparer. /// </summary> public class SchemaComparer { public void Compare( ISchemaDefinition officialSpec, ISchemaDefinition unofficialSpec, ICompareOutput output, bool detailedCheck ) { if ( officialSpec.Version != unofficialSpec.Version ) { output.ComparisonFailed ( officialSpec.Name, "SifVersion", "ToString", officialSpec.Version.ToString(), unofficialSpec.Name, unofficialSpec.Version.ToString(), "" ); } CompareObjectDictionary ( officialSpec.GetAllObjects(), officialSpec.Name, unofficialSpec.GetAllObjects(), unofficialSpec.Name, output, detailedCheck ); // Only compare enums that are defined in the official spec, but not in the unofficial spec // TODO: Provide warnings for undocumented members CompareEnumDictionary ( officialSpec.GetAllEnums(), officialSpec.Name, unofficialSpec.GetAllEnums(), unofficialSpec.Name, output ); } private static void CompareEnumDictionary( IDictionary officialSpecEnums, string db1Name, IDictionary unofficialSpecEnums, string db2Name, ICompareOutput output ) { CompareDictionaryDefs ( officialSpecEnums, db1Name, unofficialSpecEnums, db2Name, output, "EnumDef", false ); output.StartComparisonSection ( "Starting search for missing enumeration fields in both Schemas" ); CompareEnumDefs( officialSpecEnums, db1Name, unofficialSpecEnums, db2Name, output ); output.EndComparisonSection(); } private static void CompareObjectDictionary( IDictionary objects1, string db1Name, IDictionary objects2, string db2Name, ICompareOutput output, bool detailed ) { CompareDictionaryDefs( objects1, db1Name, objects2, db2Name, output, "ObjectDef", true ); CompareDictionaryDefs( objects2, db2Name, objects1, db1Name, output, "ObjectDef", true ); output.StartComparisonSection( "Starting search for missing fields in both Schemas" ); CompareObjectDefs( objects1, db1Name, objects2, db2Name, output, detailed ); output.EndComparisonSection(); } private static void CompareDictionaryDefs( IDictionary objects, string source, IDictionary targetObjects, string targetName, ICompareOutput output, string objectType, bool error ) { output.StartComparisonSection ( "Starting search for missing " + objectType + "s in " + targetName ); foreach ( AbstractDef def in objects.Values ) { // System.Diagnostics.Debug.Assert( !( def.Name.ToLower() == "homeroom" ) ); if ( !targetObjects.Contains( def.Name ) ) { if ( def.Draft ) { output.ComparisonWarning ( source, targetName, "Missing draft object " + def.Name ); } else if ( def.Deprecated ) { output.ComparisonWarning ( source, targetName, "Missing deprecated object " + def.Name ); } else if ( ! def.ShouldValidate ) { output.ComparisonWarning ( source, targetName, "Missing ignored object " + def.Name ); } // There are some cases where the SIF XSD defines an element as a complex type, even though it has // no internal elements. We'll check here for defs that have no Fields in them and output a warning instead // of an error else if ( def is ObjectDef && ((ObjectDef) def).Fields.Length == 0 ) { output.ComparisonWarning ( source, targetName, "Missing " + objectType + " " + def.Name + ", but no fields were defined in source." ); } else if ( def is ObjectDef && ((ObjectDef) def).RenderAs != null && targetObjects.Contains( ((ObjectDef) def).RenderAs ) ) { // We've found a match using RenderAs, so this case is OK } else if ( !error ) { output.ComparisonWarning ( source, targetName, "Missing " + objectType + " " + def.Name ); } else { output.ComparisonMissing ( source, def.Name, "", targetName, def.SourceLocation ); } } } output.EndComparisonSection(); } private static void CompareEnumDefs( IDictionary objects, string source, IDictionary targetObjects, string targetName, ICompareOutput output ) { foreach ( EnumDef def in objects.Values ) { EnumDef def2 = targetObjects[def.Name] as EnumDef; if ( def2 != null ) { CompareEnumDef( def, source, def2, targetName, output ); } } } private static void CompareEnumDef( EnumDef def1, string source1, EnumDef def2, string source2, ICompareOutput output ) { foreach ( ValueDef def in def1.Values ) { if ( !def2.ContainsValue( def.Value ) ) { output.ComparisonMissing ( source1, def1.Name, def.Name, source2, def1.SourceLocation ); } } foreach ( ValueDef val in def2.Values ) { if ( !def1.ContainsValue( val.Value )) { output.ComparisonMissing ( source2, def2.Name, val.Name, source1, def2.SourceLocation ); } } } private static void CompareObjectDefs( IDictionary objects, string source, IDictionary targetObjects, string targetName, ICompareOutput output, bool detailed ) { foreach ( ObjectDef def in objects.Values ) { ObjectDef def2 = targetObjects[def.Name] as ObjectDef; if ( def2 != null ) { CompareObjectDef( def, source, def2, targetName, output, detailed ); } } } private static void CompareObjectDef( ObjectDef def1, string source1, ObjectDef def2, string source2, ICompareOutput output, bool detailed ) { if ( def1.Infra != def2.Infra ) { output.ComparisonFailed ( source1, def1.Name, "Infra", def1.Infra.ToString(), source2, def2.Infra.ToString(), def1.SourceLocation ); } if ( def1.Topic != def2.Topic ) { output.ComparisonFailed ( source1, def1.Name, "Topic", def1.Topic.ToString(), source2, def2.Topic.ToString(), def1.SourceLocation ); } CompareFields( source1, def1, source2, def2, output, detailed ); CompareFields( source2, def2, source1, def1, output, detailed ); } private static void CompareFields( string source, ObjectDef sourceDef, string target, ObjectDef targetDef, ICompareOutput output, bool detailed ) { foreach ( FieldDef field1 in sourceDef.Fields ) { if ( field1.Name == "SIF_ExtendedElements" || field1.Name == "SIF_Metadata" ) { // ignore. adkgen automatically adds to "topic" objects } else { FieldDef field2; if ( field1.RenderAs != null ) { field2 = targetDef.GetField( field1.RenderAs ); } else { field2 = targetDef.GetField( field1.Name ); } if ( field2 == null ) { output.ComparisonMissing ( source, sourceDef.Name, field1.Name, target, sourceDef.SourceLocation ); } else if ( detailed ) { CompareField ( source, sourceDef, field1, target, field2, output, true ); } } } } private static void CompareField( string source1, ObjectDef def1, FieldDef field1, string source2, FieldDef field2, ICompareOutput output, bool detailedCheck ) { if ( field1.Attribute != field2.Attribute ) { output.ComparisonFailed ( source1, def1.Name + "." + field1.Name, "Attribute", field1.Attribute.ToString(), source2, field2.Attribute.ToString(), def1.SourceLocation ); } if (field1.Sequence != field2.Sequence) { output.ComparisonWarning (source1, source2, "Differing sequence: " + def1.Name + "." + field1.Name + " src(" + field1.Sequence + ") target:(" + field2.Sequence + ")"); } if ( detailedCheck ) { // if( field1.Complex != field2.Complex ) // { // output.ComparisonFailed( source1, def1.Name + "." + field1.Name, "Complex", field1.Complex.ToString(), source2, field2.Complex.ToString(), def1.SourceLocation ); // } //System.Diagnostics.Debug.Assert( !(def1.Name == "FundingSource") ); if ( !field1.FlagIntrinsicallyMatches( field2 ) ) { output.ComparisonWarning ( source1, source2, "Differing flags: " + def1.Name + "." + field1.Name + " src(" + field1.GetFlags() + ") target:(" + field2.GetFlags() + ")" ); } if ( !field1.FieldType.Equals( field2.FieldType ) ) { if( field1.FieldType.IsEnum && field2.FieldType.IsEnum ) { output.ComparisonDebug (source2, source1, "differing class type: " + def1.Name + "." + field1.Name + " src(" + field1.FieldType + ") target:(" + field2.FieldType + ")"); } output.ComparisonWarning ( source2, source1, "differing class type: " + def1.Name + "." + field1.Name + " src(" + field1.FieldType + ") target:(" + field2.FieldType + ")" ); } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using OLEDB.Test.ModuleCore; using System.IO; using XmlCoreTest.Common; namespace System.Xml.Tests { ///////////////////////////////////////////////////////////////////////// // TestCase ReadOuterXml // ///////////////////////////////////////////////////////////////////////// [InheritRequired()] public abstract partial class TCReadToDescendant : TCXMLReaderBaseGeneral { #region XMLSTR private string _xmlStr = @"<?xml version='1.0'?> <root><!--Comment--> <elem><!-- Comment --> <child1 att='1'><?pi target?> <child2 xmlns='child2'> <child3/> blahblahblah<![CDATA[ blah ]]> <child4/> </child2> <?pi target1?> </child1> </elem> <elem att='1'> <child1 att='1'> <child2 xmlns='child2'> <child3/> blahblahblah <child4/> </child2> <?pi target1?> </child1> </elem> <elem xmlns='elem'> <child1 att='1'> <child2 xmlns='child2'> <child3/> blahblahblah2 <child4/> </child2> </child1> </elem> <elem xmlns='elem' att='1'> <child1 att='1'> <child2 xmlns='child2'> <child3/> blahblahblah2 <child4/> </child2> </child1> </elem> <e:elem xmlns:e='elem2'> <e:child1 att='1'> <e:child2 xmlns='child2'> <e:child3/> blahblahblah2 <e:child4/> </e:child2> </e:child1> </e:elem> <e:elem xmlns:e='elem2' att='1'> <e:child1 att='1'> <e:child2 xmlns='child2'> <e:child3/> blahblahblah2 <e:child4/> </e:child2> </e:child1> </e:elem> </root>"; #endregion //[Variation("Simple positive test", Pri = 0, Params = new object[] { "NNS" })] //[Variation("Simple positive test", Pri = 0, Params = new object[] { "DNS" })] //[Variation("Simple positive test", Pri = 0, Params = new object[] { "NS" })] public int v() { string type = CurVariation.Params[0].ToString(); CError.WriteLine("Test Type : " + type); ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("root"); switch (type) { case "NNS": DataReader.ReadToDescendant("elem"); if (DataReader.HasAttributes) { CError.WriteLine("Positioned on wrong element"); CError.WriteIgnore(DataReader.ReadInnerXml() + "\n"); return TEST_FAIL; } while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; case "DNS": DataReader.ReadToDescendant("elem", "elem"); if (DataReader.HasAttributes) { if (DataReader.GetAttribute("xmlns") == null) { CError.WriteLine("Positioned on wrong element, not on DNS"); return TEST_FAIL; } } while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; case "NS": DataReader.ReadToDescendant("e:elem"); if (DataReader.HasAttributes) { if (DataReader.GetAttribute("xmlns:e") == null) { CError.WriteLine("Positioned on wrong element, not on NS"); return TEST_FAIL; } } while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; default: throw new CTestFailedException("Error in Test type"); } } [Variation("Read on a deep tree atleast more than 4K boundary", Pri = 2)] public int v2() { ManagedNodeWriter mnw = new ManagedNodeWriter(); mnw.PutPattern("X"); int count = 0; do { mnw.PutPattern("E/"); count++; } while (mnw.GetNodes().Length < 4096); mnw.PutText("<a/>"); mnw.Finish(); CError.WriteIgnore(mnw.GetNodes() + "\n"); ReloadSource(new StringReader(mnw.GetNodes())); DataReader.PositionOnElement("ELEMENT_1"); CError.WriteLine("Reading to : " + "a"); DataReader.ReadToDescendant("a"); CError.Compare(DataReader.Depth, count, "Depth is not correct"); CError.Compare(DataReader.NodeType, XmlNodeType.Element, "Nodetype is not correct"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("Read on a deep tree atleast more than 65535 boundary", Pri = 2)] public int v2_1() { ManagedNodeWriter mnw = new ManagedNodeWriter(); mnw.PutPattern("X"); int count = 0; do { mnw.PutPattern("E/"); count++; } while (count < 65536); mnw.PutText("<a/>"); mnw.Finish(); ReloadSource(new StringReader(mnw.GetNodes())); DataReader.PositionOnElement("ELEMENT_1"); CError.WriteLine("Reading to : a"); DataReader.ReadToDescendant("a"); CError.Compare(DataReader.Depth, 65536, "Depth is not correct"); CError.Compare(DataReader.NodeType, XmlNodeType.Element, "Nodetype is not correct"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } //[Variation("Read on descendant with same names", Pri = 1, Params = new object[] { "NNS" })] //[Variation("Read on descendant with same names", Pri = 1, Params = new object[] { "DNS" })] //[Variation("Read on descendant with same names", Pri = 1, Params = new object[] { "NS" })] public int v3() { string type = CurVariation.Params[0].ToString(); CError.WriteLine("Test Type : " + type); ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("root"); //Doing a sequential read. switch (type) { case "NNS": DataReader.ReadToDescendant("elem"); int depth = DataReader.Depth; if (DataReader.HasAttributes) { CError.WriteLine("Positioned on wrong element"); return TEST_FAIL; } CError.Compare(DataReader.ReadToDescendant("elem"), false, "There are no more descendants"); CError.Compare(DataReader.NodeType, XmlNodeType.EndElement, "Wrong node type"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; case "DNS": DataReader.ReadToDescendant("elem", "elem"); if (DataReader.HasAttributes) { if (DataReader.GetAttribute("xmlns") == null) { CError.WriteLine("Positioned on wrong element, not on DNS"); return TEST_FAIL; } } CError.Compare(DataReader.ReadToDescendant("elem", "elem"), false, "There are no more descendants"); CError.Compare(DataReader.NodeType, XmlNodeType.EndElement, "Wrong node type"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; case "NS": DataReader.ReadToDescendant("e:elem"); if (DataReader.HasAttributes) { if (DataReader.GetAttribute("xmlns:e") == null) { CError.WriteLine("Positioned on wrong element, not on DNS"); return TEST_FAIL; } } CError.Compare(DataReader.ReadToDescendant("e:elem"), false, "There are no more descendants"); CError.Compare(DataReader.NodeType, XmlNodeType.EndElement, "Wrong node type"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; default: throw new CTestFailedException("Error in Test type"); } } [Variation("If name not found, stop at end element of the subtree", Pri = 1)] public int v4() { ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("elem"); CError.Compare(DataReader.ReadToDescendant("abc"), false, "Reader returned true for an invalid name"); CError.Compare(DataReader.NodeType, XmlNodeType.EndElement, "Wrong node type"); DataReader.Read(); CError.Compare(DataReader.ReadToDescendant("abc", "elem"), false, "reader returned true for an invalid name,ns combination"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("Positioning on a level and try to find the name which is on a level higher", Pri = 1)] public int v5() { ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("child3"); CError.Compare(DataReader.ReadToDescendant("child1"), false, "Reader returned true for an invalid name"); CError.Compare(DataReader.NodeType, XmlNodeType.Element, "Wrong node type"); CError.Compare(DataReader.LocalName, "child3", "Wrong name"); DataReader.PositionOnElement("child3"); CError.Compare(DataReader.ReadToDescendant("child2", "child2"), false, "Reader returned true for an invalid name,ns"); CError.Compare(DataReader.NodeType, XmlNodeType.Element, "Wrong node type for name,ns"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("Read to Descendant on one level and again to level below it", Pri = 1)] public int v6() { ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("root"); CError.Compare(DataReader.ReadToDescendant("elem"), true, "Cant find elem"); CError.Compare(DataReader.ReadToDescendant("child1"), true, "Cant find child1"); CError.Compare(DataReader.ReadToDescendant("child2"), true, "Cant find child2"); CError.Compare(DataReader.ReadToDescendant("child3"), true, "Cant find child3"); CError.Compare(DataReader.ReadToDescendant("child4"), false, "shouldnt find child4"); CError.Compare(DataReader.NodeType, XmlNodeType.Element, "Not on EndElement"); DataReader.Read(); CError.Compare(DataReader.NodeType, XmlNodeType.Text, "Not on Element"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("Read to Descendant on one level and again to level below it, with namespace", Pri = 1)] public int v7() { ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("root"); CError.Compare(DataReader.ReadToDescendant("elem", "elem"), true, "Cant find elem"); CError.Compare(DataReader.ReadToDescendant("child1", "elem"), true, "Cant find child1"); CError.Compare(DataReader.ReadToDescendant("child2", "child2"), true, "Cant find child2"); CError.Compare(DataReader.ReadToDescendant("child3", "child2"), true, "Cant find child3"); CError.Compare(DataReader.ReadToDescendant("child4", "child2"), false, "shouldnt find child4"); CError.Compare(DataReader.NodeType, XmlNodeType.Element, "Not on EndElement"); DataReader.Read(); CError.Compare(DataReader.NodeType, XmlNodeType.Text, "Not on Element"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("Read to Descendant on one level and again to level below it, with prefix", Pri = 1)] public int v8() { ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("root"); CError.Compare(DataReader.ReadToDescendant("e:elem"), true, "Cant find elem"); CError.Compare(DataReader.ReadToDescendant("e:child1"), true, "Cant find child1"); CError.Compare(DataReader.ReadToDescendant("e:child2"), true, "Cant find child2"); CError.Compare(DataReader.ReadToDescendant("e:child3"), true, "Cant find child3"); CError.Compare(DataReader.ReadToDescendant("e:child4"), false, "shouldnt find child4"); CError.Compare(DataReader.NodeType, XmlNodeType.Element, "Not on EndElement"); DataReader.Read(); CError.Compare(DataReader.NodeType, XmlNodeType.Text, "Not on Element"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("Multiple Reads to children and then next siblings, NNS", Pri = 2)] public int v9() { ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("root"); CError.Compare(DataReader.ReadToDescendant("elem"), true, "Read fails elem"); CError.Compare(DataReader.ReadToDescendant("child3"), true, "Read fails child3"); CError.Compare(DataReader.ReadToNextSibling("child4"), true, "Read fails child4"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("Multiple Reads to children and then next siblings, DNS", Pri = 2)] public int v10() { ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("root"); CError.Compare(DataReader.ReadToDescendant("elem", "elem"), true, "Read fails elem"); CError.Compare(DataReader.ReadToDescendant("child3", "child2"), true, "Read fails child3"); CError.Compare(DataReader.ReadToNextSibling("child4", "child2"), true, "Read fails child4"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("Multiple Reads to children and then next siblings, NS", Pri = 2)] public int v11() { ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("root"); CError.Compare(DataReader.ReadToDescendant("e:elem"), true, "Read fails elem"); CError.Compare(DataReader.ReadToDescendant("e:child3"), true, "Read fails child3"); CError.Compare(DataReader.ReadToNextSibling("e:child4"), true, "Read fails child4"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("Call from different nodetypes", Pri = 1)] public int v12() { ReloadSource(new StringReader(_xmlStr)); while (DataReader.Read()) { if (DataReader.NodeType != XmlNodeType.Element) { CError.WriteLine(DataReader.NodeType.ToString()); CError.Compare(DataReader.ReadToDescendant("child1"), false, "Fails on node"); } else { if (DataReader.HasAttributes) { while (DataReader.MoveToNextAttribute()) { CError.Compare(DataReader.ReadToDescendant("abc"), false, "Fails on attribute node"); } } } } DataReader.Close(); return TEST_PASS; } [Variation("Interaction with MoveToContent", Pri = 2)] public int v13() { return TEST_SKIPPED; } [Variation("Only child has namespaces and read to it", Pri = 2)] public int v14() { ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("root"); CError.Compare(DataReader.ReadToDescendant("child2", "child2"), true, "Fails on attribute node"); DataReader.Close(); return TEST_PASS; } [Variation("Pass null to both arguments throws ArgumentException", Pri = 2)] public int v15() { ReloadSource(new StringReader("<root><b/></root>")); DataReader.Read(); if (IsBinaryReader()) DataReader.Read(); try { DataReader.ReadToDescendant(null); } catch (ArgumentNullException) { CError.WriteLine("Caught for single param"); } try { DataReader.ReadToDescendant("b", null); } catch (ArgumentNullException) { CError.WriteLine("Caught for single param"); } while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("Different names, same uri works correctly", Pri = 2)] public int v17() { ReloadSource(new StringReader("<root><child1 xmlns='foo'/>blah<child1 xmlns='bar'>blah</child1></root>")); DataReader.Read(); if (IsBinaryReader()) DataReader.Read(); DataReader.ReadToDescendant("child1", "bar"); CError.Compare(DataReader.IsEmptyElement, false, "Not on the correct node"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } //[Variation("On Root Node", Pri = 0, Params = new object[] { "NNS" })] //[Variation("On Root Node", Pri = 0, Params = new object[] { "DNS" })] //[Variation("On Root Node", Pri = 0, Params = new object[] { "NS" })] public int v18() { string type = CurVariation.Params[0].ToString(); CError.WriteLine("Test Type : " + type); ReloadSource(new StringReader(_xmlStr)); switch (type) { case "NNS": DataReader.ReadToDescendant("elem"); if (DataReader.HasAttributes) { CError.WriteLine("Positioned on wrong element"); CError.WriteIgnore(DataReader.ReadInnerXml() + "\n"); return TEST_FAIL; } while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; case "DNS": DataReader.ReadToDescendant("elem", "elem"); if (DataReader.HasAttributes) { if (DataReader.GetAttribute("xmlns") == null) { CError.WriteLine("Positioned on wrong element, not on DNS"); return TEST_FAIL; } } while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; case "NS": DataReader.ReadToDescendant("e:elem"); if (DataReader.HasAttributes) { if (DataReader.GetAttribute("xmlns:e") == null) { CError.WriteLine("Positioned on wrong element, not on NS"); return TEST_FAIL; } } while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; default: throw new CTestFailedException("Error in Test type"); } } [Variation("Assertion failed when call XmlReader.ReadToDescendant() for non-existing node", Pri = 1)] public int v19() { ReloadSource(new StringReader("<a>b</a>")); CError.Compare(DataReader.ReadToDescendant("foo"), false, "Should fail without assert"); DataReader.Close(); return TEST_PASS; } } }
/* * Farseer Physics Engine based on Box2D.XNA port: * Copyright (c) 2010 Ian Qvist * * Box2D.XNA port of Box2D: * Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler * * Original source Box2D: * Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ using GameLibrary.Dependencies.Physics.Common; using Microsoft.Xna.Framework; using System; using System.Diagnostics; namespace GameLibrary.Dependencies.Physics.Dynamics.Joints { public class LineJoint : PhysicsJoint { private Vector2 _ax, _ay; private float _bias; private bool _enableMotor; private float _gamma; private float _impulse; private Vector2 _localXAxis; private Vector2 _localYAxisA; private float _mass; private float _maxMotorTorque; private float _motorImpulse; private float _motorMass; private float _motorSpeed; private float _sAx; private float _sAy; private float _sBx; private float _sBy; private float _springImpulse; private float _springMass; // Linear constraint (point-to-line) // d = pB - pA = xB + rB - xA - rA // C = dot(ay, d) // Cdot = dot(d, cross(wA, ay)) + dot(ay, vB + cross(wB, rB) - vA - cross(wA, rA)) // = -dot(ay, vA) - dot(cross(d + rA, ay), wA) + dot(ay, vB) + dot(cross(rB, ay), vB) // J = [-ay, -cross(d + rA, ay), ay, cross(rB, ay)] // Spring linear constraint // C = dot(ax, d) // Cdot = = -dot(ax, vA) - dot(cross(d + rA, ax), wA) + dot(ax, vB) + dot(cross(rB, ax), vB) // J = [-ax -cross(d+rA, ax) ax cross(rB, ax)] // Motor rotational constraint // Cdot = wB - wA // J = [0 0 -1 0 0 1] internal LineJoint() { JointType = JointType.Line; } public LineJoint(PhysicsBody bA, PhysicsBody bB, Vector2 anchor, Vector2 axis) : base(bA, bB) { JointType = JointType.Line; LocalAnchorA = bA.GetLocalPoint(anchor); LocalAnchorB = bB.GetLocalPoint(anchor); LocalXAxis = bA.GetLocalVector(axis); } public Vector2 LocalAnchorA { get; set; } public Vector2 LocalAnchorB { get; set; } public override Vector2 WorldAnchorA { get { return BodyA.GetWorldPoint(LocalAnchorA); } } public override Vector2 WorldAnchorB { get { return BodyB.GetWorldPoint(LocalAnchorB); } set { Debug.Assert(false, "You can't set the world anchor on this joint type."); } } public float JointTranslation { get { PhysicsBody bA = BodyA; PhysicsBody bB = BodyB; Vector2 pA = bA.GetWorldPoint(LocalAnchorA); Vector2 pB = bB.GetWorldPoint(LocalAnchorB); Vector2 d = pB - pA; Vector2 axis = bA.GetWorldVector(LocalXAxis); float translation = Vector2.Dot(d, axis); return translation; } } public float JointSpeed { get { float wA = BodyA.AngularVelocityInternal; float wB = BodyB.AngularVelocityInternal; return wB - wA; } } public bool MotorEnabled { get { return _enableMotor; } set { BodyA.Awake = true; BodyB.Awake = true; _enableMotor = value; } } public float MotorSpeed { set { BodyA.Awake = true; BodyB.Awake = true; _motorSpeed = value; } get { return _motorSpeed; } } public float MaxMotorTorque { set { BodyA.Awake = true; BodyB.Awake = true; _maxMotorTorque = value; } get { return _maxMotorTorque; } } public float Frequency { get; set; } public float DampingRatio { get; set; } public Vector2 LocalXAxis { get { return _localXAxis; } set { _localXAxis = value; _localYAxisA = MathUtils.Cross(1.0f, _localXAxis); } } public override Vector2 GetReactionForce(float invDt) { return invDt * (_impulse * _ay + _springImpulse * _ax); } public override float GetReactionTorque(float invDt) { return invDt * _motorImpulse; } internal override void InitVelocityConstraints(ref TimeStep step) { PhysicsBody bA = BodyA; PhysicsBody bB = BodyB; LocalCenterA = bA.LocalCenter; LocalCenterB = bB.LocalCenter; Transform xfA; bA.GetTransform(out xfA); Transform xfB; bB.GetTransform(out xfB); // Compute the effective masses. Vector2 rA = MathUtils.Multiply(ref xfA.R, LocalAnchorA - LocalCenterA); Vector2 rB = MathUtils.Multiply(ref xfB.R, LocalAnchorB - LocalCenterB); Vector2 d = bB.Sweep.C + rB - bA.Sweep.C - rA; InvMassA = bA.InvMass; InvIA = bA.InvI; InvMassB = bB.InvMass; InvIB = bB.InvI; // Point to line constraint { _ay = MathUtils.Multiply(ref xfA.R, _localYAxisA); _sAy = MathUtils.Cross(d + rA, _ay); _sBy = MathUtils.Cross(rB, _ay); _mass = InvMassA + InvMassB + InvIA * _sAy * _sAy + InvIB * _sBy * _sBy; if (_mass > 0.0f) { _mass = 1.0f / _mass; } } // Spring constraint _springMass = 0.0f; if (Frequency > 0.0f) { _ax = MathUtils.Multiply(ref xfA.R, LocalXAxis); _sAx = MathUtils.Cross(d + rA, _ax); _sBx = MathUtils.Cross(rB, _ax); float invMass = InvMassA + InvMassB + InvIA * _sAx * _sAx + InvIB * _sBx * _sBx; if (invMass > 0.0f) { _springMass = 1.0f / invMass; float C = Vector2.Dot(d, _ax); // Frequency float omega = 2.0f * Settings.Pi * Frequency; // Damping coefficient float da = 2.0f * _springMass * DampingRatio * omega; // Spring stiffness float k = _springMass * omega * omega; // magic formulas _gamma = step.dt * (da + step.dt * k); if (_gamma > 0.0f) { _gamma = 1.0f / _gamma; } _bias = C * step.dt * k * _gamma; _springMass = invMass + _gamma; if (_springMass > 0.0f) { _springMass = 1.0f / _springMass; } } } else { _springImpulse = 0.0f; _springMass = 0.0f; } // Rotational motor if (_enableMotor) { _motorMass = InvIA + InvIB; if (_motorMass > 0.0f) { _motorMass = 1.0f / _motorMass; } } else { _motorMass = 0.0f; _motorImpulse = 0.0f; } if (Settings.EnableWarmstarting) { // Account for variable time step. _impulse *= step.dtRatio; _springImpulse *= step.dtRatio; _motorImpulse *= step.dtRatio; Vector2 P = _impulse * _ay + _springImpulse * _ax; float LA = _impulse * _sAy + _springImpulse * _sAx + _motorImpulse; float LB = _impulse * _sBy + _springImpulse * _sBx + _motorImpulse; bA.LinearVelocityInternal -= InvMassA * P; bA.AngularVelocityInternal -= InvIA * LA; bB.LinearVelocityInternal += InvMassB * P; bB.AngularVelocityInternal += InvIB * LB; } else { _impulse = 0.0f; _springImpulse = 0.0f; _motorImpulse = 0.0f; } } internal override void SolveVelocityConstraints(ref TimeStep step) { PhysicsBody bA = BodyA; PhysicsBody bB = BodyB; Vector2 vA = bA.LinearVelocity; float wA = bA.AngularVelocityInternal; Vector2 vB = bB.LinearVelocityInternal; float wB = bB.AngularVelocityInternal; // Solve spring constraint { float Cdot = Vector2.Dot(_ax, vB - vA) + _sBx * wB - _sAx * wA; float impulse = -_springMass * (Cdot + _bias + _gamma * _springImpulse); _springImpulse += impulse; Vector2 P = impulse * _ax; float LA = impulse * _sAx; float LB = impulse * _sBx; vA -= InvMassA * P; wA -= InvIA * LA; vB += InvMassB * P; wB += InvIB * LB; } // Solve rotational motor constraint { float Cdot = wB - wA - _motorSpeed; float impulse = -_motorMass * Cdot; float oldImpulse = _motorImpulse; float maxImpulse = step.dt * _maxMotorTorque; _motorImpulse = MathUtils.Clamp(_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = _motorImpulse - oldImpulse; wA -= InvIA * impulse; wB += InvIB * impulse; } // Solve point to line constraint { float Cdot = Vector2.Dot(_ay, vB - vA) + _sBy * wB - _sAy * wA; float impulse = _mass * (-Cdot); _impulse += impulse; Vector2 P = impulse * _ay; float LA = impulse * _sAy; float LB = impulse * _sBy; vA -= InvMassA * P; wA -= InvIA * LA; vB += InvMassB * P; wB += InvIB * LB; } bA.LinearVelocityInternal = vA; bA.AngularVelocityInternal = wA; bB.LinearVelocityInternal = vB; bB.AngularVelocityInternal = wB; } internal override bool SolvePositionConstraints() { PhysicsBody bA = BodyA; PhysicsBody bB = BodyB; Vector2 xA = bA.Sweep.C; float angleA = bA.Sweep.A; Vector2 xB = bB.Sweep.C; float angleB = bB.Sweep.A; Mat22 RA = new Mat22(angleA); Mat22 RB = new Mat22(angleB); Vector2 rA = MathUtils.Multiply(ref RA, LocalAnchorA - LocalCenterA); Vector2 rB = MathUtils.Multiply(ref RB, LocalAnchorB - LocalCenterB); Vector2 d = xB + rB - xA - rA; Vector2 ay = MathUtils.Multiply(ref RA, _localYAxisA); float sAy = MathUtils.Cross(d + rA, ay); float sBy = MathUtils.Cross(rB, ay); float C = Vector2.Dot(d, ay); float k = InvMassA + InvMassB + InvIA * _sAy * _sAy + InvIB * _sBy * _sBy; float impulse; if (k != 0.0f) { impulse = -C / k; } else { impulse = 0.0f; } Vector2 P = impulse * ay; float LA = impulse * sAy; float LB = impulse * sBy; xA -= InvMassA * P; angleA -= InvIA * LA; xB += InvMassB * P; angleB += InvIB * LB; // TODO_ERIN remove need for this. bA.Sweep.C = xA; bA.Sweep.A = angleA; bB.Sweep.C = xB; bB.Sweep.A = angleB; bA.SynchronizeTransform(); bB.SynchronizeTransform(); return Math.Abs(C) <= Settings.LinearSlop; } public float GetMotorTorque(float invDt) { return invDt * _motorImpulse; } } }
//----------------------------------------------------------------------- // <copyright file="CloudServiceManager.cs" company="Google LLC"> // // Copyright 2018 Google LLC. 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. // // </copyright> //----------------------------------------------------------------------- namespace GoogleARCoreInternal.CrossPlatform { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using GoogleARCore.CrossPlatform; using UnityEngine; internal class CloudServiceManager { private static CloudServiceManager s_Instance; private List<CloudAnchorRequest> m_CloudAnchorRequests = new List<CloudAnchorRequest>(); public static CloudServiceManager Instance { get { if (s_Instance == null) { s_Instance = new CloudServiceManager(); LifecycleManager.Instance.EarlyUpdate += s_Instance._OnEarlyUpdate; LifecycleManager.Instance.OnResetInstance += _ResetInstance; } return s_Instance; } } public GoogleARCore.AsyncTask<CloudAnchorResult> CreateCloudAnchor( GoogleARCore.Anchor anchor) { Action<CloudAnchorResult> onComplete; GoogleARCore.AsyncTask<CloudAnchorResult> task; if (!_CreateCloudAnchorResultAsyncTask(out onComplete, out task)) { return task; } _CreateCloudAnchor(onComplete, anchor.NativeHandle); return task; } public GoogleARCore.AsyncTask<CloudAnchorResult> CreateCloudAnchor(UnityEngine.Pose pose) { Action<CloudAnchorResult> onComplete; GoogleARCore.AsyncTask<CloudAnchorResult> task; if (!_CreateCloudAnchorResultAsyncTask(out onComplete, out task)) { return task; } // Create an native Pose and Anchor. var poseHandle = LifecycleManager.Instance.NativeSession.PoseApi.Create(pose); IntPtr arkitAnchorHandle = IntPtr.Zero; ExternApi.ARKitAnchor_create(poseHandle, ref arkitAnchorHandle); _CreateCloudAnchor(onComplete, arkitAnchorHandle); // Clean up handles for the Pose and ARKitAnchor. LifecycleManager.Instance.NativeSession.PoseApi.Destroy(poseHandle); ExternApi.ARKitAnchor_release(arkitAnchorHandle); return task; } public GoogleARCore.AsyncTask<CloudAnchorResult> ResolveCloudAnchor(string cloudAnchorId) { Action<CloudAnchorResult> onComplete; GoogleARCore.AsyncTask<CloudAnchorResult> task; if (!_CreateCloudAnchorResultAsyncTask(out onComplete, out task)) { return task; } IntPtr cloudAnchorHandle = IntPtr.Zero; var status = LifecycleManager.Instance.NativeSession.SessionApi .ResolveCloudAnchor(cloudAnchorId, out cloudAnchorHandle); if (status != ApiArStatus.Success) { onComplete(new CloudAnchorResult() { Response = status.ToCloudServiceResponse(), Anchor = null, }); return task; } _CreateAndTrackCloudAnchorRequest(cloudAnchorHandle, onComplete, cloudAnchorId); return task; } public void CancelCloudAnchorAsyncTask(string cloudAnchorId) { if (string.IsNullOrEmpty(cloudAnchorId)) { Debug.LogWarning("Couldn't find pending operation for empty cloudAnchorId."); return; } _CancelCloudAnchorRequest(cloudAnchorId); } /// <summary> /// Helper for creating and initializing the Action and AsyncTask for CloudAnchorResult. /// </summary> /// <param name="onComplete">The on complete Action initialized from the AsyncTask. /// This will always contain a valid task even when function returns false.</param> /// <param name="task">The created task. /// This will always contain a valid task even when function returns false.</param> /// <returns>Returns true if cloud anchor creation should continue. Returns false if cloud /// creation should abort.</returns> protected internal bool _CreateCloudAnchorResultAsyncTask( out Action<CloudAnchorResult> onComplete, out GoogleARCore.AsyncTask<CloudAnchorResult> task) { // Action<CloudAnchorResult> onComplete; task = new GoogleARCore.AsyncTask<CloudAnchorResult>(out onComplete); if (LifecycleManager.Instance.NativeSession == null) { onComplete(new CloudAnchorResult() { Response = CloudServiceResponse.ErrorNotSupportedByConfiguration, Anchor = null, }); return false; } return true; } /// <summary> /// Creates the and track cloud anchor request. /// </summary> /// <param name="cloudAnchorHandle">Cloud anchor handle.</param> /// <param name="onComplete">The on complete Action that was created for the /// AsyncTask<CloudAnchorResult>.</param> protected internal void _CreateAndTrackCloudAnchorRequest(IntPtr cloudAnchorHandle, Action<CloudAnchorResult> onComplete, string cloudAnchorId = null) { if (LifecycleManager.Instance.NativeSession == null || cloudAnchorHandle == IntPtr.Zero) { Debug.LogError("Cannot create cloud anchor request when NativeSession is null or " + "cloud anchor handle is IntPtr.Zero."); onComplete(new CloudAnchorResult() { Response = CloudServiceResponse.ErrorInternal, Anchor = null, }); return; } var request = new CloudAnchorRequest() { IsComplete = false, NativeSession = LifecycleManager.Instance.NativeSession, CloudAnchorId = cloudAnchorId, AnchorHandle = cloudAnchorHandle, OnTaskComplete = onComplete, }; _UpdateCloudAnchorRequest(request, true); } /// <summary> /// Helper for creating a cloud anchor for the given anchor handle. /// </summary> /// <param name="onComplete">The on complete Action that was created for the /// AsyncTask<CloudAnchorResult>.</param> /// <param name="anchorNativeHandle">The native handle for the anchor.</param> protected internal void _CreateCloudAnchor(Action<CloudAnchorResult> onComplete, IntPtr anchorNativeHandle) { IntPtr cloudAnchorHandle = IntPtr.Zero; var status = LifecycleManager.Instance.NativeSession.SessionApi .CreateCloudAnchor(anchorNativeHandle, out cloudAnchorHandle); if (status != ApiArStatus.Success) { onComplete(new CloudAnchorResult() { Response = status.ToCloudServiceResponse(), Anchor = null, }); return; } _CreateAndTrackCloudAnchorRequest(cloudAnchorHandle, onComplete); return; } protected internal void _CancelCloudAnchorRequest(string cloudAnchorId) { bool cancelledCloudAnchorRequest = false; foreach (var request in m_CloudAnchorRequests) { if (request.CloudAnchorId == null || !request.CloudAnchorId.Equals(cloudAnchorId)) { continue; } if (request.NativeSession != null && !request.NativeSession.IsDestroyed) { request.NativeSession.AnchorApi.Detach(request.AnchorHandle); } AnchorApi.Release(request.AnchorHandle); var result = new CloudAnchorResult() { Response = CloudServiceResponse.ErrorRequestCancelled, Anchor = null, }; request.OnTaskComplete(result); request.IsComplete = true; cancelledCloudAnchorRequest = true; } m_CloudAnchorRequests.RemoveAll(x => x.IsComplete); if (!cancelledCloudAnchorRequest) { Debug.LogWarning("Didn't find pending operation for cloudAnchorId: " + cloudAnchorId); } } private static void _ResetInstance() { s_Instance = null; } private void _OnEarlyUpdate() { foreach (var request in m_CloudAnchorRequests) { _UpdateCloudAnchorRequest(request); } m_CloudAnchorRequests.RemoveAll(x => x.IsComplete); } private void _UpdateCloudAnchorRequest( CloudAnchorRequest request, bool isNewRequest = false) { var cloudState = request.NativeSession.AnchorApi.GetCloudAnchorState(request.AnchorHandle); if (cloudState == ApiCloudAnchorState.Success) { XPAnchor xpAnchor = null; CloudServiceResponse response = CloudServiceResponse.Success; try { xpAnchor = XPAnchor.Factory(request.NativeSession, request.AnchorHandle); } catch (Exception e) { Debug.LogError("Failed to create XP Anchor: " + e.Message); response = CloudServiceResponse.ErrorInternal; } var result = new CloudAnchorResult() { Response = response, Anchor = xpAnchor, }; request.OnTaskComplete(result); request.IsComplete = true; } else if (cloudState != ApiCloudAnchorState.TaskInProgress) { if (request.NativeSession != null && !request.NativeSession.IsDestroyed) { request.NativeSession.AnchorApi.Detach(request.AnchorHandle); } AnchorApi.Release(request.AnchorHandle); var result = new CloudAnchorResult() { Response = cloudState.ToCloudServiceResponse(), Anchor = null }; request.OnTaskComplete(result); request.IsComplete = true; } else if (isNewRequest) { m_CloudAnchorRequests.Add(request); } } private struct ExternApi { [DllImport(ApiConstants.ARCoreNativeApi)] public static extern void ARKitAnchor_create( IntPtr poseHandle, ref IntPtr arkitAnchorHandle); [DllImport(ApiConstants.ARCoreNativeApi)] public static extern void ARKitAnchor_release(IntPtr arkitAnchorHandle); } private class CloudAnchorRequest { public bool IsComplete; public NativeSession NativeSession; public string CloudAnchorId; public IntPtr AnchorHandle; public Action<CloudAnchorResult> OnTaskComplete; } } }
using System; using System.Buffers; using System.Collections.Generic; using System.Data; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Channels; using System.Threading.Tasks; using CsvHelper.Configuration; using DataBoss.Data; using DataBoss.DataPackage.Schema; using DataBoss.IO; using DataBoss.Linq; using DataBoss.Threading; using DataBoss.Threading.Channels; using Newtonsoft.Json; namespace DataBoss.DataPackage { public class DataPackage : IDataPackageBuilder { readonly List<TabularDataResource> resources = new(); delegate bool TryGetResourceOutputPath(ResourcePath path, out string outputPath); internal const int StreamBufferSize = 81920; public const string DefaultDelimiter = ";"; public IReadOnlyList<TabularDataResource> Resources => resources.AsReadOnly(); class DataPackageResourceBuilder : IDataPackageResourceBuilder { readonly DataPackage package; readonly TabularDataResource resource; public DataPackageResourceBuilder(DataPackage package, TabularDataResource resource) { this.package = package; this.resource = resource; } public IDataPackageResourceBuilder AddResource(string name, Func<IDataReader> getData) => package.AddResource(name, getData); public IDataPackageBuilder AddResource(Action<CsvResourceBuilder> setupResource) => package.AddResource(setupResource); public void Save(Func<string, Stream> createOutput, DataPackageSaveOptions options) => package.Save(createOutput, options); public Task SaveAsync(Func<string, Stream> createOutput, DataPackageSaveOptions options) => package.SaveAsync(createOutput, options); public DataPackage Serialize(CultureInfo culture) => package.Serialize(culture); public Task<DataPackage> SerializeAsync(CultureInfo culture) => package.SerializeAsync(culture); public IDataPackageResourceBuilder WithPrimaryKey(params string[] parts) { if (parts != null && parts.Length > 0) resource.Schema.PrimaryKey.AddRange(parts); return this; } public IDataPackageResourceBuilder WithForeignKey(DataPackageForeignKey fk) { if (!package.resources.Any(x => x.Name == fk.Reference.Resource)) throw new InvalidOperationException($"Missing resource '{fk.Reference.Resource}'"); resource.Schema.ForeignKeys.Add(fk); return this; } public IDataPackageResourceBuilder WithDelimiter(string delimiter) { (resource as CsvDataResource).Delimiter = delimiter; return this; } public DataPackage Done() => package; } public static DataPackage Load(string path) { if (Regex.IsMatch(path, "http(s?)://")) return LoadUrl(path); if (path.EndsWith(".zip")) return LoadZip(path); var datapackageRoot = path.EndsWith("datapackage.json") ? Path.GetDirectoryName(path) : path; return Load(x => File.OpenRead(Path.Combine(datapackageRoot, x))); } static DataPackage LoadUrl(string url) { var source = WebResponseStream.Get(url); if (source.ContentType == "application/zip") { try { var bytes = new MemoryStream(); source.CopyTo(bytes); var buff = bytes.TryGetBuffer(out var ok) ? ok : new ArraySegment<byte>(bytes.ToArray()); return LoadZip(() => new MemoryStream(buff.Array, buff.Offset, buff.Count, writable: false)); } finally { source.Dispose(); } } else { var description = LoadPackageDescription(WebResponseStream.Get(url)); return AddCsvSources(new DataPackage(), WebResponseStream.Get, description.Resources); } } public static DataPackage Load(Func<string, Stream> openRead) { var description = LoadPackageDescription(openRead("datapackage.json")); return AddCsvSources(new DataPackage(), openRead, description.Resources); } static DataPackage AddCsvSources(DataPackage r, Func<string, Stream> openRead, IEnumerable<DataPackageResourceDescription> items) { foreach(var item in items) { var source = new CsvDataSource(item, openRead); var resource = TabularDataResource.From(item, source.CreateCsvDataReader); resource.ResourcePath = source.ResourcePath; r.AddResource(resource); } return r; } class CsvDataSource { readonly struct CsvPart { public readonly string PhysicalPath; public readonly string ResourcePath; public readonly ResourceCompression Compression; public CsvPart(string physicalPath, string resourcePath, ResourceCompression compression) { this.PhysicalPath = physicalPath; this.ResourcePath = resourcePath; this.Compression = compression; } } readonly DataPackageResourceDescription desc; readonly Func<string, Stream> openRead; readonly CsvPart[] parts; public CsvDataSource(DataPackageResourceDescription desc, Func<string, Stream> openRead) { this.desc = desc; this.openRead = openRead; this.parts = desc.Path.Select(x => { var r = ResourceCompression.Match(x, openRead); return new CsvPart(x, r.ResourcePath, r.ResourceCompression); }).ToArray(); } public ResourcePath ResourcePath => Array.ConvertAll(parts, x => x.ResourcePath); public CsvDataReader CreateCsvDataReader() => CreateCsvDataReader(new StreamReader(OpenStream(openRead), Encoding.UTF8, true, StreamBufferSize), desc.Dialect, desc.Schema); public Stream OpenStream(Func<string, Stream> open) { if (parts.Length == 1) return OpenPart(parts[0], open); return new ConcatStream(parts.Select(x => OpenPart(x, open)).GetEnumerator()); } static Stream OpenPart(in CsvPart part, Func<string, Stream> open) => part.Compression.OpenRead(part.PhysicalPath, open); static CsvDataReader CreateCsvDataReader(TextReader reader, CsvDialectDescription csvDialect, TabularDataSchema schema) => new( new CsvHelper.CsvParser( reader, new CsvConfiguration(CultureInfo.InvariantCulture) { Delimiter = csvDialect.Delimiter ?? CsvDialectDescription.DefaultDelimiter }), schema, hasHeaderRow: csvDialect.HasHeaderRow); } public static DataPackage LoadZip(string path) => LoadZip(BoundMethod.Bind(File.OpenRead, path)); public static DataPackage LoadZip(Func<Stream> openZip) { var zip = new ZipResource(openZip); return Load(zip.OpenEntry); } class ZipResource { readonly Func<Stream> openZip; public ZipResource(Func<Stream> openZip) { this.openZip = openZip; } public Stream OpenEntry(string path) { var source = new ZipArchive(openZip(), ZipArchiveMode.Read); var stream = new StreamDecorator(source.GetEntry(path).Open()); stream.Closed += source.Dispose; return stream; } } static DataPackageDescription LoadPackageDescription(Stream stream) { var json = new JsonSerializer(); using var reader = new JsonTextReader(new StreamReader(stream)); return json.Deserialize<DataPackageDescription>(reader); } public IDataPackageResourceBuilder AddResource(string name, Func<IDataReader> getData) => AddResource(new CsvResourceOptions { Name = name, Path = Path.ChangeExtension(name, "csv") }, getData); public IDataPackageResourceBuilder AddResource(CsvResourceOptions item) { var parts = item.Path .Select(path => resources.First(x => x.ResourcePath.Count == 1 && x.ResourcePath == path)) .Select(x => x.Read().AsDbDataReader()); return AddResource(item, () => ConcatDataReader.Create(parts.ToArray())); } public IDataPackageResourceBuilder AddResource(CsvResourceOptions item, Func<IDataReader> getData) { var resource = TabularDataResource.From( new DataPackageResourceDescription { Format = "csv", Name = item.Name, Path = item.Path, Schema = new TabularDataSchema { PrimaryKey = new List<string>(), ForeignKeys = new List<DataPackageForeignKey>(), }, Dialect = new CsvDialectDescription { HasHeaderRow = item.HasHeaderRow, } }, getData); AddResource(resource); return new DataPackageResourceBuilder(this, resource); } public IDataPackageBuilder AddResource(Action<CsvResourceBuilder> setupResource) { var newResource = new CsvResourceBuilder(); setupResource(newResource); return AddResource(newResource.Build()); } public IDataPackageBuilder AddResource(TabularDataResource item) { if (TryGetResource(item.Name, out var _)) throw new InvalidOperationException($"Can't add duplicate resource {item.Name}."); resources.Add(item); return this; } DataPackage IDataPackageBuilder.Done() => this; public void UpdateResource(string name, Func<TabularDataResource, TabularDataResource> doUpdate) { var found = resources.FindIndex(x => x.Name == name); if (found == -1) throw new InvalidOperationException($"Resource '{name}' not found."); resources[found] = doUpdate(resources[found]); } public void AddOrUpdateResource(string name, Action<CsvResourceBuilder> setupResource, Func<TabularDataResource, TabularDataResource> doUpdate) { var found = resources.FindIndex(x => x.Name == name); if (found != -1) resources[found] = doUpdate(resources[found]); else { var newResource = new CsvResourceBuilder(); setupResource(newResource.WithName(name)); AddResource(newResource.Build()); } } public void TransformResource(string name, Action<DataReaderTransform> defineTransform) => UpdateResource(name, xs => xs.Transform(defineTransform)); public TabularDataResource GetResource(string name) => TryGetResource(name, out var found) ? found : throw new InvalidOperationException($"Invalid resource name '{name}'"); public bool TryGetResource(string name, out TabularDataResource found) => (found = resources.SingleOrDefault(x => x.Name == name)) != null; public bool RemoveResource(string name) => RemoveResource(name, ConstraintsBehavior.Check, out var _); public bool RemoveResource(string name, out TabularDataResource value) => RemoveResource(name, ConstraintsBehavior.Check, out value); public bool RemoveResource(string name, ConstraintsBehavior constraintsBehavior, out TabularDataResource value) { if (!TryGetResource(name, out value)) return false; var references = AllForeignKeys() .Where(x => x.ForeignKey.Resource == name) .ToList(); switch (constraintsBehavior) { case ConstraintsBehavior.Check: if (references.Any()) throw new InvalidOperationException($"Can't remove resource {name}, it's referenced by: {string.Join(", ", references.Select(x => x.Resource.Name))}."); break; case ConstraintsBehavior.Drop: foreach (var (resource, _) in references) resource.Schema.ForeignKeys.RemoveAll(x => x.Reference.Resource == name); break; } resources.Remove(value); return true; } IEnumerable<(TabularDataResource Resource, DataPackageKeyReference ForeignKey)> AllForeignKeys() => resources.SelectMany(xs => xs.Schema?.ForeignKeys.EmptyIfNull().Select(x => (Resource: xs, ForeignKey: x.Reference))); public void Save(Func<string, Stream> createOutput, CultureInfo culture = null) => Save(createOutput, new DataPackageSaveOptions { Culture = culture }); public void Save(Func<string, Stream> createOutput, DataPackageSaveOptions options) => TaskRunner.Run(() => SaveAsync(createOutput, options)); public Task SaveAsync(Func<string, Stream> createOutput, CultureInfo culture = null) => SaveAsync(createOutput, new DataPackageSaveOptions { Culture = culture }); public async Task SaveAsync(Func<string, Stream> createOutput, DataPackageSaveOptions options) { var description = new DataPackageDescription(); var writtenPaths = new HashSet<string>(); foreach (var item in resources) { using var data = item.Read(); var desc = item.GetDescription(options.Culture); desc.Dialect.Delimiter ??= DefaultDelimiter; description.Resources.Add(desc); if (!desc.Path.TryGetOutputPath(out var partPath) || writtenPaths.Contains(partPath)) continue; var (outputPath, output) = options.ResourceCompression.OpenWrite(partPath, createOutput); desc.Path = outputPath; try { var view = DataRecordStringView.Create(desc.Schema.Fields, data, options.Culture); await WriteRecordsAsync(output, desc.Dialect, data, view); } catch (Exception ex) { throw new Exception($"Failed writing {item.Name}.", ex); } finally { writtenPaths.Add(outputPath); output.Dispose(); } } using var meta = new StreamWriter(createOutput("datapackage.json")); meta.Write(JsonConvert.SerializeObject(description, Formatting.Indented)); } public DataPackage Serialize(CultureInfo culture = null) { var store = new InMemoryDataPackageStore(); Save(store.OpenWrite, culture); return Load(store.OpenRead); } public async Task<DataPackage> SerializeAsync(CultureInfo culture = null) { var store = new InMemoryDataPackageStore(); await SaveAsync(store.OpenRead, culture); return Load(store.OpenRead); } static Task WriteRecordsAsync(Stream output, CsvDialectDescription csvDialect, IDataReader data, DataRecordStringView view) { var encoding = Encoding.UTF8; var bom = encoding.GetPreamble(); var csv = new CsvRecordWriter(csvDialect.Delimiter, encoding); if (csvDialect.HasHeaderRow) csv.WriteHeaderRecord(output, data); var records = Channel.CreateBounded<(IMemoryOwner<IDataRecord>, int)>(new BoundedChannelOptions(16) { SingleWriter = true, }); var chunks = Channel.CreateBounded<Stream>(new BoundedChannelOptions(16) { SingleWriter = false, SingleReader = true, }); var cancellation = new CancellationTokenSource(); var readerTask = new RecordReader(data.AsDataRecordReader(), records, cancellation.Token).RunAsync(); var writerTask = csv.WriteChunksAsync(records, chunks, view); writerTask.ContinueWith(x => { if (x.IsFaulted) cancellation.Cancel(); }, TaskContinuationOptions.ExecuteSynchronously); return Task.WhenAll( readerTask, writerTask, CopyChunks(chunks.Reader, output, bom)); } internal static Task CopyChunks(ChannelReader<Stream> chunks, Stream output, byte[] bom) => chunks.ForEachAsync(x => { try { if (!TryReadBom(x, bom)) throw new InvalidOperationException("Missing BOM in fragment."); x.CopyTo(output); } finally { x.Dispose(); } }); static bool TryReadBom(Stream stream, byte[] bom) { var fragmentBom = new byte[bom.Length]; for (var read = 0; read != fragmentBom.Length;) { var n = stream.Read(fragmentBom, read, fragmentBom.Length - read); if (n == 0) return false; read += n; } return new Span<byte>(fragmentBom).SequenceEqual(bom); } } public class DataPackageSaveOptions { public CultureInfo Culture = null; public ResourceCompression ResourceCompression = ResourceCompression.None; } public static class TabularDataResourceCsvExtensions { public static void WriteCsv(this TabularDataResource self, TextWriter writer) { using var reader = self.Read(); var desc = self.GetDescription(); var view = DataRecordStringView.Create(desc.Schema.Fields, reader, null); var csv = new CsvRecordWriter(";", writer.Encoding); csv.WriteHeaderRecord(writer, reader); csv.WriteRecords(writer, reader, view); } public static async Task WriteCsvAsync(this TabularDataResource self, Stream output) { using var reader = self.Read(); var desc = self.GetDescription(); var view = DataRecordStringView.Create(desc.Schema.Fields, reader, null); var csvDialect = new CsvDialectDescription { Delimiter = ";" }; var encoding = Encoding.UTF8; var bom = encoding.GetPreamble(); var csv = new CsvRecordWriter(csvDialect.Delimiter, encoding); if (csvDialect.HasHeaderRow) csv.WriteHeaderRecord(output, reader); var records = Channel.CreateBounded<(IMemoryOwner<IDataRecord>, int)>(new BoundedChannelOptions(16) { SingleWriter = true, }); var chunks = Channel.CreateBounded<Stream>(new BoundedChannelOptions(16) { SingleWriter = false, SingleReader = true, }); var cancellation = new CancellationTokenSource(); var readerTask = new RecordReader(reader.AsDataRecordReader(), records, cancellation.Token).RunAsync(); var writerTask = csv.WriteChunksAsync(records, chunks, view); await Task.WhenAll( readerTask, writerTask, writerTask.ContinueWith(x => { if (x.IsFaulted) cancellation.Cancel(); }, TaskContinuationOptions.ExecuteSynchronously), DataPackage.CopyChunks(chunks.Reader, output, bom)); } } }
/* * Infoplus API * * Infoplus API. * * OpenAPI spec version: v1.0 * Contact: [email protected] * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using RestSharp; using Infoplus.Client; using Infoplus.Model; namespace Infoplus.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IParcelShipmentApi : IApiAccessor { #region Synchronous Operations /// <summary> /// Search parcelShipments by filter /// </summary> /// <remarks> /// Returns the list of parcelShipments that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>List&lt;ParcelShipment&gt;</returns> List<ParcelShipment> GetParcelShipmentByFilter (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Search parcelShipments by filter /// </summary> /// <remarks> /// Returns the list of parcelShipments that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>ApiResponse of List&lt;ParcelShipment&gt;</returns> ApiResponse<List<ParcelShipment>> GetParcelShipmentByFilterWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Get a parcelShipment by id /// </summary> /// <remarks> /// Returns the parcelShipment identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="parcelShipmentId">Id of the parcelShipment to be returned.</param> /// <returns>ParcelShipment</returns> ParcelShipment GetParcelShipmentById (int? parcelShipmentId); /// <summary> /// Get a parcelShipment by id /// </summary> /// <remarks> /// Returns the parcelShipment identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="parcelShipmentId">Id of the parcelShipment to be returned.</param> /// <returns>ApiResponse of ParcelShipment</returns> ApiResponse<ParcelShipment> GetParcelShipmentByIdWithHttpInfo (int? parcelShipmentId); #endregion Synchronous Operations #region Asynchronous Operations /// <summary> /// Search parcelShipments by filter /// </summary> /// <remarks> /// Returns the list of parcelShipments that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of List&lt;ParcelShipment&gt;</returns> System.Threading.Tasks.Task<List<ParcelShipment>> GetParcelShipmentByFilterAsync (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Search parcelShipments by filter /// </summary> /// <remarks> /// Returns the list of parcelShipments that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of ApiResponse (List&lt;ParcelShipment&gt;)</returns> System.Threading.Tasks.Task<ApiResponse<List<ParcelShipment>>> GetParcelShipmentByFilterAsyncWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Get a parcelShipment by id /// </summary> /// <remarks> /// Returns the parcelShipment identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="parcelShipmentId">Id of the parcelShipment to be returned.</param> /// <returns>Task of ParcelShipment</returns> System.Threading.Tasks.Task<ParcelShipment> GetParcelShipmentByIdAsync (int? parcelShipmentId); /// <summary> /// Get a parcelShipment by id /// </summary> /// <remarks> /// Returns the parcelShipment identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="parcelShipmentId">Id of the parcelShipment to be returned.</param> /// <returns>Task of ApiResponse (ParcelShipment)</returns> System.Threading.Tasks.Task<ApiResponse<ParcelShipment>> GetParcelShipmentByIdAsyncWithHttpInfo (int? parcelShipmentId); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class ParcelShipmentApi : IParcelShipmentApi { private Infoplus.Client.ExceptionFactory _exceptionFactory = (name, response) => null; /// <summary> /// Initializes a new instance of the <see cref="ParcelShipmentApi"/> class. /// </summary> /// <returns></returns> public ParcelShipmentApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Initializes a new instance of the <see cref="ParcelShipmentApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public ParcelShipmentApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = Configuration.Default; else this.Configuration = configuration; ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <value>The base path</value> [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public Configuration Configuration {get; set;} /// <summary> /// Provides a factory method hook for the creation of exceptions. /// </summary> public Infoplus.Client.ExceptionFactory ExceptionFactory { get { if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) { throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); } return _exceptionFactory; } set { _exceptionFactory = value; } } /// <summary> /// Gets the default header. /// </summary> /// <returns>Dictionary of HTTP header</returns> [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] public Dictionary<String, String> DefaultHeader() { return this.Configuration.DefaultHeader; } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] public void AddDefaultHeader(string key, string value) { this.Configuration.AddDefaultHeader(key, value); } /// <summary> /// Search parcelShipments by filter Returns the list of parcelShipments that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>List&lt;ParcelShipment&gt;</returns> public List<ParcelShipment> GetParcelShipmentByFilter (string filter = null, int? page = null, int? limit = null, string sort = null) { ApiResponse<List<ParcelShipment>> localVarResponse = GetParcelShipmentByFilterWithHttpInfo(filter, page, limit, sort); return localVarResponse.Data; } /// <summary> /// Search parcelShipments by filter Returns the list of parcelShipments that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>ApiResponse of List&lt;ParcelShipment&gt;</returns> public ApiResponse< List<ParcelShipment> > GetParcelShipmentByFilterWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null) { var localVarPath = "/v1.0/parcelShipment/search"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter if (sort != null) localVarQueryParams.Add("sort", Configuration.ApiClient.ParameterToString(sort)); // query parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetParcelShipmentByFilter", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<List<ParcelShipment>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (List<ParcelShipment>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<ParcelShipment>))); } /// <summary> /// Search parcelShipments by filter Returns the list of parcelShipments that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of List&lt;ParcelShipment&gt;</returns> public async System.Threading.Tasks.Task<List<ParcelShipment>> GetParcelShipmentByFilterAsync (string filter = null, int? page = null, int? limit = null, string sort = null) { ApiResponse<List<ParcelShipment>> localVarResponse = await GetParcelShipmentByFilterAsyncWithHttpInfo(filter, page, limit, sort); return localVarResponse.Data; } /// <summary> /// Search parcelShipments by filter Returns the list of parcelShipments that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of ApiResponse (List&lt;ParcelShipment&gt;)</returns> public async System.Threading.Tasks.Task<ApiResponse<List<ParcelShipment>>> GetParcelShipmentByFilterAsyncWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null) { var localVarPath = "/v1.0/parcelShipment/search"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter if (sort != null) localVarQueryParams.Add("sort", Configuration.ApiClient.ParameterToString(sort)); // query parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetParcelShipmentByFilter", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<List<ParcelShipment>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (List<ParcelShipment>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<ParcelShipment>))); } /// <summary> /// Get a parcelShipment by id Returns the parcelShipment identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="parcelShipmentId">Id of the parcelShipment to be returned.</param> /// <returns>ParcelShipment</returns> public ParcelShipment GetParcelShipmentById (int? parcelShipmentId) { ApiResponse<ParcelShipment> localVarResponse = GetParcelShipmentByIdWithHttpInfo(parcelShipmentId); return localVarResponse.Data; } /// <summary> /// Get a parcelShipment by id Returns the parcelShipment identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="parcelShipmentId">Id of the parcelShipment to be returned.</param> /// <returns>ApiResponse of ParcelShipment</returns> public ApiResponse< ParcelShipment > GetParcelShipmentByIdWithHttpInfo (int? parcelShipmentId) { // verify the required parameter 'parcelShipmentId' is set if (parcelShipmentId == null) throw new ApiException(400, "Missing required parameter 'parcelShipmentId' when calling ParcelShipmentApi->GetParcelShipmentById"); var localVarPath = "/v1.0/parcelShipment/{parcelShipmentId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (parcelShipmentId != null) localVarPathParams.Add("parcelShipmentId", Configuration.ApiClient.ParameterToString(parcelShipmentId)); // path parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetParcelShipmentById", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<ParcelShipment>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (ParcelShipment) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ParcelShipment))); } /// <summary> /// Get a parcelShipment by id Returns the parcelShipment identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="parcelShipmentId">Id of the parcelShipment to be returned.</param> /// <returns>Task of ParcelShipment</returns> public async System.Threading.Tasks.Task<ParcelShipment> GetParcelShipmentByIdAsync (int? parcelShipmentId) { ApiResponse<ParcelShipment> localVarResponse = await GetParcelShipmentByIdAsyncWithHttpInfo(parcelShipmentId); return localVarResponse.Data; } /// <summary> /// Get a parcelShipment by id Returns the parcelShipment identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="parcelShipmentId">Id of the parcelShipment to be returned.</param> /// <returns>Task of ApiResponse (ParcelShipment)</returns> public async System.Threading.Tasks.Task<ApiResponse<ParcelShipment>> GetParcelShipmentByIdAsyncWithHttpInfo (int? parcelShipmentId) { // verify the required parameter 'parcelShipmentId' is set if (parcelShipmentId == null) throw new ApiException(400, "Missing required parameter 'parcelShipmentId' when calling ParcelShipmentApi->GetParcelShipmentById"); var localVarPath = "/v1.0/parcelShipment/{parcelShipmentId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (parcelShipmentId != null) localVarPathParams.Add("parcelShipmentId", Configuration.ApiClient.ParameterToString(parcelShipmentId)); // path parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetParcelShipmentById", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<ParcelShipment>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (ParcelShipment) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ParcelShipment))); } } }
using System; using System.Reactive.Linq; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; namespace Avalonia.Controls { /// <summary> /// A control scrolls its content if the content is bigger than the space available. /// </summary> public class ScrollViewer : ContentControl, IScrollable, IScrollAnchorProvider { /// <summary> /// Defines the <see cref="CanHorizontallyScroll"/> property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, bool> CanHorizontallyScrollProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, bool>( nameof(CanHorizontallyScroll), o => o.CanHorizontallyScroll); /// <summary> /// Defines the <see cref="CanVerticallyScroll"/> property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, bool> CanVerticallyScrollProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, bool>( nameof(CanVerticallyScroll), o => o.CanVerticallyScroll); /// <summary> /// Defines the <see cref="Extent"/> property. /// </summary> public static readonly DirectProperty<ScrollViewer, Size> ExtentProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, Size>(nameof(Extent), o => o.Extent, (o, v) => o.Extent = v); /// <summary> /// Defines the <see cref="Offset"/> property. /// </summary> public static readonly DirectProperty<ScrollViewer, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, Vector>( nameof(Offset), o => o.Offset, (o, v) => o.Offset = v); /// <summary> /// Defines the <see cref="Viewport"/> property. /// </summary> public static readonly DirectProperty<ScrollViewer, Size> ViewportProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, Size>(nameof(Viewport), o => o.Viewport, (o, v) => o.Viewport = v); /// <summary> /// Defines the <see cref="LargeChange"/> property. /// </summary> public static readonly DirectProperty<ScrollViewer, Size> LargeChangeProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, Size>( nameof(LargeChange), o => o.LargeChange); /// <summary> /// Defines the <see cref="SmallChange"/> property. /// </summary> public static readonly DirectProperty<ScrollViewer, Size> SmallChangeProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, Size>( nameof(SmallChange), o => o.SmallChange); /// <summary> /// Defines the HorizontalScrollBarMaximum property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, double> HorizontalScrollBarMaximumProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, double>( nameof(HorizontalScrollBarMaximum), o => o.HorizontalScrollBarMaximum); /// <summary> /// Defines the HorizontalScrollBarValue property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, double> HorizontalScrollBarValueProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, double>( nameof(HorizontalScrollBarValue), o => o.HorizontalScrollBarValue, (o, v) => o.HorizontalScrollBarValue = v); /// <summary> /// Defines the HorizontalScrollBarViewportSize property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, double> HorizontalScrollBarViewportSizeProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, double>( nameof(HorizontalScrollBarViewportSize), o => o.HorizontalScrollBarViewportSize); /// <summary> /// Defines the <see cref="HorizontalScrollBarVisibility"/> property. /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = AvaloniaProperty.RegisterAttached<ScrollViewer, Control, ScrollBarVisibility>( nameof(HorizontalScrollBarVisibility), ScrollBarVisibility.Hidden); /// <summary> /// Defines the VerticalScrollBarMaximum property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, double> VerticalScrollBarMaximumProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, double>( nameof(VerticalScrollBarMaximum), o => o.VerticalScrollBarMaximum); /// <summary> /// Defines the VerticalScrollBarValue property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, double> VerticalScrollBarValueProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, double>( nameof(VerticalScrollBarValue), o => o.VerticalScrollBarValue, (o, v) => o.VerticalScrollBarValue = v); /// <summary> /// Defines the VerticalScrollBarViewportSize property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, double> VerticalScrollBarViewportSizeProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, double>( nameof(VerticalScrollBarViewportSize), o => o.VerticalScrollBarViewportSize); /// <summary> /// Defines the <see cref="VerticalScrollBarVisibility"/> property. /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = AvaloniaProperty.RegisterAttached<ScrollViewer, Control, ScrollBarVisibility>( nameof(VerticalScrollBarVisibility), ScrollBarVisibility.Auto); /// <summary> /// Defines the <see cref="IsExpandedProperty"/> property. /// </summary> public static readonly DirectProperty<ScrollViewer, bool> IsExpandedProperty = ScrollBar.IsExpandedProperty.AddOwner<ScrollViewer>(o => o.IsExpanded); /// <summary> /// Defines the <see cref="AllowAutoHide"/> property. /// </summary> public static readonly StyledProperty<bool> AllowAutoHideProperty = ScrollBar.AllowAutoHideProperty.AddOwner<ScrollViewer>(); /// <summary> /// Defines the <see cref="ScrollChanged"/> event. /// </summary> public static readonly RoutedEvent<ScrollChangedEventArgs> ScrollChangedEvent = RoutedEvent.Register<ScrollViewer, ScrollChangedEventArgs>( nameof(ScrollChanged), RoutingStrategies.Bubble); internal const double DefaultSmallChange = 16; private IDisposable _childSubscription; private ILogicalScrollable _logicalScrollable; private Size _extent; private Vector _offset; private Size _viewport; private Size _oldExtent; private Vector _oldOffset; private Size _oldViewport; private Size _largeChange; private Size _smallChange = new Size(DefaultSmallChange, DefaultSmallChange); private bool _isExpanded; private IDisposable _scrollBarExpandSubscription; /// <summary> /// Initializes static members of the <see cref="ScrollViewer"/> class. /// </summary> static ScrollViewer() { HorizontalScrollBarVisibilityProperty.Changed.AddClassHandler<ScrollViewer>((x, e) => x.ScrollBarVisibilityChanged(e)); VerticalScrollBarVisibilityProperty.Changed.AddClassHandler<ScrollViewer>((x, e) => x.ScrollBarVisibilityChanged(e)); } /// <summary> /// Initializes a new instance of the <see cref="ScrollViewer"/> class. /// </summary> public ScrollViewer() { LayoutUpdated += OnLayoutUpdated; } /// <summary> /// Occurs when changes are detected to the scroll position, extent, or viewport size. /// </summary> public event EventHandler<ScrollChangedEventArgs> ScrollChanged { add => AddHandler(ScrollChangedEvent, value); remove => RemoveHandler(ScrollChangedEvent, value); } /// <summary> /// Gets the extent of the scrollable content. /// </summary> public Size Extent { get { return _extent; } private set { if (SetAndRaise(ExtentProperty, ref _extent, value)) { CalculatedPropertiesChanged(); } } } /// <summary> /// Gets or sets the current scroll offset. /// </summary> public Vector Offset { get { return _offset; } set { if (SetAndRaise(OffsetProperty, ref _offset, CoerceOffset(Extent, Viewport, value))) { CalculatedPropertiesChanged(); } } } /// <summary> /// Gets the size of the viewport on the scrollable content. /// </summary> public Size Viewport { get { return _viewport; } private set { if (SetAndRaise(ViewportProperty, ref _viewport, value)) { CalculatedPropertiesChanged(); } } } /// <summary> /// Gets the large (page) change value for the scroll viewer. /// </summary> public Size LargeChange => _largeChange; /// <summary> /// Gets the small (line) change value for the scroll viewer. /// </summary> public Size SmallChange => _smallChange; /// <summary> /// Gets or sets the horizontal scrollbar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get { return GetValue(HorizontalScrollBarVisibilityProperty); } set { SetValue(HorizontalScrollBarVisibilityProperty, value); } } /// <summary> /// Gets or sets the vertical scrollbar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get { return GetValue(VerticalScrollBarVisibilityProperty); } set { SetValue(VerticalScrollBarVisibilityProperty, value); } } /// <summary> /// Gets a value indicating whether the viewer can scroll horizontally. /// </summary> protected bool CanHorizontallyScroll { get { return HorizontalScrollBarVisibility != ScrollBarVisibility.Disabled; } } /// <summary> /// Gets a value indicating whether the viewer can scroll vertically. /// </summary> protected bool CanVerticallyScroll { get { return VerticalScrollBarVisibility != ScrollBarVisibility.Disabled; } } /// <inheritdoc/> public IControl CurrentAnchor => (Presenter as IScrollAnchorProvider)?.CurrentAnchor; /// <summary> /// Gets the maximum horizontal scrollbar value. /// </summary> protected double HorizontalScrollBarMaximum { get { return Max(_extent.Width - _viewport.Width, 0); } } /// <summary> /// Gets or sets the horizontal scrollbar value. /// </summary> protected double HorizontalScrollBarValue { get { return _offset.X; } set { if (_offset.X != value) { var old = Offset.X; Offset = Offset.WithX(value); RaisePropertyChanged(HorizontalScrollBarValueProperty, old, value); } } } /// <summary> /// Gets the size of the horizontal scrollbar viewport. /// </summary> protected double HorizontalScrollBarViewportSize { get { return _viewport.Width; } } /// <summary> /// Gets the maximum vertical scrollbar value. /// </summary> protected double VerticalScrollBarMaximum { get { return Max(_extent.Height - _viewport.Height, 0); } } /// <summary> /// Gets or sets the vertical scrollbar value. /// </summary> protected double VerticalScrollBarValue { get { return _offset.Y; } set { if (_offset.Y != value) { var old = Offset.Y; Offset = Offset.WithY(value); RaisePropertyChanged(VerticalScrollBarValueProperty, old, value); } } } /// <summary> /// Gets the size of the vertical scrollbar viewport. /// </summary> protected double VerticalScrollBarViewportSize { get { return _viewport.Height; } } /// <summary> /// Gets a value that indicates whether any scrollbar is expanded. /// </summary> public bool IsExpanded { get => _isExpanded; private set => SetAndRaise(ScrollBar.IsExpandedProperty, ref _isExpanded, value); } /// <summary> /// Gets a value that indicates whether scrollbars can hide itself when user is not interacting with it. /// </summary> public bool AllowAutoHide { get => GetValue(AllowAutoHideProperty); set => SetValue(AllowAutoHideProperty, value); } /// <summary> /// Scrolls the content up one line. /// </summary> public void LineUp() { Offset -= new Vector(0, _smallChange.Height); } /// <summary> /// Scrolls the content down one line. /// </summary> public void LineDown() { Offset += new Vector(0, _smallChange.Height); } /// <summary> /// Scrolls the content left one line. /// </summary> public void LineLeft() { Offset -= new Vector(_smallChange.Width, 0); } /// <summary> /// Scrolls the content right one line. /// </summary> public void LineRight() { Offset += new Vector(_smallChange.Width, 0); } /// <summary> /// Scrolls the content upward by one page. /// </summary> public void PageUp() { VerticalScrollBarValue = Math.Max(_offset.Y - _viewport.Height, 0); } /// <summary> /// Scrolls the content downward by one page. /// </summary> public void PageDown() { VerticalScrollBarValue = Math.Min(_offset.Y + _viewport.Height, VerticalScrollBarMaximum); } /// <summary> /// Scrolls the content left by one page. /// </summary> public void PageLeft() { HorizontalScrollBarValue = Math.Max(_offset.X - _viewport.Width, 0); } /// <summary> /// Scrolls the content tight by one page. /// </summary> public void PageRight() { HorizontalScrollBarValue = Math.Min(_offset.X + _viewport.Width, HorizontalScrollBarMaximum); } /// <summary> /// Scrolls to the top-left corner of the content. /// </summary> public void ScrollToHome() { Offset = new Vector(double.NegativeInfinity, double.NegativeInfinity); } /// <summary> /// Scrolls to the bottom-left corner of the content. /// </summary> public void ScrollToEnd() { Offset = new Vector(double.NegativeInfinity, double.PositiveInfinity); } /// <summary> /// Gets the value of the HorizontalScrollBarVisibility attached property. /// </summary> /// <param name="control">The control to read the value from.</param> /// <returns>The value of the property.</returns> public static ScrollBarVisibility GetHorizontalScrollBarVisibility(Control control) { return control.GetValue(HorizontalScrollBarVisibilityProperty); } /// <summary> /// Gets the value of the HorizontalScrollBarVisibility attached property. /// </summary> /// <param name="control">The control to set the value on.</param> /// <param name="value">The value of the property.</param> public static void SetHorizontalScrollBarVisibility(Control control, ScrollBarVisibility value) { control.SetValue(HorizontalScrollBarVisibilityProperty, value); } /// <summary> /// Gets the value of the VerticalScrollBarVisibility attached property. /// </summary> /// <param name="control">The control to read the value from.</param> /// <returns>The value of the property.</returns> public static ScrollBarVisibility GetVerticalScrollBarVisibility(Control control) { return control.GetValue(VerticalScrollBarVisibilityProperty); } /// <summary> /// Gets the value of the VerticalScrollBarVisibility attached property. /// </summary> /// <param name="control">The control to set the value on.</param> /// <param name="value">The value of the property.</param> public static void SetVerticalScrollBarVisibility(Control control, ScrollBarVisibility value) { control.SetValue(VerticalScrollBarVisibilityProperty, value); } /// <inheritdoc/> public void RegisterAnchorCandidate(IControl element) { (Presenter as IScrollAnchorProvider)?.RegisterAnchorCandidate(element); } /// <inheritdoc/> public void UnregisterAnchorCandidate(IControl element) { (Presenter as IScrollAnchorProvider)?.UnregisterAnchorCandidate(element); } protected override bool RegisterContentPresenter(IContentPresenter presenter) { _childSubscription?.Dispose(); _childSubscription = null; if (base.RegisterContentPresenter(presenter)) { _childSubscription = Presenter? .GetObservable(ContentPresenter.ChildProperty) .Subscribe(ChildChanged); return true; } return false; } internal static Vector CoerceOffset(Size extent, Size viewport, Vector offset) { var maxX = Math.Max(extent.Width - viewport.Width, 0); var maxY = Math.Max(extent.Height - viewport.Height, 0); return new Vector(Clamp(offset.X, 0, maxX), Clamp(offset.Y, 0, maxY)); } private static double Clamp(double value, double min, double max) { return (value < min) ? min : (value > max) ? max : value; } private static double Max(double x, double y) { var result = Math.Max(x, y); return double.IsNaN(result) ? 0 : result; } private void ChildChanged(IControl child) { if (_logicalScrollable is object) { _logicalScrollable.ScrollInvalidated -= LogicalScrollInvalidated; _logicalScrollable = null; } if (child is ILogicalScrollable logical) { _logicalScrollable = logical; logical.ScrollInvalidated += LogicalScrollInvalidated; } CalculatedPropertiesChanged(); } private void LogicalScrollInvalidated(object sender, EventArgs e) { CalculatedPropertiesChanged(); } private void ScrollBarVisibilityChanged(AvaloniaPropertyChangedEventArgs e) { var wasEnabled = !ScrollBarVisibility.Disabled.Equals(e.OldValue); var isEnabled = !ScrollBarVisibility.Disabled.Equals(e.NewValue); if (wasEnabled != isEnabled) { if (e.Property == HorizontalScrollBarVisibilityProperty) { RaisePropertyChanged( CanHorizontallyScrollProperty, wasEnabled, isEnabled); } else if (e.Property == VerticalScrollBarVisibilityProperty) { RaisePropertyChanged( CanVerticallyScrollProperty, wasEnabled, isEnabled); } } } private void CalculatedPropertiesChanged() { // Pass old values of 0 here because we don't have the old values at this point, // and it shouldn't matter as only the template uses these properies. RaisePropertyChanged(HorizontalScrollBarMaximumProperty, 0, HorizontalScrollBarMaximum); RaisePropertyChanged(HorizontalScrollBarValueProperty, 0, HorizontalScrollBarValue); RaisePropertyChanged(HorizontalScrollBarViewportSizeProperty, 0, HorizontalScrollBarViewportSize); RaisePropertyChanged(VerticalScrollBarMaximumProperty, 0, VerticalScrollBarMaximum); RaisePropertyChanged(VerticalScrollBarValueProperty, 0, VerticalScrollBarValue); RaisePropertyChanged(VerticalScrollBarViewportSizeProperty, 0, VerticalScrollBarViewportSize); if (_logicalScrollable?.IsLogicalScrollEnabled == true) { SetAndRaise(SmallChangeProperty, ref _smallChange, _logicalScrollable.ScrollSize); SetAndRaise(LargeChangeProperty, ref _largeChange, _logicalScrollable.PageScrollSize); } else { SetAndRaise(SmallChangeProperty, ref _smallChange, new Size(DefaultSmallChange, DefaultSmallChange)); SetAndRaise(LargeChangeProperty, ref _largeChange, Viewport); } } protected override void OnKeyDown(KeyEventArgs e) { if (e.Key == Key.PageUp) { PageUp(); e.Handled = true; } else if (e.Key == Key.PageDown) { PageDown(); e.Handled = true; } } /// <summary> /// Called when a change in scrolling state is detected, such as a change in scroll /// position, extent, or viewport size. /// </summary> /// <param name="e">The event args.</param> /// <remarks> /// If you override this method, call `base.OnScrollChanged(ScrollChangedEventArgs)` to /// ensure that this event is raised. /// </remarks> protected virtual void OnScrollChanged(ScrollChangedEventArgs e) { RaiseEvent(e); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); _scrollBarExpandSubscription?.Dispose(); _scrollBarExpandSubscription = SubscribeToScrollBars(e); } private IDisposable SubscribeToScrollBars(TemplateAppliedEventArgs e) { static IObservable<bool> GetExpandedObservable(ScrollBar scrollBar) { return scrollBar?.GetObservable(ScrollBar.IsExpandedProperty); } var horizontalScrollBar = e.NameScope.Find<ScrollBar>("PART_HorizontalScrollBar"); var verticalScrollBar = e.NameScope.Find<ScrollBar>("PART_VerticalScrollBar"); var horizontalExpanded = GetExpandedObservable(horizontalScrollBar); var verticalExpanded = GetExpandedObservable(verticalScrollBar); IObservable<bool> actualExpanded = null; if (horizontalExpanded != null && verticalExpanded != null) { actualExpanded = horizontalExpanded.CombineLatest(verticalExpanded, (h, v) => h || v); } else { if (horizontalExpanded != null) { actualExpanded = horizontalExpanded; } else if (verticalExpanded != null) { actualExpanded = verticalExpanded; } } return actualExpanded?.Subscribe(OnScrollBarExpandedChanged); } private void OnScrollBarExpandedChanged(bool isExpanded) { IsExpanded = isExpanded; } private void OnLayoutUpdated(object sender, EventArgs e) => RaiseScrollChanged(); private void RaiseScrollChanged() { var extentDelta = new Vector(Extent.Width - _oldExtent.Width, Extent.Height - _oldExtent.Height); var offsetDelta = Offset - _oldOffset; var viewportDelta = new Vector(Viewport.Width - _oldViewport.Width, Viewport.Height - _oldViewport.Height); if (!extentDelta.NearlyEquals(default) || !offsetDelta.NearlyEquals(default) || !viewportDelta.NearlyEquals(default)) { var e = new ScrollChangedEventArgs(extentDelta, offsetDelta, viewportDelta); OnScrollChanged(e); _oldExtent = Extent; _oldOffset = Offset; _oldViewport = Viewport; } } } }
// // 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.Management.SiteRecovery; using Microsoft.Azure.Management.SiteRecovery.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.SiteRecovery { /// <summary> /// Definition of Logical Network operations for the Site Recovery /// extension. /// </summary> internal partial class LogicalNetworkOperations : IServiceOperations<SiteRecoveryManagementClient>, ILogicalNetworkOperations { /// <summary> /// Initializes a new instance of the LogicalNetworkOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal LogicalNetworkOperations(SiteRecoveryManagementClient client) { this._client = client; } private SiteRecoveryManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.SiteRecovery.SiteRecoveryManagementClient. /// </summary> public SiteRecoveryManagementClient Client { get { return this._client; } } /// <summary> /// Gets a VM logical network. /// </summary> /// <param name='fabricName'> /// Required. Fabric unique name. /// </param> /// <param name='logicalNetworkName'> /// Required. Network name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the Logical Network object. /// </returns> public async Task<LogicalNetworkResponse> GetAsync(string fabricName, string logicalNetworkName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (fabricName == null) { throw new ArgumentNullException("fabricName"); } if (logicalNetworkName == null) { throw new ArgumentNullException("logicalNetworkName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("logicalNetworkName", logicalNetworkName); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/Subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(this.Client.ResourceGroupName); url = url + "/providers/"; url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceType); url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceName); url = url + "/replicationFabrics/"; url = url + Uri.EscapeDataString(fabricName); url = url + "/replicationLogicalNetworks/"; url = url + Uri.EscapeDataString(logicalNetworkName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-11-10"); 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 httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2015-01-01"); // 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 LogicalNetworkResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new LogicalNetworkResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { LogicalNetwork logicalNetworkInstance = new LogicalNetwork(); result.LogicalNetwork = logicalNetworkInstance; JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { LogicalNetworkProperties propertiesInstance = new LogicalNetworkProperties(); logicalNetworkInstance.Properties = propertiesInstance; JToken friendlyNameValue = propertiesValue["friendlyName"]; if (friendlyNameValue != null && friendlyNameValue.Type != JTokenType.Null) { string friendlyNameInstance = ((string)friendlyNameValue); propertiesInstance.FriendlyName = friendlyNameInstance; } JToken logicalNetworkDefinitionsStatusValue = propertiesValue["logicalNetworkDefinitionsStatus"]; if (logicalNetworkDefinitionsStatusValue != null && logicalNetworkDefinitionsStatusValue.Type != JTokenType.Null) { string logicalNetworkDefinitionsStatusInstance = ((string)logicalNetworkDefinitionsStatusValue); propertiesInstance.LogicalNetworkDefinitionsStatus = logicalNetworkDefinitionsStatusInstance; } JToken networkVirtualizationStatusValue = propertiesValue["networkVirtualizationStatus"]; if (networkVirtualizationStatusValue != null && networkVirtualizationStatusValue.Type != JTokenType.Null) { string networkVirtualizationStatusInstance = ((string)networkVirtualizationStatusValue); propertiesInstance.NetworkVirtualizationStatus = networkVirtualizationStatusInstance; } JToken logicalNetworkUsageValue = propertiesValue["logicalNetworkUsage"]; if (logicalNetworkUsageValue != null && logicalNetworkUsageValue.Type != JTokenType.Null) { string logicalNetworkUsageInstance = ((string)logicalNetworkUsageValue); propertiesInstance.LogicalNetworkUsage = logicalNetworkUsageInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); logicalNetworkInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); logicalNetworkInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); logicalNetworkInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); logicalNetworkInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); logicalNetworkInstance.Tags.Add(tagsKey, tagsValue); } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Get list of Logical Networks. /// </summary> /// <param name='fabricName'> /// Required. Fabric unique name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list of Logical Networks. /// </returns> public async Task<LogicalNetworksListResponse> ListAsync(string fabricName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (fabricName == null) { throw new ArgumentNullException("fabricName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/Subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(this.Client.ResourceGroupName); url = url + "/providers/"; url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceType); url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceName); url = url + "/replicationFabrics/"; url = url + Uri.EscapeDataString(fabricName); url = url + "/replicationLogicalNetworks"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-11-10"); 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 httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2015-01-01"); // 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 LogicalNetworksListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new LogicalNetworksListResponse(); 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)) { LogicalNetwork logicalNetworkInstance = new LogicalNetwork(); result.LogicalNetworks.Add(logicalNetworkInstance); JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { LogicalNetworkProperties propertiesInstance = new LogicalNetworkProperties(); logicalNetworkInstance.Properties = propertiesInstance; JToken friendlyNameValue = propertiesValue["friendlyName"]; if (friendlyNameValue != null && friendlyNameValue.Type != JTokenType.Null) { string friendlyNameInstance = ((string)friendlyNameValue); propertiesInstance.FriendlyName = friendlyNameInstance; } JToken logicalNetworkDefinitionsStatusValue = propertiesValue["logicalNetworkDefinitionsStatus"]; if (logicalNetworkDefinitionsStatusValue != null && logicalNetworkDefinitionsStatusValue.Type != JTokenType.Null) { string logicalNetworkDefinitionsStatusInstance = ((string)logicalNetworkDefinitionsStatusValue); propertiesInstance.LogicalNetworkDefinitionsStatus = logicalNetworkDefinitionsStatusInstance; } JToken networkVirtualizationStatusValue = propertiesValue["networkVirtualizationStatus"]; if (networkVirtualizationStatusValue != null && networkVirtualizationStatusValue.Type != JTokenType.Null) { string networkVirtualizationStatusInstance = ((string)networkVirtualizationStatusValue); propertiesInstance.NetworkVirtualizationStatus = networkVirtualizationStatusInstance; } JToken logicalNetworkUsageValue = propertiesValue["logicalNetworkUsage"]; if (logicalNetworkUsageValue != null && logicalNetworkUsageValue.Type != JTokenType.Null) { string logicalNetworkUsageInstance = ((string)logicalNetworkUsageValue); propertiesInstance.LogicalNetworkUsage = logicalNetworkUsageInstance; } } JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); logicalNetworkInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); logicalNetworkInstance.Name = nameInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); logicalNetworkInstance.Type = typeInstance; } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); logicalNetworkInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)valueValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); logicalNetworkInstance.Tags.Add(tagsKey, tagsValue); } } } } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } 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(); } } } } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ namespace Multiverse.Tools.WorldEditor { partial class PathObjectTypeDialog { /// <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() { this.label1 = new System.Windows.Forms.Label(); this.pathObjectTypeName = new System.Windows.Forms.TextBox(); this.pathObjectTypeHeight = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.pathObjectTypeWidth = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.panel1 = new System.Windows.Forms.Panel(); this.pathObjectTypeSlope = new System.Windows.Forms.TextBox(); this.label5 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.pathObjectTypeMaxDisjointDistance = new System.Windows.Forms.TextBox(); this.label8 = new System.Windows.Forms.Label(); this.pathObjectTypeMinimumFeatureSize = new System.Windows.Forms.TextBox(); this.pathObjectTypeGridResolution = new System.Windows.Forms.TextBox(); this.label10 = new System.Windows.Forms.Label(); this.okButton = new System.Windows.Forms.Button(); this.cancelButton = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.Location = new System.Drawing.Point(55, 61); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(116, 28); this.label1.TabIndex = 0; this.label1.Text = "Name of path object type"; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // pathObjectTypeName // this.pathObjectTypeName.Location = new System.Drawing.Point(176, 65); this.pathObjectTypeName.Name = "pathObjectTypeName"; this.pathObjectTypeName.Size = new System.Drawing.Size(187, 20); this.pathObjectTypeName.TabIndex = 1; this.pathObjectTypeName.TextChanged += new System.EventHandler(this.pathObjectTypeName_TextChanged); // // pathObjectTypeHeight // this.pathObjectTypeHeight.Location = new System.Drawing.Point(176, 100); this.pathObjectTypeHeight.Name = "pathObjectTypeHeight"; this.pathObjectTypeHeight.Size = new System.Drawing.Size(86, 20); this.pathObjectTypeHeight.TabIndex = 3; this.pathObjectTypeHeight.Text = "1.8"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(27, 103); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(144, 13); this.label2.TabIndex = 2; this.label2.Text = "Minimum path height (meters)"; // // pathObjectTypeWidth // this.pathObjectTypeWidth.Location = new System.Drawing.Point(176, 135); this.pathObjectTypeWidth.Name = "pathObjectTypeWidth"; this.pathObjectTypeWidth.Size = new System.Drawing.Size(86, 20); this.pathObjectTypeWidth.TabIndex = 5; this.pathObjectTypeWidth.Text = "0.5"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(30, 138); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(140, 13); this.label3.TabIndex = 4; this.label3.Text = "Minimum path width (meters)"; // // label4 // this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label4.Location = new System.Drawing.Point(52, 9); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(319, 43); this.label4.TabIndex = 6; this.label4.Text = "Define the characteristics of a \"path object type\", used to generate path informa" + "tion for mobs of this size, used by the server-side path and collision detection" + " system"; // // panel1 // this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.panel1.Location = new System.Drawing.Point(7, 204); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(400, 4); this.panel1.TabIndex = 7; // // pathObjectTypeSlope // this.pathObjectTypeSlope.Location = new System.Drawing.Point(176, 167); this.pathObjectTypeSlope.Name = "pathObjectTypeSlope"; this.pathObjectTypeSlope.Size = new System.Drawing.Size(86, 20); this.pathObjectTypeSlope.TabIndex = 9; this.pathObjectTypeSlope.Text = "0.5"; // // label5 // this.label5.Location = new System.Drawing.Point(38, 161); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(132, 32); this.label5.TabIndex = 8; this.label5.Text = "Maximum slope a mob can climb (fraction)"; this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // label6 // this.label6.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label6.Location = new System.Drawing.Point(52, 221); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(319, 31); this.label6.TabIndex = 10; this.label6.Text = "Parameters that are exposed but you should not need to change except in unusual c" + "ircumstances"; // // label7 // this.label7.Location = new System.Drawing.Point(38, 267); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(132, 41); this.label7.TabIndex = 17; this.label7.Text = "Fraction of path width to use as the path grid resolution (fraction)"; this.label7.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // pathObjectTypeMaxDisjointDistance // this.pathObjectTypeMaxDisjointDistance.Location = new System.Drawing.Point(176, 381); this.pathObjectTypeMaxDisjointDistance.Name = "pathObjectTypeMaxDisjointDistance"; this.pathObjectTypeMaxDisjointDistance.Size = new System.Drawing.Size(86, 20); this.pathObjectTypeMaxDisjointDistance.TabIndex = 16; this.pathObjectTypeMaxDisjointDistance.Text = "0.1"; // // label8 // this.label8.Location = new System.Drawing.Point(34, 370); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(136, 41); this.label8.TabIndex = 15; this.label8.Text = "Gaps allowed between collision volumes (meters)"; this.label8.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // pathObjectTypeMinimumFeatureSize // this.pathObjectTypeMinimumFeatureSize.Location = new System.Drawing.Point(176, 332); this.pathObjectTypeMinimumFeatureSize.Name = "pathObjectTypeMinimumFeatureSize"; this.pathObjectTypeMinimumFeatureSize.Size = new System.Drawing.Size(86, 20); this.pathObjectTypeMinimumFeatureSize.TabIndex = 14; this.pathObjectTypeMinimumFeatureSize.Text = "3"; // // pathObjectTypeGridResolution // this.pathObjectTypeGridResolution.Location = new System.Drawing.Point(176, 279); this.pathObjectTypeGridResolution.Name = "pathObjectTypeGridResolution"; this.pathObjectTypeGridResolution.Size = new System.Drawing.Size(86, 20); this.pathObjectTypeGridResolution.TabIndex = 12; this.pathObjectTypeGridResolution.Text = "0.25"; // // label10 // this.label10.Location = new System.Drawing.Point(38, 321); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(132, 41); this.label10.TabIndex = 19; this.label10.Text = "If a feature of the grid is smaller than this number of grid cells, ignore it"; this.label10.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // okButton // this.okButton.Location = new System.Drawing.Point(246, 423); this.okButton.Name = "okButton"; this.okButton.Size = new System.Drawing.Size(75, 23); this.okButton.TabIndex = 20; this.okButton.Text = "OK"; this.okButton.UseVisualStyleBackColor = true; this.okButton.Click += new System.EventHandler(this.okButton_Click); // // cancelButton // this.cancelButton.Location = new System.Drawing.Point(327, 423); this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(75, 23); this.cancelButton.TabIndex = 21; this.cancelButton.Text = "Cancel"; this.cancelButton.UseVisualStyleBackColor = true; this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click); // // PathObjectTypeDialog // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(414, 458); this.Controls.Add(this.cancelButton); this.Controls.Add(this.okButton); this.Controls.Add(this.label10); this.Controls.Add(this.label7); this.Controls.Add(this.pathObjectTypeMaxDisjointDistance); this.Controls.Add(this.label8); this.Controls.Add(this.pathObjectTypeMinimumFeatureSize); this.Controls.Add(this.pathObjectTypeGridResolution); this.Controls.Add(this.label6); this.Controls.Add(this.pathObjectTypeSlope); this.Controls.Add(this.label5); this.Controls.Add(this.panel1); this.Controls.Add(this.label4); this.Controls.Add(this.pathObjectTypeWidth); this.Controls.Add(this.label3); this.Controls.Add(this.pathObjectTypeHeight); this.Controls.Add(this.label2); this.Controls.Add(this.pathObjectTypeName); this.Controls.Add(this.label1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Name = "PathObjectTypeDialog"; this.ShowInTaskbar = false; this.Text = "Editing Path Object Type"; this.Shown += new System.EventHandler(this.PathObjectTypeDialog_Shown); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox pathObjectTypeName; private System.Windows.Forms.TextBox pathObjectTypeHeight; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox pathObjectTypeWidth; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.TextBox pathObjectTypeSlope; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label7; private System.Windows.Forms.TextBox pathObjectTypeMaxDisjointDistance; private System.Windows.Forms.Label label8; private System.Windows.Forms.TextBox pathObjectTypeMinimumFeatureSize; private System.Windows.Forms.TextBox pathObjectTypeGridResolution; private System.Windows.Forms.Label label10; private System.Windows.Forms.Button okButton; private System.Windows.Forms.Button cancelButton; } }
// Copyright 2022 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.Cloud.Dataproc.V1.Snippets { using Google.Api.Gax; using Google.Api.Gax.ResourceNames; using Google.LongRunning; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedBatchControllerClientSnippets { /// <summary>Snippet for CreateBatch</summary> public void CreateBatchRequestObject() { // Snippet: CreateBatch(CreateBatchRequest, CallSettings) // Create client BatchControllerClient batchControllerClient = BatchControllerClient.Create(); // Initialize request argument(s) CreateBatchRequest request = new CreateBatchRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Batch = new Batch(), BatchId = "", RequestId = "", }; // Make the request Operation<Batch, BatchOperationMetadata> response = batchControllerClient.CreateBatch(request); // Poll until the returned long-running operation is complete Operation<Batch, BatchOperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Batch result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Batch, BatchOperationMetadata> retrievedResponse = batchControllerClient.PollOnceCreateBatch(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Batch retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CreateBatchAsync</summary> public async Task CreateBatchRequestObjectAsync() { // Snippet: CreateBatchAsync(CreateBatchRequest, CallSettings) // Additional: CreateBatchAsync(CreateBatchRequest, CancellationToken) // Create client BatchControllerClient batchControllerClient = await BatchControllerClient.CreateAsync(); // Initialize request argument(s) CreateBatchRequest request = new CreateBatchRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Batch = new Batch(), BatchId = "", RequestId = "", }; // Make the request Operation<Batch, BatchOperationMetadata> response = await batchControllerClient.CreateBatchAsync(request); // Poll until the returned long-running operation is complete Operation<Batch, BatchOperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Batch result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Batch, BatchOperationMetadata> retrievedResponse = await batchControllerClient.PollOnceCreateBatchAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Batch retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CreateBatch</summary> public void CreateBatch() { // Snippet: CreateBatch(string, Batch, string, CallSettings) // Create client BatchControllerClient batchControllerClient = BatchControllerClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; Batch batch = new Batch(); string batchId = ""; // Make the request Operation<Batch, BatchOperationMetadata> response = batchControllerClient.CreateBatch(parent, batch, batchId); // Poll until the returned long-running operation is complete Operation<Batch, BatchOperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Batch result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Batch, BatchOperationMetadata> retrievedResponse = batchControllerClient.PollOnceCreateBatch(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Batch retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CreateBatchAsync</summary> public async Task CreateBatchAsync() { // Snippet: CreateBatchAsync(string, Batch, string, CallSettings) // Additional: CreateBatchAsync(string, Batch, string, CancellationToken) // Create client BatchControllerClient batchControllerClient = await BatchControllerClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; Batch batch = new Batch(); string batchId = ""; // Make the request Operation<Batch, BatchOperationMetadata> response = await batchControllerClient.CreateBatchAsync(parent, batch, batchId); // Poll until the returned long-running operation is complete Operation<Batch, BatchOperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Batch result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Batch, BatchOperationMetadata> retrievedResponse = await batchControllerClient.PollOnceCreateBatchAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Batch retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CreateBatch</summary> public void CreateBatchResourceNames() { // Snippet: CreateBatch(LocationName, Batch, string, CallSettings) // Create client BatchControllerClient batchControllerClient = BatchControllerClient.Create(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); Batch batch = new Batch(); string batchId = ""; // Make the request Operation<Batch, BatchOperationMetadata> response = batchControllerClient.CreateBatch(parent, batch, batchId); // Poll until the returned long-running operation is complete Operation<Batch, BatchOperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Batch result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Batch, BatchOperationMetadata> retrievedResponse = batchControllerClient.PollOnceCreateBatch(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Batch retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CreateBatchAsync</summary> public async Task CreateBatchResourceNamesAsync() { // Snippet: CreateBatchAsync(LocationName, Batch, string, CallSettings) // Additional: CreateBatchAsync(LocationName, Batch, string, CancellationToken) // Create client BatchControllerClient batchControllerClient = await BatchControllerClient.CreateAsync(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); Batch batch = new Batch(); string batchId = ""; // Make the request Operation<Batch, BatchOperationMetadata> response = await batchControllerClient.CreateBatchAsync(parent, batch, batchId); // Poll until the returned long-running operation is complete Operation<Batch, BatchOperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Batch result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Batch, BatchOperationMetadata> retrievedResponse = await batchControllerClient.PollOnceCreateBatchAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Batch retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for GetBatch</summary> public void GetBatchRequestObject() { // Snippet: GetBatch(GetBatchRequest, CallSettings) // Create client BatchControllerClient batchControllerClient = BatchControllerClient.Create(); // Initialize request argument(s) GetBatchRequest request = new GetBatchRequest { BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"), }; // Make the request Batch response = batchControllerClient.GetBatch(request); // End snippet } /// <summary>Snippet for GetBatchAsync</summary> public async Task GetBatchRequestObjectAsync() { // Snippet: GetBatchAsync(GetBatchRequest, CallSettings) // Additional: GetBatchAsync(GetBatchRequest, CancellationToken) // Create client BatchControllerClient batchControllerClient = await BatchControllerClient.CreateAsync(); // Initialize request argument(s) GetBatchRequest request = new GetBatchRequest { BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"), }; // Make the request Batch response = await batchControllerClient.GetBatchAsync(request); // End snippet } /// <summary>Snippet for GetBatch</summary> public void GetBatch() { // Snippet: GetBatch(string, CallSettings) // Create client BatchControllerClient batchControllerClient = BatchControllerClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/batches/[BATCH]"; // Make the request Batch response = batchControllerClient.GetBatch(name); // End snippet } /// <summary>Snippet for GetBatchAsync</summary> public async Task GetBatchAsync() { // Snippet: GetBatchAsync(string, CallSettings) // Additional: GetBatchAsync(string, CancellationToken) // Create client BatchControllerClient batchControllerClient = await BatchControllerClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/batches/[BATCH]"; // Make the request Batch response = await batchControllerClient.GetBatchAsync(name); // End snippet } /// <summary>Snippet for GetBatch</summary> public void GetBatchResourceNames() { // Snippet: GetBatch(BatchName, CallSettings) // Create client BatchControllerClient batchControllerClient = BatchControllerClient.Create(); // Initialize request argument(s) BatchName name = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"); // Make the request Batch response = batchControllerClient.GetBatch(name); // End snippet } /// <summary>Snippet for GetBatchAsync</summary> public async Task GetBatchResourceNamesAsync() { // Snippet: GetBatchAsync(BatchName, CallSettings) // Additional: GetBatchAsync(BatchName, CancellationToken) // Create client BatchControllerClient batchControllerClient = await BatchControllerClient.CreateAsync(); // Initialize request argument(s) BatchName name = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"); // Make the request Batch response = await batchControllerClient.GetBatchAsync(name); // End snippet } /// <summary>Snippet for ListBatches</summary> public void ListBatchesRequestObject() { // Snippet: ListBatches(ListBatchesRequest, CallSettings) // Create client BatchControllerClient batchControllerClient = BatchControllerClient.Create(); // Initialize request argument(s) ListBatchesRequest request = new ListBatchesRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; // Make the request PagedEnumerable<ListBatchesResponse, Batch> response = batchControllerClient.ListBatches(request); // Iterate over all response items, lazily performing RPCs as required foreach (Batch item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListBatchesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Batch item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Batch> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Batch item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListBatchesAsync</summary> public async Task ListBatchesRequestObjectAsync() { // Snippet: ListBatchesAsync(ListBatchesRequest, CallSettings) // Create client BatchControllerClient batchControllerClient = await BatchControllerClient.CreateAsync(); // Initialize request argument(s) ListBatchesRequest request = new ListBatchesRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; // Make the request PagedAsyncEnumerable<ListBatchesResponse, Batch> response = batchControllerClient.ListBatchesAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Batch item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListBatchesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Batch item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Batch> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Batch item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListBatches</summary> public void ListBatches() { // Snippet: ListBatches(string, string, int?, CallSettings) // Create client BatchControllerClient batchControllerClient = BatchControllerClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; // Make the request PagedEnumerable<ListBatchesResponse, Batch> response = batchControllerClient.ListBatches(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Batch item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListBatchesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Batch item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Batch> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Batch item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListBatchesAsync</summary> public async Task ListBatchesAsync() { // Snippet: ListBatchesAsync(string, string, int?, CallSettings) // Create client BatchControllerClient batchControllerClient = await BatchControllerClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; // Make the request PagedAsyncEnumerable<ListBatchesResponse, Batch> response = batchControllerClient.ListBatchesAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Batch item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListBatchesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Batch item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Batch> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Batch item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListBatches</summary> public void ListBatchesResourceNames() { // Snippet: ListBatches(LocationName, string, int?, CallSettings) // Create client BatchControllerClient batchControllerClient = BatchControllerClient.Create(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); // Make the request PagedEnumerable<ListBatchesResponse, Batch> response = batchControllerClient.ListBatches(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Batch item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListBatchesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Batch item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Batch> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Batch item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListBatchesAsync</summary> public async Task ListBatchesResourceNamesAsync() { // Snippet: ListBatchesAsync(LocationName, string, int?, CallSettings) // Create client BatchControllerClient batchControllerClient = await BatchControllerClient.CreateAsync(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); // Make the request PagedAsyncEnumerable<ListBatchesResponse, Batch> response = batchControllerClient.ListBatchesAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Batch item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListBatchesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Batch item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Batch> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Batch item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for DeleteBatch</summary> public void DeleteBatchRequestObject() { // Snippet: DeleteBatch(DeleteBatchRequest, CallSettings) // Create client BatchControllerClient batchControllerClient = BatchControllerClient.Create(); // Initialize request argument(s) DeleteBatchRequest request = new DeleteBatchRequest { BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"), }; // Make the request batchControllerClient.DeleteBatch(request); // End snippet } /// <summary>Snippet for DeleteBatchAsync</summary> public async Task DeleteBatchRequestObjectAsync() { // Snippet: DeleteBatchAsync(DeleteBatchRequest, CallSettings) // Additional: DeleteBatchAsync(DeleteBatchRequest, CancellationToken) // Create client BatchControllerClient batchControllerClient = await BatchControllerClient.CreateAsync(); // Initialize request argument(s) DeleteBatchRequest request = new DeleteBatchRequest { BatchName = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"), }; // Make the request await batchControllerClient.DeleteBatchAsync(request); // End snippet } /// <summary>Snippet for DeleteBatch</summary> public void DeleteBatch() { // Snippet: DeleteBatch(string, CallSettings) // Create client BatchControllerClient batchControllerClient = BatchControllerClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/batches/[BATCH]"; // Make the request batchControllerClient.DeleteBatch(name); // End snippet } /// <summary>Snippet for DeleteBatchAsync</summary> public async Task DeleteBatchAsync() { // Snippet: DeleteBatchAsync(string, CallSettings) // Additional: DeleteBatchAsync(string, CancellationToken) // Create client BatchControllerClient batchControllerClient = await BatchControllerClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/batches/[BATCH]"; // Make the request await batchControllerClient.DeleteBatchAsync(name); // End snippet } /// <summary>Snippet for DeleteBatch</summary> public void DeleteBatchResourceNames() { // Snippet: DeleteBatch(BatchName, CallSettings) // Create client BatchControllerClient batchControllerClient = BatchControllerClient.Create(); // Initialize request argument(s) BatchName name = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"); // Make the request batchControllerClient.DeleteBatch(name); // End snippet } /// <summary>Snippet for DeleteBatchAsync</summary> public async Task DeleteBatchResourceNamesAsync() { // Snippet: DeleteBatchAsync(BatchName, CallSettings) // Additional: DeleteBatchAsync(BatchName, CancellationToken) // Create client BatchControllerClient batchControllerClient = await BatchControllerClient.CreateAsync(); // Initialize request argument(s) BatchName name = BatchName.FromProjectLocationBatch("[PROJECT]", "[LOCATION]", "[BATCH]"); // Make the request await batchControllerClient.DeleteBatchAsync(name); // End snippet } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using System.Runtime.CompilerServices; namespace HTLib2 { public static partial class HStatic { public static MatrixSparse2 ToMatrixSparse2(this Matrix mat) { return MatrixSparse2.FromMatrix(mat); } } public class MatrixSparse2 : IMatrix<double>, IMatrixSparse<double>, IBinarySerializable { int _colsize; int _rowsize; Dictionary<int,double>[] _c_r_value; /////////////////////////////////////////////////// // IMatrix<double> public int ColSize { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _colsize; } } public int RowSize { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _rowsize; } } public double this[int c, int r] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return GetAt(c,r); } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { SetAt(c,r,value); } } public double this[long c, long r] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { throw new NotImplementedException(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { throw new NotImplementedException(); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public double[,] ToArray() { double[,] arr = new double[_colsize,_rowsize]; for(int c=0; c<_colsize; c++) { Dictionary<int, double> r_value = _c_r_value[c]; foreach(var item in r_value) { int r = item.Key; double val = item.Value; arr[c,r] = val; } } return arr; } // IMatrix<double> /////////////////////////////////////////////////// // IEnumerable<ValueTuple<int, int, T>> EnumElements(); public IEnumerable<ValueTuple<int, int, double>> EnumElements() { foreach(var c_r_val in EnumNonZeros()) yield return c_r_val; } // IEnumerable<ValueTuple<int, int, T>> EnumElements(); /////////////////////////////////////////////////// // IBinarySerializable public void BinarySerialize(HBinaryWriter writer) { writer.Write(_colsize); writer.Write(_rowsize); int count = 0; for(int c=0; c<_colsize; c++) { Dictionary<int, double> r_value = _c_r_value[c]; writer.Write(r_value.Count); foreach(var item in r_value) { int r = item.Key; double val = item.Value; writer.Write(r ); writer.Write(val); count ++; } } if(count != NumNonZero) throw new Exception("(count != NumNonZero)"); } public MatrixSparse2(HBinaryReader reader) { reader.Read(out _colsize); reader.Read(out _rowsize); int count = 0; _c_r_value = new Dictionary<int, double>[_colsize]; for(int c=0; c<_colsize; c++) { int c_count; reader.Read(out c_count); _c_r_value[c] = new Dictionary<int, double>(c_count); Dictionary<int, double> r_value = _c_r_value[c]; foreach(var item in r_value) { int r ; reader.Read(out r ); HDebug.Assert(r < _rowsize); double val; reader.Read(out val); r_value.Add(r, val); count ++; } } if(count != NumNonZero) throw new Exception("(count != NumNonZero)"); } // IBinarySerializable /////////////////////////////////////////////////// public MatrixSparse2(int colsize, int rowsize) { _colsize = colsize; _rowsize = rowsize; _c_r_value = new Dictionary<int, double>[_colsize]; for(int c=0; c<_colsize; c++) _c_r_value[c] = new Dictionary<int, double>(); } public static MatrixSparse2 Zeros(int colsize, int rowsize) { return new MatrixSparse2(colsize, rowsize); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public double GetAt(int c, int r) { if((c < 0) || (c >= _colsize)) throw new IndexOutOfRangeException("((c < 0) || (c >= _ColSize))"); if((c < 0) || (r >= _rowsize)) throw new IndexOutOfRangeException("((c < 0) || (r >= _RowSize))"); double value; bool hasvalue = _c_r_value[c].TryGetValue(r, out value); if(hasvalue) return value; else return 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void SetAt(int c, int r, double value) { if((c < 0) || (c >= _colsize)) throw new IndexOutOfRangeException("((c < 0) || (c >= _ColSize))"); if((c < 0) || (r >= _rowsize)) throw new IndexOutOfRangeException("((c < 0) || (r >= _RowSize))"); Dictionary<int,double> r_value = _c_r_value[c]; if(r_value.ContainsKey(r)) { if(value != 0) r_value[r] = value; else r_value.Remove(r); } else { if(value != 0) r_value.Add(r, value); else { } // do nothing } } public int NumNonZero { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { int count = 0; for(int c=0; c<_colsize; c++) count += _c_r_value[c].Count; return count; } } public double NumNonZeroRatio { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { int count = 0; for(int c=0; c<_colsize; c++) count += _c_r_value[c].Count; return count / (1.0 * _colsize * _rowsize); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public IEnumerable<(int c, int r, double val)> EnumNonZeros() { for(int c=0; c<_colsize; c++) foreach(var item in _c_r_value[c]) yield return (c, item.Key, item.Value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Matrix ToMatrix() { Matrix mat = Matrix.Zeros(_colsize, _rowsize); foreach(var item in EnumNonZeros()) { int c = item.c; int r = item.r; double val = item.val; mat[c,r] = val; } return mat; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static MatrixSparse2 FromMatrix(Matrix mat) { MatrixSparse2 smat = MatrixSparse2.Zeros(mat.ColSize, mat.RowSize); for(int c=0; c<mat.ColSize; c++) for(int r=0; r<mat.RowSize; r++) { double val = mat[c,r]; if(val == 0) continue; smat[c,r] = val; } return smat; } public static bool EqualContents(MatrixSparse2 a, MatrixSparse2 b) { if(a._colsize != b._colsize) return false; if(a._colsize != b._colsize) return false; for(int c=0; c<a._colsize; c++) { var a_r_val = a._c_r_value[c]; var b_r_val = b._c_r_value[c]; if(a_r_val.Count != b_r_val.Count) return false; foreach(var a_item in a_r_val) { int r = a_item.Key; double a_val = a_item.Value; double b_val; if(b_r_val.TryGetValue(r, out b_val) == false) return false; if(a_val != b_val ) return false; } } return true; } } }
/* * 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.IO; using System.Reflection; using System.Text.RegularExpressions; using System.Threading; using log4net; using OpenMetaverse; using OpenMetaverse.Assets; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes.Serialization; using OpenSim.Services.Interfaces; using OpenSimAssetType = OpenSim.Framework.SLUtil.OpenSimAssetType; namespace OpenSim.Region.Framework.Scenes { /// <summary> /// Gather uuids for a given entity. /// </summary> /// <remarks> /// This does a deep inspection of the entity to retrieve all the assets it uses (whether as textures, as scripts /// contained in inventory, as scripts contained in objects contained in another object's inventory, etc. Assets /// are only retrieved when they are necessary to carry out the inspection (i.e. a serialized object needs to be /// retrieved to work out which assets it references). /// </remarks> public class UuidGatherer { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Is gathering complete? /// </summary> public bool Complete { get { return m_assetUuidsToInspect.Count <= 0; } } /// <summary> /// The dictionary of UUIDs gathered so far. If Complete == true then this is all the reachable UUIDs. /// </summary> /// <value>The gathered uuids.</value> public IDictionary<UUID, sbyte> GatheredUuids { get; private set; } public HashSet<UUID> FailedUUIDs { get; private set; } public HashSet<UUID> UncertainAssetsUUIDs { get; private set; } public int possibleNotAssetCount { get; set; } public int ErrorCount { get; private set; } /// <summary> /// Gets the next UUID to inspect. /// </summary> /// <value>If there is no next UUID then returns null</value> public UUID? NextUuidToInspect { get { if (Complete) return null; else return m_assetUuidsToInspect.Peek(); } } protected IAssetService m_assetService; protected Queue<UUID> m_assetUuidsToInspect; /// <summary> /// Initializes a new instance of the <see cref="OpenSim.Region.Framework.Scenes.UuidGatherer"/> class. /// </summary> /// <remarks>In this case the collection of gathered assets will start out blank.</remarks> /// <param name="assetService"> /// Asset service. /// </param> public UuidGatherer(IAssetService assetService) : this(assetService, new Dictionary<UUID, sbyte>(), new HashSet <UUID>(),new HashSet <UUID>()) {} public UuidGatherer(IAssetService assetService, IDictionary<UUID, sbyte> collector) : this(assetService, collector, new HashSet <UUID>(), new HashSet <UUID>()) {} /// <summary> /// Initializes a new instance of the <see cref="OpenSim.Region.Framework.Scenes.UuidGatherer"/> class. /// </summary> /// <param name="assetService"> /// Asset service. /// </param> /// <param name="collector"> /// Gathered UUIDs will be collected in this dictionary. /// It can be pre-populated if you want to stop the gatherer from analyzing assets that have already been fetched and inspected. /// </param> public UuidGatherer(IAssetService assetService, IDictionary<UUID, sbyte> collector, HashSet <UUID> failedIDs, HashSet <UUID> uncertainAssetsUUIDs) { m_assetService = assetService; GatheredUuids = collector; // FIXME: Not efficient for searching, can improve. m_assetUuidsToInspect = new Queue<UUID>(); FailedUUIDs = failedIDs; UncertainAssetsUUIDs = uncertainAssetsUUIDs; ErrorCount = 0; possibleNotAssetCount = 0; } /// <summary> /// Adds the asset uuid for inspection during the gathering process. /// </summary> /// <returns><c>true</c>, if for inspection was added, <c>false</c> otherwise.</returns> /// <param name="uuid">UUID.</param> public bool AddForInspection(UUID uuid) { if(uuid == UUID.Zero) return false; if(FailedUUIDs.Contains(uuid)) { if(UncertainAssetsUUIDs.Contains(uuid)) possibleNotAssetCount++; else ErrorCount++; return false; } if(GatheredUuids.ContainsKey(uuid)) return false; if (m_assetUuidsToInspect.Contains(uuid)) return false; // m_log.DebugFormat("[UUID GATHERER]: Adding asset {0} for inspection", uuid); m_assetUuidsToInspect.Enqueue(uuid); return true; } /// <summary> /// Gather all the asset uuids associated with a given object. /// </summary> /// <remarks> /// This includes both those directly associated with /// it (e.g. face textures) and recursively, those of items within it's inventory (e.g. objects contained /// within this object). /// </remarks> /// <param name="sceneObject">The scene object for which to gather assets</param> public void AddForInspection(SceneObjectGroup sceneObject) { // m_log.DebugFormat( // "[UUID GATHERER]: Getting assets for object {0}, {1}", sceneObject.Name, sceneObject.UUID); if(sceneObject.IsDeleted) return; SceneObjectPart[] parts = sceneObject.Parts; for (int i = 0; i < parts.Length; i++) { SceneObjectPart part = parts[i]; // m_log.DebugFormat( // "[UUID GATHERER]: Getting part {0}, {1} for object {2}", part.Name, part.UUID, sceneObject.UUID); try { Primitive.TextureEntry textureEntry = part.Shape.Textures; if (textureEntry != null) { // Get the prim's default texture. This will be used for faces which don't have their own texture if (textureEntry.DefaultTexture != null) RecordTextureEntryAssetUuids(textureEntry.DefaultTexture); if (textureEntry.FaceTextures != null) { // Loop through the rest of the texture faces (a non-null face means the face is different from DefaultTexture) foreach (Primitive.TextureEntryFace texture in textureEntry.FaceTextures) { if (texture != null) RecordTextureEntryAssetUuids(texture); } } } // If the prim is a sculpt then preserve this information too if (part.Shape.SculptTexture != UUID.Zero) GatheredUuids[part.Shape.SculptTexture] = (sbyte)AssetType.Texture; if (part.Shape.ProjectionTextureUUID != UUID.Zero) GatheredUuids[part.Shape.ProjectionTextureUUID] = (sbyte)AssetType.Texture; UUID collisionSound = part.CollisionSound; if ( collisionSound != UUID.Zero && collisionSound != part.invalidCollisionSoundUUID) GatheredUuids[collisionSound] = (sbyte)AssetType.Sound; if (part.ParticleSystem.Length > 0) { try { Primitive.ParticleSystem ps = new Primitive.ParticleSystem(part.ParticleSystem, 0); if (ps.Texture != UUID.Zero) GatheredUuids[ps.Texture] = (sbyte)AssetType.Texture; } catch (Exception) { m_log.WarnFormat( "[UUID GATHERER]: Could not check particle system for part {0} {1} in object {2} {3} since it is corrupt. Continuing.", part.Name, part.UUID, sceneObject.Name, sceneObject.UUID); } } TaskInventoryDictionary taskDictionary = (TaskInventoryDictionary)part.TaskInventory.Clone(); // Now analyze this prim's inventory items to preserve all the uuids that they reference foreach (TaskInventoryItem tii in taskDictionary.Values) { // m_log.DebugFormat( // "[ARCHIVER]: Analysing item {0} asset type {1} in {2} {3}", // tii.Name, tii.Type, part.Name, part.UUID); AddForInspection(tii.AssetID, (sbyte)tii.Type); } // FIXME: We need to make gathering modular but we cannot yet, since gatherers are not guaranteed // to be called with scene objects that are in a scene (e.g. in the case of hg asset mapping and // inventory transfer. There needs to be a way for a module to register a method without assuming a // Scene.EventManager is present. // part.ParentGroup.Scene.EventManager.TriggerGatherUuids(part, assetUuids); // still needed to retrieve textures used as materials for any parts containing legacy materials stored in DynAttrs RecordMaterialsUuids(part); } catch (Exception e) { m_log.ErrorFormat("[UUID GATHERER]: Failed to get part - {0}", e); } } } /// <summary> /// Gathers the next set of assets returned by the next uuid to get from the asset service. /// </summary> /// <returns>false if gathering is already complete, true otherwise</returns> public bool GatherNext() { if (Complete) return false; UUID nextToInspect = m_assetUuidsToInspect.Dequeue(); // m_log.DebugFormat("[UUID GATHERER]: Inspecting asset {0}", nextToInspect); GetAssetUuids(nextToInspect); return true; } /// <summary> /// Gathers all remaining asset UUIDS no matter how many calls are required to the asset service. /// </summary> /// <returns>false if gathering is already complete, true otherwise</returns> public bool GatherAll() { if (Complete) return false; while (GatherNext()); return true; } /// <summary> /// Gather all the asset uuids associated with the asset referenced by a given uuid /// </summary> /// <remarks> /// This includes both those directly associated with /// it (e.g. face textures) and recursively, those of items within it's inventory (e.g. objects contained /// within this object). /// This method assumes that the asset type associated with this asset in persistent storage is correct (which /// should always be the case). So with this method we always need to retrieve asset data even if the asset /// is of a type which is known not to reference any other assets /// </remarks> /// <param name="assetUuid">The uuid of the asset for which to gather referenced assets</param> private void GetAssetUuids(UUID assetUuid) { if(assetUuid == UUID.Zero) return; if(FailedUUIDs.Contains(assetUuid)) { if(UncertainAssetsUUIDs.Contains(assetUuid)) possibleNotAssetCount++; else ErrorCount++; return; } // avoid infinite loops if (GatheredUuids.ContainsKey(assetUuid)) return; AssetBase assetBase; try { assetBase = GetAsset(assetUuid); } catch (Exception e) { m_log.ErrorFormat("[UUID GATHERER]: Failed to get asset {0} : {1}", assetUuid, e.Message); ErrorCount++; FailedUUIDs.Add(assetUuid); return; } if(assetBase == null) { // m_log.ErrorFormat("[UUID GATHERER]: asset {0} not found", assetUuid); FailedUUIDs.Add(assetUuid); if(UncertainAssetsUUIDs.Contains(assetUuid)) possibleNotAssetCount++; else ErrorCount++; return; } if(UncertainAssetsUUIDs.Contains(assetUuid)) UncertainAssetsUUIDs.Remove(assetUuid); sbyte assetType = assetBase.Type; if(assetBase.Data == null || assetBase.Data.Length == 0) { // m_log.ErrorFormat("[UUID GATHERER]: asset {0}, type {1} has no data", assetUuid, assetType); ErrorCount++; FailedUUIDs.Add(assetUuid); return; } GatheredUuids[assetUuid] = assetType; try { if ((sbyte)AssetType.Bodypart == assetType || (sbyte)AssetType.Clothing == assetType) { RecordWearableAssetUuids(assetBase); } else if ((sbyte)AssetType.Gesture == assetType) { RecordGestureAssetUuids(assetBase); } else if ((sbyte)AssetType.Notecard == assetType) { RecordTextEmbeddedAssetUuids(assetBase); } else if ((sbyte)AssetType.LSLText == assetType) { RecordTextEmbeddedAssetUuids(assetBase); } else if ((sbyte)OpenSimAssetType.Material == assetType) { RecordMaterialAssetUuids(assetBase); } else if ((sbyte)AssetType.Object == assetType) { RecordSceneObjectAssetUuids(assetBase); } } catch (Exception e) { m_log.ErrorFormat("[UUID GATHERER]: Failed to gather uuids for asset with id {0} type {1}: {2}", assetUuid, assetType, e.Message); GatheredUuids.Remove(assetUuid); ErrorCount++; FailedUUIDs.Add(assetUuid); } } private void AddForInspection(UUID assetUuid, sbyte assetType) { if(assetUuid == UUID.Zero) return; // Here, we want to collect uuids which require further asset fetches but mark the others as gathered if(FailedUUIDs.Contains(assetUuid)) { if(UncertainAssetsUUIDs.Contains(assetUuid)) possibleNotAssetCount++; else ErrorCount++; return; } if(GatheredUuids.ContainsKey(assetUuid)) return; try { if ((sbyte)AssetType.Bodypart == assetType || (sbyte)AssetType.Clothing == assetType || (sbyte)AssetType.Gesture == assetType || (sbyte)AssetType.Notecard == assetType || (sbyte)AssetType.LSLText == assetType || (sbyte)OpenSimAssetType.Material == assetType || (sbyte)AssetType.Object == assetType) { AddForInspection(assetUuid); } else { GatheredUuids[assetUuid] = assetType; } } catch (Exception) { m_log.ErrorFormat( "[UUID GATHERER]: Failed to gather uuids for asset id {0}, type {1}", assetUuid, assetType); throw; } } /// <summary> /// Collect all the asset uuids found in one face of a Texture Entry. /// </summary> private void RecordTextureEntryAssetUuids(Primitive.TextureEntryFace texture) { GatheredUuids[texture.TextureID] = (sbyte)AssetType.Texture; if (texture.MaterialID != UUID.Zero) AddForInspection(texture.MaterialID); } /// <summary> /// Gather all of the texture asset UUIDs used to reference "Materials" such as normal and specular maps /// stored in legacy format in part.DynAttrs /// </summary> /// <param name="part"></param> private void RecordMaterialsUuids(SceneObjectPart part) { // scan thru the dynAttrs map of this part for any textures used as materials OSD osdMaterials = null; lock (part.DynAttrs) { if (part.DynAttrs.ContainsStore("OpenSim", "Materials")) { OSDMap materialsStore = part.DynAttrs.GetStore("OpenSim", "Materials"); if (materialsStore == null) return; materialsStore.TryGetValue("Materials", out osdMaterials); } if (osdMaterials != null) { //m_log.Info("[UUID Gatherer]: found Materials: " + OSDParser.SerializeJsonString(osd)); if (osdMaterials is OSDArray) { OSDArray matsArr = osdMaterials as OSDArray; foreach (OSDMap matMap in matsArr) { try { if (matMap.ContainsKey("Material")) { OSDMap mat = matMap["Material"] as OSDMap; if (mat.ContainsKey("NormMap")) { UUID normalMapId = mat["NormMap"].AsUUID(); if (normalMapId != UUID.Zero) { GatheredUuids[normalMapId] = (sbyte)AssetType.Texture; //m_log.Info("[UUID Gatherer]: found normal map ID: " + normalMapId.ToString()); } } if (mat.ContainsKey("SpecMap")) { UUID specularMapId = mat["SpecMap"].AsUUID(); if (specularMapId != UUID.Zero) { GatheredUuids[specularMapId] = (sbyte)AssetType.Texture; //m_log.Info("[UUID Gatherer]: found specular map ID: " + specularMapId.ToString()); } } } } catch (Exception e) { m_log.Warn("[UUID Gatherer]: exception getting materials: " + e.Message); } } } } } } /// <summary> /// Get an asset synchronously, potentially using an asynchronous callback. If the /// asynchronous callback is used, we will wait for it to complete. /// </summary> /// <param name="uuid"></param> /// <returns></returns> protected virtual AssetBase GetAsset(UUID uuid) { return m_assetService.Get(uuid.ToString()); } /// <summary> /// Record the asset uuids embedded within the given text (e.g. a script). /// </summary> /// <param name="textAsset"></param> private void RecordTextEmbeddedAssetUuids(AssetBase textAsset) { // m_log.DebugFormat("[ASSET GATHERER]: Getting assets for uuid references in asset {0}", embeddingAssetId); string text = Utils.BytesToString(textAsset.Data); // m_log.DebugFormat("[UUID GATHERER]: Text {0}", text); MatchCollection uuidMatches = Util.PermissiveUUIDPattern.Matches(text); // m_log.DebugFormat("[UUID GATHERER]: Found {0} matches in text", uuidMatches.Count); foreach (Match uuidMatch in uuidMatches) { UUID uuid = new UUID(uuidMatch.Value); if(uuid == UUID.Zero) continue; // m_log.DebugFormat("[UUID GATHERER]: Recording {0} in text", uuid); if(!UncertainAssetsUUIDs.Contains(uuid)) UncertainAssetsUUIDs.Add(uuid); AddForInspection(uuid); } } /// <summary> /// Record the uuids referenced by the given wearable asset /// </summary> /// <param name="assetBase"></param> private void RecordWearableAssetUuids(AssetBase assetBase) { //m_log.Debug(new System.Text.ASCIIEncoding().GetString(bodypartAsset.Data)); AssetWearable wearableAsset = new AssetBodypart(assetBase.FullID, assetBase.Data); wearableAsset.Decode(); //m_log.DebugFormat( // "[ARCHIVER]: Wearable asset {0} references {1} assets", wearableAssetUuid, wearableAsset.Textures.Count); foreach (UUID uuid in wearableAsset.Textures.Values) GatheredUuids[uuid] = (sbyte)AssetType.Texture; } /// <summary> /// Get all the asset uuids associated with a given object. This includes both those directly associated with /// it (e.g. face textures) and recursively, those of items within it's inventory (e.g. objects contained /// within this object). /// </summary> /// <param name="sceneObjectAsset"></param> private void RecordSceneObjectAssetUuids(AssetBase sceneObjectAsset) { string xml = Utils.BytesToString(sceneObjectAsset.Data); CoalescedSceneObjects coa; if (CoalescedSceneObjectsSerializer.TryFromXml(xml, out coa)) { foreach (SceneObjectGroup sog in coa.Objects) AddForInspection(sog); } else { SceneObjectGroup sog = SceneObjectSerializer.FromOriginalXmlFormat(xml); if (null != sog) AddForInspection(sog); } } /// <summary> /// Get the asset uuid associated with a gesture /// </summary> /// <param name="gestureAsset"></param> private void RecordGestureAssetUuids(AssetBase gestureAsset) { using (MemoryStream ms = new MemoryStream(gestureAsset.Data)) using (StreamReader sr = new StreamReader(ms)) { sr.ReadLine(); // Unknown (Version?) sr.ReadLine(); // Unknown sr.ReadLine(); // Unknown sr.ReadLine(); // Name sr.ReadLine(); // Comment ? int count = Convert.ToInt32(sr.ReadLine()); // Item count for (int i = 0 ; i < count ; i++) { string type = sr.ReadLine(); if (type == null) break; string name = sr.ReadLine(); if (name == null) break; string id = sr.ReadLine(); if (id == null) break; string unknown = sr.ReadLine(); if (unknown == null) break; // If it can be parsed as a UUID, it is an asset ID UUID uuid; if (UUID.TryParse(id, out uuid)) GatheredUuids[uuid] = (sbyte)AssetType.Animation; // the asset is either an Animation or a Sound, but this distinction isn't important } } } /// <summary> /// Get the asset uuid's referenced in a material. /// </summary> private void RecordMaterialAssetUuids(AssetBase materialAsset) { OSDMap mat; try { mat = (OSDMap)OSDParser.DeserializeLLSDXml(materialAsset.Data); } catch (Exception e) { m_log.WarnFormat("[Materials]: cannot decode material asset {0}: {1}", materialAsset.ID, e.Message); return; } UUID normMap = mat["NormMap"].AsUUID(); if (normMap != UUID.Zero) GatheredUuids[normMap] = (sbyte)AssetType.Texture; UUID specMap = mat["SpecMap"].AsUUID(); if (specMap != UUID.Zero) GatheredUuids[specMap] = (sbyte)AssetType.Texture; } } public class HGUuidGatherer : UuidGatherer { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected string m_assetServerURL; public HGUuidGatherer(IAssetService assetService, string assetServerURL) : this(assetService, assetServerURL, new Dictionary<UUID, sbyte>()) {} public HGUuidGatherer(IAssetService assetService, string assetServerURL, IDictionary<UUID, sbyte> collector) : base(assetService, collector) { m_assetServerURL = assetServerURL; if (!m_assetServerURL.EndsWith("/") && !m_assetServerURL.EndsWith("=")) m_assetServerURL = m_assetServerURL + "/"; } protected override AssetBase GetAsset(UUID uuid) { if (string.Empty == m_assetServerURL) return base.GetAsset(uuid); else return FetchAsset(uuid); } public AssetBase FetchAsset(UUID assetID) { // Test if it's already here AssetBase asset = m_assetService.Get(assetID.ToString()); if (asset == null) { // It's not, so fetch it from abroad asset = m_assetService.Get(m_assetServerURL + assetID.ToString()); if (asset != null) m_log.DebugFormat("[HGUUIDGatherer]: Copied asset {0} from {1} to local asset server", assetID, m_assetServerURL); else m_log.DebugFormat("[HGUUIDGatherer]: Failed to fetch asset {0} from {1}", assetID, m_assetServerURL); } //else // m_log.DebugFormat("[HGUUIDGatherer]: Asset {0} from {1} was already here", assetID, m_assetServerURL); return asset; } } }
//--------------------------------------------------------------------------- // // Copyright (c) Microsoft Corporation. All rights reserved. // // Description: InputBamlStreamList class // It enumerates all the baml streams in the input file for parsing // //--------------------------------------------------------------------------- using System; using System.IO; using System.Globalization; using System.Runtime.InteropServices; using System.Collections; using System.Reflection; using System.Diagnostics; using System.Resources; namespace BamlLocalization { /// <summary> /// Class that enumerates all the baml streams in the input file /// </summary> internal class InputBamlStreamList { /// <summary> /// constructor /// </summary> internal InputBamlStreamList(LocBamlOptions options) { _bamlStreams = new ArrayList(); switch(options.InputType) { case FileType.BAML: { _bamlStreams.Add( new BamlStream( Path.GetFileName(options.Input), File.OpenRead(options.Input) ) ); break; } case FileType.RESOURCES: { using (ResourceReader resourceReader = new ResourceReader(options.Input)) { // enumerate all bamls in a resources EnumerateBamlInResources(resourceReader, options.Input); } break; } case FileType.EXE: case FileType.DLL: { // for a dll, it is the same idea Assembly assembly = Assembly.LoadFrom(options.Input); foreach (string resourceName in assembly.GetManifestResourceNames()) { ResourceLocation resourceLocation = assembly.GetManifestResourceInfo(resourceName).ResourceLocation; // if this resource is in another assemlby, we will skip it if ((resourceLocation & ResourceLocation.ContainedInAnotherAssembly) != 0) { continue; // in resource assembly, we don't have resource that is contained in another assembly } Stream resourceStream = assembly.GetManifestResourceStream(resourceName); using (ResourceReader reader = new ResourceReader(resourceStream)) { EnumerateBamlInResources(reader, resourceName); } } break; } default: { Debug.Assert(false, "Not supported type"); break; } } } /// <summary> /// return the number of baml streams found /// </summary> internal int Count { get{return _bamlStreams.Count;} } /// <summary> /// Gets the baml stream in the input file through indexer /// </summary> internal BamlStream this[int i] { get { return (BamlStream) _bamlStreams[i];} } /// <summary> /// Close the baml streams enumerated /// </summary> internal void Close() { for (int i = 0; i < _bamlStreams.Count; i++) { ((BamlStream) _bamlStreams[i]).Close(); } } //-------------------------------- // private function //-------------------------------- /// <summary> /// Enumerate baml streams in a resources file /// </summary> private void EnumerateBamlInResources(ResourceReader reader, string resourceName) { foreach (DictionaryEntry entry in reader) { string name = entry.Key as string; if (BamlStream.IsResourceEntryBamlStream(name, entry.Value)) { _bamlStreams.Add( new BamlStream( BamlStream.CombineBamlStreamName(resourceName, name), (Stream) entry.Value ) ); } } } ArrayList _bamlStreams; } /// <summary> /// BamlStream class which represents a baml stream /// </summary> internal class BamlStream { private string _name; private Stream _stream; /// <summary> /// constructor /// </summary> internal BamlStream(string name, Stream stream) { _name = name; _stream = stream; } /// <summary> /// name of the baml /// </summary> internal string Name { get { return _name;} } /// <summary> /// The actual Baml stream /// </summary> internal Stream Stream { get { return _stream;} } /// <summary> /// close the stream /// </summary> internal void Close() { if (_stream != null) { _stream.Close(); } } /// <summary> /// Helper method which determines whether a stream name and value pair indicates a baml stream /// </summary> internal static bool IsResourceEntryBamlStream(string name, object value) { string extension = Path.GetExtension(name); if (string.Compare( extension, "." + FileType.BAML.ToString(), true, CultureInfo.InvariantCulture ) == 0 ) { //it has .Baml at the end Type type = value.GetType(); if (typeof(Stream).IsAssignableFrom(type)) return true; } return false; } /// <summary> /// Combine baml stream name and resource name to uniquely identify a baml within a /// localization project /// </summary> internal static string CombineBamlStreamName(string resource, string bamlName) { Debug.Assert(resource != null && bamlName != null, "Resource name and baml name can't be null"); string suffix = Path.GetFileName(bamlName); string prefix = Path.GetFileName(resource); return prefix + LocBamlConst.BamlAndResourceSeperator + suffix; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using Umbraco.Cms.Core.Exceptions; using Umbraco.Cms.Core.Strings; namespace Umbraco.Cms.Core.Models { /// <summary> /// Represents an abstract class for composition specific ContentType properties and methods /// </summary> [Serializable] [DataContract(IsReference = true)] public abstract class ContentTypeCompositionBase : ContentTypeBase, IContentTypeComposition { private List<IContentTypeComposition> _contentTypeComposition = new List<IContentTypeComposition>(); private List<int> _removedContentTypeKeyTracker = new List<int>(); protected ContentTypeCompositionBase(IShortStringHelper shortStringHelper, int parentId) : base(shortStringHelper, parentId) { } protected ContentTypeCompositionBase(IShortStringHelper shortStringHelper,IContentTypeComposition parent) : this(shortStringHelper, parent, null) { } protected ContentTypeCompositionBase(IShortStringHelper shortStringHelper, IContentTypeComposition parent, string alias) : base(shortStringHelper, parent, alias) { AddContentType(parent); } public IEnumerable<int> RemovedContentTypes => _removedContentTypeKeyTracker; /// <summary> /// Gets or sets the content types that compose this content type. /// </summary> [DataMember] public IEnumerable<IContentTypeComposition> ContentTypeComposition { get => _contentTypeComposition; set { _contentTypeComposition = value.ToList(); OnPropertyChanged(nameof(ContentTypeComposition)); } } /// <inheritdoc /> [IgnoreDataMember] public IEnumerable<PropertyGroup> CompositionPropertyGroups { get { // we need to "acquire" composition groups and properties here, ie get our own clones, // so that we can change their variation according to this content type variations. // // it would be nice to cache the resulting enumerable, but alas we cannot, otherwise // any change to compositions are ignored and that breaks many things - and tracking // changes to refresh the cache would be expensive. void AcquireProperty(IPropertyType propertyType) { propertyType.Variations &= Variations; propertyType.ResetDirtyProperties(false); } return PropertyGroups.Union(ContentTypeComposition.SelectMany(x => x.CompositionPropertyGroups) .Select(group => { group = (PropertyGroup) group.DeepClone(); foreach (var property in group.PropertyTypes) AcquireProperty(property); return group; })); } } /// <inheritdoc /> [IgnoreDataMember] public IEnumerable<IPropertyType> CompositionPropertyTypes { get { // we need to "acquire" composition properties here, ie get our own clones, // so that we can change their variation according to this content type variations. // // see note in CompositionPropertyGroups for comments on caching the resulting enumerable IPropertyType AcquireProperty(IPropertyType propertyType) { propertyType = (IPropertyType) propertyType.DeepClone(); propertyType.Variations &= Variations; propertyType.ResetDirtyProperties(false); return propertyType; } return ContentTypeComposition .SelectMany(x => x.CompositionPropertyTypes) .Select(AcquireProperty) .Union(PropertyTypes); } } /// <inheritdoc /> public IEnumerable<IPropertyType> GetOriginalComposedPropertyTypes() => GetRawComposedPropertyTypes(); private IEnumerable<IPropertyType> GetRawComposedPropertyTypes(bool start = true) { var propertyTypes = ContentTypeComposition .Cast<ContentTypeCompositionBase>() .SelectMany(x => start ? x.GetRawComposedPropertyTypes(false) : x.CompositionPropertyTypes); if (!start) propertyTypes = propertyTypes.Union(PropertyTypes); return propertyTypes; } /// <summary> /// Adds a content type to the composition. /// </summary> /// <param name="contentType">The content type to add.</param> /// <returns>True if the content type was added, otherwise false.</returns> public bool AddContentType(IContentTypeComposition contentType) { if (contentType.ContentTypeComposition.Any(x => x.CompositionAliases().Any(ContentTypeCompositionExists))) return false; if (string.IsNullOrEmpty(Alias) == false && Alias.Equals(contentType.Alias)) return false; if (ContentTypeCompositionExists(contentType.Alias) == false) { // Before we actually go ahead and add the ContentType as a Composition we ensure that we don't // end up with duplicate PropertyType aliases - in which case we throw an exception. var conflictingPropertyTypeAliases = CompositionPropertyTypes.SelectMany( x => contentType.CompositionPropertyTypes .Where(y => y.Alias.Equals(x.Alias, StringComparison.InvariantCultureIgnoreCase)) .Select(p => p.Alias)).ToList(); if (conflictingPropertyTypeAliases.Any()) throw new InvalidCompositionException(Alias, contentType.Alias, conflictingPropertyTypeAliases.ToArray()); _contentTypeComposition.Add(contentType); OnPropertyChanged(nameof(ContentTypeComposition)); return true; } return false; } /// <summary> /// Removes a content type with a specified alias from the composition. /// </summary> /// <param name="alias">The alias of the content type to remove.</param> /// <returns>True if the content type was removed, otherwise false.</returns> public bool RemoveContentType(string alias) { if (ContentTypeCompositionExists(alias)) { var contentTypeComposition = ContentTypeComposition.FirstOrDefault(x => x.Alias == alias); if (contentTypeComposition == null) // You can't remove a composition from another composition return false; _removedContentTypeKeyTracker.Add(contentTypeComposition.Id); // If the ContentType we are removing has Compositions of its own these needs to be removed as well var compositionIdsToRemove = contentTypeComposition.CompositionIds().ToList(); if (compositionIdsToRemove.Any()) _removedContentTypeKeyTracker.AddRange(compositionIdsToRemove); OnPropertyChanged(nameof(ContentTypeComposition)); return _contentTypeComposition.Remove(contentTypeComposition); } return false; } /// <summary> /// Checks if a ContentType with the supplied alias exists in the list of composite ContentTypes /// </summary> /// <param name="alias">Alias of a <see cref="ContentType"/></param> /// <returns>True if ContentType with alias exists, otherwise returns False</returns> public bool ContentTypeCompositionExists(string alias) { if (ContentTypeComposition.Any(x => x.Alias.Equals(alias))) return true; if (ContentTypeComposition.Any(x => x.ContentTypeCompositionExists(alias))) return true; return false; } /// <summary> /// Checks whether a PropertyType with a given alias already exists /// </summary> /// <param name="alias">Alias of the PropertyType</param> /// <returns>Returns <c>True</c> if a PropertyType with the passed in alias exists, otherwise <c>False</c></returns> public override bool PropertyTypeExists(string alias) => CompositionPropertyTypes.Any(x => x.Alias == alias); /// <inheritdoc /> public override bool AddPropertyGroup(string alias, string name) => AddAndReturnPropertyGroup(alias, name) != null; private PropertyGroup AddAndReturnPropertyGroup(string alias, string name) { // Ensure we don't have it already if (PropertyGroups.Contains(alias)) return null; // Add new group var group = new PropertyGroup(SupportsPublishing) { Alias = alias, Name = name }; // check if it is inherited - there might be more than 1 but we want the 1st, to // reuse its sort order - if there are more than 1 and they have different sort // orders... there isn't much we can do anyways var inheritGroup = CompositionPropertyGroups.FirstOrDefault(x => x.Alias == alias); if (inheritGroup == null) { // no, just local, set sort order var lastGroup = PropertyGroups.LastOrDefault(); if (lastGroup != null) group.SortOrder = lastGroup.SortOrder + 1; } else { // yes, inherited, re-use sort order group.SortOrder = inheritGroup.SortOrder; } // add PropertyGroups.Add(group); return group; } /// <inheritdoc /> public override bool AddPropertyType(IPropertyType propertyType, string propertyGroupAlias, string propertyGroupName = null) { // ensure no duplicate alias - over all composition properties if (PropertyTypeExists(propertyType.Alias)) return false; // get and ensure a group local to this content type PropertyGroup group; var index = PropertyGroups.IndexOfKey(propertyGroupAlias); if (index != -1) { group = PropertyGroups[index]; } else if (!string.IsNullOrEmpty(propertyGroupName)) { group = AddAndReturnPropertyGroup(propertyGroupAlias, propertyGroupName); if (group == null) return false; } else { // No group name specified, so we can't create a new one and add the property type return false; } // add property to group propertyType.PropertyGroupId = new Lazy<int>(() => group.Id); group.PropertyTypes.Add(propertyType); return true; } /// <summary> /// Gets a list of ContentType aliases from the current composition /// </summary> /// <returns>An enumerable list of string aliases</returns> /// <remarks>Does not contain the alias of the Current ContentType</remarks> public IEnumerable<string> CompositionAliases() => ContentTypeComposition .Select(x => x.Alias) .Union(ContentTypeComposition.SelectMany(x => x.CompositionAliases())); /// <summary> /// Gets a list of ContentType Ids from the current composition /// </summary> /// <returns>An enumerable list of integer ids</returns> /// <remarks>Does not contain the Id of the Current ContentType</remarks> public IEnumerable<int> CompositionIds() => ContentTypeComposition .Select(x => x.Id) .Union(ContentTypeComposition.SelectMany(x => x.CompositionIds())); protected override void PerformDeepClone(object clone) { base.PerformDeepClone(clone); var clonedEntity = (ContentTypeCompositionBase)clone; // need to manually assign since this is an internal field and will not be automatically mapped clonedEntity._removedContentTypeKeyTracker = new List<int>(); clonedEntity._contentTypeComposition = ContentTypeComposition.Select(x => (IContentTypeComposition)x.DeepClone()).ToList(); } } }
using System; using System.Data.Linq; using System.Data.SqlTypes; using System.IO; using System.Linq.Expressions; using System.Text; using System.Xml; namespace LinqToDB.DataProvider.SqlServer { using Common; using Expressions; using LinqToDB.Metadata; using Mapping; using SqlQuery; public class SqlServerMappingSchema : MappingSchema { public SqlServerMappingSchema() : base(ProviderName.SqlServer) { ColumnNameComparer = StringComparer.OrdinalIgnoreCase; SetConvertExpression<SqlXml, XmlReader>( s => s.IsNull ? DefaultValue<XmlReader>.Value : s.CreateReader(), s => s.CreateReader()); SetConvertExpression<string,SqlXml>(s => new SqlXml(new MemoryStream(Encoding.UTF8.GetBytes(s)))); AddScalarType(typeof(SqlBinary), SqlBinary. Null, true, DataType.VarBinary); AddScalarType(typeof(SqlBinary?), SqlBinary. Null, true, DataType.VarBinary); AddScalarType(typeof(SqlBoolean), SqlBoolean. Null, true, DataType.Boolean); AddScalarType(typeof(SqlBoolean?), SqlBoolean. Null, true, DataType.Boolean); AddScalarType(typeof(SqlByte), SqlByte. Null, true, DataType.Byte); AddScalarType(typeof(SqlByte?), SqlByte. Null, true, DataType.Byte); AddScalarType(typeof(SqlDateTime), SqlDateTime.Null, true, DataType.DateTime); AddScalarType(typeof(SqlDateTime?), SqlDateTime.Null, true, DataType.DateTime); AddScalarType(typeof(SqlDecimal), SqlDecimal. Null, true, DataType.Decimal); AddScalarType(typeof(SqlDecimal?), SqlDecimal. Null, true, DataType.Decimal); AddScalarType(typeof(SqlDouble), SqlDouble. Null, true, DataType.Double); AddScalarType(typeof(SqlDouble?), SqlDouble. Null, true, DataType.Double); AddScalarType(typeof(SqlGuid), SqlGuid. Null, true, DataType.Guid); AddScalarType(typeof(SqlGuid?), SqlGuid. Null, true, DataType.Guid); AddScalarType(typeof(SqlInt16), SqlInt16. Null, true, DataType.Int16); AddScalarType(typeof(SqlInt16?), SqlInt16. Null, true, DataType.Int16); AddScalarType(typeof(SqlInt32), SqlInt32. Null, true, DataType.Int32); AddScalarType(typeof(SqlInt32?), SqlInt32. Null, true, DataType.Int32); AddScalarType(typeof(SqlInt64), SqlInt64. Null, true, DataType.Int64); AddScalarType(typeof(SqlInt64?), SqlInt64. Null, true, DataType.Int64); AddScalarType(typeof(SqlMoney), SqlMoney. Null, true, DataType.Money); AddScalarType(typeof(SqlMoney?), SqlMoney. Null, true, DataType.Money); AddScalarType(typeof(SqlSingle), SqlSingle. Null, true, DataType.Single); AddScalarType(typeof(SqlSingle?), SqlSingle. Null, true, DataType.Single); AddScalarType(typeof(SqlString), SqlString. Null, true, DataType.NVarChar); AddScalarType(typeof(SqlString?), SqlString. Null, true, DataType.NVarChar); AddScalarType(typeof(SqlXml), SqlXml. Null, true, DataType.Xml); AddScalarType(typeof(DateTime), DataType.DateTime); AddScalarType(typeof(DateTime?), DataType.DateTime); SqlServerTypes.Configure(this); SetValueToSqlConverter(typeof(string), (sb,dt,v) => ConvertStringToSql (sb, dt, v.ToString()!)); SetValueToSqlConverter(typeof(char), (sb,dt,v) => ConvertCharToSql (sb, dt, (char)v)); SetValueToSqlConverter(typeof(DateTime), (sb,dt,v) => ConvertDateTimeToSql (sb, null, (DateTime)v)); SetValueToSqlConverter(typeof(TimeSpan), (sb,dt,v) => ConvertTimeSpanToSql (sb, dt, (TimeSpan)v)); SetValueToSqlConverter(typeof(DateTimeOffset), (sb,dt,v) => ConvertDateTimeOffsetToSql(sb, dt, (DateTimeOffset)v)); SetValueToSqlConverter(typeof(byte[]), (sb,dt,v) => ConvertBinaryToSql (sb, (byte[])v)); SetValueToSqlConverter(typeof(Binary), (sb,dt,v) => ConvertBinaryToSql (sb, ((Binary)v).ToArray())); SetDataType(typeof(string), new SqlDataType(DataType.NVarChar, typeof(string))); AddMetadataReader(new SystemDataSqlServerAttributeReader()); } internal static SqlServerMappingSchema Instance = new SqlServerMappingSchema(); // TODO: move to SqlServerTypes.Configure? public override LambdaExpression? TryGetConvertExpression(Type @from, Type to) { if (@from != to && @from.FullName == to.FullName && @from.Namespace == SqlServerTypes.TypesNamespace) { var p = Expression.Parameter(@from); return Expression.Lambda( Expression.Call(to, "Parse", new Type[0], Expression.New( MemberHelper.ConstructorOf(() => new SqlString("")), Expression.Call( Expression.Convert(p, typeof(object)), "ToString", new Type[0]))), p); } return base.TryGetConvertExpression(@from, to); } static void AppendConversion(StringBuilder stringBuilder, int value) { stringBuilder .Append("char(") .Append(value) .Append(')') ; } static void ConvertStringToSql(StringBuilder stringBuilder, SqlDataType sqlDataType, string value) { string? startPrefix; switch (sqlDataType.Type.DataType) { case DataType.Char : case DataType.VarChar : case DataType.Text : startPrefix = null; break; default : startPrefix = "N"; break; } DataTools.ConvertStringToSql(stringBuilder, "+", startPrefix, AppendConversion, value, null); } static void ConvertCharToSql(StringBuilder stringBuilder, SqlDataType sqlDataType, char value) { string start; switch (sqlDataType.Type.DataType) { case DataType.Char : case DataType.VarChar : case DataType.Text : start = "'"; break; default : start = "N'"; break; } DataTools.ConvertCharToSql(stringBuilder, start, AppendConversion, value); } internal static void ConvertDateTimeToSql(StringBuilder stringBuilder, SqlDataType? dt, DateTime value) { var format = value.Millisecond == 0 ? "yyyy-MM-ddTHH:mm:ss" : dt == null || dt.Type.DataType != DataType.DateTime2 ? "yyyy-MM-ddTHH:mm:ss.fff" : dt.Type.Precision == 0 ? "yyyy-MM-ddTHH:mm:ss" : "yyyy-MM-ddTHH:mm:ss." + new string('f', dt.Type.Precision ?? 7); stringBuilder .Append('\'') .Append(value.ToString(format)) .Append('\'') ; } static void ConvertTimeSpanToSql(StringBuilder stringBuilder, SqlDataType sqlDataType, TimeSpan value) { if (sqlDataType.Type.DataType == DataType.Int64) { stringBuilder.Append(value.Ticks); } else { var format = value.Days > 0 ? value.Ticks % 10000000 != 0 ? "d\\.hh\\:mm\\:ss\\.fffffff" : "d\\.hh\\:mm\\:ss" : value.Ticks % 10000000 != 0 ? "hh\\:mm\\:ss\\.fffffff" : "hh\\:mm\\:ss"; stringBuilder .Append('\'') .Append(value.ToString(format)) .Append('\'') ; } } static void ConvertDateTimeOffsetToSql(StringBuilder stringBuilder, SqlDataType sqlDataType, DateTimeOffset value) { var format = "'{0:yyyy-MM-dd HH:mm:ss.fffffff zzz}'"; switch (sqlDataType.Type.Precision ?? sqlDataType.Type.Scale) { case 0 : format = "'{0:yyyy-MM-dd HH:mm:ss zzz}'"; break; case 1 : format = "'{0:yyyy-MM-dd HH:mm:ss.f zzz}'"; break; case 2 : format = "'{0:yyyy-MM-dd HH:mm:ss.ff zzz}'"; break; case 3 : format = "'{0:yyyy-MM-dd HH:mm:ss.fff zzz}'"; break; case 4 : format = "'{0:yyyy-MM-dd HH:mm:ss.ffff zzz}'"; break; case 5 : format = "'{0:yyyy-MM-dd HH:mm:ss.fffff zzz}'"; break; case 6 : format = "'{0:yyyy-MM-dd HH:mm:ss.ffffff zzz}'"; break; case 7 : format = "'{0:yyyy-MM-dd HH:mm:ss.fffffff zzz}'"; break; } stringBuilder.AppendFormat(format, value); } static void ConvertBinaryToSql(StringBuilder stringBuilder, byte[] value) { stringBuilder.Append("0x"); foreach (var b in value) stringBuilder.Append(b.ToString("X2")); } } public class SqlServer2000MappingSchema : MappingSchema { public SqlServer2000MappingSchema() : base(ProviderName.SqlServer2000, SqlServerMappingSchema.Instance) { ColumnNameComparer = StringComparer.OrdinalIgnoreCase; } public override LambdaExpression? TryGetConvertExpression(Type @from, Type to) { return SqlServerMappingSchema.Instance.TryGetConvertExpression(@from, to); } } public class SqlServer2005MappingSchema : MappingSchema { public SqlServer2005MappingSchema() : base(ProviderName.SqlServer2005, SqlServerMappingSchema.Instance) { ColumnNameComparer = StringComparer.OrdinalIgnoreCase; } public override LambdaExpression? TryGetConvertExpression(Type @from, Type to) { return SqlServerMappingSchema.Instance.TryGetConvertExpression(@from, to); } } public class SqlServer2008MappingSchema : MappingSchema { public SqlServer2008MappingSchema() : base(ProviderName.SqlServer2008, SqlServerMappingSchema.Instance) { ColumnNameComparer = StringComparer.OrdinalIgnoreCase; SetValueToSqlConverter(typeof(DateTime), (sb, dt, v) => SqlServerMappingSchema.ConvertDateTimeToSql(sb, dt, (DateTime)v)); } public override LambdaExpression? TryGetConvertExpression(Type @from, Type to) { return SqlServerMappingSchema.Instance.TryGetConvertExpression(@from, to); } } public class SqlServer2012MappingSchema : MappingSchema { public SqlServer2012MappingSchema() : base(ProviderName.SqlServer2012, SqlServerMappingSchema.Instance) { ColumnNameComparer = StringComparer.OrdinalIgnoreCase; SetValueToSqlConverter(typeof(DateTime), (sb, dt, v) => SqlServerMappingSchema.ConvertDateTimeToSql(sb, dt, (DateTime)v)); } public override LambdaExpression? TryGetConvertExpression(Type @from, Type to) { return SqlServerMappingSchema.Instance.TryGetConvertExpression(@from, to); } } public class SqlServer2017MappingSchema : MappingSchema { public SqlServer2017MappingSchema() : base(ProviderName.SqlServer2017, SqlServerMappingSchema.Instance) { ColumnNameComparer = StringComparer.OrdinalIgnoreCase; SetValueToSqlConverter(typeof(DateTime), (sb, dt, v) => SqlServerMappingSchema.ConvertDateTimeToSql(sb, dt, (DateTime)v)); } public override LambdaExpression? TryGetConvertExpression(Type @from, Type to) { return SqlServerMappingSchema.Instance.TryGetConvertExpression(@from, to); } } }
using System; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Runtime.InteropServices; using System.Windows.Forms; namespace BizHawk.Client.EmuHawk { #region win32interop [StructLayout(LayoutKind.Sequential)] internal struct LvDispInfo { public NmHdr Hdr; public LvItem Item; } [StructLayout(LayoutKind.Sequential)] internal struct NmHdr { public IntPtr HwndFrom; public IntPtr IdFrom; public int Code; } [StructLayout(LayoutKind.Sequential)] internal struct NmItemActivate { public NmHdr Hdr; public int Item; public int SubItem; public uint NewState; public uint OldState; public uint uChanged; public POINT Action; public uint lParam; public uint KeyFlags; } [StructLayout(LayoutKind.Sequential)] internal struct RECT { public int Top; public int Left; public int Bottom; public int Right; } [StructLayout(LayoutKind.Sequential)] internal struct NmCustomDrawInfo { public NmHdr Hdr; public uint dwDrawStage; public IntPtr Hdc; public RECT Rect; public int dwItemSpec; public uint ItemState; public int lItemlParam; } [StructLayout(LayoutKind.Sequential)] internal struct NmLvCustomDraw { public NmCustomDrawInfo Nmcd; public int ClearText; public int ClearTextBackground; public int SubItem; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct LvItem { public uint Mask; public int Item; public int SubItem; public uint State; public uint StateMask; public IntPtr PszText; public int cchTextMax; public int Image; public IntPtr lParam; public int Indent; } [FlagsAttribute] internal enum CustomDrawReturnFlags { CDRF_DODEFAULT = 0x00000000, CDRF_NEWFONT = 0x00000002, CDRF_SKIPDEFAULT = 0x00000004, CDRF_NOTIFYPOSTPAINT = 0x00000010, CDRF_NOTIFYITEMDRAW = 0x00000020, CDRF_NOTIFYSUBITEMDRAW = 0x00000020, CDRF_NOTIFYPOSTERASE = 0x00000040, } [FlagsAttribute] internal enum CustomDrawDrawStageFlags { CDDS_PREPAINT = 0x00000001, CDDS_POSTPAINT = 0x00000002, CDDS_PREERASE = 0x00000003, CDDS_POSTERASE = 0x00000004, // the 0x000010000 bit means it's individual item specific CDDS_ITEM = 0x00010000, CDDS_ITEMPREPAINT = (CDDS_ITEM | CDDS_PREPAINT), CDDS_ITEMPOSTPAINT = (CDDS_ITEM | CDDS_POSTPAINT), CDDS_ITEMPREERASE = (CDDS_ITEM | CDDS_PREERASE), CDDS_ITEMPOSTERASE = (CDDS_ITEM | CDDS_POSTERASE), CDDS_SUBITEM = 0x00020000, CDDS_SUBITEMPREPAINT = (CDDS_SUBITEM | CDDS_ITEMPREPAINT), CDDS_SUBITEMPOSTPAINT = (CDDS_SUBITEM | CDDS_ITEMPOSTPAINT), CDDS_SUBITEMPREERASE = (CDDS_SUBITEM | CDDS_ITEMPREERASE), CDDS_SUBITEMPOSTERASE = (CDDS_SUBITEM | CDDS_ITEMPOSTERASE), } [FlagsAttribute] internal enum LvHitTestFlags { LVHT_NOWHERE = 0x0001, LVHT_ONITEMICON = 0x0002, LVHT_ONITEMLABEL = 0x0004, LVHT_ONITEMSTATEICON = 0x0008, LVHT_ONITEM = (LVHT_ONITEMICON | LVHT_ONITEMLABEL | LVHT_ONITEMSTATEICON), LVHT_ABOVE = 0x0008, LVHT_BELOW = 0x0010, LVHT_TORIGHT = 0x0020, LVHT_TOLEFT = 0x0040 } [StructLayout(LayoutKind.Sequential)] internal struct POINT { public int X; public int Y; } [StructLayout(LayoutKind.Sequential)] internal class LvHitTestInfo { public POINT Point; public uint Flags; public int Item; public int SubItem; } [StructLayout(LayoutKind.Sequential)] internal struct NMLISTVIEW { public NmHdr hdr; public int iItem; public int iSubItem; public uint uNewState; public uint uOldState; public uint uChanged; public POINT ptAction; public IntPtr lParam; } internal enum ListViewItemMask : short { LVIF_TEXT = 0x0001, LVIF_IMAGE = 0x0002, LVIF_PARAM = 0x0004, LVIF_STATE = 0x0008, LVIF_INDENT = 0x0010, LVIF_NORECOMPUTE = 0x0800, LVIF_GROUPID = 0x0100, LVIF_COLUMNS = 0x0200 } internal enum LvNi { ALL = 0x0000, FOCUSED = 0x0001, SELECTED = 0x0002, CUT = 0x0004, DROPHILITED = 0x0008, ABOVE = 0x0100, BELOW = 0x0200, TOLEFT = 0x0400, TORIGHT = 0x0800 } internal enum ListViewMessages { LVM_FIRST = 0x1000, LVM_GETITEMCOUNT = (LVM_FIRST + 4), LVM_SETCALLBACKMASK = (LVM_FIRST + 11), LVM_GETNEXTITEM = (LVM_FIRST + 12), LVM_HITTEST = (LVM_FIRST + 18), LVM_ENSUREVISIBLE = (LVM_FIRST + 19), LVM_SETITEMSTATE = (LVM_FIRST + 43), LVM_GETITEMSTATE = (LVM_FIRST + 44), LVM_SETITEMCOUNT = (LVM_FIRST + 47), LVM_GETSUBITEMRECT = (LVM_FIRST + 56) } internal enum ListViewStyles : short { LVS_OWNERDATA = 0x1000, LVS_SORTASCENDING = 0x0010, LVS_SORTDESCENDING = 0x0020, LVS_SHAREIMAGELISTS = 0x0040, LVS_NOLABELWRAP = 0x0080, LVS_AUTOARRANGE = 0x0100 } internal enum ListViewStylesICF : uint { LVSICF_NOINVALIDATEALL = 0x00000001, LVSICF_NOSCROLL = 0x00000002 } internal enum WindowsMessage : uint { WM_ERASEBKGND = 0x0014, WM_SCROLL = 0x115, WM_LBUTTONDOWN = 0x0201, WM_LBUTTONUP = 0x0202, WM_LBUTTONDBLCLK = 0x0203, WM_RBUTTONDOWN = 0x0204, WM_RBUTTONUP = 0x0205, WM_RBUTTONDBLCLK = 0x0206, WM_SETFOCUS = 0x0007, WM_NOTIFY = 0x004E, WM_USER = 0x0400, WM_REFLECT = WM_USER + 0x1c00 } internal enum Notices { NM_FIRST = 0, NM_CUSTOMDRAW = NM_FIRST - 12, NM_CLICK = NM_FIRST - 2, NM_DBLCLICK = NM_FIRST - 3, } internal enum ListViewNotices { LVN_FIRST = (0 - 100), LVN_LAST = (0 - 199), LVN_BEGINDRAG = LVN_FIRST - 9, LVN_BEGINRDRAG = LVN_FIRST - 11, LVN_GETDISPINFOA = LVN_FIRST - 50, LVN_GETDISPINFOW = LVN_FIRST - 77, LVN_SETDISPINFOA = LVN_FIRST - 51, LVN_SETDISPINFOW = LVN_FIRST - 78, LVN_ODCACHEHINT = LVN_FIRST - 13, LVN_ODFINDITEMW = LVN_FIRST - 79 } [Flags] internal enum ListViewCallBackMask : uint { LVIS_FOCUSED = 0x0001, LVIS_SELECTED = 0x0002, LVIS_CUT = 0x0004, LVIS_DROPHILITED = 0x0008, LVIS_GLOW = 0x0010, LVIS_ACTIVATING = 0x0020, LVIS_OVERLAYMASK = 0x0F00, LVIS_STATEIMAGEMASK = 0xF000, } #endregion #region VirtualListView Delegates /// <summary> /// Retrieve the background color for a Listview cell (item and subitem). /// </summary> /// <param name="item">Listview item (row).</param> /// <param name="subItem">Listview subitem (column).</param> /// <param name="color">Background color to use</param> public delegate void QueryItemBkColorHandler(int item, int subItem, ref Color color); /// <summary> /// Retrieve the text for a Listview cell (item and subitem). /// </summary> /// <param name="item">Listview item (row).</param> /// <param name="subItem">Listview subitem (column).</param> /// <param name="text">Text to display.</param> public delegate void QueryItemTextHandler(int item, int subItem, out string text); /// <summary> /// Retrieve the image index for a Listview item. /// </summary> /// <param name="item">Listview item (row).</param> /// <param name="subItem">Listview subitem (column) - should always be zero.</param> /// <param name="imageIndex">Index of associated ImageList.</param> public delegate void QueryItemImageHandler(int item, int subItem, out int imageIndex); /// <summary> /// Retrieve the indent for a Listview item. The indent is always width of an image. /// For example, 1 indents the Listview item one image width. /// </summary> /// <param name="item">Listview item (row).</param> /// <param name="itemIndent">The amount to indent the Listview item.</param> public delegate void QueryItemIndentHandler(int item, out int itemIndent); public delegate void QueryItemHandler(int idx, out ListViewItem item); #endregion /// <summary> /// VirtualListView is a virtual Listview which allows for a large number of items(rows) /// to be displayed. The virtual Listview contains very little actual information - /// mainly item selection and focus information. /// </summary> public class VirtualListView : ListView { // store the item count to prevent the call to SendMessage(LVM_GETITEMCOUNT) private int _itemCount; #region Display query callbacks /// <summary> /// Fire the QueryItemBkColor event which requests the background color for the passed Listview cell /// </summary> public event QueryItemBkColorHandler QueryItemBkColor; /// <summary> /// Fire the QueryItemText event which requests the text for the passed Listview cell. /// </summary> [Category("Data")] public event QueryItemTextHandler QueryItemText; /// <summary> /// Fire the QueryItemImage event which requests the ImageIndex for the passed Listview item. /// </summary> [Category("Data")] public event QueryItemImageHandler QueryItemImage; /// <summary> /// Fire the QueryItemIndent event which requests the indent for the passed Listview item. /// </summary> [Category("Data")] public event QueryItemIndentHandler QueryItemIndent; [Category("Data")] public event QueryItemHandler QueryItem; #endregion #region Properties /// <summary> /// Gets or sets the sets the virtual number of items to be displayed. /// </summary> [Category("Behavior")] public int ItemCount { get { return _itemCount; } set { _itemCount = value; // If the virtual item count is set before the handle is created // then the image lists don't get loaded properly if (!IsHandleCreated) { return; } SetVirtualItemCount(); } } /// <summary> /// Gets or sets how list items are to be displayed. /// Hide the ListView.View property. /// Virtual Listviews only allow Details or List. /// </summary> public new View View { get { return base.View; } set { if (value == View.LargeIcon || value == View.SmallIcon) { throw new ArgumentException("Icon views are invalid for virtual ListViews", "View"); } base.View = value; } } /// <summary> /// Gets the required creation parameters when the control handle is created. /// Use LVS_OWNERDATA to set this as a virtual Listview. /// </summary> protected override CreateParams CreateParams { get { var cp = base.CreateParams; // LVS_OWNERDATA style must be set when the control is created cp.Style |= (int)ListViewStyles.LVS_OWNERDATA; return cp; } } #endregion [Browsable(false)] [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)] public int LineHeight { get; private set; } [Browsable(false)] [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden)] public int NumberOfVisibleRows { get { return Height / LineHeight; } } #region Constructors /// <summary> /// Initializes a new instance of the <see cref="VirtualListView"/> class. /// Create a new instance of this control. /// </summary> public VirtualListView() { // virtual listviews must be Details or List view with no sorting View = View.Details; Sorting = SortOrder.None; UseCustomBackground = true; ptrlvhti = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LvHitTestInfo))); SetStyle(ControlStyles.OptimizedDoubleBuffer, true); SetStyle(ControlStyles.Opaque, true); SetStyle(ControlStyles.AllPaintingInWmPaint, true); LineHeight = this.Font.Height + 5; } ~VirtualListView() { Marshal.FreeHGlobal(ptrlvhti); } #endregion #region Methods /// <summary> /// Set the state of the passed Listview item's index. /// </summary> /// <param name="index">Listview item's index.</param> /// <param name="selected">Select the passed item?</param> public void SelectItem(int index, bool selected) { var ptrItem = IntPtr.Zero; try { // Determine whether selecting or unselecting. uint select = selected ? (uint)ListViewCallBackMask.LVIS_SELECTED : 0; // Fill in the LVITEM structure with state fields. var stateItem = new LvItem { Mask = (uint)ListViewItemMask.LVIF_STATE, Item = index, SubItem = 0, State = @select, StateMask = (uint)ListViewCallBackMask.LVIS_SELECTED }; // Copy the structure to unmanaged memory. ptrItem = Marshal.AllocHGlobal(Marshal.SizeOf(stateItem.GetType())); Marshal.StructureToPtr(stateItem, ptrItem, true); // Send the message to the control window. Win32.SendMessage( this.Handle, (int)ListViewMessages.LVM_SETITEMSTATE, index, ptrItem.ToInt32()); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine("VirtualListView.SetItemState error=" + ex.Message); // TODO: should this eat any exceptions? throw; } finally { // Always release the unmanaged memory. if (ptrItem != IntPtr.Zero) { Marshal.FreeHGlobal(ptrItem); } } } private void SetVirtualItemCount() { Win32.SendMessage( this.Handle, (int)ListViewMessages.LVM_SETITEMCOUNT, this._itemCount, 0); } protected void OnDispInfoNotice(ref Message m, bool useAnsi) { var info = (LvDispInfo)m.GetLParam(typeof(LvDispInfo)); if ((info.Item.Mask & (uint)ListViewItemMask.LVIF_TEXT) > 0) { if (QueryItemText != null) { string lvtext; QueryItemText(info.Item.Item, info.Item.SubItem, out lvtext); if (lvtext != null) { try { int maxIndex = Math.Min(info.Item.cchTextMax - 1, lvtext.Length); var data = new char[maxIndex + 1]; lvtext.CopyTo(0, data, 0, lvtext.Length); data[maxIndex] = '\0'; Marshal.Copy(data, 0, info.Item.PszText, data.Length); } catch (Exception e) { Debug.WriteLine("Failed to copy text name from client: " + e, "VirtualListView.OnDispInfoNotice"); } } } } if ((info.Item.Mask & (uint)ListViewItemMask.LVIF_IMAGE) > 0) { int imageIndex = 0; if (QueryItemImage != null) { QueryItemImage(info.Item.Item, info.Item.SubItem, out imageIndex); } info.Item.Image = imageIndex; Marshal.StructureToPtr(info, m.LParam, false); } if ((info.Item.Mask & (uint)ListViewItemMask.LVIF_INDENT) > 0) { int itemIndent = 0; if (QueryItemIndent != null) { QueryItemIndent(info.Item.Item, out itemIndent); } info.Item.Indent = itemIndent; Marshal.StructureToPtr(info, m.LParam, false); } m.Result = new IntPtr(0); } protected void OnCustomDrawNotice(ref Message m) { var cd = (NmLvCustomDraw)m.GetLParam(typeof(NmLvCustomDraw)); switch (cd.Nmcd.dwDrawStage) { case (int)CustomDrawDrawStageFlags.CDDS_ITEMPREPAINT: case (int)CustomDrawDrawStageFlags.CDDS_PREPAINT: m.Result = new IntPtr((int)CustomDrawReturnFlags.CDRF_NOTIFYSUBITEMDRAW); break; case (int)CustomDrawDrawStageFlags.CDDS_SUBITEMPREPAINT: if (QueryItemBkColor != null) { var color = Color.FromArgb(cd.ClearTextBackground & 0xFF, (cd.ClearTextBackground >> 8) & 0xFF, (cd.ClearTextBackground >> 16) & 0xFF); QueryItemBkColor(cd.Nmcd.dwItemSpec, cd.SubItem, ref color); cd.ClearTextBackground = (color.B << 16) | (color.G << 8) | color.R; Marshal.StructureToPtr(cd, m.LParam, false); } m.Result = new IntPtr((int)CustomDrawReturnFlags.CDRF_DODEFAULT); break; } } /// <summary> /// Event to be fired whenever the control scrolls /// </summary> public event ScrollEventHandler Scroll; protected virtual void OnScroll(ScrollEventArgs e) { var handler = this.Scroll; if (handler != null) { handler(this, e); } } [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern int GetScrollPos(IntPtr hWnd, Orientation nBar); /// <summary> /// Gets the Vertical Scroll position of the control. /// </summary> public int VScrollPos { get { return GetScrollPos(this.Handle, Orientation.Vertical); } } protected override void WndProc(ref Message m) { var messageProcessed = false; switch (m.Msg) { case (int)WindowsMessage.WM_REFLECT + (int)WindowsMessage.WM_NOTIFY: var nm1 = (NmHdr)m.GetLParam(typeof(NmHdr)); switch (nm1.Code) { case (int)Notices.NM_CUSTOMDRAW: OnCustomDrawNotice(ref m); messageProcessed = true; if (QueryItemBkColor == null || !UseCustomBackground) { m.Result = (IntPtr)0; } break; case (int)ListViewNotices.LVN_GETDISPINFOW: OnDispInfoNotice(ref m, false); messageProcessed = true; break; case (int)ListViewNotices.LVN_BEGINDRAG: OnBeginItemDrag(MouseButtons.Left, ref m); messageProcessed = true; break; case (int)ListViewNotices.LVN_BEGINRDRAG: OnBeginItemDrag(MouseButtons.Right, ref m); messageProcessed = true; break; } break; case (int)WindowsMessage.WM_SCROLL: // http://stackoverflow.com/questions/1851620/handling-scroll-event-on-listview-in-c-sharp OnScroll(new ScrollEventArgs((ScrollEventType)(m.WParam.ToInt32() & 0xffff), m.WParam.ToInt32())); break; case (int)WindowsMessage.WM_ERASEBKGND: if (BlazingFast) { messageProcessed = true; m.Result = new IntPtr(1); } break; } if (!messageProcessed) { try { base.WndProc(ref m); } catch (Exception ex) { Trace.WriteLine(string.Format("Message {0} caused an exception: {1}", m, ex.Message)); } } } public bool BlazingFast { get; set; } public bool UseCustomBackground { get; set; } protected ListViewItem GetItem(int idx) { ListViewItem item = null; if (QueryItem != null) { QueryItem(idx, out item); } if (item == null) { throw new ArgumentException("cannot find item " + idx + " via QueryItem event"); } return item; } protected void OnBeginItemDrag(MouseButtons mouseButton, ref Message m) { var info = (NMLISTVIEW)m.GetLParam(typeof(NMLISTVIEW)); ListViewItem item = null; if (QueryItem != null) { QueryItem(info.iItem, out item); } OnItemDrag(new ItemDragEventArgs(mouseButton, item)); } protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); // ensure the value for ItemCount is sent to the control properly if the user set it // before the handle was created SetVirtualItemCount(); } protected override void OnHandleDestroyed(EventArgs e) { // the ListView OnHandleDestroyed accesses the Items list for all selected items ItemCount = 0; base.OnHandleDestroyed(e); } #endregion LvHitTestInfo lvhti = new LvHitTestInfo(); IntPtr ptrlvhti; int selection = -1; public int hitTest(int x, int y) { lvhti.Point.X = x; lvhti.Point.Y = y; Marshal.StructureToPtr(lvhti, ptrlvhti, true); int z = Win32.SendMessage(this.Handle, (int)ListViewMessages.LVM_HITTEST, 0, ptrlvhti.ToInt32()); Marshal.PtrToStructure(ptrlvhti, lvhti); return z; } public void ensureVisible(int index) { Win32.SendMessage(Handle, (int)ListViewMessages.LVM_ENSUREVISIBLE, index, 1); } public void ensureVisible() { ensureVisible(selectedItem); } public void setSelection(int index) { clearSelection(); selection = index; SelectItem(selection, true); } public int selectedItem { get { if (SelectedIndices.Count == 0) { return -1; } else { return SelectedIndices[0]; } } set { setSelection(value); } } public void clearSelection() { if (selection != -1) { SelectItem(selection, false); } selection = -1; } // Informs user that a select all event is in place, can be used in change events to wait until this is false public bool SelectAllInProgress { get; set; } public void SelectAll() { this.BeginUpdate(); SelectAllInProgress = true; for (var i = 0; i < _itemCount; i++) { if (i == _itemCount - 1) { SelectAllInProgress = false; } this.SelectItem(i, true); } this.EndUpdate(); } public void DeselectAll() { this.BeginUpdate(); SelectAllInProgress = true; for (var i = 0; i < _itemCount; i++) { if (i == _itemCount - 1) { SelectAllInProgress = false; } this.SelectItem(i, false); } this.EndUpdate(); } protected override void OnKeyDown(KeyEventArgs e) { if (e.KeyCode == Keys.A && e.Control && !e.Alt && !e.Shift) // Select All { SelectAll(); } base.OnKeyDown(e); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Threading; using Its.Configuration.Features; using NUnit.Framework; using Assert = NUnit.Framework.Assert; namespace Its.Configuration.Tests.Features { [TestFixture] public class FeatureActivatorTests { private CompositeDisposable disposables; [SetUp] public void SetUp() { disposables = new CompositeDisposable(); } [TearDown] public void TearDown() { disposables.Dispose(); } [Test] public void Is_available_by_default() { var activated = false; var activator = new FeatureActivator(() => { activated = true; }); Assert.That(activator.First(), Is.True); Assert.That(activated); } [Test] public void Is_not_initially_available_if_dependency_returns_false() { var activator = new FeatureActivator(() => { }, dependsOn: Observable.Return(false)); Assert.That(activator.First(), Is.False); } [Test] public void Produces_a_value_each_time_the_aggregate_availability_of_dependencies_changes() { var dependency = new BehaviorSubject<bool>(false); var activator = new FeatureActivator(() => { }, dependsOn: dependency); var notifications = new List<bool>(); disposables.Add(activator.Subscribe(notifications.Add)); dependency.OnNext(false); dependency.OnNext(false); dependency.OnNext(true); dependency.OnNext(true); dependency.OnNext(true); dependency.OnNext(true); dependency.OnNext(false); dependency.OnNext(false); dependency.OnNext(false); Assert.That(notifications.IsSameSequenceAs(false, true, false)); } [Test] public void Activate_is_not_called_before_subscribe() { var activations = 0; new FeatureActivator(() => activations++); Assert.That(activations, Is.EqualTo(0)); } [Test] public void Activate_is_not_called_more_than_once_during_concurrent_calls_when_activator_has_no_dependencies() { var activations = 0; var notifications = 0; var barrier = new Barrier(2); var activator = new FeatureActivator(() => { Interlocked.Increment(ref activations); barrier.SignalAndWait(); }); for (var i = 0; i < 10; i++) { disposables.Add(activator .ObserveOn(NewThreadScheduler.Default) .SubscribeOn(NewThreadScheduler.Default) .Subscribe(n => { Console.WriteLine(Thread.CurrentThread.ManagedThreadId); Interlocked.Increment(ref notifications); })); } // give both subscribers enough time to make sure one has advanced to the activator barrier Thread.Sleep(500); barrier.SignalAndWait(); // give them enough time to propagate their notifications Thread.Sleep(500); Assert.That(activations, Is.EqualTo(1)); Assert.That(notifications, Is.EqualTo(10)); } [Test] public void Activate_is_not_called_more_than_once_during_concurrent_calls_when_activator_has_dependencies() { var activations = 0; var notifications = 0; var barrier = new Barrier(2); var subject = new BehaviorSubject<bool>(false); var activator = new FeatureActivator(() => { Console.WriteLine("activated!"); Interlocked.Increment(ref activations); barrier.SignalAndWait(); }, dependsOn: subject); for (var i = 0; i < 10; i++) { disposables.Add(activator .ObserveOn(NewThreadScheduler.Default) .SubscribeOn(NewThreadScheduler.Default) .Subscribe(n => { Console.WriteLine(Thread.CurrentThread.ManagedThreadId); Interlocked.Increment(ref notifications); })); } new Thread(() => subject.OnNext(true)).Start(); // give both subscribers enough time to make sure one has advanced to the activator barrier Thread.Sleep(1000); barrier.SignalAndWait(3000); // give them enough time to propagate their notifications Thread.Sleep(1000); Assert.That(notifications, Is.AtLeast(10)); // sanity check Assert.That(activations, Is.EqualTo(1)); } [Test] public void When_there_are_multiple_subscribers_then_activate_is_not_called_repeatedly() { var activations = 0; var activator = new FeatureActivator(() => activations++); disposables.Add(activator.Subscribe(_ => { })); disposables.Add(activator.Subscribe(_ => { })); disposables.Add(activator.Subscribe(_ => { })); Assert.That(activations, Is.EqualTo(1)); } [Test] public void Activate_is_not_called_until_dependencies_return_true() { var activations = 0; var notifications = new List<bool>(); var subject = new BehaviorSubject<bool>(false); var activator = new FeatureActivator(() => activations++, dependsOn: subject); disposables.Add(activator.Subscribe(notifications.Add)); Assert.That(activations, Is.EqualTo(0)); Assert.That(notifications.IsSameSequenceAs(false)); subject.OnNext(false); Assert.That(activations, Is.EqualTo(0)); Assert.That(notifications.IsSameSequenceAs(false)); subject.OnNext(true); Assert.That(activations, Is.EqualTo(1)); Assert.That(notifications.IsSameSequenceAs(false, true)); disposables.Add(activator.Subscribe(notifications.Add)); Assert.That(activations, Is.EqualTo(1)); Assert.That(notifications.IsSameSequenceAs(false, true, true)); } [Test] public void When_there_are_multiple_dependencies_they_must_all_return_true_before_Activate_is_called() { var activations = 0; var dependency1 = new BehaviorSubject<bool>(false); var dependency2 = new BehaviorSubject<bool>(false); var activator = new FeatureActivator( activate: () => activations++, dependsOn: new[] { dependency1, dependency2 }); var notifications = new List<bool>(); disposables.Add(activator.Subscribe(notifications.Add)); Assert.That(activations, Is.EqualTo(0)); Assert.That(notifications.IsSameSequenceAs(false)); dependency1.OnNext(true); Assert.That(activations, Is.EqualTo(0)); Assert.That(notifications.IsSameSequenceAs(false)); dependency2.OnNext(true); Assert.That(activations, Is.EqualTo(1)); Assert.That(notifications.IsSameSequenceAs(false, true)); } [Test] public void When_any_dependency_produces_false_then_deactivate_is_called() { var deactivations = 0; var dependency1 = new BehaviorSubject<bool>(true); var dependency2 = new BehaviorSubject<bool>(true); var activator = new FeatureActivator( activate: () => { }, deactivate: () => deactivations++, dependsOn: new[] { dependency1, dependency2 }); var notifications = new List<bool>(); disposables.Add(activator.Subscribe(notifications.Add)); Assert.That(deactivations, Is.EqualTo(0)); Assert.That(notifications.IsSameSequenceAs(true)); dependency1.OnNext(false); Assert.That(deactivations, Is.EqualTo(1)); Assert.That(notifications.IsSameSequenceAs(true, false)); } [Test] public void Deactivate_is_not_called_until_after_activate_has_been_called() { var deactivations = 0; var subject = new BehaviorSubject<bool>(false); var activator = new FeatureActivator(() => { }, () => deactivations++, dependsOn: subject); disposables.Add(activator.Subscribe(_ => { })); subject.OnNext(true); Assert.That(deactivations, Is.EqualTo(0)); subject.OnNext(false); Assert.That(deactivations, Is.EqualTo(1)); } } }
#region Header /** * JsonData.cs * Generic type to hold JSON data (objects, arrays, and so on). This is * the default type returned by JsonMapper.ToObject(). * * The authors disclaim copyright to this source code. For more details, see * the COPYING file included with this distribution. **/ #endregion using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; namespace LitJson { public class JsonData : IJsonWrapper, IEquatable<JsonData> { #region Fields private IList<JsonData> inst_array; private bool inst_boolean; private double inst_double; private float inst_float; private int inst_int; private long inst_long; private IDictionary<string, JsonData> inst_object; private string inst_string; private string json; private JsonType type; // Used to implement the IOrderedDictionary interface private IList<KeyValuePair<string, JsonData>> object_list; #endregion #region Properties public int Count { get { return EnsureCollection ().Count; } } public bool IsArray { get { return type == JsonType.Array; } } public bool IsBoolean { get { return type == JsonType.Boolean; } } public bool IsDouble { get { return type == JsonType.Double; } } public bool IsFloat{ get { return type == JsonType.Float; } } public bool IsInt { get { return type == JsonType.Int; } } public bool IsLong { get { return type == JsonType.Long; } } public bool IsObject { get { return type == JsonType.Object; } } public bool IsString { get { return type == JsonType.String; } } public ICollection<string> Keys { get { EnsureDictionary (); return inst_object.Keys; } } public bool ContainsKey(string key) { return this.Keys.Contains(key); } public bool TryGetValue(string key, out object value) { if (this.Keys.Contains(key)) { value = inst_object[key]; return true; } value = null; return false; } #endregion #region ICollection Properties int ICollection.Count { get { return Count; } } bool ICollection.IsSynchronized { get { return EnsureCollection ().IsSynchronized; } } object ICollection.SyncRoot { get { return EnsureCollection ().SyncRoot; } } #endregion #region IDictionary Properties bool IDictionary.IsFixedSize { get { return EnsureDictionary ().IsFixedSize; } } bool IDictionary.IsReadOnly { get { return EnsureDictionary ().IsReadOnly; } } ICollection IDictionary.Keys { get { EnsureDictionary (); IList<string> keys = new List<string> (); foreach (KeyValuePair<string, JsonData> entry in object_list) { keys.Add (entry.Key); } return (ICollection) keys; } } ICollection IDictionary.Values { get { EnsureDictionary (); IList<JsonData> values = new List<JsonData> (); foreach (KeyValuePair<string, JsonData> entry in object_list) { values.Add (entry.Value); } return (ICollection) values; } } #endregion #region IJsonWrapper Properties bool IJsonWrapper.IsArray { get { return IsArray; } } bool IJsonWrapper.IsBoolean { get { return IsBoolean; } } bool IJsonWrapper.IsDouble { get { return IsDouble; } } bool IJsonWrapper.IsInt { get { return IsInt; } } bool IJsonWrapper.IsLong { get { return IsLong; } } bool IJsonWrapper.IsObject { get { return IsObject; } } bool IJsonWrapper.IsString { get { return IsString; } } #endregion #region IList Properties bool IList.IsFixedSize { get { return EnsureList ().IsFixedSize; } } bool IList.IsReadOnly { get { return EnsureList ().IsReadOnly; } } #endregion #region IDictionary Indexer object IDictionary.this[object key] { get { return EnsureDictionary ()[key]; } set { if (! (key is String)) throw new ArgumentException ( "The key has to be a string"); JsonData data = ToJsonData (value); this[(string) key] = data; } } #endregion #region IOrderedDictionary Indexer object IOrderedDictionary.this[int idx] { get { EnsureDictionary (); return object_list[idx].Value; } set { EnsureDictionary (); JsonData data = ToJsonData (value); KeyValuePair<string, JsonData> old_entry = object_list[idx]; inst_object[old_entry.Key] = data; KeyValuePair<string, JsonData> entry = new KeyValuePair<string, JsonData> (old_entry.Key, data); object_list[idx] = entry; } } #endregion #region IList Indexer object IList.this[int index] { get { return EnsureList ()[index]; } set { EnsureList (); JsonData data = ToJsonData (value); this[index] = data; } } #endregion #region Public Indexers public JsonData this[string prop_name] { get { EnsureDictionary (); return inst_object[prop_name]; } set { EnsureDictionary (); KeyValuePair<string, JsonData> entry = new KeyValuePair<string, JsonData> (prop_name, value); if (inst_object.ContainsKey (prop_name)) { for (int i = 0; i < object_list.Count; i++) { if (object_list[i].Key == prop_name) { object_list[i] = entry; break; } } } else object_list.Add (entry); inst_object[prop_name] = value; json = null; } } public JsonData this[int index] { get { EnsureCollection (); if (type == JsonType.Array) return inst_array[index]; return object_list[index].Value; } set { EnsureCollection (); if (type == JsonType.Array) inst_array[index] = value; else { KeyValuePair<string, JsonData> entry = object_list[index]; KeyValuePair<string, JsonData> new_entry = new KeyValuePair<string, JsonData> (entry.Key, value); object_list[index] = new_entry; inst_object[entry.Key] = value; } json = null; } } #endregion #region Constructors public JsonData () { } public JsonData (bool boolean) { type = JsonType.Boolean; inst_boolean = boolean; } public JsonData (double number) { type = JsonType.Double; inst_double = number; } public JsonData (float number) { type = JsonType.Float; inst_float = number; } public JsonData (int number) { type = JsonType.Int; inst_int = number; } public JsonData (long number) { type = JsonType.Long; inst_long = number; } public JsonData (object obj) { if (obj is Boolean) { type = JsonType.Boolean; inst_boolean = (bool) obj; return; } if (obj is Double) { type = JsonType.Double; inst_double = (double) obj; return; } if (obj is Int32) { type = JsonType.Int; inst_int = (int) obj; return; } if (obj is Int64) { type = JsonType.Long; inst_long = (long) obj; return; } if (obj is String) { type = JsonType.String; inst_string = (string) obj; return; } if (obj is float) { type = JsonType.Float; inst_float = (float)obj; return; } if (obj is JsonData) { JsonData dd = (JsonData)obj; inst_array = dd.inst_array; inst_boolean = dd.inst_boolean; inst_double = dd.inst_double; inst_float = dd.inst_float; inst_int = dd.inst_int; inst_long = dd.inst_long; inst_object = dd.inst_object; inst_string = dd.inst_string; json = dd.json; type = dd.type; object_list = dd.object_list; return; } throw new ArgumentException ( "Unable to wrap the given object with JsonData"); } public JsonData (string str) { type = JsonType.String; inst_string = str; } #endregion #region Implicit Conversions public static implicit operator JsonData (Boolean data) { return new JsonData (data); } public static implicit operator JsonData (Double data) { return new JsonData (data); } public static implicit operator JsonData (Int32 data) { return new JsonData (data); } public static implicit operator JsonData (Int64 data) { return new JsonData (data); } public static implicit operator JsonData (String data) { return new JsonData (data); } #endregion #region Explicit Conversions public static explicit operator Boolean (JsonData data) { if (data.type != JsonType.Boolean) throw new InvalidCastException ( "Instance of JsonData doesn't hold a double"); return data.inst_boolean; } public static explicit operator Double (JsonData data) { if (data.type != JsonType.Double) throw new InvalidCastException ( "Instance of JsonData doesn't hold a double"); return data.inst_double; } public static explicit operator float(JsonData data) { if (data.type != JsonType.Float) throw new InvalidCastException( "Instance of JsonData doesn't hold a float"); return data.inst_float; } public static explicit operator Int32 (JsonData data) { if (data.type != JsonType.Int) throw new InvalidCastException ( "Instance of JsonData doesn't hold an int"); return data.inst_int; } public static explicit operator Int64 (JsonData data) { if (data.type != JsonType.Long) throw new InvalidCastException ( "Instance of JsonData doesn't hold an int"); return data.inst_long; } public static explicit operator String (JsonData data) { if (data.type != JsonType.String) throw new InvalidCastException ( "Instance of JsonData doesn't hold a string"); return data.inst_string; } #endregion #region ICollection Methods void ICollection.CopyTo (Array array, int index) { EnsureCollection ().CopyTo (array, index); } #endregion #region IDictionary Methods void IDictionary.Add (object key, object value) { JsonData data = ToJsonData (value); EnsureDictionary ().Add (key, data); KeyValuePair<string, JsonData> entry = new KeyValuePair<string, JsonData> ((string) key, data); object_list.Add (entry); json = null; } void IDictionary.Clear () { EnsureDictionary ().Clear (); object_list.Clear (); json = null; } bool IDictionary.Contains (object key) { return EnsureDictionary ().Contains (key); } IDictionaryEnumerator IDictionary.GetEnumerator () { return ((IOrderedDictionary) this).GetEnumerator (); } void IDictionary.Remove (object key) { EnsureDictionary ().Remove (key); for (int i = 0; i < object_list.Count; i++) { if (object_list[i].Key == (string) key) { object_list.RemoveAt (i); break; } } json = null; } #endregion #region IEnumerable Methods IEnumerator IEnumerable.GetEnumerator () { return EnsureCollection ().GetEnumerator (); } #endregion #region IJsonWrapper Methods bool IJsonWrapper.GetBoolean () { if (type != JsonType.Boolean) throw new InvalidOperationException ( "JsonData instance doesn't hold a boolean"); return inst_boolean; } double IJsonWrapper.GetDouble () { if (type != JsonType.Double) throw new InvalidOperationException ( "JsonData instance doesn't hold a double"); return inst_double; } float IJsonWrapper.GetFloat() { if (type != JsonType.Float) throw new InvalidOperationException( "JsonData instance doesn't hold a float"); return inst_float; } int IJsonWrapper.GetInt () { if (type != JsonType.Int) throw new InvalidOperationException ( "JsonData instance doesn't hold an int"); return inst_int; } long IJsonWrapper.GetLong () { if (type != JsonType.Long) throw new InvalidOperationException ( "JsonData instance doesn't hold a long"); return inst_long; } string IJsonWrapper.GetString () { if (type != JsonType.String) throw new InvalidOperationException ( "JsonData instance doesn't hold a string"); return inst_string; } void IJsonWrapper.SetBoolean (bool val) { type = JsonType.Boolean; inst_boolean = val; json = null; } void IJsonWrapper.SetDouble (double val) { type = JsonType.Double; inst_double = val; json = null; } void IJsonWrapper.SetFloat(float val) { type = JsonType.Float; inst_float = val; json = null; } void IJsonWrapper.SetInt (int val) { type = JsonType.Int; inst_int = val; json = null; } void IJsonWrapper.SetLong (long val) { type = JsonType.Long; inst_long = val; json = null; } void IJsonWrapper.SetString (string val) { type = JsonType.String; inst_string = val; json = null; } string IJsonWrapper.ToJson () { return ToJson (); } void IJsonWrapper.ToJson (JsonWriter writer) { ToJson (writer); } #endregion #region IList Methods int IList.Add (object value) { return Add (value); } void IList.Clear () { EnsureList ().Clear (); json = null; } bool IList.Contains (object value) { return EnsureList ().Contains (value); } int IList.IndexOf (object value) { return EnsureList ().IndexOf (value); } void IList.Insert (int index, object value) { EnsureList ().Insert (index, value); json = null; } void IList.Remove (object value) { EnsureList ().Remove (value); json = null; } void IList.RemoveAt (int index) { EnsureList ().RemoveAt (index); json = null; } #endregion #region IOrderedDictionary Methods IDictionaryEnumerator IOrderedDictionary.GetEnumerator () { EnsureDictionary (); return new OrderedDictionaryEnumerator ( object_list.GetEnumerator ()); } void IOrderedDictionary.Insert (int idx, object key, object value) { string property = (string) key; JsonData data = ToJsonData (value); this[property] = data; KeyValuePair<string, JsonData> entry = new KeyValuePair<string, JsonData> (property, data); object_list.Insert (idx, entry); } void IOrderedDictionary.RemoveAt (int idx) { EnsureDictionary (); inst_object.Remove (object_list[idx].Key); object_list.RemoveAt (idx); } #endregion #region Private Methods private ICollection EnsureCollection () { if (type == JsonType.Array) return (ICollection) inst_array; if (type == JsonType.Object) return (ICollection) inst_object; throw new InvalidOperationException ( "The JsonData instance has to be initialized first"); } private IDictionary EnsureDictionary () { if (type == JsonType.Object) return (IDictionary) inst_object; if (type != JsonType.None) throw new InvalidOperationException ( "Instance of JsonData is not a dictionary"); type = JsonType.Object; inst_object = new Dictionary<string, JsonData> (); object_list = new List<KeyValuePair<string, JsonData>> (); return (IDictionary) inst_object; } private IList EnsureList () { if (type == JsonType.Array) return (IList) inst_array; if (type != JsonType.None) throw new InvalidOperationException ( "Instance of JsonData is not a list"); type = JsonType.Array; inst_array = new List<JsonData> (); return (IList) inst_array; } private JsonData ToJsonData (object obj) { if (obj == null) return null; if (obj is JsonData) return (JsonData) obj; return new JsonData (obj); } private static void WriteJson (IJsonWrapper obj, JsonWriter writer) { if (obj == null) { writer.Write (null); return; } if (obj.IsString) { writer.Write (obj.GetString ()); return; } if (obj.IsBoolean) { writer.Write (obj.GetBoolean ()); return; } if (obj.IsDouble) { writer.Write (obj.GetDouble ()); return; } if (obj.IsInt) { writer.Write (obj.GetInt ()); return; } if (obj.IsLong) { writer.Write (obj.GetLong ()); return; } if (obj.IsArray) { writer.WriteArrayStart (); foreach (object elem in (IList) obj) WriteJson ((JsonData) elem, writer); writer.WriteArrayEnd (); return; } if (obj.IsObject) { writer.WriteObjectStart(); foreach (DictionaryEntry entry in ((IDictionary)obj)) { writer.WritePropertyName((string)entry.Key); WriteJson((JsonData)entry.Value, writer); } writer.WriteObjectEnd(); return; } else { writer.WriteObjectStart(); writer.WriteObjectEnd(); } } #endregion public int Add (object value) { JsonData data = ToJsonData (value); json = null; return EnsureList ().Add (data); } public void Clear () { if (IsObject) { ((IDictionary) this).Clear (); return; } if (IsArray) { ((IList) this).Clear (); return; } } public bool Equals (JsonData x) { if (x == null) return false; if (x.type != this.type) return false; switch (this.type) { case JsonType.None: return true; case JsonType.Object: return this.inst_object.Equals (x.inst_object); case JsonType.Array: return this.inst_array.Equals (x.inst_array); case JsonType.String: return this.inst_string.Equals (x.inst_string); case JsonType.Int: return this.inst_int.Equals (x.inst_int); case JsonType.Long: return this.inst_long.Equals (x.inst_long); case JsonType.Double: return this.inst_double.Equals (x.inst_double); case JsonType.Boolean: return this.inst_boolean.Equals (x.inst_boolean); case JsonType.Float: return this.inst_float.Equals(x.inst_float); } return false; } public JsonType GetJsonType () { return type; } public void SetJsonType (JsonType type) { if (this.type == type) return; switch (type) { case JsonType.None: break; case JsonType.Object: inst_object = new Dictionary<string, JsonData> (); object_list = new List<KeyValuePair<string, JsonData>> (); break; case JsonType.Array: inst_array = new List<JsonData> (); break; case JsonType.String: inst_string = default (String); break; case JsonType.Int: inst_int = default (Int32); break; case JsonType.Long: inst_long = default (Int64); break; case JsonType.Double: inst_double = default (Double); break; case JsonType.Boolean: inst_boolean = default (Boolean); break; case JsonType.Float: inst_float = default(float); break; } this.type = type; } public string ToJson () { if (json != null) return json; StringWriter sw = new StringWriter (); JsonWriter writer = new JsonWriter (sw); writer.Validate = false; WriteJson (this, writer); json = sw.ToString (); return json; } public void ToJson (JsonWriter writer) { bool old_validate = writer.Validate; writer.Validate = false; WriteJson (this, writer); writer.Validate = old_validate; } public override string ToString () { switch (type) { case JsonType.Array: return "JsonData array"; case JsonType.Boolean: return inst_boolean.ToString (); case JsonType.Double: return inst_double.ToString (); case JsonType.Float: return inst_float.ToString(); case JsonType.Int: return inst_int.ToString (); case JsonType.Long: return inst_long.ToString (); case JsonType.Object: return "JsonData object"; case JsonType.String: return inst_string; } return "Uninitialized JsonData"; } } internal class OrderedDictionaryEnumerator : IDictionaryEnumerator { IEnumerator<KeyValuePair<string, JsonData>> list_enumerator; public object Current { get { return Entry; } } public DictionaryEntry Entry { get { KeyValuePair<string, JsonData> curr = list_enumerator.Current; return new DictionaryEntry (curr.Key, curr.Value); } } public object Key { get { return list_enumerator.Current.Key; } } public object Value { get { return list_enumerator.Current.Value; } } public OrderedDictionaryEnumerator ( IEnumerator<KeyValuePair<string, JsonData>> enumerator) { list_enumerator = enumerator; } public bool MoveNext () { return list_enumerator.MoveNext (); } public void Reset () { list_enumerator.Reset (); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.SiteRecovery; using Microsoft.Azure.Management.SiteRecovery.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.SiteRecovery { /// <summary> /// Definition of storage mapping operations for the Site Recovery /// extension. /// </summary> internal partial class StorageClassificationMappingOperations : IServiceOperations<SiteRecoveryManagementClient>, IStorageClassificationMappingOperations { /// <summary> /// Initializes a new instance of the /// StorageClassificationMappingOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal StorageClassificationMappingOperations(SiteRecoveryManagementClient client) { this._client = client; } private SiteRecoveryManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.SiteRecovery.SiteRecoveryManagementClient. /// </summary> public SiteRecoveryManagementClient Client { get { return this._client; } } /// <summary> /// Pairs storage to a given storage. /// </summary> /// <param name='fabricName'> /// Required. Fabric name. /// </param> /// <param name='storageClassificationName'> /// Required. Storage name. /// </param> /// <param name='storageClassificationMappingName'> /// Required. Storage mapping name. /// </param> /// <param name='input'> /// Required. Create mapping input. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public async Task<LongRunningOperationResponse> BeginPairStorageClassificationAsync(string fabricName, string storageClassificationName, string storageClassificationMappingName, StorageClassificationMappingInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (fabricName == null) { throw new ArgumentNullException("fabricName"); } if (storageClassificationName == null) { throw new ArgumentNullException("storageClassificationName"); } if (storageClassificationMappingName == null) { throw new ArgumentNullException("storageClassificationMappingName"); } if (input == null) { throw new ArgumentNullException("input"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("storageClassificationName", storageClassificationName); tracingParameters.Add("storageClassificationMappingName", storageClassificationMappingName); tracingParameters.Add("input", input); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "BeginPairStorageClassificationAsync", 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(this.Client.ResourceGroupName); url = url + "/providers/"; url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceType); url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceName); url = url + "/replicationFabrics/"; url = url + Uri.EscapeDataString(fabricName); url = url + "/replicationStorageClassifications/"; url = url + Uri.EscapeDataString(storageClassificationName); url = url + "/replicationStorageClassificationMappings/"; url = url + Uri.EscapeDataString(storageClassificationMappingName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-11-10"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Culture); httpRequest.Headers.Add("Agent-Authentication", customRequestHeaders.AgentAuthenticationHeader); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2015-01-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject storageClassificationMappingInputValue = new JObject(); requestDoc = storageClassificationMappingInputValue; if (input.Properties != null) { JObject propertiesValue = new JObject(); storageClassificationMappingInputValue["properties"] = propertiesValue; if (input.Properties.TargetStorageClassificationId != null) { propertiesValue["targetStorageClassificationId"] = input.Properties.TargetStorageClassificationId; } } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result LongRunningOperationResponse result = null; // Deserialize Response result = new LongRunningOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Azure-AsyncOperation")) { result.AsyncOperation = httpResponse.Headers.GetValues("Azure-AsyncOperation").FirstOrDefault(); } if (httpResponse.Content != null && httpResponse.Content.Headers.Contains("Content-Type")) { result.ContentType = httpResponse.Content.Headers.GetValues("Content-Type").FirstOrDefault(); } if (httpResponse.Headers.Contains("Date")) { result.Date = httpResponse.Headers.GetValues("Date").FirstOrDefault(); } if (httpResponse.Headers.Contains("Location")) { result.Location = httpResponse.Headers.GetValues("Location").FirstOrDefault(); } if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture); } if (httpResponse.Headers.Contains("x-ms-client-request-id")) { result.ClientRequestId = httpResponse.Headers.GetValues("x-ms-client-request-id").FirstOrDefault(); } if (httpResponse.Headers.Contains("x-ms-correlation-request-id")) { result.CorrelationRequestId = httpResponse.Headers.GetValues("x-ms-correlation-request-id").FirstOrDefault(); } 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> /// Unpairs storage to a given storage. /// </summary> /// <param name='fabricName'> /// Required. Fabric name. /// </param> /// <param name='storageClassificationName'> /// Required. Storage name. /// </param> /// <param name='storageClassificationMappingName'> /// Required. Storage mapping name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public async Task<LongRunningOperationResponse> BeginUnpairStorageClassificationAsync(string fabricName, string storageClassificationName, string storageClassificationMappingName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (fabricName == null) { throw new ArgumentNullException("fabricName"); } if (storageClassificationName == null) { throw new ArgumentNullException("storageClassificationName"); } if (storageClassificationMappingName == null) { throw new ArgumentNullException("storageClassificationMappingName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("storageClassificationName", storageClassificationName); tracingParameters.Add("storageClassificationMappingName", storageClassificationMappingName); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "BeginUnpairStorageClassificationAsync", 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(this.Client.ResourceGroupName); url = url + "/providers/"; url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceType); url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceName); url = url + "/replicationFabrics/"; url = url + Uri.EscapeDataString(fabricName); url = url + "/replicationStorageClassifications/"; url = url + Uri.EscapeDataString(storageClassificationName); url = url + "/replicationStorageClassificationMappings/"; url = url + Uri.EscapeDataString(storageClassificationMappingName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-11-10"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Culture); httpRequest.Headers.Add("Agent-Authentication", customRequestHeaders.AgentAuthenticationHeader); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2015-01-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted) { 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 LongRunningOperationResponse result = null; // Deserialize Response result = new LongRunningOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Azure-AsyncOperation")) { result.AsyncOperation = httpResponse.Headers.GetValues("Azure-AsyncOperation").FirstOrDefault(); } if (httpResponse.Content != null && httpResponse.Content.Headers.Contains("Content-Type")) { result.ContentType = httpResponse.Content.Headers.GetValues("Content-Type").FirstOrDefault(); } if (httpResponse.Headers.Contains("Date")) { result.Date = httpResponse.Headers.GetValues("Date").FirstOrDefault(); } if (httpResponse.Headers.Contains("Location")) { result.Location = httpResponse.Headers.GetValues("Location").FirstOrDefault(); } if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture); } if (httpResponse.Headers.Contains("x-ms-client-request-id")) { result.ClientRequestId = httpResponse.Headers.GetValues("x-ms-client-request-id").FirstOrDefault(); } if (httpResponse.Headers.Contains("x-ms-correlation-request-id")) { result.CorrelationRequestId = httpResponse.Headers.GetValues("x-ms-correlation-request-id").FirstOrDefault(); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets the replication storage mapping object by name. /// </summary> /// <param name='fabricName'> /// Required. Fabric unique name. /// </param> /// <param name='storageClassificationName'> /// Required. Storage unique name. /// </param> /// <param name='storageClassificationMappingName'> /// Required. Storage mapping unique name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the storage mapping object /// </returns> public async Task<StorageClassificationMappingResponse> GetAsync(string fabricName, string storageClassificationName, string storageClassificationMappingName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (fabricName == null) { throw new ArgumentNullException("fabricName"); } if (storageClassificationName == null) { throw new ArgumentNullException("storageClassificationName"); } if (storageClassificationMappingName == null) { throw new ArgumentNullException("storageClassificationMappingName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("storageClassificationName", storageClassificationName); tracingParameters.Add("storageClassificationMappingName", storageClassificationMappingName); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/Subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(this.Client.ResourceGroupName); url = url + "/providers/"; url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceType); url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceName); url = url + "/replicationFabrics/"; url = url + Uri.EscapeDataString(fabricName); url = url + "/replicationStorageClassifications/"; url = url + Uri.EscapeDataString(storageClassificationName); url = url + "/replicationStorageClassificationMappings/"; url = url + Uri.EscapeDataString(storageClassificationMappingName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-11-10"); 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 httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Culture); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2015-01-01"); // 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 StorageClassificationMappingResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new StorageClassificationMappingResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { StorageClassificationMapping storageClassificationMappingInstance = new StorageClassificationMapping(); result.StorageMapping = storageClassificationMappingInstance; JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { StorageClassificationMappingProperties propertiesInstance = new StorageClassificationMappingProperties(); storageClassificationMappingInstance.Properties = propertiesInstance; JToken targetStorageClassificationIdValue = propertiesValue["targetStorageClassificationId"]; if (targetStorageClassificationIdValue != null && targetStorageClassificationIdValue.Type != JTokenType.Null) { string targetStorageClassificationIdInstance = ((string)targetStorageClassificationIdValue); propertiesInstance.TargetStorageClassificationId = targetStorageClassificationIdInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); storageClassificationMappingInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); storageClassificationMappingInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); storageClassificationMappingInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); storageClassificationMappingInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); storageClassificationMappingInstance.Tags.Add(tagsKey, tagsValue); } } JToken clientRequestIdValue = responseDoc["ClientRequestId"]; if (clientRequestIdValue != null && clientRequestIdValue.Type != JTokenType.Null) { string clientRequestIdInstance = ((string)clientRequestIdValue); result.ClientRequestId = clientRequestIdInstance; } JToken correlationRequestIdValue = responseDoc["CorrelationRequestId"]; if (correlationRequestIdValue != null && correlationRequestIdValue.Type != JTokenType.Null) { string correlationRequestIdInstance = ((string)correlationRequestIdValue); result.CorrelationRequestId = correlationRequestIdInstance; } JToken dateValue = responseDoc["Date"]; if (dateValue != null && dateValue.Type != JTokenType.Null) { string dateInstance = ((string)dateValue); result.Date = dateInstance; } JToken contentTypeValue = responseDoc["ContentType"]; if (contentTypeValue != null && contentTypeValue.Type != JTokenType.Null) { string contentTypeInstance = ((string)contentTypeValue); result.ContentType = contentTypeInstance; } } } result.StatusCode = statusCode; if (httpResponse.Content != null && httpResponse.Content.Headers.Contains("Content-Type")) { result.ContentType = httpResponse.Content.Headers.GetValues("Content-Type").FirstOrDefault(); } if (httpResponse.Headers.Contains("Date")) { result.Date = httpResponse.Headers.GetValues("Date").FirstOrDefault(); } if (httpResponse.Headers.Contains("x-ms-client-request-id")) { result.ClientRequestId = httpResponse.Headers.GetValues("x-ms-client-request-id").FirstOrDefault(); } if (httpResponse.Headers.Contains("x-ms-correlation-request-id")) { result.CorrelationRequestId = httpResponse.Headers.GetValues("x-ms-correlation-request-id").FirstOrDefault(); } 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> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Service response for operation which change status of mapping for /// storage. /// </returns> public async Task<StorageClassificationMappingOperationResponse> GetPairStorageClassificationStatusAsync(string operationStatusLink, CancellationToken cancellationToken) { // Validate if (operationStatusLink == null) { throw new ArgumentNullException("operationStatusLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("operationStatusLink", operationStatusLink); TracingAdapter.Enter(invocationId, this, "GetPairStorageClassificationStatusAsync", tracingParameters); } // Construct URL string url = ""; url = url + operationStatusLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); httpRequest.Headers.Add("x-ms-version", "2015-01-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted) { 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 StorageClassificationMappingOperationResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new StorageClassificationMappingOperationResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { StorageClassificationMapping storageMappingInstance = new StorageClassificationMapping(); result.StorageMapping = storageMappingInstance; JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { StorageClassificationMappingProperties propertiesInstance = new StorageClassificationMappingProperties(); storageMappingInstance.Properties = propertiesInstance; JToken targetStorageClassificationIdValue = propertiesValue["targetStorageClassificationId"]; if (targetStorageClassificationIdValue != null && targetStorageClassificationIdValue.Type != JTokenType.Null) { string targetStorageClassificationIdInstance = ((string)targetStorageClassificationIdValue); propertiesInstance.TargetStorageClassificationId = targetStorageClassificationIdInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); storageMappingInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); storageMappingInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); storageMappingInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); storageMappingInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); storageMappingInstance.Tags.Add(tagsKey, tagsValue); } } JToken locationValue2 = responseDoc["Location"]; if (locationValue2 != null && locationValue2.Type != JTokenType.Null) { string locationInstance2 = ((string)locationValue2); result.Location = locationInstance2; } JToken retryAfterValue = responseDoc["RetryAfter"]; if (retryAfterValue != null && retryAfterValue.Type != JTokenType.Null) { int retryAfterInstance = ((int)retryAfterValue); result.RetryAfter = retryAfterInstance; } JToken asyncOperationValue = responseDoc["AsyncOperation"]; if (asyncOperationValue != null && asyncOperationValue.Type != JTokenType.Null) { string asyncOperationInstance = ((string)asyncOperationValue); result.AsyncOperation = asyncOperationInstance; } JToken statusValue = responseDoc["Status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { OperationStatus statusInstance = ((OperationStatus)Enum.Parse(typeof(OperationStatus), ((string)statusValue), true)); result.Status = statusInstance; } JToken cultureValue = responseDoc["Culture"]; if (cultureValue != null && cultureValue.Type != JTokenType.Null) { string cultureInstance = ((string)cultureValue); result.Culture = cultureInstance; } JToken clientRequestIdValue = responseDoc["ClientRequestId"]; if (clientRequestIdValue != null && clientRequestIdValue.Type != JTokenType.Null) { string clientRequestIdInstance = ((string)clientRequestIdValue); result.ClientRequestId = clientRequestIdInstance; } JToken correlationRequestIdValue = responseDoc["CorrelationRequestId"]; if (correlationRequestIdValue != null && correlationRequestIdValue.Type != JTokenType.Null) { string correlationRequestIdInstance = ((string)correlationRequestIdValue); result.CorrelationRequestId = correlationRequestIdInstance; } JToken dateValue = responseDoc["Date"]; if (dateValue != null && dateValue.Type != JTokenType.Null) { string dateInstance = ((string)dateValue); result.Date = dateInstance; } JToken contentTypeValue = responseDoc["ContentType"]; if (contentTypeValue != null && contentTypeValue.Type != JTokenType.Null) { string contentTypeInstance = ((string)contentTypeValue); result.ContentType = contentTypeInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Azure-AsyncOperation")) { result.AsyncOperation = httpResponse.Headers.GetValues("Azure-AsyncOperation").FirstOrDefault(); } if (httpResponse.Content != null && httpResponse.Content.Headers.Contains("Content-Type")) { result.ContentType = httpResponse.Content.Headers.GetValues("Content-Type").FirstOrDefault(); } if (httpResponse.Headers.Contains("Date")) { result.Date = httpResponse.Headers.GetValues("Date").FirstOrDefault(); } if (httpResponse.Headers.Contains("Location")) { result.Location = httpResponse.Headers.GetValues("Location").FirstOrDefault(); } if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture); } if (httpResponse.Headers.Contains("x-ms-client-request-id")) { result.ClientRequestId = httpResponse.Headers.GetValues("x-ms-client-request-id").FirstOrDefault(); } if (httpResponse.Headers.Contains("x-ms-correlation-request-id")) { result.CorrelationRequestId = httpResponse.Headers.GetValues("x-ms-correlation-request-id").FirstOrDefault(); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (statusCode == HttpStatusCode.NoContent) { result.Status = OperationStatus.Failed; } if (statusCode == HttpStatusCode.Accepted) { result.Status = OperationStatus.InProgress; } if (statusCode == HttpStatusCode.OK) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public async Task<LongRunningOperationResponse> GetUnpairStorageClassificationStatusAsync(string operationStatusLink, CancellationToken cancellationToken) { // Validate if (operationStatusLink == null) { throw new ArgumentNullException("operationStatusLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("operationStatusLink", operationStatusLink); TracingAdapter.Enter(invocationId, this, "GetUnpairStorageClassificationStatusAsync", tracingParameters); } // Construct URL string url = ""; url = url + operationStatusLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); httpRequest.Headers.Add("x-ms-version", "2015-01-01"); // 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.Accepted && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result LongRunningOperationResponse result = null; // Deserialize Response result = new LongRunningOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Azure-AsyncOperation")) { result.AsyncOperation = httpResponse.Headers.GetValues("Azure-AsyncOperation").FirstOrDefault(); } if (httpResponse.Content != null && httpResponse.Content.Headers.Contains("Content-Type")) { result.ContentType = httpResponse.Content.Headers.GetValues("Content-Type").FirstOrDefault(); } if (httpResponse.Headers.Contains("Date")) { result.Date = httpResponse.Headers.GetValues("Date").FirstOrDefault(); } if (httpResponse.Headers.Contains("Location")) { result.Location = httpResponse.Headers.GetValues("Location").FirstOrDefault(); } if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture); } if (httpResponse.Headers.Contains("x-ms-client-request-id")) { result.ClientRequestId = httpResponse.Headers.GetValues("x-ms-client-request-id").FirstOrDefault(); } if (httpResponse.Headers.Contains("x-ms-correlation-request-id")) { result.CorrelationRequestId = httpResponse.Headers.GetValues("x-ms-correlation-request-id").FirstOrDefault(); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (statusCode == HttpStatusCode.OK) { result.Status = OperationStatus.Failed; } if (statusCode == HttpStatusCode.Accepted) { result.Status = OperationStatus.InProgress; } if (statusCode == HttpStatusCode.NoContent) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets the replication storage mapping objects under a storage. /// </summary> /// <param name='fabricName'> /// Required. Fabric unique name. /// </param> /// <param name='storageClassificationName'> /// Required. Storage unique name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list storage mapping operation. /// </returns> public async Task<StorageClassificationMappingListResponse> ListAsync(string fabricName, string storageClassificationName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (fabricName == null) { throw new ArgumentNullException("fabricName"); } if (storageClassificationName == null) { throw new ArgumentNullException("storageClassificationName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("storageClassificationName", storageClassificationName); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/Subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(this.Client.ResourceGroupName); url = url + "/providers/"; url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceType); url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceName); url = url + "/replicationFabrics/"; url = url + Uri.EscapeDataString(fabricName); url = url + "/replicationStorageClassifications/"; url = url + Uri.EscapeDataString(storageClassificationName); url = url + "/replicationStorageClassificationMappings"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-11-10"); 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 httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Culture); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2015-01-01"); // 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 StorageClassificationMappingListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new StorageClassificationMappingListResponse(); 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)) { StorageClassificationMapping storageClassificationMappingInstance = new StorageClassificationMapping(); result.StorageClassificationMappings.Add(storageClassificationMappingInstance); JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { StorageClassificationMappingProperties propertiesInstance = new StorageClassificationMappingProperties(); storageClassificationMappingInstance.Properties = propertiesInstance; JToken targetStorageClassificationIdValue = propertiesValue["targetStorageClassificationId"]; if (targetStorageClassificationIdValue != null && targetStorageClassificationIdValue.Type != JTokenType.Null) { string targetStorageClassificationIdInstance = ((string)targetStorageClassificationIdValue); propertiesInstance.TargetStorageClassificationId = targetStorageClassificationIdInstance; } } JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); storageClassificationMappingInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); storageClassificationMappingInstance.Name = nameInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); storageClassificationMappingInstance.Type = typeInstance; } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); storageClassificationMappingInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)valueValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); storageClassificationMappingInstance.Tags.Add(tagsKey, tagsValue); } } } } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } JToken clientRequestIdValue = responseDoc["ClientRequestId"]; if (clientRequestIdValue != null && clientRequestIdValue.Type != JTokenType.Null) { string clientRequestIdInstance = ((string)clientRequestIdValue); result.ClientRequestId = clientRequestIdInstance; } JToken correlationRequestIdValue = responseDoc["CorrelationRequestId"]; if (correlationRequestIdValue != null && correlationRequestIdValue.Type != JTokenType.Null) { string correlationRequestIdInstance = ((string)correlationRequestIdValue); result.CorrelationRequestId = correlationRequestIdInstance; } JToken dateValue = responseDoc["Date"]; if (dateValue != null && dateValue.Type != JTokenType.Null) { string dateInstance = ((string)dateValue); result.Date = dateInstance; } JToken contentTypeValue = responseDoc["ContentType"]; if (contentTypeValue != null && contentTypeValue.Type != JTokenType.Null) { string contentTypeInstance = ((string)contentTypeValue); result.ContentType = contentTypeInstance; } } } result.StatusCode = statusCode; if (httpResponse.Content != null && httpResponse.Content.Headers.Contains("Content-Type")) { result.ContentType = httpResponse.Content.Headers.GetValues("Content-Type").FirstOrDefault(); } if (httpResponse.Headers.Contains("Date")) { result.Date = httpResponse.Headers.GetValues("Date").FirstOrDefault(); } if (httpResponse.Headers.Contains("x-ms-client-request-id")) { result.ClientRequestId = httpResponse.Headers.GetValues("x-ms-client-request-id").FirstOrDefault(); } if (httpResponse.Headers.Contains("x-ms-correlation-request-id")) { result.CorrelationRequestId = httpResponse.Headers.GetValues("x-ms-correlation-request-id").FirstOrDefault(); } 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> /// Pairs storage to a given storage. /// </summary> /// <param name='fabricName'> /// Required. Fabric name. /// </param> /// <param name='storageClassificationName'> /// Required. Storage classsification name. /// </param> /// <param name='storageClassificationMappingName'> /// Required. Storage classification mapping name. /// </param> /// <param name='input'> /// Required. Create mapping input. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public async Task<LongRunningOperationResponse> PairStorageClassificationAsync(string fabricName, string storageClassificationName, string storageClassificationMappingName, StorageClassificationMappingInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { SiteRecoveryManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("storageClassificationName", storageClassificationName); tracingParameters.Add("storageClassificationMappingName", storageClassificationMappingName); tracingParameters.Add("input", input); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "PairStorageClassificationAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); LongRunningOperationResponse response = await client.StorageClassificationMapping.BeginPairStorageClassificationAsync(fabricName, storageClassificationName, storageClassificationMappingName, input, customRequestHeaders, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); StorageClassificationMappingOperationResponse result = await client.StorageClassificationMapping.GetPairStorageClassificationStatusAsync(response.Location, cancellationToken).ConfigureAwait(false); int delayInSeconds = 30; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while (result.Status == OperationStatus.InProgress) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.StorageClassificationMapping.GetPairStorageClassificationStatusAsync(response.Location, cancellationToken).ConfigureAwait(false); delayInSeconds = 30; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } /// <summary> /// Removes storage classification pairing. /// </summary> /// <param name='fabricName'> /// Required. Fabric name. /// </param> /// <param name='storageName'> /// Required. Storage name. /// </param> /// <param name='storageMappingName'> /// Required. Storage mapping name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public async Task<LongRunningOperationResponse> UnpairStorageClassificationAsync(string fabricName, string storageName, string storageMappingName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { SiteRecoveryManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("storageName", storageName); tracingParameters.Add("storageMappingName", storageMappingName); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "UnpairStorageClassificationAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); LongRunningOperationResponse response = await client.StorageClassificationMapping.BeginUnpairStorageClassificationAsync(fabricName, storageName, storageMappingName, customRequestHeaders, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); LongRunningOperationResponse result = await client.StorageClassificationMapping.GetUnpairStorageClassificationStatusAsync(response.Location, cancellationToken).ConfigureAwait(false); int delayInSeconds = 30; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while (result.Status == OperationStatus.InProgress) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.StorageClassificationMapping.GetUnpairStorageClassificationStatusAsync(response.Location, cancellationToken).ConfigureAwait(false); delayInSeconds = 30; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } } }
// // Copyright (c) 2004-2018 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using JetBrains.Annotations; namespace NLog.UnitTests { using System; using System.Collections.Generic; using System.IO; using System.Linq; using Xunit; using NLog.Common; using NLog.Config; using NLog.Targets; using System.Threading.Tasks; public class LogManagerTests : NLogTestBase { [Fact] public void GetLoggerTest() { ILogger loggerA = LogManager.GetLogger("A"); ILogger loggerA2 = LogManager.GetLogger("A"); ILogger loggerB = LogManager.GetLogger("B"); Assert.Same(loggerA, loggerA2); Assert.NotSame(loggerA, loggerB); Assert.Equal("A", loggerA.Name); Assert.Equal("B", loggerB.Name); } [Fact] public void GarbageCollectionTest() { string uniqueLoggerName = Guid.NewGuid().ToString(); ILogger loggerA1 = LogManager.GetLogger(uniqueLoggerName); GC.Collect(); ILogger loggerA2 = LogManager.GetLogger(uniqueLoggerName); Assert.Same(loggerA1, loggerA2); } static WeakReference GetWeakReferenceToTemporaryLogger() { string uniqueLoggerName = Guid.NewGuid().ToString(); return new WeakReference(LogManager.GetLogger(uniqueLoggerName)); } [Fact] public void GarbageCollection2Test() { WeakReference wr = GetWeakReferenceToTemporaryLogger(); // nobody's holding a reference to this Logger anymore, so GC.Collect(2) should free it GC.Collect(); Assert.False(wr.IsAlive); } [Fact] public void NullLoggerTest() { ILogger l = LogManager.CreateNullLogger(); Assert.Equal(String.Empty, l.Name); } [Fact] public void ThrowExceptionsTest() { FileTarget ft = new FileTarget(); ft.FileName = ""; // invalid file name SimpleConfigurator.ConfigureForTargetLogging(ft); LogManager.ThrowExceptions = false; LogManager.GetLogger("A").Info("a"); LogManager.ThrowExceptions = true; try { LogManager.GetLogger("A").Info("a"); Assert.True(false, "Should not be reached."); } catch { Assert.True(true); } LogManager.ThrowExceptions = false; } [Fact(Skip="Side effects to other unit tests.")] public void GlobalThresholdTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog globalThreshold='Info'> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Assert.Equal(LogLevel.Info, LogManager.GlobalThreshold); // nothing gets logged because of globalThreshold LogManager.GetLogger("A").Debug("xxx"); AssertDebugLastMessage("debug", ""); // lower the threshold LogManager.GlobalThreshold = LogLevel.Trace; LogManager.GetLogger("A").Debug("yyy"); AssertDebugLastMessage("debug", "yyy"); // raise the threshold LogManager.GlobalThreshold = LogLevel.Info; // this should be yyy, meaning that the target is in place // only rules have been modified. LogManager.GetLogger("A").Debug("zzz"); AssertDebugLastMessage("debug", "yyy"); LogManager.Shutdown(); LogManager.Configuration = null; } [Fact] public void DisableLoggingTest_UsingStatement() { const string LoggerConfig = @" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='DisableLoggingTest_UsingStatement_A' levels='Trace' writeTo='debug' /> <logger name='DisableLoggingTest_UsingStatement_B' levels='Error' writeTo='debug' /> </rules> </nlog>"; // Disable/Enable logging should affect ALL the loggers. ILogger loggerA = LogManager.GetLogger("DisableLoggingTest_UsingStatement_A"); ILogger loggerB = LogManager.GetLogger("DisableLoggingTest_UsingStatement_B"); LogManager.Configuration = CreateConfigurationFromString(LoggerConfig); // The starting state for logging is enable. Assert.True(LogManager.IsLoggingEnabled()); loggerA.Trace("TTT"); AssertDebugLastMessage("debug", "TTT"); loggerB.Error("EEE"); AssertDebugLastMessage("debug", "EEE"); loggerA.Trace("---"); AssertDebugLastMessage("debug", "---"); using (LogManager.DisableLogging()) { Assert.False(LogManager.IsLoggingEnabled()); // The last of LastMessage outside using statement should be returned. loggerA.Trace("TTT"); AssertDebugLastMessage("debug", "---"); loggerB.Error("EEE"); AssertDebugLastMessage("debug", "---"); } Assert.True(LogManager.IsLoggingEnabled()); loggerA.Trace("TTT"); AssertDebugLastMessage("debug", "TTT"); loggerB.Error("EEE"); AssertDebugLastMessage("debug", "EEE"); LogManager.Shutdown(); LogManager.Configuration = null; } [Fact] public void DisableLoggingTest_WithoutUsingStatement() { const string LoggerConfig = @" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='DisableLoggingTest_WithoutUsingStatement_A' levels='Trace' writeTo='debug' /> <logger name='DisableLoggingTest_WithoutUsingStatement_B' levels='Error' writeTo='debug' /> </rules> </nlog>"; // Disable/Enable logging should affect ALL the loggers. ILogger loggerA = LogManager.GetLogger("DisableLoggingTest_WithoutUsingStatement_A"); ILogger loggerB = LogManager.GetLogger("DisableLoggingTest_WithoutUsingStatement_B"); LogManager.Configuration = CreateConfigurationFromString(LoggerConfig); // The starting state for logging is enable. Assert.True(LogManager.IsLoggingEnabled()); loggerA.Trace("TTT"); AssertDebugLastMessage("debug", "TTT"); loggerB.Error("EEE"); AssertDebugLastMessage("debug", "EEE"); loggerA.Trace("---"); AssertDebugLastMessage("debug", "---"); LogManager.DisableLogging(); Assert.False(LogManager.IsLoggingEnabled()); // The last value of LastMessage before DisableLogging() should be returned. loggerA.Trace("TTT"); AssertDebugLastMessage("debug", "---"); loggerB.Error("EEE"); AssertDebugLastMessage("debug", "---"); LogManager.EnableLogging(); Assert.True(LogManager.IsLoggingEnabled()); loggerA.Trace("TTT"); AssertDebugLastMessage("debug", "TTT"); loggerB.Error("EEE"); AssertDebugLastMessage("debug", "EEE"); LogManager.Shutdown(); LogManager.Configuration = null; } private int _reloadCounter = 0; private void WaitForConfigReload(int counter) { while (_reloadCounter < counter) { System.Threading.Thread.Sleep(100); } } private void OnConfigReloaded(object sender, LoggingConfigurationReloadedEventArgs e) { Console.WriteLine("OnConfigReloaded success={0}", e.Succeeded); _reloadCounter++; } [Fact] public void AutoReloadTest() { #if NETSTANDARD if (IsTravis()) { Console.WriteLine("[SKIP] LogManagerTests.AutoReloadTest because we are running in Travis"); return; } #endif using (new InternalLoggerScope()) { string fileName = Path.GetTempFileName(); try { _reloadCounter = 0; LogManager.ConfigurationReloaded += OnConfigReloaded; using (StreamWriter fs = File.CreateText(fileName)) { fs.Write(@"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } LogManager.Configuration = new XmlLoggingConfiguration(fileName); AssertDebugCounter("debug", 0); ILogger logger = LogManager.GetLogger("A"); logger.Debug("aaa"); AssertDebugLastMessage("debug", "aaa"); InternalLogger.Info("Rewriting test file..."); // now write the file again using (StreamWriter fs = File.CreateText(fileName)) { fs.Write(@"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='xxx ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } InternalLogger.Info("Rewritten."); WaitForConfigReload(1); logger.Debug("aaa"); AssertDebugLastMessage("debug", "xxx aaa"); // write the file again, this time make an error using (StreamWriter fs = File.CreateText(fileName)) { fs.Write(@"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='xxx ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } WaitForConfigReload(2); logger.Debug("bbb"); AssertDebugLastMessage("debug", "xxx bbb"); // write the corrected file again using (StreamWriter fs = File.CreateText(fileName)) { fs.Write(@"<nlog autoReload='true'> <targets><target name='debug' type='Debug' layout='zzz ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); } WaitForConfigReload(3); logger.Debug("ccc"); AssertDebugLastMessage("debug", "zzz ccc"); } finally { LogManager.ConfigurationReloaded -= OnConfigReloaded; if (File.Exists(fileName)) File.Delete(fileName); } } } [Fact] public void GivenCurrentClass_WhenGetCurrentClassLogger_ThenLoggerShouldBeCurrentClass() { var logger = LogManager.GetCurrentClassLogger(); Assert.Equal(GetType().FullName, logger.Name); } private static class ImAStaticClass { [UsedImplicitly] public static readonly Logger Logger = LogManager.GetCurrentClassLogger(); static ImAStaticClass() { } public static void DummyToInvokeInitializers() { } } [Fact] public void GetCurrentClassLogger_static_class() { ImAStaticClass.DummyToInvokeInitializers(); Assert.Equal(typeof(ImAStaticClass).FullName, ImAStaticClass.Logger.Name); } private abstract class ImAAbstractClass { public Logger Logger { get; private set; } public Logger LoggerType { get; private set; } public string BaseName => typeof(ImAAbstractClass).FullName; /// <summary> /// Initializes a new instance of the <see cref="T:System.Object"/> class. /// </summary> protected ImAAbstractClass() { Logger = LogManager.GetCurrentClassLogger(); LoggerType = LogManager.GetCurrentClassLogger(typeof(Logger)); } protected ImAAbstractClass(string param1, Func<string> param2) { Logger = LogManager.GetCurrentClassLogger(); LoggerType = LogManager.GetCurrentClassLogger(typeof(Logger)); } } private class InheritedFromAbstractClass : ImAAbstractClass { public Logger LoggerInherited = LogManager.GetCurrentClassLogger(); public Logger LoggerTypeInherited = LogManager.GetCurrentClassLogger(typeof(Logger)); public string InheritedName => GetType().FullName; public InheritedFromAbstractClass() : base() { } public InheritedFromAbstractClass(string param1, Func<string> param2) : base(param1, param2) { } } /// <summary> /// Creating instance in a abstract ctor should not be a problem /// </summary> [Fact] public void GetCurrentClassLogger_abstract_class() { var instance = new InheritedFromAbstractClass(); Assert.Equal(instance.BaseName, instance.Logger.Name); Assert.Equal(instance.BaseName, instance.LoggerType.Name); Assert.Equal(instance.InheritedName, instance.LoggerInherited.Name); Assert.Equal(instance.InheritedName, instance.LoggerTypeInherited.Name); } /// <summary> /// Creating instance in a abstract ctor should not be a problem /// </summary> [Fact] public void GetCurrentClassLogger_abstract_class_with_parameter() { var instance = new InheritedFromAbstractClass("Hello", null); Assert.Equal(instance.BaseName, instance.Logger.Name); Assert.Equal(instance.BaseName, instance.LoggerType.Name); } /// <summary> /// I'm a class which isn't inhereting from Logger /// </summary> private class ImNotALogger { } /// <summary> /// ImNotALogger inherits not from Logger , but should not throw an exception /// </summary> [Fact] public void GetLogger_wrong_loggertype_should_continue() { var instance = LogManager.GetLogger("a", typeof(ImNotALogger)); Assert.NotNull(instance); } /// <summary> /// ImNotALogger inherits not from Logger , but should not throw an exception /// </summary> [Fact] public void GetLogger_wrong_loggertype_should_continue_even_if_class_is_static() { var instance = LogManager.GetLogger("a", typeof(ImAStaticClass)); Assert.NotNull(instance); } [Fact] public void GivenLazyClass_WhenGetCurrentClassLogger_ThenLoggerNameShouldBeCurrentClass() { var logger = new Lazy<ILogger>(LogManager.GetCurrentClassLogger); Assert.Equal(GetType().FullName, logger.Value.Name); } [Fact] public void ThreadSafe_Shutdown() { LogManager.Configuration = new LoggingConfiguration(); LogManager.ThrowExceptions = true; LogManager.Configuration.AddTarget("memory", new NLog.Targets.Wrappers.BufferingTargetWrapper(new MemoryQueueTarget(500), 5, 1)); LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, LogManager.Configuration.FindTargetByName("memory"))); LogManager.Configuration.AddTarget("memory2", new NLog.Targets.Wrappers.BufferingTargetWrapper(new MemoryQueueTarget(500), 5, 1)); LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, LogManager.Configuration.FindTargetByName("memory2"))); var stopFlag = false; var exceptionThrown = false; Task.Run(() => { try { var logger = LogManager.GetLogger("Hello"); while (!stopFlag) { logger.Debug("Hello World"); System.Threading.Thread.Sleep(1); } } catch { exceptionThrown = true; } }); Task.Run(() => { try { var logger = LogManager.GetLogger("Hello"); while (!stopFlag) { logger.Debug("Hello World"); System.Threading.Thread.Sleep(1); } } catch { exceptionThrown = true; } }); System.Threading.Thread.Sleep(20); LogManager.Shutdown(); // Shutdown active LoggingConfiguration System.Threading.Thread.Sleep(20); stopFlag = true; System.Threading.Thread.Sleep(20); Assert.False(exceptionThrown); } /// <summary> /// Note: THe problem can be reproduced when: debugging the unittest + "break when exception is thrown" checked in visual studio. /// /// https://github.com/NLog/NLog/issues/500 /// </summary> [Fact] public void ThreadSafe_getCurrentClassLogger_test() { MemoryQueueTarget mTarget = new MemoryQueueTarget(1000) { Name = "memory" }; MemoryQueueTarget mTarget2 = new MemoryQueueTarget(1000) { Name = "memory2" }; var task1 = Task.Run(() => { //need for init LogManager.Configuration = new LoggingConfiguration(); LogManager.ThrowExceptions = true; LogManager.Configuration.AddTarget(mTarget.Name, mTarget); LogManager.Configuration.AddRuleForAllLevels(mTarget.Name); System.Threading.Thread.Sleep(1); LogManager.ReconfigExistingLoggers(); System.Threading.Thread.Sleep(1); mTarget.Layout = @"${date:format=HH\:mm\:ss}|${level:uppercase=true}|${message} ${exception:format=tostring}"; }); var task2 = task1.ContinueWith((t) => { LogManager.Configuration.AddTarget(mTarget2.Name, mTarget2); LogManager.Configuration.AddRuleForAllLevels(mTarget2.Name); System.Threading.Thread.Sleep(1); LogManager.ReconfigExistingLoggers(); System.Threading.Thread.Sleep(1); mTarget2.Layout = @"${date:format=HH\:mm\:ss}|${level:uppercase=true}|${message} ${exception:format=tostring}"; }); System.Threading.Thread.Sleep(1); Parallel.For(0, 8, new ParallelOptions() { MaxDegreeOfParallelism = 8 }, (e) => { bool task1Complete = false, task2Complete = false; for (int i = 0; i < 100; ++i) { if (i > 25 && !task1Complete) { task1.Wait(5000); task1Complete = true; } if (i > 75 && !task2Complete) { task2.Wait(5000); task2Complete = true; } // Multiple threads initializing new loggers while configuration is changing var loggerA = LogManager.GetLogger(e + "A" + i); loggerA.Info("Hi there {0}", e); var loggerB = LogManager.GetLogger(e + "B" + i); loggerB.Info("Hi there {0}", e); var loggerC = LogManager.GetLogger(e + "C" + i); loggerC.Info("Hi there {0}", e); var loggerD = LogManager.GetLogger(e + "D" + i); loggerD.Info("Hi there {0}", e); }; }); Assert.NotEqual(0, mTarget.Logs.Count + mTarget2.Logs.Count); } [Fact] public void RemovedTargetShouldNotLog() { LogManager.ThrowExceptions = true; var config = new LoggingConfiguration(); var targetA = new MemoryQueueTarget("TargetA") { Layout = "A | ${message}" }; var targetB = new MemoryQueueTarget("TargetB") { Layout = "B | ${message}" }; config.AddRule(LogLevel.Debug, LogLevel.Fatal, targetA); config.AddRule(LogLevel.Debug, LogLevel.Fatal, targetB); LogManager.Configuration = config; Assert.Equal(new[] { "TargetA", "TargetB" }, LogManager.Configuration.ConfiguredNamedTargets.Select(target => target.Name)); Assert.NotNull(LogManager.Configuration.FindTargetByName("TargetA")); Assert.NotNull(LogManager.Configuration.FindTargetByName("TargetB")); var logger = LogManager.GetCurrentClassLogger(); logger.Info("Hello World"); Assert.Equal("A | Hello World", targetA.Logs.LastOrDefault()); Assert.Equal("B | Hello World", targetB.Logs.LastOrDefault()); // Remove the first target from the configuration LogManager.Configuration.RemoveTarget("TargetA"); Assert.Equal(new[] { "TargetB" }, LogManager.Configuration.ConfiguredNamedTargets.Select(target => target.Name)); Assert.Null(LogManager.Configuration.FindTargetByName("TargetA")); Assert.NotNull(LogManager.Configuration.FindTargetByName("TargetB")); logger.Info("Goodbye World"); Assert.Null(targetA.Logs); // Flushed and closed Assert.Equal("B | Goodbye World", targetB.Logs.LastOrDefault()); } /// <summary> /// target for <see cref="ThreadSafe_getCurrentClassLogger_test"/> /// </summary> [Target("Memory")] public sealed class MemoryQueueTarget : TargetWithLayout { private int maxSize; public MemoryQueueTarget() : this(1) { } public MemoryQueueTarget(string name) : this(1) { Name = name; } public MemoryQueueTarget(int size) { maxSize = size; } protected override void InitializeTarget() { base.InitializeTarget(); Logs = new Queue<string>(maxSize); } protected override void CloseTarget() { base.CloseTarget(); Logs = null; } internal Queue<string> Logs { get; private set; } protected override void Write(LogEventInfo logEvent) { if (Logs == null) throw new ObjectDisposedException("MemoryQueueTarget"); string msg = Layout.Render(logEvent); if (msg.Length > 100) msg = msg.Substring(0, 100) + "..."; Logs.Enqueue(msg); while (Logs.Count > maxSize) { Logs.Dequeue(); } } } } }
namespace Fixtures.SwaggerBatBodyArray { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; /// <summary> /// Test Infrastructure for AutoRest Swagger BAT /// </summary> public partial interface IArray { /// <summary> /// Get null array value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<int?>>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get invalid array [1, 2, 3 /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<int?>>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get empty array value [] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<int?>>> GetEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set array value empty [] /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> PutEmptyWithHttpMessagesAsync(IList<string> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get boolean array value [true, false, false, true] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<bool?>>> GetBooleanTfftWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set array value empty [true, false, false, true] /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> PutBooleanTfftWithHttpMessagesAsync(IList<bool?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get boolean array value [true, null, false] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<bool?>>> GetBooleanInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get boolean array value [true, 'boolean', false] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<bool?>>> GetBooleanInvalidStringWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get integer array value [1, -1, 3, 300] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<int?>>> GetIntegerValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set array value empty [1, -1, 3, 300] /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> PutIntegerValidWithHttpMessagesAsync(IList<int?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get integer array value [1, null, 0] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<int?>>> GetIntInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get integer array value [1, 'integer', 0] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<int?>>> GetIntInvalidStringWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get integer array value [1, -1, 3, 300] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<long?>>> GetLongValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set array value empty [1, -1, 3, 300] /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> PutLongValidWithHttpMessagesAsync(IList<long?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get long array value [1, null, 0] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<long?>>> GetLongInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get long array value [1, 'integer', 0] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<long?>>> GetLongInvalidStringWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get float array value [0, -0.01, 1.2e20] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<double?>>> GetFloatValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set array value [0, -0.01, 1.2e20] /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> PutFloatValidWithHttpMessagesAsync(IList<double?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get float array value [0.0, null, -1.2e20] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<double?>>> GetFloatInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get boolean array value [1.0, 'number', 0.0] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<double?>>> GetFloatInvalidStringWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get float array value [0, -0.01, 1.2e20] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<double?>>> GetDoubleValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set array value [0, -0.01, 1.2e20] /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> PutDoubleValidWithHttpMessagesAsync(IList<double?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get float array value [0.0, null, -1.2e20] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<double?>>> GetDoubleInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get boolean array value [1.0, 'number', 0.0] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<double?>>> GetDoubleInvalidStringWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get string array value ['foo1', 'foo2', 'foo3'] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<string>>> GetStringValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set array value ['foo1', 'foo2', 'foo3'] /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> PutStringValidWithHttpMessagesAsync(IList<string> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get string array value ['foo', null, 'foo2'] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<string>>> GetStringWithNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get string array value ['foo', 123, 'foo2'] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<string>>> GetStringWithInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get integer array value ['2000-12-01', '1980-01-02', '1492-10-12'] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<DateTime?>>> GetDateValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set array value ['2000-12-01', '1980-01-02', '1492-10-12'] /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> PutDateValidWithHttpMessagesAsync(IList<DateTime?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get date array value ['2012-01-01', null, '1776-07-04'] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<DateTime?>>> GetDateInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get date array value ['2011-03-22', 'date'] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<DateTime?>>> GetDateInvalidCharsWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get date-time array value ['2000-12-01t00:00:01z', /// '1980-01-02T00:11:35+01:00', '1492-10-12T10:15:01-08:00'] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<DateTime?>>> GetDateTimeValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set array value ['2000-12-01t00:00:01z', /// '1980-01-02T00:11:35+01:00', '1492-10-12T10:15:01-08:00'] /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> PutDateTimeValidWithHttpMessagesAsync(IList<DateTime?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get date array value ['2000-12-01t00:00:01z', null] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<DateTime?>>> GetDateTimeInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get date array value ['2000-12-01t00:00:01z', 'date-time'] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<DateTime?>>> GetDateTimeInvalidCharsWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get byte array value [hex(FF FF FF FA), hex(01 02 03), hex (25, /// 29, 43)] with each item encoded in base64 /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<byte[]>>> GetByteValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put the array value [hex(FF FF FF FA), hex(01 02 03), hex (25, 29, /// 43)] with each elementencoded in base 64 /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> PutByteValidWithHttpMessagesAsync(IList<byte[]> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get byte array value [hex(AB, AC, AD), null] with the first item /// base64 encoded /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<byte[]>>> GetByteInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get array of complex type null value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<Product>>> GetComplexNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get empty array of complex type [] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<Product>>> GetComplexEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get array of complex type with null item [{'integer': 1 'string': /// '2'}, null, {'integer': 5, 'string': '6'}] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<Product>>> GetComplexItemNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get array of complex type with empty item [{'integer': 1 'string': /// '2'}, {}, {'integer': 5, 'string': '6'}] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<Product>>> GetComplexItemEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get array of complex type with [{'integer': 1 'string': '2'}, /// {'integer': 3, 'string': '4'}, {'integer': 5, 'string': '6'}] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<Product>>> GetComplexValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put an array of complex type with values [{'integer': 1 'string': /// '2'}, {'integer': 3, 'string': '4'}, {'integer': 5, 'string': /// '6'}] /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> PutComplexValidWithHttpMessagesAsync(IList<Product> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get a null array /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<IList<string>>>> GetArrayNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an empty array [] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<IList<string>>>> GetArrayEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an array of array of strings [['1', '2', '3'], null, ['7', /// '8', '9']] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<IList<string>>>> GetArrayItemNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an array of array of strings [['1', '2', '3'], [], ['7', '8', /// '9']] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<IList<string>>>> GetArrayItemEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an array of array of strings [['1', '2', '3'], ['4', '5', /// '6'], ['7', '8', '9']] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<IList<string>>>> GetArrayValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put An array of array of strings [['1', '2', '3'], ['4', '5', /// '6'], ['7', '8', '9']] /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> PutArrayValidWithHttpMessagesAsync(IList<IList<string>> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an array of Dictionaries with value null /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<IDictionary<string, string>>>> GetDictionaryNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an array of Dictionaries of type &lt;string, string&gt; with /// value [] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<IDictionary<string, string>>>> GetDictionaryEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an array of Dictionaries of type &lt;string, string&gt; with /// value [{'1': 'one', '2': 'two', '3': 'three'}, null, {'7': /// 'seven', '8': 'eight', '9': 'nine'}] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<IDictionary<string, string>>>> GetDictionaryItemNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an array of Dictionaries of type &lt;string, string&gt; with /// value [{'1': 'one', '2': 'two', '3': 'three'}, {}, {'7': 'seven', /// '8': 'eight', '9': 'nine'}] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<IDictionary<string, string>>>> GetDictionaryItemEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an array of Dictionaries of type &lt;string, string&gt; with /// value [{'1': 'one', '2': 'two', '3': 'three'}, {'4': 'four', '5': /// 'five', '6': 'six'}, {'7': 'seven', '8': 'eight', '9': 'nine'}] /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse<IList<IDictionary<string, string>>>> GetDictionaryValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an array of Dictionaries of type &lt;string, string&gt; with /// value [{'1': 'one', '2': 'two', '3': 'three'}, {'4': 'four', '5': /// 'five', '6': 'six'}, {'7': 'seven', '8': 'eight', '9': 'nine'}] /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> Task<HttpOperationResponse> PutDictionaryValidWithHttpMessagesAsync(IList<IDictionary<string, string>> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; public class doublemm { public static Random rand; public static int size; public static double GenerateDbl() { int e; int op1 = (int)((float)rand.Next() / Int32.MaxValue * 2); if (op1 == 0) e = -rand.Next(0, 1000); else e = +rand.Next(0, 1000); return Math.Pow(2, e); } public static void Init2DMatrix(out double[,] m, out double[][] refm) { int i, j; i = 0; double temp; m = new double[size, size]; refm = new double[size][]; for (int k = 0; k < refm.Length; k++) refm[k] = new double[size]; while (i < size) { j = 0; while (j < size) { temp = GenerateDbl(); m[i, j] = temp - 60; refm[i][j] = temp - 60; j++; } i++; } } public static void InnerProduct2D(out double res, ref double[,] a, ref double[,] b, int row, int col) { int i; res = 0; i = 0; while (i < size) { res = res + a[row, i] * b[i, col]; i++; } } public static void InnerProduct2DRef(out double res, ref double[][] a, ref double[][] b, int row, int col) { int i; res = 0; i = 0; while (i < size) { res = res + a[row][i] * b[i][col]; i++; } } public static void Init3DMatrix(double[,,] m, double[][] refm) { int i, j; i = 0; double temp; while (i < size) { j = 0; while (j < size) { temp = GenerateDbl(); m[i, j, size] = temp - 60; refm[i][j] = temp - 60; j++; } i++; } } public static void InnerProduct3D(out double res, double[,,] a, double[,,] b, int row, int col) { int i; res = 0; i = 0; while (i < size) { res = res + a[row, i, size] * b[i, col, size]; i++; } } public static void InnerProduct3DRef(out double res, double[][] a, double[][] b, int row, int col) { int i; res = 0; i = 0; while (i < size) { res = res + a[row][i] * b[i][col]; i++; } } public static int Main() { bool pass = false; rand = new Random(); size = rand.Next(2, 10); Console.WriteLine(); Console.WriteLine("2D Array"); Console.WriteLine("Testing inner product of {0} by {0} matrices", size); Console.WriteLine("Matrix is member of a Jagged array, element stores random double"); Console.WriteLine("array set/get, ref/out param are used"); double[][,] ima2d = new double[3][,]; ima2d[2] = new double[size, size]; double[,] imb2d = new double[size, size]; double[][,] imr2d = new double[5][,]; imr2d[0] = new double[size, size]; double[][] refa2d = new double[size][]; double[][] refb2d = new double[size][]; double[][] refr2d = new double[size][]; for (int k = 0; k < refr2d.Length; k++) refr2d[k] = new double[size]; Init2DMatrix(out ima2d[2], out refa2d); Init2DMatrix(out imb2d, out refb2d); int m = 0; int n = 0; while (m < size) { n = 0; while (n < size) { InnerProduct2D(out imr2d[0][m, n], ref ima2d[2], ref imb2d, m, n); InnerProduct2DRef(out refr2d[m][n], ref refa2d, ref refb2d, m, n); n++; } m++; } for (int i = 0; i < size; i++) { pass = true; for (int j = 0; j < size; j++) if (imr2d[0][i, j] != refr2d[i][j]) { Console.WriteLine("i={0}, j={1}, imr2d[0][i,j] {2}!=refr2d[i][j] {3}", i, j, imr2d[0][i, j], refr2d[i][j]); pass = false; } } Console.WriteLine(); Console.WriteLine("3D Array"); Console.WriteLine("Testing inner product of one slice of two 3D matrices", size); Console.WriteLine("Matrix is member of a Jagged array, element stores random double"); double[][,,] ima3d = new double[3][,,]; ima3d[2] = new double[size + 3, size + 2, size + 1]; double[,,] imb3d = new double[size + 1, size + 3, size + 2]; double[][,,] imr3d = new double[5][,,]; imr3d[0] = new double[size + 5, size + 4, size + 3]; for (int i = 0; i < size; i++) for (int j = 0; j < size; j++) imr3d[0][size, i, j] = 1; double[][] refa3d = new double[size][]; double[][] refb3d = new double[size][]; double[][] refr3d = new double[size][]; for (int k = 0; k < refa3d.Length; k++) refa3d[k] = new double[size + 1]; for (int k = 0; k < refb3d.Length; k++) refb3d[k] = new double[size + 2]; for (int k = 0; k < refr3d.Length; k++) refr3d[k] = new double[size + 2]; Init3DMatrix(ima3d[2], refa3d); Init3DMatrix(imb3d, refb3d); m = 0; n = 0; while (m < size) { n = 0; while (n < size) { InnerProduct3D(out imr3d[0][size, m, n], ima3d[2], imb3d, m, n); InnerProduct3DRef(out refr3d[m][n], refa3d, refb3d, m, n); n++; } m++; } for (int i = 0; i < size; i++) { pass = true; for (int j = 0; j < size; j++) if (imr3d[0][size, i, j] != refr3d[i][j]) { Console.WriteLine("i={0}, j={1}, imr3d[0][{4},i,j] {2}!=refr3d[i][j] {3}", i, j, imr3d[0][size, i, j], refr3d[i][j], size); pass = false; } } if (pass) { Console.WriteLine("PASSED"); return 100; } else { Console.WriteLine("FAILED"); return 1; } } }
using System; using System.Collections.Generic; using System.Text; using System.Drawing; using AxiomCoders.PdfTemplateEditor.EditorStuff; using AxiomCoders.PdfTemplateEditor.Common; namespace AxiomCoders.PdfTemplateEditor.EditorItems { /// <summary> /// Class used to show report page /// </summary> public class ReportPageViewer: EditorItemViewer { private ReportPage owner; public ReportPageViewer(ReportPage owner) { this.owner = owner; } /// <summary> /// Check if horizontal scrollbar is required /// </summary> private bool horizontalScrollRequired = false; public bool HorizontalScrollRequired { get { return horizontalScrollRequired; } set { horizontalScrollRequired = value; } } /// <summary> /// Check if vertical scroller is required /// </summary> private bool verticalScrollRequired = false; public bool VerticalScrollRequired { get { return verticalScrollRequired; } set { verticalScrollRequired = value; } } /// <summary> /// Current X position for scrolling /// </summary> private float offsetXValue = 0; public float OffsetXValue { get { return offsetXValue; } set { offsetXValue = value; } } /// <summary> /// Current Y position for scrolling /// </summary> private float offsetYValue = 0; public float OffsetYValue { get { return offsetYValue; } set { offsetYValue = value; } } /// <summary> /// What is max value for horizontal scroller /// </summary> private int horizontalScrollerMaxValue = 0; public int HorizontalScrollerMaxValue { get { return horizontalScrollerMaxValue; } set { horizontalScrollerMaxValue = value; } } /// <summary> /// What is max value for vertical scroller /// </summary> private int verticalScrollerMaxValue = 0; public int VerticalScrollerMaxValue { get { return verticalScrollerMaxValue; } set { verticalScrollerMaxValue = value; } } /// <summary> /// Where is top-left corner of page /// </summary> private float pageStartX; public float PageStartX { get { return pageStartX; } } private float pageStartY; public float PageStartY { get { return pageStartY; } } /// <summary> /// Width of whole page in pixels /// </summary> private float drawWidth; public float DrawWidth { get { return drawWidth; } } /// <summary> /// Height of whole page in pixels /// </summary> private float drawHeight; public float DrawHeight { get { return drawHeight; } } private float centerX; public float CenterX { get { return centerX; } set { centerX = value; } } private float centerY; public float CenterY { get { return centerY; } set { centerY = value; } } public void UpdateValues(Rectangle clipRect) { centerX = ((float)clipRect.Width / 2.0f); centerY = ((float)clipRect.Height / 2.0f); // draw white background in size of page considering zoom level. Also initiate drawing of other items on page drawWidth = owner.WidthInPixels; //UnitsManager.Instance.ConvertUnit(, owner.MeasureUnit, MeasureUnits.pixel); drawHeight = owner.HeightInPixels; // UnitsManager.Instance.ConvertUnit(owner.Size.Height, owner.MeasureUnit, MeasureUnits.pixel); drawWidth *= (float)owner.ZoomLevel / 100.0f; drawHeight *= (float)owner.ZoomLevel / 100.0f; pageStartX = (float)clipRect.Width / 2.0f - (drawWidth / 2.0f); if (pageStartX < 0) { pageStartX = 0; } pageStartY = (float)clipRect.Height / 2.0f - (drawHeight / 2.0f); if (pageStartY < 0) { pageStartY = 0; } if (drawWidth < clipRect.Width) { horizontalScrollRequired = false; } else { horizontalScrollRequired = true; horizontalScrollerMaxValue = (int)drawWidth - clipRect.Width + 50; } if (drawHeight < clipRect.Height) { verticalScrollRequired = false; } else { verticalScrollRequired = true; verticalScrollerMaxValue = (int)drawHeight - clipRect.Height + 50; } } #region EditorItemViewer Members public void Draw(int offsetX, int offsetY, int parentX, int parentY, float zoomLevel, Graphics gc, Rectangle clipRect) { // draw white background in size of page considering zoom level. Also initiate drawing of other items on page /*drawWidth = owner.WidthInPixels; //UnitsManager.Instance.ConvertUnit(, owner.MeasureUnit, MeasureUnits.pixel); drawHeight = owner.HeightInPixels; // UnitsManager.Instance.ConvertUnit(owner.Size.Height, owner.MeasureUnit, MeasureUnits.pixel); drawWidth *= owner.ZoomLevel / 100.0f; drawHeight *= owner.ZoomLevel / 100.0f; pageStartX = (float)clipRect.Width / 2.0f - (drawWidth / 2.0f); if (pageStartX < 0) { pageStartX = 0; } pageStartY = (float)clipRect.Height / 2.0f - (drawHeight / 2.0f); if (pageStartY < 0) { pageStartY = 0; } if (drawWidth < clipRect.Width) { horizontalScrollRequired = false; } else { horizontalScrollRequired = true; horizontalScrollerMaxValue = (int)drawWidth - clipRect.Width + 50; } if (drawHeight < clipRect.Height) { verticalScrollRequired = false; } else { verticalScrollRequired = true; verticalScrollerMaxValue = (int)drawHeight - clipRect.Height + 50; } gc.FillRectangle(Brushes.White, (float)pageStartX, (float)pageStartY, (float)drawWidth, (float)drawHeight); */ } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3; using rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion; using LSLInteger = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger; namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase { public partial class ScriptBaseClass { // LSL CONSTANTS public static readonly LSLInteger TRUE = new LSLInteger(1); public static readonly LSLInteger FALSE = new LSLInteger(0); public const int STATUS_PHYSICS = 1; public const int STATUS_ROTATE_X = 2; public const int STATUS_ROTATE_Y = 4; public const int STATUS_ROTATE_Z = 8; public const int STATUS_PHANTOM = 16; public const int STATUS_SANDBOX = 32; public const int STATUS_BLOCK_GRAB = 64; public const int STATUS_DIE_AT_EDGE = 128; public const int STATUS_RETURN_AT_EDGE = 256; public const int STATUS_CAST_SHADOWS = 512; public const int AGENT = 1; public const int AGENT_BY_LEGACY_NAME = 1; public const int AGENT_BY_USERNAME = 0x10; public const int NPC = 0x20; public const int ACTIVE = 2; public const int PASSIVE = 4; public const int SCRIPTED = 8; public const int OS_NPC = 0x01000000; public const int CONTROL_FWD = 1; public const int CONTROL_BACK = 2; public const int CONTROL_LEFT = 4; public const int CONTROL_RIGHT = 8; public const int CONTROL_UP = 16; public const int CONTROL_DOWN = 32; public const int CONTROL_ROT_LEFT = 256; public const int CONTROL_ROT_RIGHT = 512; public const int CONTROL_LBUTTON = 268435456; public const int CONTROL_ML_LBUTTON = 1073741824; //Permissions public const int PERMISSION_DEBIT = 2; public const int PERMISSION_TAKE_CONTROLS = 4; public const int PERMISSION_REMAP_CONTROLS = 8; public const int PERMISSION_TRIGGER_ANIMATION = 16; public const int PERMISSION_ATTACH = 32; public const int PERMISSION_RELEASE_OWNERSHIP = 64; public const int PERMISSION_CHANGE_LINKS = 128; public const int PERMISSION_CHANGE_JOINTS = 256; public const int PERMISSION_CHANGE_PERMISSIONS = 512; public const int PERMISSION_TRACK_CAMERA = 1024; public const int PERMISSION_CONTROL_CAMERA = 2048; public const int AGENT_FLYING = 1; public const int AGENT_ATTACHMENTS = 2; public const int AGENT_SCRIPTED = 4; public const int AGENT_MOUSELOOK = 8; public const int AGENT_SITTING = 16; public const int AGENT_ON_OBJECT = 32; public const int AGENT_AWAY = 64; public const int AGENT_WALKING = 128; public const int AGENT_IN_AIR = 256; public const int AGENT_TYPING = 512; public const int AGENT_CROUCHING = 1024; public const int AGENT_BUSY = 2048; public const int AGENT_ALWAYS_RUN = 4096; //Particle Systems public const int PSYS_PART_INTERP_COLOR_MASK = 1; public const int PSYS_PART_INTERP_SCALE_MASK = 2; public const int PSYS_PART_BOUNCE_MASK = 4; public const int PSYS_PART_WIND_MASK = 8; public const int PSYS_PART_FOLLOW_SRC_MASK = 16; public const int PSYS_PART_FOLLOW_VELOCITY_MASK = 32; public const int PSYS_PART_TARGET_POS_MASK = 64; public const int PSYS_PART_TARGET_LINEAR_MASK = 128; public const int PSYS_PART_EMISSIVE_MASK = 256; public const int PSYS_PART_RIBBON_MASK = 1024; public const int PSYS_PART_FLAGS = 0; public const int PSYS_PART_START_COLOR = 1; public const int PSYS_PART_START_ALPHA = 2; public const int PSYS_PART_END_COLOR = 3; public const int PSYS_PART_END_ALPHA = 4; public const int PSYS_PART_START_SCALE = 5; public const int PSYS_PART_END_SCALE = 6; public const int PSYS_PART_MAX_AGE = 7; public const int PSYS_SRC_ACCEL = 8; public const int PSYS_SRC_PATTERN = 9; public const int PSYS_SRC_INNERANGLE = 10; public const int PSYS_SRC_OUTERANGLE = 11; public const int PSYS_SRC_TEXTURE = 12; public const int PSYS_SRC_BURST_RATE = 13; public const int PSYS_SRC_BURST_PART_COUNT = 15; public const int PSYS_SRC_BURST_RADIUS = 16; public const int PSYS_SRC_BURST_SPEED_MIN = 17; public const int PSYS_SRC_BURST_SPEED_MAX = 18; public const int PSYS_SRC_MAX_AGE = 19; public const int PSYS_SRC_TARGET_KEY = 20; public const int PSYS_SRC_OMEGA = 21; public const int PSYS_SRC_ANGLE_BEGIN = 22; public const int PSYS_SRC_ANGLE_END = 23; public const int PSYS_PART_BLEND_FUNC_SOURCE = 24; public const int PSYS_PART_BLEND_FUNC_DEST = 25; public const int PSYS_PART_START_GLOW = 26; public const int PSYS_PART_END_GLOW = 27; public const int PSYS_PART_BF_ONE = 0; public const int PSYS_PART_BF_ZERO = 1; public const int PSYS_PART_BF_DEST_COLOR = 2; public const int PSYS_PART_BF_SOURCE_COLOR = 3; public const int PSYS_PART_BF_ONE_MINUS_DEST_COLOR = 4; public const int PSYS_PART_BF_ONE_MINUS_SOURCE_COLOR = 5; public const int PSYS_PART_BF_SOURCE_ALPHA = 7; public const int PSYS_PART_BF_ONE_MINUS_SOURCE_ALPHA = 9; public const int PSYS_SRC_PATTERN_DROP = 1; public const int PSYS_SRC_PATTERN_EXPLODE = 2; public const int PSYS_SRC_PATTERN_ANGLE = 4; public const int PSYS_SRC_PATTERN_ANGLE_CONE = 8; public const int PSYS_SRC_PATTERN_ANGLE_CONE_EMPTY = 16; public const int VEHICLE_TYPE_NONE = 0; public const int VEHICLE_TYPE_SLED = 1; public const int VEHICLE_TYPE_CAR = 2; public const int VEHICLE_TYPE_BOAT = 3; public const int VEHICLE_TYPE_AIRPLANE = 4; public const int VEHICLE_TYPE_BALLOON = 5; public const int VEHICLE_LINEAR_FRICTION_TIMESCALE = 16; public const int VEHICLE_ANGULAR_FRICTION_TIMESCALE = 17; public const int VEHICLE_LINEAR_MOTOR_DIRECTION = 18; public const int VEHICLE_LINEAR_MOTOR_OFFSET = 20; public const int VEHICLE_ANGULAR_MOTOR_DIRECTION = 19; public const int VEHICLE_HOVER_HEIGHT = 24; public const int VEHICLE_HOVER_EFFICIENCY = 25; public const int VEHICLE_HOVER_TIMESCALE = 26; public const int VEHICLE_BUOYANCY = 27; public const int VEHICLE_LINEAR_DEFLECTION_EFFICIENCY = 28; public const int VEHICLE_LINEAR_DEFLECTION_TIMESCALE = 29; public const int VEHICLE_LINEAR_MOTOR_TIMESCALE = 30; public const int VEHICLE_LINEAR_MOTOR_DECAY_TIMESCALE = 31; public const int VEHICLE_ANGULAR_DEFLECTION_EFFICIENCY = 32; public const int VEHICLE_ANGULAR_DEFLECTION_TIMESCALE = 33; public const int VEHICLE_ANGULAR_MOTOR_TIMESCALE = 34; public const int VEHICLE_ANGULAR_MOTOR_DECAY_TIMESCALE = 35; public const int VEHICLE_VERTICAL_ATTRACTION_EFFICIENCY = 36; public const int VEHICLE_VERTICAL_ATTRACTION_TIMESCALE = 37; public const int VEHICLE_BANKING_EFFICIENCY = 38; public const int VEHICLE_BANKING_MIX = 39; public const int VEHICLE_BANKING_TIMESCALE = 40; public const int VEHICLE_REFERENCE_FRAME = 44; public const int VEHICLE_RANGE_BLOCK = 45; public const int VEHICLE_ROLL_FRAME = 46; public const int VEHICLE_FLAG_NO_DEFLECTION_UP = 1; public const int VEHICLE_FLAG_LIMIT_ROLL_ONLY = 2; public const int VEHICLE_FLAG_HOVER_WATER_ONLY = 4; public const int VEHICLE_FLAG_HOVER_TERRAIN_ONLY = 8; public const int VEHICLE_FLAG_HOVER_GLOBAL_HEIGHT = 16; public const int VEHICLE_FLAG_HOVER_UP_ONLY = 32; public const int VEHICLE_FLAG_LIMIT_MOTOR_UP = 64; public const int VEHICLE_FLAG_MOUSELOOK_STEER = 128; public const int VEHICLE_FLAG_MOUSELOOK_BANK = 256; public const int VEHICLE_FLAG_CAMERA_DECOUPLED = 512; public const int VEHICLE_FLAG_NO_X = 1024; public const int VEHICLE_FLAG_NO_Y = 2048; public const int VEHICLE_FLAG_NO_Z = 4096; public const int VEHICLE_FLAG_LOCK_HOVER_HEIGHT = 8192; public const int VEHICLE_FLAG_NO_DEFLECTION = 16392; public const int VEHICLE_FLAG_LOCK_ROTATION = 32784; public const int INVENTORY_ALL = -1; public const int INVENTORY_NONE = -1; public const int INVENTORY_TEXTURE = 0; public const int INVENTORY_SOUND = 1; public const int INVENTORY_LANDMARK = 3; public const int INVENTORY_CLOTHING = 5; public const int INVENTORY_OBJECT = 6; public const int INVENTORY_NOTECARD = 7; public const int INVENTORY_SCRIPT = 10; public const int INVENTORY_BODYPART = 13; public const int INVENTORY_ANIMATION = 20; public const int INVENTORY_GESTURE = 21; public const int ATTACH_CHEST = 1; public const int ATTACH_HEAD = 2; public const int ATTACH_LSHOULDER = 3; public const int ATTACH_RSHOULDER = 4; public const int ATTACH_LHAND = 5; public const int ATTACH_RHAND = 6; public const int ATTACH_LFOOT = 7; public const int ATTACH_RFOOT = 8; public const int ATTACH_BACK = 9; public const int ATTACH_PELVIS = 10; public const int ATTACH_MOUTH = 11; public const int ATTACH_CHIN = 12; public const int ATTACH_LEAR = 13; public const int ATTACH_REAR = 14; public const int ATTACH_LEYE = 15; public const int ATTACH_REYE = 16; public const int ATTACH_NOSE = 17; public const int ATTACH_RUARM = 18; public const int ATTACH_RLARM = 19; public const int ATTACH_LUARM = 20; public const int ATTACH_LLARM = 21; public const int ATTACH_RHIP = 22; public const int ATTACH_RULEG = 23; public const int ATTACH_RLLEG = 24; public const int ATTACH_LHIP = 25; public const int ATTACH_LULEG = 26; public const int ATTACH_LLLEG = 27; public const int ATTACH_BELLY = 28; public const int ATTACH_RPEC = 29; public const int ATTACH_LPEC = 30; public const int ATTACH_LEFT_PEC = 29; // Same value as ATTACH_RPEC, see https://jira.secondlife.com/browse/SVC-580 public const int ATTACH_RIGHT_PEC = 30; // Same value as ATTACH_LPEC, see https://jira.secondlife.com/browse/SVC-580 public const int ATTACH_HUD_CENTER_2 = 31; public const int ATTACH_HUD_TOP_RIGHT = 32; public const int ATTACH_HUD_TOP_CENTER = 33; public const int ATTACH_HUD_TOP_LEFT = 34; public const int ATTACH_HUD_CENTER_1 = 35; public const int ATTACH_HUD_BOTTOM_LEFT = 36; public const int ATTACH_HUD_BOTTOM = 37; public const int ATTACH_HUD_BOTTOM_RIGHT = 38; #region osMessageAttachments constants /// <summary> /// Instructs osMessageAttachements to send the message to attachments /// on every point. /// </summary> /// <remarks> /// One might expect this to be named OS_ATTACH_ALL, but then one might /// also expect functions designed to attach or detach or get /// attachments to work with it too. Attaching a no-copy item to /// many attachments could be dangerous. /// when combined with OS_ATTACH_MSG_INVERT_POINTS, will prevent the /// message from being sent. /// if combined with OS_ATTACH_MSG_OBJECT_CREATOR or /// OS_ATTACH_MSG_SCRIPT_CREATOR, could result in no message being /// sent- this is expected behaviour. /// </remarks> public const int OS_ATTACH_MSG_ALL = -65535; /// <summary> /// Instructs osMessageAttachements to invert how the attachment points /// list should be treated (e.g. go from inclusive operation to /// exclusive operation). /// </summary> /// <remarks> /// This might be used if you want to deliver a message to one set of /// attachments and a different message to everything else. With /// this flag, you only need to build one explicit list for both calls. /// </remarks> public const int OS_ATTACH_MSG_INVERT_POINTS = 1; /// <summary> /// Instructs osMessageAttachments to only send the message to /// attachments with a CreatorID that matches the host object CreatorID /// </summary> /// <remarks> /// This would be used if distributed in an object vendor/updater server. /// </remarks> public const int OS_ATTACH_MSG_OBJECT_CREATOR = 2; /// <summary> /// Instructs osMessageAttachments to only send the message to /// attachments with a CreatorID that matches the sending script CreatorID /// </summary> /// <remarks> /// This might be used if the script is distributed independently of a /// containing object. /// </remarks> public const int OS_ATTACH_MSG_SCRIPT_CREATOR = 4; #endregion public const int LAND_LEVEL = 0; public const int LAND_RAISE = 1; public const int LAND_LOWER = 2; public const int LAND_SMOOTH = 3; public const int LAND_NOISE = 4; public const int LAND_REVERT = 5; public const int LAND_SMALL_BRUSH = 1; public const int LAND_MEDIUM_BRUSH = 2; public const int LAND_LARGE_BRUSH = 3; //Agent Dataserver public const int DATA_ONLINE = 1; public const int DATA_NAME = 2; public const int DATA_BORN = 3; public const int DATA_RATING = 4; public const int DATA_SIM_POS = 5; public const int DATA_SIM_STATUS = 6; public const int DATA_SIM_RATING = 7; public const int DATA_PAYINFO = 8; public const int DATA_SIM_RELEASE = 128; public const int ANIM_ON = 1; public const int LOOP = 2; public const int REVERSE = 4; public const int PING_PONG = 8; public const int SMOOTH = 16; public const int ROTATE = 32; public const int SCALE = 64; public const int ALL_SIDES = -1; public const int LINK_SET = -1; public const int LINK_ROOT = 1; public const int LINK_ALL_OTHERS = -2; public const int LINK_ALL_CHILDREN = -3; public const int LINK_THIS = -4; public const int CHANGED_INVENTORY = 1; public const int CHANGED_COLOR = 2; public const int CHANGED_SHAPE = 4; public const int CHANGED_SCALE = 8; public const int CHANGED_TEXTURE = 16; public const int CHANGED_LINK = 32; public const int CHANGED_ALLOWED_DROP = 64; public const int CHANGED_OWNER = 128; public const int CHANGED_REGION = 256; public const int CHANGED_TELEPORT = 512; public const int CHANGED_REGION_RESTART = 1024; public const int CHANGED_REGION_START = 1024; //LL Changed the constant from CHANGED_REGION_RESTART public const int CHANGED_MEDIA = 2048; public const int CHANGED_ANIMATION = 16384; public const int TYPE_INVALID = 0; public const int TYPE_INTEGER = 1; public const int TYPE_FLOAT = 2; public const int TYPE_STRING = 3; public const int TYPE_KEY = 4; public const int TYPE_VECTOR = 5; public const int TYPE_ROTATION = 6; //XML RPC Remote Data Channel public const int REMOTE_DATA_CHANNEL = 1; public const int REMOTE_DATA_REQUEST = 2; public const int REMOTE_DATA_REPLY = 3; //llHTTPRequest public const int HTTP_METHOD = 0; public const int HTTP_MIMETYPE = 1; public const int HTTP_BODY_MAXLENGTH = 2; public const int HTTP_VERIFY_CERT = 3; public const int HTTP_VERBOSE_THROTTLE = 4; public const int HTTP_CUSTOM_HEADER = 5; public const int HTTP_PRAGMA_NO_CACHE = 6; // llSetContentType public const int CONTENT_TYPE_TEXT = 0; //text/plain public const int CONTENT_TYPE_HTML = 1; //text/html public const int CONTENT_TYPE_XML = 2; //application/xml public const int CONTENT_TYPE_XHTML = 3; //application/xhtml+xml public const int CONTENT_TYPE_ATOM = 4; //application/atom+xml public const int CONTENT_TYPE_JSON = 5; //application/json public const int CONTENT_TYPE_LLSD = 6; //application/llsd+xml public const int CONTENT_TYPE_FORM = 7; //application/x-www-form-urlencoded public const int CONTENT_TYPE_RSS = 8; //application/rss+xml public const int PRIM_MATERIAL = 2; public const int PRIM_PHYSICS = 3; public const int PRIM_TEMP_ON_REZ = 4; public const int PRIM_PHANTOM = 5; public const int PRIM_POSITION = 6; public const int PRIM_SIZE = 7; public const int PRIM_ROTATION = 8; public const int PRIM_TYPE = 9; public const int PRIM_TEXTURE = 17; public const int PRIM_COLOR = 18; public const int PRIM_BUMP_SHINY = 19; public const int PRIM_FULLBRIGHT = 20; public const int PRIM_FLEXIBLE = 21; public const int PRIM_TEXGEN = 22; public const int PRIM_CAST_SHADOWS = 24; // Not implemented, here for completeness sake public const int PRIM_POINT_LIGHT = 23; // Huh? public const int PRIM_GLOW = 25; public const int PRIM_TEXT = 26; public const int PRIM_NAME = 27; public const int PRIM_DESC = 28; public const int PRIM_ROT_LOCAL = 29; public const int PRIM_OMEGA = 32; public const int PRIM_POS_LOCAL = 33; public const int PRIM_LINK_TARGET = 34; public const int PRIM_SLICE = 35; public const int PRIM_TEXGEN_DEFAULT = 0; public const int PRIM_TEXGEN_PLANAR = 1; public const int PRIM_TYPE_BOX = 0; public const int PRIM_TYPE_CYLINDER = 1; public const int PRIM_TYPE_PRISM = 2; public const int PRIM_TYPE_SPHERE = 3; public const int PRIM_TYPE_TORUS = 4; public const int PRIM_TYPE_TUBE = 5; public const int PRIM_TYPE_RING = 6; public const int PRIM_TYPE_SCULPT = 7; public const int PRIM_HOLE_DEFAULT = 0; public const int PRIM_HOLE_CIRCLE = 16; public const int PRIM_HOLE_SQUARE = 32; public const int PRIM_HOLE_TRIANGLE = 48; public const int PRIM_MATERIAL_STONE = 0; public const int PRIM_MATERIAL_METAL = 1; public const int PRIM_MATERIAL_GLASS = 2; public const int PRIM_MATERIAL_WOOD = 3; public const int PRIM_MATERIAL_FLESH = 4; public const int PRIM_MATERIAL_PLASTIC = 5; public const int PRIM_MATERIAL_RUBBER = 6; public const int PRIM_MATERIAL_LIGHT = 7; public const int PRIM_SHINY_NONE = 0; public const int PRIM_SHINY_LOW = 1; public const int PRIM_SHINY_MEDIUM = 2; public const int PRIM_SHINY_HIGH = 3; public const int PRIM_BUMP_NONE = 0; public const int PRIM_BUMP_BRIGHT = 1; public const int PRIM_BUMP_DARK = 2; public const int PRIM_BUMP_WOOD = 3; public const int PRIM_BUMP_BARK = 4; public const int PRIM_BUMP_BRICKS = 5; public const int PRIM_BUMP_CHECKER = 6; public const int PRIM_BUMP_CONCRETE = 7; public const int PRIM_BUMP_TILE = 8; public const int PRIM_BUMP_STONE = 9; public const int PRIM_BUMP_DISKS = 10; public const int PRIM_BUMP_GRAVEL = 11; public const int PRIM_BUMP_BLOBS = 12; public const int PRIM_BUMP_SIDING = 13; public const int PRIM_BUMP_LARGETILE = 14; public const int PRIM_BUMP_STUCCO = 15; public const int PRIM_BUMP_SUCTION = 16; public const int PRIM_BUMP_WEAVE = 17; public const int PRIM_SCULPT_TYPE_SPHERE = 1; public const int PRIM_SCULPT_TYPE_TORUS = 2; public const int PRIM_SCULPT_TYPE_PLANE = 3; public const int PRIM_SCULPT_TYPE_CYLINDER = 4; public const int PRIM_SCULPT_FLAG_INVERT = 64; public const int PRIM_SCULPT_FLAG_MIRROR = 128; public const int PROFILE_NONE = 0; public const int PROFILE_SCRIPT_MEMORY = 1; public const int MASK_BASE = 0; public const int MASK_OWNER = 1; public const int MASK_GROUP = 2; public const int MASK_EVERYONE = 3; public const int MASK_NEXT = 4; public const int PERM_TRANSFER = 8192; public const int PERM_MODIFY = 16384; public const int PERM_COPY = 32768; public const int PERM_MOVE = 524288; public const int PERM_ALL = 2147483647; public const int PARCEL_MEDIA_COMMAND_STOP = 0; public const int PARCEL_MEDIA_COMMAND_PAUSE = 1; public const int PARCEL_MEDIA_COMMAND_PLAY = 2; public const int PARCEL_MEDIA_COMMAND_LOOP = 3; public const int PARCEL_MEDIA_COMMAND_TEXTURE = 4; public const int PARCEL_MEDIA_COMMAND_URL = 5; public const int PARCEL_MEDIA_COMMAND_TIME = 6; public const int PARCEL_MEDIA_COMMAND_AGENT = 7; public const int PARCEL_MEDIA_COMMAND_UNLOAD = 8; public const int PARCEL_MEDIA_COMMAND_AUTO_ALIGN = 9; public const int PARCEL_MEDIA_COMMAND_TYPE = 10; public const int PARCEL_MEDIA_COMMAND_SIZE = 11; public const int PARCEL_MEDIA_COMMAND_DESC = 12; public const int PARCEL_FLAG_ALLOW_FLY = 0x1; // parcel allows flying public const int PARCEL_FLAG_ALLOW_SCRIPTS = 0x2; // parcel allows outside scripts public const int PARCEL_FLAG_ALLOW_LANDMARK = 0x8; // parcel allows landmarks to be created public const int PARCEL_FLAG_ALLOW_TERRAFORM = 0x10; // parcel allows anyone to terraform the land public const int PARCEL_FLAG_ALLOW_DAMAGE = 0x20; // parcel allows damage public const int PARCEL_FLAG_ALLOW_CREATE_OBJECTS = 0x40; // parcel allows anyone to create objects public const int PARCEL_FLAG_USE_ACCESS_GROUP = 0x100; // parcel limits access to a group public const int PARCEL_FLAG_USE_ACCESS_LIST = 0x200; // parcel limits access to a list of residents public const int PARCEL_FLAG_USE_BAN_LIST = 0x400; // parcel uses a ban list, including restricting access based on payment info public const int PARCEL_FLAG_USE_LAND_PASS_LIST = 0x800; // parcel allows passes to be purchased public const int PARCEL_FLAG_LOCAL_SOUND_ONLY = 0x8000; // parcel restricts spatialized sound to the parcel public const int PARCEL_FLAG_RESTRICT_PUSHOBJECT = 0x200000; // parcel restricts llPushObject public const int PARCEL_FLAG_ALLOW_GROUP_SCRIPTS = 0x2000000; // parcel allows scripts owned by group public const int PARCEL_FLAG_ALLOW_CREATE_GROUP_OBJECTS = 0x4000000; // parcel allows group object creation public const int PARCEL_FLAG_ALLOW_ALL_OBJECT_ENTRY = 0x8000000; // parcel allows objects owned by any user to enter public const int PARCEL_FLAG_ALLOW_GROUP_OBJECT_ENTRY = 0x10000000; // parcel allows with the same group to enter public const int REGION_FLAG_ALLOW_DAMAGE = 0x1; // region is entirely damage enabled public const int REGION_FLAG_FIXED_SUN = 0x10; // region has a fixed sun position public const int REGION_FLAG_BLOCK_TERRAFORM = 0x40; // region terraforming disabled public const int REGION_FLAG_SANDBOX = 0x100; // region is a sandbox public const int REGION_FLAG_DISABLE_COLLISIONS = 0x1000; // region has disabled collisions public const int REGION_FLAG_DISABLE_PHYSICS = 0x4000; // region has disabled physics public const int REGION_FLAG_BLOCK_FLY = 0x80000; // region blocks flying public const int REGION_FLAG_ALLOW_DIRECT_TELEPORT = 0x100000; // region allows direct teleports public const int REGION_FLAG_RESTRICT_PUSHOBJECT = 0x400000; // region restricts llPushObject //llManageEstateAccess public const int ESTATE_ACCESS_ALLOWED_AGENT_ADD = 0; public const int ESTATE_ACCESS_ALLOWED_AGENT_REMOVE = 1; public const int ESTATE_ACCESS_ALLOWED_GROUP_ADD = 2; public const int ESTATE_ACCESS_ALLOWED_GROUP_REMOVE = 3; public const int ESTATE_ACCESS_BANNED_AGENT_ADD = 4; public const int ESTATE_ACCESS_BANNED_AGENT_REMOVE = 5; public static readonly LSLInteger PAY_HIDE = new LSLInteger(-1); public static readonly LSLInteger PAY_DEFAULT = new LSLInteger(-2); public const string NULL_KEY = "00000000-0000-0000-0000-000000000000"; public const string EOF = "\n\n\n"; public const double PI = 3.14159274f; public const double TWO_PI = 6.28318548f; public const double PI_BY_TWO = 1.57079637f; public const double DEG_TO_RAD = 0.01745329238f; public const double RAD_TO_DEG = 57.29578f; public const double SQRT2 = 1.414213538f; public const int STRING_TRIM_HEAD = 1; public const int STRING_TRIM_TAIL = 2; public const int STRING_TRIM = 3; public const int LIST_STAT_RANGE = 0; public const int LIST_STAT_MIN = 1; public const int LIST_STAT_MAX = 2; public const int LIST_STAT_MEAN = 3; public const int LIST_STAT_MEDIAN = 4; public const int LIST_STAT_STD_DEV = 5; public const int LIST_STAT_SUM = 6; public const int LIST_STAT_SUM_SQUARES = 7; public const int LIST_STAT_NUM_COUNT = 8; public const int LIST_STAT_GEOMETRIC_MEAN = 9; public const int LIST_STAT_HARMONIC_MEAN = 100; //ParcelPrim Categories public const int PARCEL_COUNT_TOTAL = 0; public const int PARCEL_COUNT_OWNER = 1; public const int PARCEL_COUNT_GROUP = 2; public const int PARCEL_COUNT_OTHER = 3; public const int PARCEL_COUNT_SELECTED = 4; public const int PARCEL_COUNT_TEMP = 5; public const int DEBUG_CHANNEL = 0x7FFFFFFF; public const int PUBLIC_CHANNEL = 0x00000000; // Constants for llGetObjectDetails public const int OBJECT_UNKNOWN_DETAIL = -1; public const int OBJECT_NAME = 1; public const int OBJECT_DESC = 2; public const int OBJECT_POS = 3; public const int OBJECT_ROT = 4; public const int OBJECT_VELOCITY = 5; public const int OBJECT_OWNER = 6; public const int OBJECT_GROUP = 7; public const int OBJECT_CREATOR = 8; public const int OBJECT_RUNNING_SCRIPT_COUNT = 9; public const int OBJECT_TOTAL_SCRIPT_COUNT = 10; public const int OBJECT_SCRIPT_MEMORY = 11; public const int OBJECT_SCRIPT_TIME = 12; public const int OBJECT_PRIM_EQUIVALENCE = 13; public const int OBJECT_SERVER_COST = 14; public const int OBJECT_STREAMING_COST = 15; public const int OBJECT_PHYSICS_COST = 16; public const int OBJECT_CHARACTER_TIME = 17; public const int OBJECT_ROOT = 18; public const int OBJECT_ATTACHED_POINT = 19; public const int OBJECT_PATHFINDING_TYPE = 20; public const int OBJECT_PHYSICS = 21; public const int OBJECT_PHANTOM = 22; public const int OBJECT_TEMP_ON_REZ = 23; // Pathfinding types public const int OPT_OTHER = -1; public const int OPT_LEGACY_LINKSET = 0; public const int OPT_AVATAR = 1; public const int OPT_CHARACTER = 2; public const int OPT_WALKABLE = 3; public const int OPT_STATIC_OBSTACLE = 4; public const int OPT_MATERIAL_VOLUME = 5; public const int OPT_EXCLUSION_VOLUME = 6; // for llGetAgentList public const int AGENT_LIST_PARCEL = 1; public const int AGENT_LIST_PARCEL_OWNER = 2; public const int AGENT_LIST_REGION = 4; // Can not be public const? public static readonly vector ZERO_VECTOR = new vector(0.0, 0.0, 0.0); public static readonly rotation ZERO_ROTATION = new rotation(0.0, 0.0, 0.0, 1.0); // constants for llSetCameraParams public const int CAMERA_PITCH = 0; public const int CAMERA_FOCUS_OFFSET = 1; public const int CAMERA_FOCUS_OFFSET_X = 2; public const int CAMERA_FOCUS_OFFSET_Y = 3; public const int CAMERA_FOCUS_OFFSET_Z = 4; public const int CAMERA_POSITION_LAG = 5; public const int CAMERA_FOCUS_LAG = 6; public const int CAMERA_DISTANCE = 7; public const int CAMERA_BEHINDNESS_ANGLE = 8; public const int CAMERA_BEHINDNESS_LAG = 9; public const int CAMERA_POSITION_THRESHOLD = 10; public const int CAMERA_FOCUS_THRESHOLD = 11; public const int CAMERA_ACTIVE = 12; public const int CAMERA_POSITION = 13; public const int CAMERA_POSITION_X = 14; public const int CAMERA_POSITION_Y = 15; public const int CAMERA_POSITION_Z = 16; public const int CAMERA_FOCUS = 17; public const int CAMERA_FOCUS_X = 18; public const int CAMERA_FOCUS_Y = 19; public const int CAMERA_FOCUS_Z = 20; public const int CAMERA_POSITION_LOCKED = 21; public const int CAMERA_FOCUS_LOCKED = 22; // constants for llGetParcelDetails public const int PARCEL_DETAILS_NAME = 0; public const int PARCEL_DETAILS_DESC = 1; public const int PARCEL_DETAILS_OWNER = 2; public const int PARCEL_DETAILS_GROUP = 3; public const int PARCEL_DETAILS_AREA = 4; public const int PARCEL_DETAILS_ID = 5; public const int PARCEL_DETAILS_SEE_AVATARS = 6; // not implemented //osSetParcelDetails public const int PARCEL_DETAILS_CLAIMDATE = 10; // constants for llSetClickAction public const int CLICK_ACTION_NONE = 0; public const int CLICK_ACTION_TOUCH = 0; public const int CLICK_ACTION_SIT = 1; public const int CLICK_ACTION_BUY = 2; public const int CLICK_ACTION_PAY = 3; public const int CLICK_ACTION_OPEN = 4; public const int CLICK_ACTION_PLAY = 5; public const int CLICK_ACTION_OPEN_MEDIA = 6; public const int CLICK_ACTION_ZOOM = 7; // constants for the llDetectedTouch* functions public const int TOUCH_INVALID_FACE = -1; public static readonly vector TOUCH_INVALID_TEXCOORD = new vector(-1.0, -1.0, 0.0); public static readonly vector TOUCH_INVALID_VECTOR = ZERO_VECTOR; // constants for llGetPrimMediaParams/llSetPrimMediaParams public const int PRIM_MEDIA_ALT_IMAGE_ENABLE = 0; public const int PRIM_MEDIA_CONTROLS = 1; public const int PRIM_MEDIA_CURRENT_URL = 2; public const int PRIM_MEDIA_HOME_URL = 3; public const int PRIM_MEDIA_AUTO_LOOP = 4; public const int PRIM_MEDIA_AUTO_PLAY = 5; public const int PRIM_MEDIA_AUTO_SCALE = 6; public const int PRIM_MEDIA_AUTO_ZOOM = 7; public const int PRIM_MEDIA_FIRST_CLICK_INTERACT = 8; public const int PRIM_MEDIA_WIDTH_PIXELS = 9; public const int PRIM_MEDIA_HEIGHT_PIXELS = 10; public const int PRIM_MEDIA_WHITELIST_ENABLE = 11; public const int PRIM_MEDIA_WHITELIST = 12; public const int PRIM_MEDIA_PERMS_INTERACT = 13; public const int PRIM_MEDIA_PERMS_CONTROL = 14; public const int PRIM_MEDIA_CONTROLS_STANDARD = 0; public const int PRIM_MEDIA_CONTROLS_MINI = 1; public const int PRIM_MEDIA_PERM_NONE = 0; public const int PRIM_MEDIA_PERM_OWNER = 1; public const int PRIM_MEDIA_PERM_GROUP = 2; public const int PRIM_MEDIA_PERM_ANYONE = 4; public const int PRIM_PHYSICS_SHAPE_TYPE = 30; public const int PRIM_PHYSICS_SHAPE_PRIM = 0; public const int PRIM_PHYSICS_SHAPE_CONVEX = 2; public const int PRIM_PHYSICS_SHAPE_NONE = 1; public const int PRIM_PHYSICS_MATERIAL = 31; public const int DENSITY = 1; public const int FRICTION = 2; public const int RESTITUTION = 4; public const int GRAVITY_MULTIPLIER = 8; // extra constants for llSetPrimMediaParams public static readonly LSLInteger LSL_STATUS_OK = new LSLInteger(0); public static readonly LSLInteger LSL_STATUS_MALFORMED_PARAMS = new LSLInteger(1000); public static readonly LSLInteger LSL_STATUS_TYPE_MISMATCH = new LSLInteger(1001); public static readonly LSLInteger LSL_STATUS_BOUNDS_ERROR = new LSLInteger(1002); public static readonly LSLInteger LSL_STATUS_NOT_FOUND = new LSLInteger(1003); public static readonly LSLInteger LSL_STATUS_NOT_SUPPORTED = new LSLInteger(1004); public static readonly LSLInteger LSL_STATUS_INTERNAL_ERROR = new LSLInteger(1999); public static readonly LSLInteger LSL_STATUS_WHITELIST_FAILED = new LSLInteger(2001); // Constants for default textures public const string TEXTURE_BLANK = "5748decc-f629-461c-9a36-a35a221fe21f"; public const string TEXTURE_DEFAULT = "89556747-24cb-43ed-920b-47caed15465f"; public const string TEXTURE_PLYWOOD = "89556747-24cb-43ed-920b-47caed15465f"; public const string TEXTURE_TRANSPARENT = "8dcd4a48-2d37-4909-9f78-f7a9eb4ef903"; public const string TEXTURE_MEDIA = "8b5fec65-8d8d-9dc5-cda8-8fdf2716e361"; // Constants for osGetRegionStats public const int STATS_TIME_DILATION = 0; public const int STATS_SIM_FPS = 1; public const int STATS_PHYSICS_FPS = 2; public const int STATS_AGENT_UPDATES = 3; public const int STATS_ROOT_AGENTS = 4; public const int STATS_CHILD_AGENTS = 5; public const int STATS_TOTAL_PRIMS = 6; public const int STATS_ACTIVE_PRIMS = 7; public const int STATS_FRAME_MS = 8; public const int STATS_NET_MS = 9; public const int STATS_PHYSICS_MS = 10; public const int STATS_IMAGE_MS = 11; public const int STATS_OTHER_MS = 12; public const int STATS_IN_PACKETS_PER_SECOND = 13; public const int STATS_OUT_PACKETS_PER_SECOND = 14; public const int STATS_UNACKED_BYTES = 15; public const int STATS_AGENT_MS = 16; public const int STATS_PENDING_DOWNLOADS = 17; public const int STATS_PENDING_UPLOADS = 18; public const int STATS_ACTIVE_SCRIPTS = 19; public const int STATS_SCRIPT_LPS = 20; // Constants for osNpc* functions public const int OS_NPC_FLY = 0; public const int OS_NPC_NO_FLY = 1; public const int OS_NPC_LAND_AT_TARGET = 2; public const int OS_NPC_RUNNING = 4; public const int OS_NPC_SIT_NOW = 0; public const int OS_NPC_CREATOR_OWNED = 0x1; public const int OS_NPC_NOT_OWNED = 0x2; public const int OS_NPC_SENSE_AS_AGENT = 0x4; public const string URL_REQUEST_GRANTED = "URL_REQUEST_GRANTED"; public const string URL_REQUEST_DENIED = "URL_REQUEST_DENIED"; public static readonly LSLInteger RC_REJECT_TYPES = 0; public static readonly LSLInteger RC_DETECT_PHANTOM = 1; public static readonly LSLInteger RC_DATA_FLAGS = 2; public static readonly LSLInteger RC_MAX_HITS = 3; public static readonly LSLInteger RC_REJECT_AGENTS = 1; public static readonly LSLInteger RC_REJECT_PHYSICAL = 2; public static readonly LSLInteger RC_REJECT_NONPHYSICAL = 4; public static readonly LSLInteger RC_REJECT_LAND = 8; public static readonly LSLInteger RC_GET_NORMAL = 1; public static readonly LSLInteger RC_GET_ROOT_KEY = 2; public static readonly LSLInteger RC_GET_LINK_NUM = 4; public static readonly LSLInteger RCERR_UNKNOWN = -1; public static readonly LSLInteger RCERR_SIM_PERF_LOW = -2; public static readonly LSLInteger RCERR_CAST_TIME_EXCEEDED = 3; public const int KFM_MODE = 1; public const int KFM_LOOP = 1; public const int KFM_REVERSE = 3; public const int KFM_FORWARD = 0; public const int KFM_PING_PONG = 2; public const int KFM_DATA = 2; public const int KFM_TRANSLATION = 2; public const int KFM_ROTATION = 1; public const int KFM_COMMAND = 0; public const int KFM_CMD_PLAY = 0; public const int KFM_CMD_STOP = 1; public const int KFM_CMD_PAUSE = 2; /// <summary> /// process name parameter as regex /// </summary> public const int OS_LISTEN_REGEX_NAME = 0x1; /// <summary> /// process message parameter as regex /// </summary> public const int OS_LISTEN_REGEX_MESSAGE = 0x2; } }
// 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.InteropServices; namespace System.Drawing.Drawing2D { public class CustomLineCap : MarshalByRefObject, ICloneable, IDisposable { #if FINALIZATION_WATCH private string allocationSite = Graphics.GetAllocationStack(); #endif // Handle to native line cap object internal SafeCustomLineCapHandle nativeCap = null; private bool _disposed = false; // For subclass creation internal CustomLineCap() { } public CustomLineCap(GraphicsPath fillPath, GraphicsPath strokePath) : this(fillPath, strokePath, LineCap.Flat) { } public CustomLineCap(GraphicsPath fillPath, GraphicsPath strokePath, LineCap baseCap) : this(fillPath, strokePath, baseCap, 0) { } public CustomLineCap(GraphicsPath fillPath, GraphicsPath strokePath, LineCap baseCap, float baseInset) { IntPtr nativeLineCap; int status = SafeNativeMethods.Gdip.GdipCreateCustomLineCap( new HandleRef(fillPath, (fillPath == null) ? IntPtr.Zero : fillPath.nativePath), new HandleRef(strokePath, (strokePath == null) ? IntPtr.Zero : strokePath.nativePath), baseCap, baseInset, out nativeLineCap); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); SetNativeLineCap(nativeLineCap); } internal CustomLineCap(IntPtr nativeLineCap) => SetNativeLineCap(nativeLineCap); internal void SetNativeLineCap(IntPtr handle) { if (handle == IntPtr.Zero) throw new ArgumentNullException("handle"); nativeCap = new SafeCustomLineCapHandle(handle); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_disposed) return; #if FINALIZATION_WATCH if (!disposing && nativeCap != null) Debug.WriteLine("**********************\nDisposed through finalization:\n" + allocationSite); #endif // propagate the explicit dispose call to the child if (disposing && nativeCap != null) { nativeCap.Dispose(); } _disposed = true; } ~CustomLineCap() => Dispose(false); public object Clone() { IntPtr clonedCap; int status = SafeNativeMethods.Gdip.GdipCloneCustomLineCap(new HandleRef(this, nativeCap), out clonedCap); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return CreateCustomLineCapObject(clonedCap); } internal static CustomLineCap CreateCustomLineCapObject(IntPtr cap) { int status = SafeNativeMethods.Gdip.GdipGetCustomLineCapType(new HandleRef(null, cap), out CustomLineCapType capType); if (status != SafeNativeMethods.Gdip.Ok) { SafeNativeMethods.Gdip.GdipDeleteCustomLineCap(new HandleRef(null, cap)); throw SafeNativeMethods.Gdip.StatusException(status); } switch (capType) { case CustomLineCapType.Default: return new CustomLineCap(cap); case CustomLineCapType.AdjustableArrowCap: return new AdjustableArrowCap(cap); } SafeNativeMethods.Gdip.GdipDeleteCustomLineCap(new HandleRef(null, cap)); throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.NotImplemented); } public void SetStrokeCaps(LineCap startCap, LineCap endCap) { int status = SafeNativeMethods.Gdip.GdipSetCustomLineCapStrokeCaps(new HandleRef(this, nativeCap), startCap, endCap); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } public void GetStrokeCaps(out LineCap startCap, out LineCap endCap) { int status = SafeNativeMethods.Gdip.GdipGetCustomLineCapStrokeCaps(new HandleRef(this, nativeCap), out startCap, out endCap); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } public LineJoin StrokeJoin { get { int status = SafeNativeMethods.Gdip.GdipGetCustomLineCapStrokeJoin(new HandleRef(this, nativeCap), out LineJoin lineJoin); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return lineJoin; } set { int status = SafeNativeMethods.Gdip.GdipSetCustomLineCapStrokeJoin(new HandleRef(this, nativeCap), value); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } } public LineCap BaseCap { get { int status = SafeNativeMethods.Gdip.GdipGetCustomLineCapBaseCap(new HandleRef(this, nativeCap), out LineCap baseCap); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return baseCap; } set { int status = SafeNativeMethods.Gdip.GdipSetCustomLineCapBaseCap(new HandleRef(this, nativeCap), value); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } } public float BaseInset { get { int status = SafeNativeMethods.Gdip.GdipGetCustomLineCapBaseInset(new HandleRef(this, nativeCap), out float inset); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return inset; } set { int status = SafeNativeMethods.Gdip.GdipSetCustomLineCapBaseInset(new HandleRef(this, nativeCap), value); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } } public float WidthScale { get { int status = SafeNativeMethods.Gdip.GdipGetCustomLineCapWidthScale(new HandleRef(this, nativeCap), out float widthScale); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return widthScale; } set { int status = SafeNativeMethods.Gdip.GdipSetCustomLineCapWidthScale(new HandleRef(this, nativeCap), value); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } } } }
using System; using System.Collections; using System.Diagnostics; namespace Amib.Threading.Internal { #region PriorityQueue class /// <summary> /// PriorityQueue class /// This class is not thread safe because we use external lock /// </summary> public sealed class PriorityQueue : IEnumerable { #region Private members /// <summary> /// The number of queues, there is one for each type of priority /// </summary> private const int _queuesCount = WorkItemPriority.Highest-WorkItemPriority.Lowest+1; /// <summary> /// Work items queues. There is one for each type of priority /// </summary> private readonly Queue [] _queues = new Queue[_queuesCount]; /// <summary> /// The total number of work items within the queues /// </summary> private int _workItemsCount; /// <summary> /// Use with IEnumerable interface /// </summary> private int _version; #endregion #region Contructor public PriorityQueue() { for(int i = 0; i < _queues.Length; ++i) { _queues[i] = new Queue(); } } #endregion #region Methods /// <summary> /// Enqueue a work item. /// </summary> /// <param name="workItem">A work item</param> public void Enqueue(IHasWorkItemPriority workItem) { Debug.Assert(null != workItem); int queueIndex = _queuesCount-(int)workItem.WorkItemPriority-1; Debug.Assert(queueIndex >= 0); Debug.Assert(queueIndex < _queuesCount); _queues[queueIndex].Enqueue(workItem); ++_workItemsCount; ++_version; } /// <summary> /// Dequeque a work item. /// </summary> /// <returns>Returns the next work item</returns> public IHasWorkItemPriority Dequeue() { IHasWorkItemPriority workItem = null; if(_workItemsCount > 0) { int queueIndex = GetNextNonEmptyQueue(-1); Debug.Assert(queueIndex >= 0); workItem = _queues[queueIndex].Dequeue() as IHasWorkItemPriority; Debug.Assert(null != workItem); --_workItemsCount; ++_version; } return workItem; } /// <summary> /// Find the next non empty queue starting at queue queueIndex+1 /// </summary> /// <param name="queueIndex">The index-1 to start from</param> /// <returns> /// The index of the next non empty queue or -1 if all the queues are empty /// </returns> private int GetNextNonEmptyQueue(int queueIndex) { for(int i = queueIndex+1; i < _queuesCount; ++i) { if(_queues[i].Count > 0) { return i; } } return -1; } /// <summary> /// The number of work items /// </summary> public int Count { get { return _workItemsCount; } } /// <summary> /// Clear all the work items /// </summary> public void Clear() { if (_workItemsCount > 0) { foreach(Queue queue in _queues) { queue.Clear(); } _workItemsCount = 0; ++_version; } } #endregion #region IEnumerable Members /// <summary> /// Returns an enumerator to iterate over the work items /// </summary> /// <returns>Returns an enumerator</returns> public IEnumerator GetEnumerator() { return new PriorityQueueEnumerator(this); } #endregion #region PriorityQueueEnumerator /// <summary> /// The class the implements the enumerator /// </summary> private class PriorityQueueEnumerator : IEnumerator { private readonly PriorityQueue _priorityQueue; private int _version; private int _queueIndex; private IEnumerator _enumerator; public PriorityQueueEnumerator(PriorityQueue priorityQueue) { _priorityQueue = priorityQueue; _version = _priorityQueue._version; _queueIndex = _priorityQueue.GetNextNonEmptyQueue(-1); if (_queueIndex >= 0) { _enumerator = _priorityQueue._queues[_queueIndex].GetEnumerator(); } else { _enumerator = null; } } #region IEnumerator Members public void Reset() { _version = _priorityQueue._version; _queueIndex = _priorityQueue.GetNextNonEmptyQueue(-1); if (_queueIndex >= 0) { _enumerator = _priorityQueue._queues[_queueIndex].GetEnumerator(); } else { _enumerator = null; } } public object Current { get { Debug.Assert(null != _enumerator); return _enumerator.Current; } } public bool MoveNext() { if (null == _enumerator) { return false; } if(_version != _priorityQueue._version) { throw new InvalidOperationException("The collection has been modified"); } if (!_enumerator.MoveNext()) { _queueIndex = _priorityQueue.GetNextNonEmptyQueue(_queueIndex); if(-1 == _queueIndex) { return false; } _enumerator = _priorityQueue._queues[_queueIndex].GetEnumerator(); _enumerator.MoveNext(); return true; } return true; } #endregion } #endregion } #endregion }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace CH10___Audio { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; // our sound objects AudioEngine m_audio; WaveBank m_wave; SoundBank m_sound; // sound categories AudioCategory m_catMusic; AudioCategory m_catDefault; // keep a reference to Zoe's story so we can pause and resume it Cue m_story; // texture rects for volume HUD Rectangle m_rectVolumeMusic = new Rectangle(0, 0, 32, 256); Rectangle m_rectVolumeSfx = new Rectangle(32, 0, 32, 256); // on-screen size and locations for volume HUD elements Vector2 m_v2HudMusic = new Vector2(100, 112); Vector2 m_v2HudSfx = new Vector2(508, 112); // the one and only game texture Texture2D m_Texture = null; // number of discrete volume steps public const float VOLUME_STEP = 0.01f; // background music volume private float m_MusicVolume = 1.0f; public float MusicVolume { get { return m_MusicVolume; } set { m_MusicVolume = MathHelper.Clamp(value, 0.0f, 1.0f); m_catMusic.SetVolume(m_MusicVolume); } } // laser and story volume private float m_GameVolume = 1.0f; public float GameVolume { get { return m_GameVolume; } set { m_GameVolume = MathHelper.Clamp(value, 0.0f, 1.0f); m_catDefault.SetVolume(m_GameVolume); } } public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { //// use a fixed frame rate of 30 frames per second //IsFixedTimeStep = true; //TargetElapsedTime = new TimeSpan(0, 0, 0, 0, 33); // run at full speed IsFixedTimeStep = false; // set screen size InitScreen(); // initialize our sound objects m_audio = new AudioEngine(@"Content\example.xgs"); m_wave = new WaveBank(m_audio, @"Content\example.xwb"); m_sound = new SoundBank(m_audio, @"Content\example.xsb"); // get a reference to our two sound categories m_catMusic = m_audio.GetCategory("Music"); m_catDefault = m_audio.GetCategory("Default"); // get a reference to Zoe's story m_story = m_sound.GetCue("zoe"); // start playing our background music m_sound.PlayCue("ensalada"); base.Initialize(); } // screen constants const int SCREEN_WIDTH = 640; const int SCREEN_HEIGHT = 480; // screen-related init tasks public void InitScreen() { // back buffer graphics.PreferredBackBufferHeight = SCREEN_HEIGHT; graphics.PreferredBackBufferWidth = SCREEN_WIDTH; graphics.PreferMultiSampling = false; graphics.ApplyChanges(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // load our game's only texture m_Texture = Content.Load<Texture2D>(@"media\game"); } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); // allow the Audio APIs to do their magic m_audio.Update(); // process player input GamePadState pad1 = GamePad.GetState(PlayerIndex.One); KeyboardState key1 = Keyboard.GetState(); m_PressDelay += gameTime.ElapsedGameTime.TotalSeconds; ProcessInput(pad1, key1); base.Update(gameTime); } private const double PRESS_DELAY = 0.25; private double m_PressDelay = PRESS_DELAY; public void ProcessInput(GamePadState pad1, KeyboardState key1) { // process music volume changes immediately, // don't worry about the PRESS_DELAY here. if (pad1.ThumbSticks.Left.Y < 0 || key1.IsKeyDown(Keys.Down)) { // decrease the volume of the music MusicVolume -= VOLUME_STEP; } else if (pad1.ThumbSticks.Left.Y > 0 || key1.IsKeyDown(Keys.Up)) { // increase the volume of the music MusicVolume += VOLUME_STEP; } // process game volume changes immediately, // don't worry about the PRESS_DELAY here. if (pad1.ThumbSticks.Right.Y < 0 || key1.IsKeyDown(Keys.PageDown)) { // decrease the volume of the laser and story GameVolume -= VOLUME_STEP; } else if (pad1.ThumbSticks.Right.Y > 0 || key1.IsKeyDown(Keys.PageUp)) { // increase the volume of the laser and story GameVolume += VOLUME_STEP; } // enforce delay before laser sound and playing // or pausing Zoe's story. without the delay, // we might register 2 or more presses before the // player can release the button. if (m_PressDelay >= PRESS_DELAY) { // assume that we will handle the button or key press bool PressWasHandled = true; if (pad1.Buttons.A == ButtonState.Pressed || key1.IsKeyDown(Keys.Space)) { // kick off a new instance of the laser cue m_sound.PlayCue("laser"); } else if (pad1.Buttons.B == ButtonState.Pressed || key1.IsKeyDown(Keys.Enter)) { // play or pause Zoe's story if (m_story.IsPaused) { // resume a prepared and paused cue m_story.Resume(); } else if (m_story.IsPlaying) { // pause a prepared and playing cue m_story.Pause(); } else if (m_story.IsPrepared) { // play a prepared cue m_story.Play(); } else { // prepare and play a stopped cue m_story = m_sound.GetCue("zoe"); m_story.Play(); } } else { // we did not handle this button or key press PressWasHandled = false; } if (PressWasHandled) { // reset delay counter m_PressDelay = 0; } } } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { if (m_PressDelay < 0.125) { // when a new butotn or key press is registered, // flash the screen graphics.GraphicsDevice.Clear(Color.Wheat); } else { // otherwise, show our familiar friend, CornflowerBlue graphics.GraphicsDevice.Clear(Color.CornflowerBlue); } spriteBatch.Begin(); // draw white music volume meter Rectangle rect = m_rectVolumeMusic; Vector2 loc = m_v2HudMusic; spriteBatch.Draw(m_Texture, loc, rect, Color.White); // draw green music volume meter rect.Height = (int)Math.Round(rect.Height * MusicVolume); loc.Y += m_rectVolumeMusic.Height - rect.Height; rect.Y = m_rectVolumeMusic.Height - rect.Height; spriteBatch.Draw(m_Texture, loc, rect, Color.Lime); // draw white game volume meter rect = m_rectVolumeSfx; loc = m_v2HudSfx; spriteBatch.Draw(m_Texture, loc, rect, Color.White); // draw green game volume meter rect.Height = (int)Math.Round(rect.Height * GameVolume); loc.Y += m_rectVolumeSfx.Height - rect.Height; rect.Y += m_rectVolumeSfx.Height - rect.Height; spriteBatch.Draw(m_Texture, loc, rect, Color.Lime); // if Zoe's story is playing, render blue meter if (m_story.IsPlaying && !m_story.IsStopped && !m_story.IsPaused) { spriteBatch.Draw(m_Texture, loc, rect, Color.RoyalBlue); } spriteBatch.End(); base.Draw(gameTime); } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.XWPF.UserModel { using System; using NPOI.OpenXml4Net.Exceptions; using NPOI.OpenXml4Net.OPC; using System.Collections.Generic; using NPOI.OpenXmlFormats.Wordprocessing; using System.IO; using System.Xml.Serialization; using System.Xml; /** * @author Philipp Epp * */ public class XWPFNumbering : POIXMLDocumentPart { protected List<XWPFAbstractNum> abstractNums = new List<XWPFAbstractNum>(); protected List<XWPFNum> nums = new List<XWPFNum>(); private CT_Numbering ctNumbering; bool isNew; /** *create a new styles object with an existing document */ public XWPFNumbering(PackagePart part, PackageRelationship rel) : base(part, rel) { isNew = true; } /** * create a new XWPFNumbering object for use in a new document */ public XWPFNumbering() { abstractNums = new List<XWPFAbstractNum>(); nums = new List<XWPFNum>(); isNew = true; } /** * read numbering form an existing package */ internal override void OnDocumentRead() { NumberingDocument numberingDoc = null; XmlDocument doc = ConvertStreamToXml(GetPackagePart().GetInputStream()); try { numberingDoc = NumberingDocument.Parse(doc, NamespaceManager); ctNumbering = numberingDoc.Numbering; //get any Nums foreach(CT_Num ctNum in ctNumbering.GetNumList()) { nums.Add(new XWPFNum(ctNum, this)); } foreach(CT_AbstractNum ctAbstractNum in ctNumbering.GetAbstractNumList()){ abstractNums.Add(new XWPFAbstractNum(ctAbstractNum, this)); } isNew = false; } catch (Exception e) { throw new POIXMLException(e); } } /** * save and Commit numbering */ protected override void Commit() { /*XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); xmlOptions.SaveSyntheticDocumentElement=(new QName(CTNumbering.type.Name.NamespaceURI, "numbering")); Dictionary<String,String> map = new Dictionary<String,String>(); map.Put("http://schemas.Openxmlformats.org/markup-compatibility/2006", "ve"); map.Put("urn:schemas-microsoft-com:office:office", "o"); map.Put("http://schemas.Openxmlformats.org/officeDocument/2006/relationships", "r"); map.Put("http://schemas.Openxmlformats.org/officeDocument/2006/math", "m"); map.Put("urn:schemas-microsoft-com:vml", "v"); map.Put("http://schemas.Openxmlformats.org/drawingml/2006/wordProcessingDrawing", "wp"); map.Put("urn:schemas-microsoft-com:office:word", "w10"); map.Put("http://schemas.Openxmlformats.org/wordProcessingml/2006/main", "w"); map.Put("http://schemas.microsoft.com/office/word/2006/wordml", "wne"); xmlOptions.SaveSuggestedPrefixes=(map);*/ PackagePart part = GetPackagePart(); Stream out1 = part.GetOutputStream(); NumberingDocument doc = new NumberingDocument(ctNumbering); //XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] { // new XmlQualifiedName("ve", "http://schemas.openxmlformats.org/markup-compatibility/2006"), // new XmlQualifiedName("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"), // new XmlQualifiedName("m", "http://schemas.openxmlformats.org/officeDocument/2006/math"), // new XmlQualifiedName("v", "urn:schemas-microsoft-com:vml"), // new XmlQualifiedName("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"), // new XmlQualifiedName("w10", "urn:schemas-microsoft-com:office:word"), // new XmlQualifiedName("wne", "http://schemas.microsoft.com/office/word/2006/wordml"), // new XmlQualifiedName("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main") // }); doc.Save(out1); out1.Close(); } /** * Sets the ctNumbering * @param numbering */ public void SetNumbering(CT_Numbering numbering) { ctNumbering = numbering; } /** * Checks whether number with numID exists * @param numID * @return bool true if num exist, false if num not exist */ public bool NumExist(string numID) { foreach (XWPFNum num in nums) { if (num.GetCTNum().numId.Equals(numID)) return true; } return false; } /** * add a new number to the numbering document * @param num */ public string AddNum(XWPFNum num){ ctNumbering.AddNewNum(); int pos = (ctNumbering.GetNumList().Count) - 1; ctNumbering.SetNumArray(pos, num.GetCTNum()); nums.Add(num); return num.GetCTNum().numId; } /** * Add a new num with an abstractNumID * @return return NumId of the Added num */ public string AddNum(string abstractNumID) { CT_Num ctNum = this.ctNumbering.AddNewNum(); ctNum.AddNewAbstractNumId(); ctNum.abstractNumId.val = (abstractNumID); ctNum.numId = (nums.Count + 1).ToString(); XWPFNum num = new XWPFNum(ctNum, this); nums.Add(num); return ctNum.numId; } /** * Add a new num with an abstractNumID and a numID * @param abstractNumID * @param numID */ public void AddNum(string abstractNumID, string numID) { CT_Num ctNum = this.ctNumbering.AddNewNum(); ctNum.AddNewAbstractNumId(); ctNum.abstractNumId.val = (abstractNumID); ctNum.numId = (numID); XWPFNum num = new XWPFNum(ctNum, this); nums.Add(num); } /** * Get Num by NumID * @param numID * @return abstractNum with NumId if no Num exists with that NumID * null will be returned */ public XWPFNum GetNum(string numID){ foreach(XWPFNum num in nums){ if(num.GetCTNum().numId.Equals(numID)) return num; } return null; } /** * Get AbstractNum by abstractNumID * @param abstractNumID * @return abstractNum with abstractNumId if no abstractNum exists with that abstractNumID * null will be returned */ public XWPFAbstractNum GetAbstractNum(string abstractNumID){ foreach(XWPFAbstractNum abstractNum in abstractNums){ if(abstractNum.GetAbstractNum().abstractNumId.Equals(abstractNumID)){ return abstractNum; } } return null; } /** * Compare AbstractNum with abstractNums of this numbering document. * If the content of abstractNum Equals with an abstractNum of the List in numbering * the Bigint Value of it will be returned. * If no equal abstractNum is existing null will be returned * * @param abstractNum * @return Bigint */ public string GetIdOfAbstractNum(XWPFAbstractNum abstractNum) { CT_AbstractNum copy = (CT_AbstractNum)abstractNum.GetCTAbstractNum().Copy(); XWPFAbstractNum newAbstractNum = new XWPFAbstractNum(copy, this); int i; for (i = 0; i < abstractNums.Count; i++) { newAbstractNum.GetCTAbstractNum().abstractNumId = i.ToString(); newAbstractNum.SetNumbering(this); if (newAbstractNum.GetCTAbstractNum().ValueEquals(abstractNums[i].GetCTAbstractNum())) { return newAbstractNum.GetCTAbstractNum().abstractNumId; } } return null; } /** * add a new AbstractNum and return its AbstractNumID * @param abstractNum */ public string AddAbstractNum(XWPFAbstractNum abstractNum) { int pos = abstractNums.Count; if (abstractNum.GetAbstractNum() != null) { // Use the current CTAbstractNum if it exists ctNumbering.AddNewAbstractNum().Set(abstractNum.GetAbstractNum()); } else { ctNumbering.AddNewAbstractNum(); abstractNum.GetAbstractNum().abstractNumId = pos.ToString(); ctNumbering.SetAbstractNumArray(pos, abstractNum.GetAbstractNum()); } abstractNums.Add(abstractNum); return abstractNum.GetAbstractNum().abstractNumId; } /// <summary> /// Add a new AbstractNum /// </summary> /// <returns></returns> /// @author antony liu public string AddAbstractNum() { CT_AbstractNum ctAbstractNum = ctNumbering.AddNewAbstractNum(); XWPFAbstractNum abstractNum = new XWPFAbstractNum(ctAbstractNum, this); abstractNum.AbstractNumId = abstractNums.Count.ToString(); abstractNum.MultiLevelType = MultiLevelType.HybridMultilevel; abstractNum.InitLvl(); abstractNums.Add(abstractNum); return abstractNum.GetAbstractNum().abstractNumId; } /** * remove an existing abstractNum * @param abstractNumID * @return true if abstractNum with abstractNumID exists in NumberingArray, * false if abstractNum with abstractNumID not exists */ public bool RemoveAbstractNum(string abstractNumID) { if (int.Parse(abstractNumID) < abstractNums.Count) { ctNumbering.RemoveAbstractNum(int.Parse(abstractNumID)); abstractNums.RemoveAt(int.Parse(abstractNumID)); return true; } return false; } /** *return the abstractNumID *If the AbstractNumID not exists *return null * @param numID * @return abstractNumID */ public string GetAbstractNumID(string numID) { XWPFNum num = GetNum(numID); if (num == null) return null; if (num.GetCTNum() == null) return null; if (num.GetCTNum().abstractNumId == null) return null; return num.GetCTNum().abstractNumId.val; } } }
// 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.Convention; using System.Composition.Debugging; using System.Composition.Hosting.Core; using System.Composition.TypedParts; using System.Composition.TypedParts.Util; using System.Diagnostics; using System.Linq; using System.Reflection; namespace System.Composition.Hosting { /// <summary> /// Configures and constructs a lightweight container. /// </summary> [DebuggerTypeProxy(typeof(ContainerConfigurationDebuggerProxy))] public class ContainerConfiguration { private AttributedModelProvider _defaultAttributeContext; private readonly IList<ExportDescriptorProvider> _addedSources = new List<ExportDescriptorProvider>(); private readonly IList<Tuple<IEnumerable<Type>, AttributedModelProvider>> _types = new List<Tuple<IEnumerable<Type>, AttributedModelProvider>>(); /// <summary> /// Create the container. The value returned from this method provides /// the exports in the container, as well as a means to dispose the container. /// </summary> /// <returns>The container.</returns> public CompositionHost CreateContainer() { var providers = _addedSources.ToList(); foreach (var typeSet in _types) { var ac = typeSet.Item2 ?? _defaultAttributeContext ?? new DirectAttributeContext(); providers.Add(new TypedPartExportDescriptorProvider(typeSet.Item1, ac)); } return CompositionHost.CreateCompositionHost(providers.ToArray()); } /// <summary> /// Add an export descriptor provider to the container. /// </summary> /// <param name="exportDescriptorProvider">An export descriptor provider.</param> /// <returns>A configuration object allowing configuration to continue.</returns> public ContainerConfiguration WithProvider(ExportDescriptorProvider exportDescriptorProvider) { if (exportDescriptorProvider == null) throw new ArgumentNullException("ExportDescriptorProvider"); _addedSources.Add(exportDescriptorProvider); return this; } /// <summary> /// Add conventions defined using a <see cref="AttributedModelProvider"/> to the container. /// These will be used as the default conventions; types and assemblies added with a /// specific convention will use their own. /// </summary> /// <param name="conventions"></param> /// <returns>A configuration object allowing configuration to continue.</returns> public ContainerConfiguration WithDefaultConventions(AttributedModelProvider conventions) { if (conventions == null) throw new ArgumentNullException("conventions"); if (_defaultAttributeContext != null) throw new InvalidOperationException(System.Composition.Properties.Resources.ContainerConfiguration_DefaultConventionSet); _defaultAttributeContext = conventions; return this; } /// <summary> /// Add a part type to the container. If the part type does not have any exports it /// will be ignored. /// </summary> /// <param name="partType">The part type.</param> /// <returns>A configuration object allowing configuration to continue.</returns> public ContainerConfiguration WithPart(Type partType) { return WithPart(partType, null); } /// <summary> /// Add a part type to the container. If the part type does not have any exports it /// will be ignored. /// </summary> /// <param name="partType">The part type.</param> /// <param name="conventions">Conventions represented by a <see cref="AttributedModelProvider"/>, or null.</param> /// <returns>A configuration object allowing configuration to continue.</returns> public ContainerConfiguration WithPart(Type partType, AttributedModelProvider conventions) { if (partType == null) throw new ArgumentNullException("partType"); return WithParts(new[] { partType }, conventions); } /// <summary> /// Add a part type to the container. If the part type does not have any exports it /// will be ignored. /// </summary> /// <typeparam name="TPart">The part type.</typeparam> /// <returns>A configuration object allowing configuration to continue.</returns> public ContainerConfiguration WithPart<TPart>() { return WithPart<TPart>(null); } /// <summary> /// Add a part type to the container. If the part type does not have any exports it /// will be ignored. /// </summary> /// <typeparam name="TPart">The part type.</typeparam> /// <param name="conventions">Conventions represented by a <see cref="AttributedModelProvider"/>, or null.</param> /// <returns>A configuration object allowing configuration to continue.</returns> public ContainerConfiguration WithPart<TPart>(AttributedModelProvider conventions) { return WithPart(typeof(TPart), conventions); } /// <summary> /// Add part types to the container. If a part type does not have any exports it /// will be ignored. /// </summary> /// <param name="partTypes">The part types.</param> /// <returns>A configuration object allowing configuration to continue.</returns> public ContainerConfiguration WithParts(params Type[] partTypes) { return WithParts((IEnumerable<Type>)partTypes); } /// <summary> /// Add part types to the container. If a part type does not have any exports it /// will be ignored. /// </summary> /// <param name="partTypes">The part types.</param> /// <returns>A configuration object allowing configuration to continue.</returns> public ContainerConfiguration WithParts(IEnumerable<Type> partTypes) { return WithParts(partTypes, null); } /// <summary> /// Add part types to the container. If a part type does not have any exports it /// will be ignored. /// </summary> /// <param name="partTypes">The part types.</param> /// <param name="conventions">Conventions represented by a <see cref="AttributedModelProvider"/>, or null.</param> /// <returns>A configuration object allowing configuration to continue.</returns> public ContainerConfiguration WithParts(IEnumerable<Type> partTypes, AttributedModelProvider conventions) { if (partTypes == null) throw new ArgumentNullException("partTypes"); _types.Add(Tuple.Create(partTypes, conventions)); return this; } /// <summary> /// Add part types from an assembly to the container. If a part type does not have any exports it /// will be ignored. /// </summary> /// <param name="assembly">The assembly from which to add part types.</param> /// <returns>A configuration object allowing configuration to continue.</returns> public ContainerConfiguration WithAssembly(Assembly assembly) { return WithAssembly(assembly, null); } /// <summary> /// Add part types from an assembly to the container. If a part type does not have any exports it /// will be ignored. /// </summary> /// <param name="assembly">The assembly from which to add part types.</param> /// <param name="conventions">Conventions represented by a <see cref="AttributedModelProvider"/>, or null.</param> /// <returns>A configuration object allowing configuration to continue.</returns> public ContainerConfiguration WithAssembly(Assembly assembly, AttributedModelProvider conventions) { return WithAssemblies(new[] { assembly }, conventions); } /// <summary> /// Add part types from a list of assemblies to the container. If a part type does not have any exports it /// will be ignored. /// </summary> /// <param name="assemblies">Assemblies containing part types.</param> /// <returns>A configuration object allowing configuration to continue.</returns> public ContainerConfiguration WithAssemblies(IEnumerable<Assembly> assemblies) { return WithAssemblies(assemblies, null); } /// <summary> /// Add part types from a list of assemblies to the container. If a part type does not have any exports it /// will be ignored. /// </summary> /// <param name="assemblies">Assemblies containing part types.</param> /// <param name="conventions">Conventions represented by a <see cref="AttributedModelProvider"/>, or null.</param> /// <returns>A configuration object allowing configuration to continue.</returns> public ContainerConfiguration WithAssemblies(IEnumerable<Assembly> assemblies, AttributedModelProvider conventions) { if (assemblies == null) throw new ArgumentNullException("assemblies"); return WithParts(assemblies.SelectMany(a => a.DefinedTypes.Select(dt => dt.AsType())), conventions); } internal ExportDescriptorProvider[] DebugGetAddedExportDescriptorProviders() { return _addedSources.ToArray(); } internal Tuple<IEnumerable<Type>, AttributedModelProvider>[] DebugGetRegisteredTypes() { return _types.ToArray(); } internal AttributedModelProvider DebugGetDefaultAttributeContext() { return _defaultAttributeContext; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using Xunit; namespace System.IO.Tests { public class FileStream_ctor_str_fm : FileSystemTest { protected virtual FileStream CreateFileStream(string path, FileMode mode) { return new FileStream(path, mode); } [Fact] public void NullPathThrows() { Assert.Throws<ArgumentNullException>(() => CreateFileStream(null, FileMode.Open)); } [Fact] public void EmptyPathThrows() { Assert.Throws<ArgumentException>(() => CreateFileStream(String.Empty, FileMode.Open)); } [Fact] public void DirectoryThrows() { Assert.Throws<UnauthorizedAccessException>(() => CreateFileStream(".", FileMode.Open)); } [Fact] public void InvalidModeThrows() { AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", () => CreateFileStream(GetTestFilePath(), ~FileMode.Open)); } [Fact] public void FileModeCreate() { using (CreateFileStream(GetTestFilePath(), FileMode.Create)) { } } [Fact] public void FileModeCreateExisting() { string fileName = GetTestFilePath(); using (FileStream fs = CreateFileStream(fileName, FileMode.Create)) { fs.WriteByte(0); } using (FileStream fs = CreateFileStream(fileName, FileMode.Create)) { // Ensure that the file was re-created Assert.Equal(0L, fs.Length); Assert.Equal(0L, fs.Position); Assert.True(fs.CanRead); Assert.True(fs.CanWrite); } } [Fact] public void FileModeCreateNew() { using (CreateFileStream(GetTestFilePath(), FileMode.CreateNew)) { } } [Fact] public void FileModeCreateNewExistingThrows() { string fileName = GetTestFilePath(); using (FileStream fs = CreateFileStream(fileName, FileMode.CreateNew)) { fs.WriteByte(0); Assert.True(fs.CanRead); Assert.True(fs.CanWrite); } Assert.Throws<IOException>(() => CreateFileStream(fileName, FileMode.CreateNew)); } [Fact] public void FileModeOpenThrows() { string fileName = GetTestFilePath(); FileNotFoundException fnfe = Assert.Throws<FileNotFoundException>(() => CreateFileStream(fileName, FileMode.Open)); Assert.Equal(fileName, fnfe.FileName); } [Fact] public void FileModeOpenExisting() { string fileName = GetTestFilePath(); using (FileStream fs = CreateFileStream(fileName, FileMode.Create)) { fs.WriteByte(0); } using (FileStream fs = CreateFileStream(fileName, FileMode.Open)) { // Ensure that the file was re-opened Assert.Equal(1L, fs.Length); Assert.Equal(0L, fs.Position); Assert.True(fs.CanRead); Assert.True(fs.CanWrite); } } [Fact] public void FileModeOpenOrCreate() { using (CreateFileStream(GetTestFilePath(), FileMode.OpenOrCreate)) {} } [Fact] public void FileModeOpenOrCreateExisting() { string fileName = GetTestFilePath(); using (FileStream fs = CreateFileStream(fileName, FileMode.Create)) { fs.WriteByte(0); } using (FileStream fs = CreateFileStream(fileName, FileMode.OpenOrCreate)) { // Ensure that the file was re-opened Assert.Equal(1L, fs.Length); Assert.Equal(0L, fs.Position); Assert.True(fs.CanRead); Assert.True(fs.CanWrite); } } [Fact] public void FileModeTruncateThrows() { string fileName = GetTestFilePath(); FileNotFoundException fnfe = Assert.Throws<FileNotFoundException>(() => CreateFileStream(fileName, FileMode.Truncate)); Assert.Equal(fileName, fnfe.FileName); } [Fact] public void FileModeTruncateExisting() { string fileName = GetTestFilePath(); using (FileStream fs = CreateFileStream(fileName, FileMode.Create)) { fs.WriteByte(0); } using (FileStream fs = CreateFileStream(fileName, FileMode.Truncate)) { // Ensure that the file was re-opened and truncated Assert.Equal(0L, fs.Length); Assert.Equal(0L, fs.Position); Assert.True(fs.CanRead); Assert.True(fs.CanWrite); } } [Fact] public virtual void FileModeAppend() { using (FileStream fs = CreateFileStream(GetTestFilePath(), FileMode.Append)) { Assert.Equal(false, fs.CanRead); Assert.Equal(true, fs.CanWrite); } } [Fact] public virtual void FileModeAppendExisting() { string fileName = GetTestFilePath(); using (FileStream fs = CreateFileStream(fileName, FileMode.Create)) { fs.WriteByte(0); } using (FileStream fs = CreateFileStream(fileName, FileMode.Append)) { // Ensure that the file was re-opened and position set to end Assert.Equal(1L, fs.Length); Assert.Equal(1L, fs.Position); Assert.False(fs.CanRead); Assert.True(fs.CanSeek); Assert.True(fs.CanWrite); Assert.Throws<IOException>(() => fs.Seek(-1, SeekOrigin.Current)); Assert.Throws<NotSupportedException>(() => fs.ReadByte()); } } } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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. //----------------------------------------------------------------------------- function GuiInspectorEntityGroup::CreateContent(%this) { } function GuiInspectorEntityGroup::InspectObject( %this, %targetObject ) { %this.stack.clear(); %this.stack.addGuiControl(%this.createAddComponentList()); } function GuiInspectorEntityGroup::createAddComponentList(%this) { %extent = %this.getExtent(); %container = new GuiControl() { Profile = "EditorContainerProfile"; HorizSizing = "width"; VertSizing = "bottom"; Position = "0 0"; Extent = %extent.x SPC "25"; }; %componentList = new GuiPopUpMenuCtrlEx(QuickEditComponentList) { Profile = "GuiPopupMenuProfile"; HorizSizing = "width"; VertSizing = "bottom"; position = "28 4"; Extent = (%extent.x - 28) SPC "18"; hovertime = "100"; tooltip = "The component to add to the object"; tooltipProfile = "EditorToolTipProfile"; }; %addButton = new GuiIconButtonCtrl() { class = AddComponentQuickEditButton; Profile = "EditorButton"; HorizSizing = "right"; VertSizing = "bottom"; Position = "2 0"; Extent = "24 24"; buttonMargin = "4 4"; iconLocation = "Left"; sizeIconToButton = "0"; iconBitmap = "tools/gui/images/iconAdd.png"; hovertime = "100"; tooltip = "Add the selected component to the object"; tooltipProfile = "EditorToolTipProfile"; componentList = %componentList; }; %componentList.refresh(); %container.add(%componentList); %container.add(%addButton); if(!isObject("componentTooltipTheme")) { %theme = createsupertooltiptheme("componentTooltipTheme"); %theme.addstyle("headerstyle", "<just:left><font:arial bold:16><color:000000>"); %theme.addstyle("headertwostyle", "<font:arial bold:14><color:000000>"); %theme.addstyle("basictextstyle", "<font:arial:14><color:000000>"); %theme.setdefaultstyle("title", "headerstyle"); %theme.setdefaultstyle("paramtitle", "headertwostyle"); %theme.setdefaultstyle("param", "basictextstyle"); %theme.setspacing(3, 0); } return %container; } function QuickEditComponentList::refresh(%this) { %this.clear(); //find all ComponentAssets %assetQuery = new AssetQuery(); if(!AssetDatabase.findAssetType(%assetQuery, "ComponentAsset")) return; //if we didn't find ANY, just exit // Find all the types. %count = %assetQuery.getCount(); %categories = ""; for (%i = 0; %i < %count; %i++) { %assetId = %assetQuery.getAsset(%i); %componentAsset = AssetDatabase.acquireAsset(%assetId); %componentType = %componentAsset.componentType; if (!isInList(%componentType, %categories)) %categories = %categories TAB %componentType; } %categories = trim(%categories); %index = 0; %categoryCount = getFieldCount(%categories); for (%i = 0; %i < %categoryCount; %i++) { %category = getField(%categories, %i); %this.addCategory(%category); for (%j = 0; %j < %count; %j++) { %assetId = %assetQuery.getAsset(%j); %componentAsset = AssetDatabase.acquireAsset(%assetId); %componentType = %componentAsset.componentType; %friendlyName = %componentAsset.friendlyName; if (%componentType $= %category) { //TODO: Haven't worked out getting categories to look distinct //from entries in the drop-down so for now just indent them for the visual distinction %spacedName = " " @ %friendlyName; %this.add(%spacedName, %index); %this.component[%index] = %componentAsset; %index++; } } } } function QuickEditComponentList::onHotTrackItem( %this, %itemID ) { %componentObj = %this.component[%itemID]; if( isObject( %componentObj ) && %this.componentDesc != %componentObj ) { SuperTooltipDlg.init("componentTooltipTheme"); SuperTooltipDlg.setTitle(%componentObj.friendlyName); SuperTooltipDlg.addParam("", %componentObj.description @ "\n"); /*%fieldCount = %componentObj.getComponentFieldCount(); for (%i = 0; %i < %fieldCount; %i++) { %name = getField(%componentObj.getComponentField(%i), 0); SuperTooltipDlg.addParam(%name, %description @ "\n"); }*/ %position = %this.getGlobalPosition(); SuperTooltipDlg.processTooltip( %position,0,1 ); %this.opened = true; %this.componentDesc = %componentObj; } else if( !isObject( %componentObj ) ) { if( %this.opened == true ) SuperTooltipDlg.hide(); %this.componentDesc = ""; } } function QuickEditComponentList::setProperty(%this, %object) { %this.objectToAdd = %object; } function QuickEditComponentList::onSelect(%this) { if( %this.opened == true ) SuperTooltipDlg.hide(); %this.componentToAdd = %this.component[%this.getSelected()]; } function QuickEditComponentList::onCancel( %this ) { if( %this.opened == true ) SuperTooltipDlg.hide(); } function AddComponentQuickEditButton::onClick(%this) { %component = %this.componentList.componentToAdd; %componentName = %this.componentList.componentToAdd.componentName; %componentClass = %this.componentList.componentToAdd.componentClass; %command = "$ComponentEditor::newComponent = new" SPC %componentClass SPC "(){ class = \"" @ %componentName @ "\"; };"; eval(%command); %instance = $ComponentEditor::newComponent; %undo = new UndoScriptAction() { actionName = "Added Component"; class = UndoAddComponent; object = %this.componentList.objectToAdd; component = %instance; }; %undo.addToManager(LevelBuilderUndoManager); %instance.owner = Inspector.getInspectObject(0); %instance.owner.add(%instance); schedule( 50, 0, "refreshInspector", Inspector.getInspectObject(0) ); EWorldEditor.isDirty = true; } function addComponent(%obj, %instance) { echo("Adding the component!"); %obj.addComponent(%instance); //Inspector.schedule( 50, "refresh" ); schedule( 50, 0, "refreshInspector", Inspector.getInspectObject(0) ); EWorldEditor.isDirty = true; } function refreshInspector(%entity) { inspector.removeInspect(%entity); inspector.addInspect(%entity); } function GuiInspectorComponentGroup::onConstructComponentField(%this, %component, %fieldName) { //echo("Tried to make a component field for component:" @ %component @ " for the " @ %fieldName @ " field."); %fieldType = %component.getComponentFieldType(%fieldName); %makeCommand = %this @ ".build" @ %fieldType @ "Field("@ %component @ "," @ %fieldName @ ");"; eval(%makeCommand); } function GuiInspectorComponentGroup::onRightMouseUp(%this, %point) { if( !isObject( InspectComponentPopup ) ) new PopupMenu( InspectComponentPopup ) { superClass = "MenuBuilder"; isPopup = true; item[ 0 ] = "View in Asset Browser" TAB "" TAB "AssetBrowser.editAsset();"; item[ 1 ] = "Delete Component" TAB "" TAB "schedule(10, 0, ComponentEditorRemoveComponent, InspectComponentPopup.componentOwner, InspectComponentPopup.component);"; item[ 2 ] = "Edit Script" TAB "" TAB "AssetBrowser.editAsset();"; item[ 3 ] = ""; }; %comp = %this.getComponent(); InspectComponentPopup.componentOwner = %comp.owner; InspectComponentPopup.component = %comp; //Find out our asset! %componentName = %this.caption; %assetQuery = new AssetQuery(); if(!AssetDatabase.findAssetType(%assetQuery, "ComponentAsset")) return; //if we didn't find ANY, just exit EditAssetPopup.assetId = ""; // Find all the types. %count = %assetQuery.getCount(); %categories = ""; for (%i = 0; %i < %count; %i++) { %assetId = %assetQuery.getAsset(%i); %componentAsset = AssetDatabase.acquireAsset(%assetId); %friendlyName = %componentAsset.friendlyName; if(%friendlyName !$= "" && %friendlyName $= %componentName) { EditAssetPopup.assetId = %assetId; break; } %compName = %componentAsset.componentName; if(%compName !$= "" && %compName $= %componentName) { EditAssetPopup.assetId = %assetId; break; } } if(EditAssetPopup.assetId $= "") { //didn't find it InspectComponentPopup.enableItem(0, false); InspectComponentPopup.enableItem(2, false); } else { InspectComponentPopup.enableItem(0, true); InspectComponentPopup.enableItem(2, true); } InspectComponentPopup.showPopup(Canvas); } function ComponentEditorRemoveComponent(%entity, %component) { %entity.removeComponent(%component, true); inspector.removeInspect(%entity); inspector.addInspect(%entity); }
using System; using System.Drawing; using UIKit; using Foundation; using CoreGraphics; using RectangleF = CoreGraphics.CGRect; using SizeF = CoreGraphics.CGSize; using PointF = CoreGraphics.CGPoint; namespace SidebarNavigation { public class SidebarController : UIViewController { protected readonly Sidebar _sidebar; /// <summary> /// Required contructor. /// </summary> public SidebarController(IntPtr handle) : base(handle) { } /// <summary> /// Contructor. /// </summary> /// <param name="rootViewController"> /// The view controller that the Sidebar is being added to. /// </param> /// <param name="contentViewController"> /// The view controller for the content area. /// </param> /// <param name="menuViewController"> /// The view controller for the side menu. /// </param> public SidebarController( UIViewController rootViewController, UIViewController contentViewController, UIViewController menuViewController) { _sidebar = new Sidebar(rootViewController, contentViewController, menuViewController); _sidebar.StateChangeHandler += (sender, e) => { if (StateChangeHandler != null) StateChangeHandler.Invoke(sender, e); }; ChangeMenuView(menuViewController); ChangeContentView(contentViewController); AttachSidebarControllerToRootController(rootViewController); } /// <summary> /// This Event will be called when the Sidebar menu is Opened/Closed (at the end of the animation). /// The Event Arg is a Boolean = isOpen. /// </summary> public event EventHandler<bool> StateChangeHandler; /// <summary> /// The view controller shown in the content area. /// </summary> public virtual UIViewController ContentAreaController { get { return _sidebar.ContentViewController; } } /// <summary> /// The view controller for the side menu. /// This is what will be shown when the menu is displayed. /// </summary> public virtual UIViewController MenuAreaController { get { return _sidebar.MenuViewController; } } /// <summary> /// Exposes the underlying sidebar object /// </summary> public virtual Sidebar Sidebar => _sidebar; /// <summary> /// Determines the percent of width to complete slide action. /// </summary> public float FlingPercentage { get { return _sidebar.FlingPercentage; } set { _sidebar.FlingPercentage = value; } } /// <summary> /// Determines the minimum velocity considered a "fling" to complete slide action. /// </summary> public float FlingVelocity { get { return _sidebar.FlingVelocity; } set { _sidebar.FlingVelocity = value; } } /// <summary> /// Active area where the Pan gesture is intercepted. /// </summary> public float GestureActiveArea { get { return _sidebar.GestureActiveArea; } set { _sidebar.GestureActiveArea = value; } } /// <summary> /// Gets or sets a value indicating whether there should be shadowing effects on the content view. /// </summary> public bool HasShadowing { get { return _sidebar.HasShadowing; } set { _sidebar.HasShadowing = value; } } /// <summary> /// Gets or sets the shadow opacity. /// </summary> public float ShadowOpacity { get { return _sidebar.ShadowOpacity; } set { _sidebar.ShadowOpacity = value; } } /// <summary> /// Gets or sets the color of the shadow. /// </summary> public UIColor ShadowColor { get { return _sidebar.ShadowColor; } set { _sidebar.ShadowColor = value; } } /// <summary> /// Gets or sets the shadow radius. /// </summary> /// <value>The shadow radius.</value> public float ShadowRadius { get { return _sidebar.ShadowRadius; } set { _sidebar.ShadowRadius = value; } } /// <summary> /// Gets or sets a value indicating whether there should be a dark overlay effect on the content view. /// </summary> public bool HasDarkOverlay { get { return _sidebar.HasDarkOverlay; } set { _sidebar.HasDarkOverlay = value; } } /// <summary> /// Gets or sets a value indicating the dark overlay alpha. /// </summary> public float DarkOverlayAlpha { get { return _sidebar.DarkOverlayAlpha; } set { _sidebar.DarkOverlayAlpha = value; } } /// <summary> /// Determines if the menu should be reopened after the screen is roated. /// </summary> public bool ReopenOnRotate { get { return _sidebar.ReopenOnRotate; } set { _sidebar.ReopenOnRotate = value; } } /// <summary> /// Determines the width of the menu when open. /// </summary> public int MenuWidth { get { return _sidebar.MenuWidth; } set { _sidebar.MenuWidth = value; } } /// <summary> /// Determines if the menu is on the left or right of the screen. /// </summary> public MenuLocations MenuLocation { get { return _sidebar.MenuLocation; } set { _sidebar.MenuLocation = value; } } /// <summary> /// Disables all open/close actions when set to true. /// </summary> public bool Disabled { get { return _sidebar.Disabled; } set { _sidebar.Disabled = value; } } /// <summary> /// Gets or sets a value indicating whether the pan gesture is disabled. /// </summary> public bool DisablePanGesture { get { return _sidebar.DisablePanGesture; } set { _sidebar.DisablePanGesture = value; } } /// <summary> /// Gets the current state of the menu. /// Setting this property will open/close the menu respectively. /// </summary> public virtual bool IsOpen { get { return _sidebar.IsOpen; } set { _sidebar.IsOpen = value; if (_sidebar.IsOpen) CloseMenu(); else OpenMenu(); } } /// <summary> /// Toggles the menu open or closed. /// </summary> public virtual void ToggleMenu() { if (IsOpen) _sidebar.CloseMenu(); else _sidebar.OpenMenu(); } /// <summary> /// Shows the slideout navigation menu. /// </summary> public virtual void OpenMenu() { _sidebar.OpenMenu(); } /// <summary> /// Hides the slideout navigation menu. /// </summary> public virtual void CloseMenu(bool animate = true) { _sidebar.CloseMenu(animate); } /// <summary> /// Replaces the content area view controller with the specified view controller. /// </summary> /// <param name="newContentView"> /// New content view. /// </param> public virtual void ChangeContentView(UIViewController newContentView) { _sidebar.ChangeContentView(newContentView); AddContentViewToSidebar(); CloseMenu(); } /// <summary> /// Replaces the menu area view controller with the specified view controller. /// </summary> /// <param name="newMenuView"> /// New menu view. /// </param> public virtual void ChangeMenuView(UIViewController newMenuView) { _sidebar.ChangeMenuView(newMenuView); AddMenuViewToSidebar(); } protected virtual void AddContentViewToSidebar() { SetContentViewBounds(); SetContentViewPosition(); View.AddSubview(ContentAreaController.View); AddChildViewController(ContentAreaController); } protected virtual void SetContentViewBounds() { var sidebarBounds = View.Bounds; if (ContentAreaController.View.Bounds.Equals(sidebarBounds)) return; ContentAreaController.View.Bounds = sidebarBounds; } protected virtual void SetContentViewPosition() { var sidebarBounds = View.Bounds; if (IsOpen) sidebarBounds.X = MenuWidth; ContentAreaController.View.Layer.AnchorPoint = new PointF(.5f, .5f); if (ContentAreaController.View.Frame.Location.Equals(sidebarBounds.Location)) return; var sidebarCenter = new PointF(sidebarBounds.Left + sidebarBounds.Width / 2, sidebarBounds.Top + sidebarBounds.Height / 2); ContentAreaController.View.Center = sidebarCenter; } protected virtual void AddMenuViewToSidebar() { SetMenuViewPosition(); View.AddSubview(MenuAreaController.View); View.SendSubviewToBack(MenuAreaController.View); } protected virtual void SetMenuViewPosition() { var menuFrame = MenuAreaController.View.Frame; menuFrame.X = MenuLocation == MenuLocations.Left ? 0 : View.Frame.Width - MenuWidth; menuFrame.Width = MenuWidth; menuFrame.Height = View.Frame.Height; MenuAreaController.View.Frame = menuFrame; } protected virtual void AttachSidebarControllerToRootController(UIViewController rootViewController) { rootViewController.AddChildViewController(this); rootViewController.View.AddSubview(this.View); this.DidMoveToParentViewController(rootViewController); } /// <summary> /// Ensures that the menu view gets properly positioned. /// </summary> public override void ViewDidLayoutSubviews() { base.ViewDidLayoutSubviews(); SetMenuViewPosition(); } /// <summary> /// Ensures that the menu view gets properly positioned. /// </summary> public override void ViewWillAppear(bool animated) { View.SetNeedsLayout(); base.ViewWillAppear(animated); } protected bool _openWhenRotated = false; /// <summary> /// Overridden to handle reopening the menu after rotation. /// </summary> public override void WillRotate(UIInterfaceOrientation toInterfaceOrientation, double duration) { base.WillRotate(toInterfaceOrientation, duration); if (IsOpen) _openWhenRotated = true; _sidebar.CloseMenu(false); } /// <summary> /// Overridden to handle reopening the menu after rotation. /// </summary> public override void DidRotate(UIInterfaceOrientation fromInterfaceOrientation) { base.DidRotate(fromInterfaceOrientation); if (_openWhenRotated && ReopenOnRotate) _sidebar.OpenMenu(); _openWhenRotated = false; } } }
// 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 0.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.DevTestLabs { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure.OData; using Microsoft.Rest.Azure; using Models; /// <summary> /// PolicyOperations operations. /// </summary> internal partial class PolicyOperations : IServiceOperations<DevTestLabsClient>, IPolicyOperations { /// <summary> /// Initializes a new instance of the PolicyOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal PolicyOperations(DevTestLabsClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the DevTestLabsClient /// </summary> public DevTestLabsClient Client { get; private set; } /// <summary> /// List policies in a given policy set. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='policySetName'> /// The name of the policy set. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Policy>>> ListWithHttpMessagesAsync(string resourceGroupName, string labName, string policySetName, ODataQuery<Policy> odataQuery = default(ODataQuery<Policy>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (labName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "labName"); } if (policySetName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "policySetName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("labName", labName); tracingParameters.Add("policySetName", policySetName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/policysets/{policySetName}/policies").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{labName}", Uri.EscapeDataString(labName)); _url = _url.Replace("{policySetName}", Uri.EscapeDataString(policySetName)); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Policy>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<Policy>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get policy. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='policySetName'> /// The name of the policy set. /// </param> /// <param name='name'> /// The name of the policy. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Policy>> GetResourceWithHttpMessagesAsync(string resourceGroupName, string labName, string policySetName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (labName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "labName"); } if (policySetName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "policySetName"); } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("labName", labName); tracingParameters.Add("policySetName", policySetName); tracingParameters.Add("name", name); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetResource", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/policysets/{policySetName}/policies/{name}").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{labName}", Uri.EscapeDataString(labName)); _url = _url.Replace("{policySetName}", Uri.EscapeDataString(policySetName)); _url = _url.Replace("{name}", Uri.EscapeDataString(name)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Policy>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Policy>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Create or replace an existing policy. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='policySetName'> /// The name of the policy set. /// </param> /// <param name='name'> /// The name of the policy. /// </param> /// <param name='policy'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Policy>> CreateOrUpdateResourceWithHttpMessagesAsync(string resourceGroupName, string labName, string policySetName, string name, Policy policy, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (labName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "labName"); } if (policySetName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "policySetName"); } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (policy == null) { throw new ValidationException(ValidationRules.CannotBeNull, "policy"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("labName", labName); tracingParameters.Add("policySetName", policySetName); tracingParameters.Add("name", name); tracingParameters.Add("policy", policy); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdateResource", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/policysets/{policySetName}/policies/{name}").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{labName}", Uri.EscapeDataString(labName)); _url = _url.Replace("{policySetName}", Uri.EscapeDataString(policySetName)); _url = _url.Replace("{name}", Uri.EscapeDataString(name)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(policy != null) { _requestContent = SafeJsonConvert.SerializeObject(policy, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Policy>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Policy>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Policy>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Delete policy. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='policySetName'> /// The name of the policy set. /// </param> /// <param name='name'> /// The name of the policy. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteResourceWithHttpMessagesAsync(string resourceGroupName, string labName, string policySetName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (labName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "labName"); } if (policySetName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "policySetName"); } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("labName", labName); tracingParameters.Add("policySetName", policySetName); tracingParameters.Add("name", name); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "DeleteResource", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/policysets/{policySetName}/policies/{name}").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{labName}", Uri.EscapeDataString(labName)); _url = _url.Replace("{policySetName}", Uri.EscapeDataString(policySetName)); _url = _url.Replace("{name}", Uri.EscapeDataString(name)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Modify properties of policies. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='labName'> /// The name of the lab. /// </param> /// <param name='policySetName'> /// The name of the policy set. /// </param> /// <param name='name'> /// The name of the policy. /// </param> /// <param name='policy'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Policy>> PatchResourceWithHttpMessagesAsync(string resourceGroupName, string labName, string policySetName, string name, Policy policy, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (labName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "labName"); } if (policySetName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "policySetName"); } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (policy == null) { throw new ValidationException(ValidationRules.CannotBeNull, "policy"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("labName", labName); tracingParameters.Add("policySetName", policySetName); tracingParameters.Add("name", name); tracingParameters.Add("policy", policy); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PatchResource", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/policysets/{policySetName}/policies/{name}").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{labName}", Uri.EscapeDataString(labName)); _url = _url.Replace("{policySetName}", Uri.EscapeDataString(policySetName)); _url = _url.Replace("{name}", Uri.EscapeDataString(name)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(policy != null) { _requestContent = SafeJsonConvert.SerializeObject(policy, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Policy>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Policy>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// List policies in a given policy set. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Policy>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Policy>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<Policy>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
#region Imported Types using DeviceSQL.SQLTypes.ROC.Data; using Microsoft.SqlServer.Server; using System; using System.Data.SqlTypes; using System.IO; #endregion namespace DeviceSQL.SQLTypes.ROC { [Serializable()] [SqlUserDefinedType(Format.UserDefined, IsByteOrdered = false, IsFixedLength = false, MaxByteSize = 61)] public struct Parameter : INullable, IBinarySerialize { #region Fields private byte parameterType; private byte[] rawValue; #endregion #region Properties public bool IsNull { get; private set; } public static Parameter Null { get { return (new Parameter() { IsNull = true }); } } public byte PointType { get; set; } public byte LogicalNumber { get; set; } public byte ParameterNumber { get; set; } public string Type { get { return RawType.ToString(); } } internal ParameterType RawType { get { return (ParameterType)parameterType; } set { parameterType = (byte)value; } } internal byte[] RawValue { get { if (rawValue == null) { switch ((ParameterType)parameterType) { case ParameterType.AC3: rawValue = new byte[3]; break; case ParameterType.AC7: rawValue = new byte[3]; break; case ParameterType.AC10: rawValue = new byte[10]; break; case ParameterType.AC12: rawValue = new byte[12]; break; case ParameterType.AC20: rawValue = new byte[20]; break; case ParameterType.AC30: rawValue = new byte[30]; break; case ParameterType.AC40: rawValue = new byte[40]; break; case ParameterType.BIN: rawValue = new byte[1]; break; case ParameterType.FL: rawValue = new byte[4]; break; case ParameterType.DOUBLE: rawValue = new byte[8]; break; case ParameterType.INT16: rawValue = new byte[2]; break; case ParameterType.INT32: rawValue = new byte[4]; break; case ParameterType.INT8: rawValue = new byte[1]; break; case ParameterType.TLP: rawValue = new byte[3]; break; case ParameterType.UINT16: rawValue = new byte[2]; break; case ParameterType.UINT32: rawValue = new byte[4]; break; case ParameterType.TIME: rawValue = new byte[4]; break; case ParameterType.UINT8: rawValue = new byte[10]; break; } } return rawValue; } set { rawValue = value; } } #endregion #region Helper Methods public override string ToString() { if (this.IsNull) { return "NULL"; } else { switch ((ParameterType)parameterType) { case ParameterType.AC3: return (new Ac3Parameter() { Data = RawValue }).Value; case ParameterType.AC7: return (new Ac7Parameter() { Data = RawValue }).Value; case ParameterType.AC10: return (new Ac10Parameter() { Data = RawValue }).Value; case ParameterType.AC12: return (new Ac12Parameter() { Data = RawValue }).Value; case ParameterType.AC20: return (new Ac20Parameter() { Data = RawValue }).Value; case ParameterType.AC30: return (new Ac30Parameter() { Data = RawValue }).Value; case ParameterType.AC40: return (new Ac40Parameter() { Data = RawValue }).Value; case ParameterType.BIN: return (new BinParameter() { Data = RawValue }).Value.ToString(); case ParameterType.FL: return (new FlpParameter() { Data = RawValue }).Value.ToString(); case ParameterType.DOUBLE: return (new DoubleParameter() { Data = RawValue }).Value.ToString(); case ParameterType.INT16: return (new Int16Parameter() { Data = RawValue }).Value.ToString(); case ParameterType.INT32: return (new Int32Parameter() { Data = RawValue }).Value.ToString(); case ParameterType.INT8: return (new Int8Parameter() { Data = RawValue }).Value.ToString(); case ParameterType.TLP: { var tlpParameter = new TlpParameter() { Data = RawValue }; return string.Format("{0}.{1}.{2}", tlpParameter.Value.PointType.ToString(), tlpParameter.Value.LogicalNumber.ToString(), tlpParameter.Value.Parameter.ToString()); } case ParameterType.UINT16: return (new UInt16Parameter() { Data = RawValue }).Value.ToString(); case ParameterType.UINT32: return (new Int32Parameter() { Data = RawValue }).Value.ToString(); case ParameterType.TIME: return (new TimeParameter() { Data = RawValue }).Value.ToString(); case ParameterType.UINT8: return (new UInt8Parameter() { Data = RawValue }).Value.ToString(); default: return "NULL"; } } } public SqlByte ToBin() { return (new BinParameter() { Data = RawValue }).Value; } public SqlByte ToUInt8() { return (new UInt8Parameter() { Data = RawValue }).Value; } public SqlInt16 ToInt8() { return (new Int8Parameter() { Data = RawValue }).Value; } public SqlInt16 ToInt16() { return (new Int16Parameter() { Data = RawValue }).Value; } public SqlInt32 ToUInt16() { return (new UInt16Parameter() { Data = RawValue }).Value; } public SqlInt32 ToInt32() { return (new Int32Parameter() { Data = RawValue }).Value; } public SqlInt64 ToUInt32() { return (new UInt32Parameter() { Data = RawValue }).Value; } public SqlDateTime ToTime() { return (new TimeParameter() { Data = RawValue }).Value; } public SqlSingle ToFl() { var flpValue = new FlpParameter() { Data = RawValue }.NullableValue; return flpValue.HasValue ? flpValue.Value : SqlSingle.Null; } public SqlDouble ToDouble() { var doubleValue = new DoubleParameter() { Data = RawValue }.NullableValue; return doubleValue.HasValue ? doubleValue.Value : SqlDouble.Null; } public static Parameter Parse(SqlString stringToParse) { if (stringToParse.IsNull) { return Null; } var parsedROCPointData = stringToParse.Value.Split(",".ToCharArray()); var parsedROCParameter = new Parameter() { PointType = byte.Parse(parsedROCPointData[0]), LogicalNumber = byte.Parse(parsedROCPointData[1]), ParameterNumber = byte.Parse(parsedROCPointData[2]) }; parsedROCParameter.parameterType = (byte)((ParameterType)Enum.Parse(typeof(ParameterType), parsedROCPointData[3])); switch (parsedROCPointData[3]) { case "AC3": parsedROCParameter.rawValue = (new Ac3Parameter() { Value = parsedROCPointData[4] }).Data; break; case "AC7": parsedROCParameter.rawValue = (new Ac7Parameter() { Value = parsedROCPointData[4] }).Data; break; case "AC10": parsedROCParameter.rawValue = (new Ac10Parameter() { Value = parsedROCPointData[4] }).Data; break; case "AC12": parsedROCParameter.rawValue = (new Ac12Parameter() { Value = parsedROCPointData[4] }).Data; break; case "AC20": parsedROCParameter.rawValue = (new Ac20Parameter() { Value = parsedROCPointData[4] }).Data; break; case "AC30": parsedROCParameter.rawValue = (new Ac30Parameter() { Value = parsedROCPointData[4] }).Data; break; case "AC40": parsedROCParameter.rawValue = (new Ac40Parameter() { Value = parsedROCPointData[4] }).Data; break; case "BIN": parsedROCParameter.rawValue = (new BinParameter() { Value = byte.Parse(parsedROCPointData[4]) }).Data; break; case "FL": parsedROCParameter.rawValue = (new FlpParameter() { Value = float.Parse(parsedROCPointData[4]) }).Data; break; case "DOUBLE": parsedROCParameter.rawValue = (new DoubleParameter() { Value = double.Parse(parsedROCPointData[8]) }).Data; break; case "INT16": parsedROCParameter.rawValue = (new Int16Parameter() { Value = short.Parse(parsedROCPointData[4]) }).Data; break; case "INT32": parsedROCParameter.rawValue = (new Int32Parameter() { Value = int.Parse(parsedROCPointData[4]) }).Data; break; case "Int8": parsedROCParameter.rawValue = (new Int8Parameter() { Value = SByte.Parse(parsedROCPointData[4]) }).Data; break; case "TLP": { var parsedTlp = parsedROCPointData[4].Split(".".ToCharArray()); parsedROCParameter.rawValue = (new TlpParameter() { Value = new Tlp(byte.Parse(parsedTlp[0]), byte.Parse(parsedTlp[1]), byte.Parse(parsedTlp[2])) }).Data; } break; case "UINT16": parsedROCParameter.rawValue = (new UInt16Parameter() { Value = ushort.Parse(parsedROCPointData[4]) }).Data; break; case "UINT32": parsedROCParameter.rawValue = (new UInt32Parameter() { Value = uint.Parse(parsedROCPointData[4]) }).Data; break; case "TIME": parsedROCParameter.rawValue = (new TimeParameter() { Value = (new DateTime(1970, 01, 01).AddSeconds(uint.Parse(parsedROCPointData[4]))) }).Data; break; case "UINT8": parsedROCParameter.rawValue = (new UInt8Parameter() { Value = byte.Parse(parsedROCPointData[4]) }).Data; break; } return parsedROCParameter; } public static Parameter ParseTlp(byte pointType, byte logicalNumber, byte parameter, byte pointTypeValue, byte logicalNumberValue, byte parameterValue) { return new Parameter() { PointType = pointType, LogicalNumber = logicalNumber, ParameterNumber = parameter, parameterType = (byte)ParameterType.TLP, rawValue = (new TlpParameter() { Value = new Tlp(pointTypeValue, logicalNumberValue, parameterValue) }).Data }; } public static Parameter ParseAc3(byte pointType, byte logicalNumber, byte parameter, string value) { return new Parameter() { PointType = pointType, LogicalNumber = logicalNumber, ParameterNumber = parameter, parameterType = (byte)ParameterType.AC3, rawValue = (new Ac3Parameter() { Value = value }).Data }; } public static Parameter ParseAc7(byte pointType, byte logicalNumber, byte parameter, string value) { return new Parameter() { PointType = pointType, LogicalNumber = logicalNumber, ParameterNumber = parameter, parameterType = (byte)ParameterType.AC7, rawValue = (new Ac3Parameter() { Value = value }).Data }; } public static Parameter ParseAc10(byte pointType, byte logicalNumber, byte parameter, string value) { return new Parameter() { PointType = pointType, LogicalNumber = logicalNumber, ParameterNumber = parameter, parameterType = (byte)ParameterType.AC10, rawValue = (new Ac10Parameter() { Value = value }).Data }; } public static Parameter ParseAc12(byte pointType, byte logicalNumber, byte parameter, string value) { return new Parameter() { PointType = pointType, LogicalNumber = logicalNumber, ParameterNumber = parameter, parameterType = (byte)ParameterType.AC12, rawValue = (new Ac12Parameter() { Value = value }).Data }; } public static Parameter ParseAc20(byte pointType, byte logicalNumber, byte parameter, string value) { return new Parameter() { PointType = pointType, LogicalNumber = logicalNumber, ParameterNumber = parameter, parameterType = (byte)ParameterType.AC20, rawValue = (new Ac20Parameter() { Value = value }).Data }; } public static Parameter ParseAc30(byte pointType, byte logicalNumber, byte parameter, string value) { return new Parameter() { PointType = pointType, LogicalNumber = logicalNumber, ParameterNumber = parameter, parameterType = (byte)ParameterType.AC30, rawValue = (new Ac30Parameter() { Value = value }).Data }; } public static Parameter ParseAc40(byte pointType, byte logicalNumber, byte parameter, string value) { return new Parameter() { PointType = pointType, LogicalNumber = logicalNumber, ParameterNumber = parameter, parameterType = (byte)ParameterType.AC40, rawValue = (new Ac40Parameter() { Value = value }).Data }; } public static Parameter ParseBin(byte pointType, byte logicalNumber, byte parameter, byte value) { return new Parameter() { PointType = pointType, LogicalNumber = logicalNumber, ParameterNumber = parameter, parameterType = (byte)ParameterType.BIN, rawValue = (new BinParameter() { Value = value }).Data }; } public static Parameter ParseInt8(byte pointType, byte logicalNumber, byte parameter, short value) { return new Parameter() { PointType = pointType, LogicalNumber = logicalNumber, ParameterNumber = parameter, parameterType = (byte)ParameterType.INT8, rawValue = (new Int8Parameter() { Value = Convert.ToSByte(value) }).Data }; } public static Parameter ParseUInt8(byte pointType, byte logicalNumber, byte parameter, byte value) { return new Parameter() { PointType = pointType, LogicalNumber = logicalNumber, ParameterNumber = parameter, parameterType = (byte)ParameterType.UINT8, rawValue = (new UInt8Parameter() { Value = value }).Data }; } public static Parameter ParseInt16(byte pointType, byte logicalNumber, byte parameter, short value) { return new Parameter() { PointType = pointType, LogicalNumber = logicalNumber, ParameterNumber = parameter, parameterType = (byte)ParameterType.INT16, rawValue = (new Int16Parameter() { Value = value }).Data }; } public static Parameter ParseUInt16(byte pointType, byte logicalNumber, byte parameter, int value) { return new Parameter() { PointType = pointType, LogicalNumber = logicalNumber, ParameterNumber = parameter, parameterType = (byte)ParameterType.UINT16, rawValue = (new UInt16Parameter() { Value = Convert.ToUInt16(value) }).Data }; } public static Parameter ParseInt32(byte pointType, byte logicalNumber, byte parameter, int value) { return new Parameter() { PointType = pointType, LogicalNumber = logicalNumber, ParameterNumber = parameter, parameterType = (byte)ParameterType.INT32, rawValue = (new Int32Parameter() { Value = value }).Data }; } public static Parameter ParseUInt32(byte pointType, byte logicalNumber, byte parameter, long value) { return new Parameter() { PointType = pointType, LogicalNumber = logicalNumber, ParameterNumber = parameter, parameterType = (byte)ParameterType.UINT32, rawValue = (new UInt32Parameter() { Value = Convert.ToUInt32(value) }).Data }; } public static Parameter ParseTime(byte pointType, byte logicalNumber, byte parameter, DateTime value) { return new Parameter() { PointType = pointType, LogicalNumber = logicalNumber, ParameterNumber = parameter, parameterType = (byte)ParameterType.TIME, rawValue = (new TimeParameter() { Value = value }).Data }; } public static Parameter ParseFl(byte pointType, byte logicalNumber, byte parameter, float value) { return new Parameter() { PointType = pointType, LogicalNumber = logicalNumber, ParameterNumber = parameter, parameterType = (byte)ParameterType.FL, rawValue = (new FlpParameter() { Value = value }).Data }; } public static Parameter ParseDouble(byte pointType, byte logicalNumber, byte parameter, double value) { return new Parameter() { PointType = pointType, LogicalNumber = logicalNumber, ParameterNumber = parameter, parameterType = (byte)ParameterType.DOUBLE, rawValue = (new DoubleParameter() { Value = value }).Data }; } #endregion #region Serialization Methods public void Read(BinaryReader binaryReader) { IsNull = binaryReader.ReadBoolean(); if (!IsNull) { PointType = binaryReader.ReadByte(); LogicalNumber = binaryReader.ReadByte(); ParameterNumber = binaryReader.ReadByte(); parameterType = binaryReader.ReadByte(); rawValue = new byte[binaryReader.ReadInt32()]; binaryReader.Read(rawValue, 0, rawValue.Length); } } public void Write(BinaryWriter binaryWriter) { binaryWriter.Write(IsNull); if (!IsNull) { binaryWriter.Write(PointType); binaryWriter.Write(LogicalNumber); binaryWriter.Write(ParameterNumber); binaryWriter.Write(parameterType); binaryWriter.Write(RawValue.Length); binaryWriter.Write(RawValue); } } #endregion } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; namespace ASC.Api.Utils { public static class Binder { private static object CreateParamType(Type modelType) { var type = modelType; if (modelType.IsGenericType) { var genericTypeDefinition = modelType.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(IDictionary<,>)) type = typeof(Dictionary<,>).MakeGenericType(modelType.GetGenericArguments()); else if (genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>) || genericTypeDefinition == typeof(IList<>)) type = typeof(List<>).MakeGenericType(modelType.GetGenericArguments()); } if (modelType.IsArray && modelType.HasElementType) { //Create generic list and we will convert it to aaray later type = typeof(List<>).MakeGenericType(modelType.GetElementType()); } return Activator.CreateInstance(type); } public static Type GetCollectionType(Type modelType) { Type type = null; if (modelType.IsGenericType) { var genericTypeDefinition = modelType.GetGenericTypeDefinition(); if (typeof(IDictionary).IsAssignableFrom(genericTypeDefinition)) type = modelType.GetGenericArguments().Last(); else if (typeof(IEnumerable).IsAssignableFrom(genericTypeDefinition) || typeof(ICollection).IsAssignableFrom(genericTypeDefinition) || typeof(IList).IsAssignableFrom(genericTypeDefinition)) type = modelType.GetGenericArguments().Last(); } if (modelType.IsArray && modelType.HasElementType) { type = modelType.GetElementType(); } return type; } public static object Bind(Type type, NameValueCollection collection) { return Bind(type, collection, string.Empty); } public static T Bind<T>(NameValueCollection collection) { return Bind<T>(collection, string.Empty); } public static T Bind<T>(NameValueCollection collection, string prefix) { return (T)Bind(typeof(T), collection, prefix); } public static object Bind(Type type, NameValueCollection collection, string prefix) { if (IsSimple(type)) { //Just bind var value = GetValue(GetNameTransforms(prefix), collection, string.Empty); if (value != null) { return ConvertUtils.GetConverted(value, type); } } var binded = CreateParamType(type); //Get all props if (IsCollection(type)) { BindCollection(prefix, (IList)binded, collection); } else { binded = BindObject(type, binded, collection, prefix); } return ConvertToSourceType(binded, type); } private static object ConvertToSourceType(object binded, Type type) { if (binded != null) { if (type.IsArray && type.HasElementType && binded.GetType().IsGenericType && IsCollection(binded.GetType())) { var genericType = binded.GetType().GetGenericArguments(); var arrayType = type.GetElementType(); if (genericType.Length == 1 && genericType[0] == arrayType) { IList collection = (IList)binded; //Its list need to convert to array Array array = Array.CreateInstance(arrayType, collection.Count); collection.CopyTo(array, 0); return array; } } } return binded; } private static object BindObject(IReflect type, object binded, NameValueCollection values, string prefix) { //Get properties var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public); var isBinded = false; foreach (var propertyInfo in properties) { if (IsSimple(propertyInfo.PropertyType)) { //Set from collection var value = GetValue(GetName(propertyInfo), values, prefix); if (value != null) { propertyInfo.SetValue(binded, ConvertUtils.GetConverted(value, propertyInfo), null); isBinded = true; } } else { var propNames = GetName(propertyInfo); PropertyInfo info = propertyInfo; foreach (string propName in propNames) { string bindPrefix = !string.IsNullOrEmpty(prefix) ? prefix + string.Format("[{0}]", propName) : propName; //find prefix in collection if (IsPrefixExists(bindPrefix, values)) { var result = Bind(info.PropertyType, values, bindPrefix); if (result != null) { propertyInfo.SetValue(binded, result, null); isBinded = true; break; } } } } } return isBinded ? binded : null; } private static bool IsPrefixExists(string prefix, NameValueCollection values) { return values.AllKeys.Any(x => x != null && x.StartsWith(prefix)); } private static IEnumerable<string> GetName(PropertyInfo property) { return GetNameTransforms(property.Name); } private static IEnumerable<string> GetNameTransforms(string name) { return new[] { name, StringUtils.ToCamelCase(name), name.ToLower() }; } private static string GetValue(IEnumerable<string> names, NameValueCollection values, string prefix) { if (string.IsNullOrEmpty(prefix)) { return names.Select(name => values[name]).FirstOrDefault(value => !string.IsNullOrEmpty(value)); } //var regex = new Regex(@"^(\[){0,1}(" + string.Join("|", names.Select(name => Regex.Escape(name)).ToArray()) + @")(\]){0,1}"); var keys = from key in values.AllKeys where key != null && key.StartsWith(prefix) let nameKey = key.Substring(prefix.Length).Trim('[', '.', ']') where names.Contains(nameKey) select key; return values[keys.SingleOrDefault() ?? string.Empty]; } private static readonly ConcurrentDictionary<string, Regex> CollectionPrefixCache = new ConcurrentDictionary<string, Regex>(); private static void BindCollection(string prefix, IList collection, NameValueCollection values) { Regex parse = GetParseRegex(prefix); //Parse values related to collection const string simple = "simple"; var keys = from key in values.AllKeys.Where(key => key != null) let match = parse.Match(key) group key by string.IsNullOrEmpty(match.Groups["pos"].Value) ? (match.Groups["arrleft"].Success ? string.Empty : simple) : match.Groups["pos"].Value into key select key; foreach (var key in keys) { int index; bool indexed = int.TryParse(key.Key, out index); Type genericType = null; var collectionType = collection.GetType(); if (collectionType.IsGenericType) { genericType = collectionType.GetGenericArguments().SingleOrDefault(); } else if (collectionType.IsArray && collectionType.HasElementType) { //Create array genericType = collectionType.GetElementType(); } if (genericType != null) { var newprefix = simple.Equals(key.Key) ? prefix : prefix + "[" + (indexed ? index.ToString(CultureInfo.InvariantCulture) : "") + "]"; if (IsSimple(genericType)) { //Collect all and insert var collectionValues = values.GetValues(newprefix); if (collectionValues != null) { foreach (var collectionValue in collectionValues) { collection.Add(ConvertUtils.GetConverted(collectionValue, genericType)); } } } else { var constructed = Bind(genericType, values, newprefix); if (constructed != null) collection.Insert(index, constructed); } } } } private static Regex GetParseRegex(string prefix) { Regex value = null; if (!CollectionPrefixCache.TryGetValue(prefix, out value)) { value = new Regex("(?'prefix'^" + Regex.Escape(prefix) + @"(?'arrleft'\[){0,1}(?'pos'[\d]+){0,1}(?'arrright'\]){0,1})(?'suffix'.+){0,1}", RegexOptions.Singleline | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.Compiled); CollectionPrefixCache.TryAdd(prefix, value); } return value; } public static bool IsCollection(Type type) { return !IsSimple(type) && (type.IsArray || HasInterface(type, typeof(IEnumerable))); } public static bool HasInterface(Type type, Type interfaceType) { return type.GetInterfaces().Any(x => x == interfaceType); } private static readonly IDictionary<Type, bool> SimpleMap = new ConcurrentDictionary<Type, bool>(); private static bool IsSimple(Type type) { bool simple; if (type.IsPrimitive) return true; if (!SimpleMap.TryGetValue(type, out simple)) { var converter = TypeDescriptor.GetConverter(type);//TODO: optimize? simple = converter.CanConvertFrom(typeof(string)); SimpleMap[type] = simple; } return simple; } public static long GetCollectionCount(object collection) { var collection1 = collection as ICollection; if (collection1 != null) return (collection1).Count; var responceType = collection.GetType(); var lengthProperty = responceType.GetProperty("Count", BindingFlags.Public | BindingFlags.Instance) ?? responceType.GetProperty("Length", BindingFlags.Public | BindingFlags.Instance); if (lengthProperty != null) { return Convert.ToInt64(lengthProperty.GetValue(collection, new object[0])); } return 1; } } }
// 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.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using Xunit; namespace Test { public class OrderByThenByTests { private const int KeyFactor = 4; private const int GroupFactor = 8; // Get ranges from 0 to each count. The data is random, seeded from the size of the range. public static IEnumerable<object[]> OrderByRandomData(object[] counts) { foreach (int count in counts.Cast<int>()) { int[] randomInput = GetRandomInput(count); yield return new object[] { Labeled.Label("Array-Random", randomInput.AsParallel()), count }; yield return new object[] { Labeled.Label("List-Random", randomInput.ToList().AsParallel()), count }; yield return new object[] { Labeled.Label("Partitioner-Random", Partitioner.Create(randomInput).AsParallel()), count }; } } private static int[] GetRandomInput(int count) { Random source = new Random(count); int[] data = new int[count]; for (int i = 0; i < count; i++) { data[i] = source.Next(count); } return data; } // Get a set of ranges, from 0 to each count, and an additional parameter denoting degree of parallelism. public static IEnumerable<object[]> OrderByThreadedData(object[] counts, object[] degrees) { foreach (object[] results in UnorderedSources.Ranges(counts.Cast<int>(), x => degrees.Cast<int>())) { yield return results; } foreach (object[] results in Sources.Ranges(counts.Cast<int>(), x => degrees.Cast<int>())) { yield return results; } foreach (object[] results in OrderByRandomData(counts)) { foreach (int degree in degrees) { yield return new object[] { results[0], results[1], degree }; } } } // // OrderBy // [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 0, 1, 2, 16 }))] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void OrderBy(Labeled<ParallelQuery<int>> labeled, int count) { int prev = int.MinValue; foreach (int i in labeled.Item.OrderBy(x => x)) { Assert.True(i >= prev); prev = i; } } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 1024, 1024 * 32 }))] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(UnorderedSources))] public static void OrderBy_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { OrderBy(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 0, 1, 2, 16 }))] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void OrderBy_Reversed(Labeled<ParallelQuery<int>> labeled, int count) { int prev = int.MaxValue; foreach (int i in labeled.Item.OrderBy(x => -x)) { Assert.True(i <= prev); prev = i; } } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 1024, 1024 * 32 }))] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(UnorderedSources))] public static void OrderBy_Reversed_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { OrderBy_Reversed(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 0, 1, 2, 16 }))] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void OrderByDescending(Labeled<ParallelQuery<int>> labeled, int count) { int prev = int.MaxValue; foreach (int i in labeled.Item.OrderByDescending(x => x)) { Assert.True(i <= prev); prev = i; } } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 1024, 1024 * 32 }))] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(UnorderedSources))] public static void OrderByDescending_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { OrderByDescending(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 0, 1, 2, 16 }))] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void OrderByDescending_Reversed(Labeled<ParallelQuery<int>> labeled, int count) { int prev = int.MinValue; foreach (int i in labeled.Item.OrderByDescending(x => -x)) { Assert.True(i >= prev); prev = i; } } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 1024, 1024 * 32 }))] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(UnorderedSources))] public static void OrderByDescending_Reversed_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { OrderByDescending_Reversed(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 0, 1, 2, 16 }))] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void OrderBy_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count) { int prev = int.MinValue; Assert.All(labeled.Item.OrderBy(x => x).ToList(), x => { Assert.True(x >= prev); prev = x; }); } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 1024, 1024 * 32 }))] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(UnorderedSources))] public static void OrderBy_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { OrderBy_NotPipelined(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 0, 1, 2, 16 }))] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void OrderBy_Reversed_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count) { int prev = int.MaxValue; Assert.All(labeled.Item.OrderBy(x => -x).ToList(), x => { Assert.True(x <= prev); prev = x; }); } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 1024, 1024 * 32 }))] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(UnorderedSources))] public static void OrderBy_Reversed_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { OrderBy_Reversed_NotPipelined(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 0, 1, 2, 16 }))] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void OrderByDescending_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count) { int prev = int.MaxValue; Assert.All(labeled.Item.OrderByDescending(x => x).ToList(), x => { Assert.True(x <= prev); prev = x; }); } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 1024, 1024 * 32 }))] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(UnorderedSources))] public static void OrderByDescending_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { OrderByDescending_NotPipelined(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 0, 1, 2, 16 }))] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void OrderByDescending_Reversed_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count) { int prev = int.MinValue; Assert.All(labeled.Item.OrderByDescending(x => -x).ToList(), x => { Assert.True(x >= prev); prev = x; }); } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 1024, 1024 * 32 }))] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(UnorderedSources))] public static void OrderByDescending_Reversed_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { OrderByDescending_Reversed_NotPipelined(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 0, 1, 2, 16 }))] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void OrderBy_CustomComparer(Labeled<ParallelQuery<int>> labeled, int count) { int prev = int.MaxValue; foreach (int i in labeled.Item.OrderBy(x => x, ReverseComparer.Instance)) { Assert.True(i <= prev); prev = i; } } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 1024, 1024 * 32 }))] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(UnorderedSources))] public static void OrderBy_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { OrderBy_CustomComparer(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 0, 1, 2, 16 }))] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void OrderByDescending_CustomComparer(Labeled<ParallelQuery<int>> labeled, int count) { int prev = int.MinValue; foreach (int i in labeled.Item.OrderByDescending(x => x, ReverseComparer.Instance)) { Assert.True(i >= prev); prev = i; } } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 1024, 1024 * 32 }))] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(UnorderedSources))] public static void OrderByDescending_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { OrderByDescending_CustomComparer(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 0, 1, 2, 16 }))] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void OrderBy_NotPipelined_CustomComparer(Labeled<ParallelQuery<int>> labeled, int count) { int prev = int.MaxValue; Assert.All(labeled.Item.OrderBy(x => x, ReverseComparer.Instance).ToList(), x => { Assert.True(x <= prev); prev = x; }); } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 1024, 1024 * 32 }))] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(UnorderedSources))] public static void OrderBy_NotPipelined_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { OrderBy_NotPipelined_CustomComparer(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 0, 1, 2, 16 }))] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void OrderByDescending_NotPipelined_CustomComparer(Labeled<ParallelQuery<int>> labeled, int count) { int prev = int.MinValue; Assert.All(labeled.Item.OrderByDescending(x => x, ReverseComparer.Instance).ToList(), x => { Assert.True(x >= prev); prev = x; }); } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 1024, 1024 * 32 }))] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(UnorderedSources))] public static void OrderByDescending_NotPipelined_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { OrderByDescending_NotPipelined_CustomComparer(labeled, count); } [Fact] public static void OrderBy_ArgumentNullException() { Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).OrderBy(x => x)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).OrderBy((Func<int, int>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).OrderBy(x => x, Comparer<int>.Default)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).OrderBy((Func<int, int>)null, Comparer<int>.Default)); } [Fact] public static void OrderByDescending_ArgumentNullException() { Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).OrderByDescending(x => x)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).OrderByDescending((Func<int, int>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).OrderByDescending(x => x, Comparer<int>.Default)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).OrderByDescending((Func<int, int>)null, Comparer<int>.Default)); } // Heavily exercises OrderBy in the face of user-delegate exceptions. // On CTP-M1, this would deadlock for DOP=7,9,11,... on 4-core, but works for DOP=1..6 and 8,10,12, ... // // In this test, every call to the key-selector delegate throws. [Theory] [MemberData("OrderByThreadedData", new[] { 1, 2, 16, 128, 1024 }, new[] { 1, 2, 4, 7, 8, 31, 32 })] public static void OrderBy_ThreadedDeadlock(Labeled<ParallelQuery<int>> labeled, int count, int degree) { ParallelQuery<int> query = labeled.Item.WithDegreeOfParallelism(degree).OrderBy<int, int>(x => { throw new DeliberateTestException(); }); AggregateException ae = Assert.Throws<AggregateException>(() => { foreach (int i in query) { } }); Assert.All(ae.InnerExceptions, e => Assert.IsType<DeliberateTestException>(e)); } // Heavily exercises OrderBy, but only throws one user delegate exception to simulate an occasional failure. [Theory] [MemberData("OrderByThreadedData", new[] { 1, 2, 16, 128, 1024 }, new[] { 1, 2, 4, 7, 8, 31, 32 })] public static void OrderBy_ThreadedDeadlock_SingleException(Labeled<ParallelQuery<int>> labeled, int count, int degree) { int countdown = Math.Min(count / 2, degree) + 1; ParallelQuery<int> query = labeled.Item.WithDegreeOfParallelism(degree).OrderBy(x => { if (Interlocked.Decrement(ref countdown) == 0) throw new DeliberateTestException(); return x; }); AggregateException ae = Assert.Throws<AggregateException>(() => { foreach (int i in query) { } }); Assert.Single(ae.InnerExceptions); Assert.All(ae.InnerExceptions, e => Assert.IsType<DeliberateTestException>(e)); } // // Thenby // [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 0, 1, 2, 16 }))] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void ThenBy(Labeled<ParallelQuery<int>> labeled, int count) { int prevPrimary = 0; int prevSecondary = int.MaxValue; foreach (int i in labeled.Item.OrderBy(x => x % GroupFactor).ThenBy(x => -x)) { Assert.True(i % GroupFactor >= prevPrimary); if (i % GroupFactor != prevPrimary) { prevPrimary = i % GroupFactor; prevSecondary = int.MaxValue; } Assert.True(i <= prevSecondary); prevSecondary = i; } } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 1024, 1024 * 32 }))] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(UnorderedSources))] public static void ThenBy_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { ThenBy(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 0, 1, 2, 16 }))] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void ThenBy_Reversed(Labeled<ParallelQuery<int>> labeled, int count) { int prevPrimary = GroupFactor - 1; int prevSecondary = 0; foreach (int i in labeled.Item.OrderBy(x => -x % GroupFactor).ThenBy(x => x)) { Assert.True(i % GroupFactor <= prevPrimary); if (i % GroupFactor != prevPrimary) { prevPrimary = i % GroupFactor; prevSecondary = 0; } Assert.True(i >= prevSecondary); prevSecondary = i; } } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 1024, 1024 * 32 }))] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(UnorderedSources))] public static void ThenBy_Reversed_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { ThenBy_Reversed(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 0, 1, 2, 16 }))] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void ThenByDescending(Labeled<ParallelQuery<int>> labeled, int count) { int prevPrimary = GroupFactor - 1; int prevSecondary = 0; foreach (int i in labeled.Item.OrderByDescending(x => x % GroupFactor).ThenByDescending(x => -x)) { Assert.True(i % GroupFactor <= prevPrimary); if (i % GroupFactor != prevPrimary) { prevPrimary = i % GroupFactor; prevSecondary = 0; } Assert.True(i >= prevSecondary); prevSecondary = i; } } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 1024, 1024 * 32 }))] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(UnorderedSources))] public static void ThenByDescending_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { ThenByDescending(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 0, 1, 2, 16 }))] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void ThenByDescending_Reversed(Labeled<ParallelQuery<int>> labeled, int count) { int prevPrimary = 0; int prevSecondary = int.MaxValue; foreach (int i in labeled.Item.OrderByDescending(x => -x % GroupFactor).ThenByDescending(x => x)) { Assert.True(i % GroupFactor >= prevPrimary); if (i % GroupFactor != prevPrimary) { prevPrimary = i % GroupFactor; prevSecondary = int.MaxValue; } Assert.True(i <= prevSecondary); prevSecondary = i; } } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 1024, 1024 * 32 }))] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(UnorderedSources))] public static void ThenByDescending_Reversed_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { ThenByDescending_Reversed(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 0, 1, 2, 16 }))] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void ThenBy_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count) { int prevPrimary = 0; int prevSecondary = int.MaxValue; Assert.All(labeled.Item.OrderBy(x => x % GroupFactor).ThenBy(x => -x).ToList(), x => { Assert.True(x % GroupFactor >= prevPrimary); if (x % GroupFactor != prevPrimary) { prevPrimary = x % GroupFactor; prevSecondary = int.MaxValue; } Assert.True(x <= prevSecondary); prevSecondary = x; }); } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 1024, 1024 * 32 }))] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(UnorderedSources))] public static void ThenBy_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { ThenBy_NotPipelined(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 0, 1, 2, 16 }))] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void ThenBy_Reversed_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count) { int prevPrimary = GroupFactor - 1; int prevSecondary = 0; Assert.All(labeled.Item.OrderBy(x => -x % GroupFactor).ThenBy(x => x).ToList(), x => { Assert.True(x % GroupFactor <= prevPrimary); if (x % GroupFactor != prevPrimary) { prevPrimary = x % GroupFactor; prevSecondary = 0; } Assert.True(x >= prevSecondary); prevSecondary = x; }); } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 1024, 1024 * 32 }))] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(UnorderedSources))] public static void ThenBy_Reversed_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { ThenBy_Reversed_NotPipelined(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 0, 1, 2, 16 }))] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void ThenByDescending_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count) { int prevPrimary = GroupFactor - 1; int prevSecondary = 0; Assert.All(labeled.Item.OrderByDescending(x => x % GroupFactor).ThenByDescending(x => -x).ToList(), x => { Assert.True(x % GroupFactor <= prevPrimary); if (x % GroupFactor != prevPrimary) { prevPrimary = x % GroupFactor; prevSecondary = 0; } Assert.True(x >= prevSecondary); prevSecondary = x; }); } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 1024, 1024 * 32 }))] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(UnorderedSources))] public static void ThenByDescending_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { ThenByDescending_NotPipelined(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 0, 1, 2, 16 }))] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void ThenByDescending_Reversed_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count) { int prevPrimary = 0; int prevSecondary = int.MaxValue; Assert.All(labeled.Item.OrderByDescending(x => -x % GroupFactor).ThenByDescending(x => x).ToList(), x => { Assert.True(x % GroupFactor >= prevPrimary); if (x % GroupFactor != prevPrimary) { prevPrimary = x % GroupFactor; prevSecondary = int.MaxValue; } Assert.True(x <= prevSecondary); prevSecondary = x; }); } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 1024, 1024 * 32 }))] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(UnorderedSources))] public static void ThenByDescending_Reversed_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { ThenByDescending_Reversed_NotPipelined(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 0, 1, 2, 16 }))] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void ThenBy_CustomComparer(Labeled<ParallelQuery<int>> labeled, int count) { int prevPrimary = 0; int prevSecondary = int.MaxValue; foreach (int i in labeled.Item.OrderBy(x => x % GroupFactor).ThenBy(x => x, ReverseComparer.Instance)) { Assert.True(i % GroupFactor >= prevPrimary); if (i % GroupFactor != prevPrimary) { prevPrimary = i % GroupFactor; prevSecondary = int.MaxValue; } Assert.True(i <= prevSecondary); prevSecondary = i; } } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 1024, 1024 * 32 }))] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(UnorderedSources))] public static void ThenBy_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { ThenBy_CustomComparer(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 0, 1, 2, 16 }))] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void ThenByDescending_CustomComparer(Labeled<ParallelQuery<int>> labeled, int count) { int prevPrimary = GroupFactor - 1; int prevSecondary = 0; foreach (int i in labeled.Item.OrderByDescending(x => x % GroupFactor).ThenByDescending(x => x, ReverseComparer.Instance)) { Assert.True(i % GroupFactor <= prevPrimary); if (i % GroupFactor != prevPrimary) { prevPrimary = i % GroupFactor; prevSecondary = 0; } Assert.True(i >= prevSecondary); prevSecondary = i; } } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 1024, 1024 * 32 }))] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(UnorderedSources))] public static void ThenByDescending_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { ThenByDescending_CustomComparer(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 0, 1, 2, 16 }))] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void ThenBy_NotPipelined_CustomComparer(Labeled<ParallelQuery<int>> labeled, int count) { int prevPrimary = 0; int prevSecondary = int.MaxValue; Assert.All(labeled.Item.OrderBy(x => x % GroupFactor).ThenBy(x => x, ReverseComparer.Instance).ToList(), x => { Assert.True(x % GroupFactor >= prevPrimary); if (x % GroupFactor != prevPrimary) { prevPrimary = x % GroupFactor; prevSecondary = int.MaxValue; } Assert.True(x <= prevSecondary); prevSecondary = x; }); } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 1024, 1024 * 32 }))] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(UnorderedSources))] public static void ThenBy_NotPipelined_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { ThenBy_NotPipelined_CustomComparer(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 0, 1, 2, 16 }))] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void ThenByDescending_NotPipelined_CustomComparer(Labeled<ParallelQuery<int>> labeled, int count) { int prevPrimary = GroupFactor - 1; int prevSecondary = 0; Assert.All(labeled.Item.OrderByDescending(x => x % GroupFactor).ThenByDescending(x => x, ReverseComparer.Instance).ToList(), x => { Assert.True(x % GroupFactor <= prevPrimary); if (x % GroupFactor != prevPrimary) { prevPrimary = x % GroupFactor; prevSecondary = 0; } Assert.True(x >= prevSecondary); prevSecondary = x; }); } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 1024, 1024 * 32 }))] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(UnorderedSources))] public static void ThenByDescending_NotPipelined_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { ThenByDescending_NotPipelined_CustomComparer(labeled, count); } // Recursive sort with nested ThenBy...s // Due to the use of randomized input, cycles will not start with a known input (and may skip values, etc). [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 0, 1, 2, 16 }))] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void ThenBy_ThenBy(Labeled<ParallelQuery<int>> labeled, int count) { var prev = KeyValuePair.Create(0, KeyValuePair.Create(0, 0)); foreach (var pOuter in labeled.Item.Select(x => KeyValuePair.Create(x % GroupFactor, KeyValuePair.Create((KeyFactor - 1) - x % KeyFactor, x))) .OrderBy(o => o.Key).ThenBy(o => o.Value.Key).ThenBy(o => o.Value.Value)) { Assert.True(pOuter.Key >= prev.Key); Assert.True(pOuter.Value.Key >= prev.Value.Key || pOuter.Key > prev.Key); Assert.True(pOuter.Value.Value >= prev.Value.Value || pOuter.Value.Key > prev.Value.Key || pOuter.Key > prev.Key); prev = pOuter; } } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 1024, 1024 * 32 }))] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(UnorderedSources))] public static void ThenBy_ThenBy_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { ThenBy_ThenBy(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 0, 1, 2, 16 }))] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void ThenByDescending_ThenByDescending(Labeled<ParallelQuery<int>> labeled, int count) { var prev = KeyValuePair.Create(GroupFactor - 1, KeyValuePair.Create(KeyFactor - 1, int.MaxValue)); foreach (var pOuter in labeled.Item.Select(x => KeyValuePair.Create(x % GroupFactor, KeyValuePair.Create((KeyFactor - 1) - x % KeyFactor, x))) .OrderByDescending(o => o.Key).ThenByDescending(o => o.Value.Key).ThenByDescending(o => o.Value.Value)) { Assert.True(pOuter.Key <= prev.Key); Assert.True(pOuter.Value.Key <= prev.Value.Key || pOuter.Key < prev.Key); Assert.True(pOuter.Value.Value <= prev.Value.Value || pOuter.Value.Key < prev.Value.Key || pOuter.Key < prev.Key); prev = pOuter; } } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 1024, 1024 * 32 }))] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(UnorderedSources))] public static void ThenByDescending_ThenByDescending_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { ThenByDescending_ThenByDescending(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 0, 1, 2, 16 }))] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void ThenBy_ThenBy_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count) { var prev = KeyValuePair.Create(0, KeyValuePair.Create(0, 0)); Assert.All(labeled.Item.Select(x => KeyValuePair.Create(x % GroupFactor, KeyValuePair.Create((KeyFactor - 1) - x % KeyFactor, x))) .OrderBy(o => o.Key).ThenBy(o => o.Value.Key).ThenBy(o => o.Value.Value).ToList(), pOuter => { Assert.True(pOuter.Key >= prev.Key); Assert.True(pOuter.Value.Key >= prev.Value.Key || pOuter.Key > prev.Key); Assert.True(pOuter.Value.Value >= prev.Value.Value || pOuter.Value.Key > prev.Value.Key || pOuter.Key > prev.Key); prev = pOuter; }); } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 1024, 1024 * 32 }))] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(UnorderedSources))] public static void ThenBy_ThenBy_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { ThenBy_ThenBy_NotPipelined(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 0, 1, 2, 16 }))] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void ThenByDescending_ThenByDescending_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count) { var prev = KeyValuePair.Create(GroupFactor - 1, KeyValuePair.Create(KeyFactor - 1, int.MaxValue)); Assert.All(labeled.Item.Select(x => KeyValuePair.Create(x % GroupFactor, KeyValuePair.Create((KeyFactor - 1) - x % KeyFactor, x))) .OrderByDescending(o => o.Key).ThenByDescending(o => o.Value.Key).ThenByDescending(o => o.Value.Value).ToList(), pOuter => { Assert.True(pOuter.Key <= prev.Key); Assert.True(pOuter.Value.Key <= prev.Value.Key || pOuter.Key < prev.Key); Assert.True(pOuter.Value.Value <= prev.Value.Value || pOuter.Value.Key < prev.Value.Key || pOuter.Key < prev.Key); prev = pOuter; }); } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(Sources))] [MemberData("OrderByRandomData", (object)(new[] { 1024, 1024 * 32 }))] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(UnorderedSources))] public static void ThenByDescending_ThenByDescending_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { ThenByDescending_ThenByDescending_NotPipelined(labeled, count); } [Fact] public static void ThenBy_ArgumentNullException() { Assert.Throws<ArgumentNullException>(() => ((OrderedParallelQuery<int>)null).ThenBy(x => x)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).OrderBy(x => 0).ThenBy((Func<int, int>)null)); Assert.Throws<ArgumentNullException>(() => ((OrderedParallelQuery<int>)null).ThenBy(x => x, Comparer<int>.Default)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).OrderBy(x => 0).ThenBy((Func<int, int>)null, Comparer<int>.Default)); } [Fact] public static void ThenByDescending_ArgumentNullException() { Assert.Throws<ArgumentNullException>(() => ((OrderedParallelQuery<int>)null).ThenByDescending(x => x)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).OrderBy(x => 0).ThenByDescending((Func<int, int>)null)); Assert.Throws<ArgumentNullException>(() => ((OrderedParallelQuery<int>)null).ThenByDescending(x => x, Comparer<int>.Default)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).OrderBy(x => 0).ThenByDescending((Func<int, int>)null, Comparer<int>.Default)); } // // Stable Sort // [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void StableSort(Labeled<ParallelQuery<int>> labeled, int count) { var prev = KeyValuePair.Create(0, KeyValuePair.Create(0, 0)); foreach (var pOuter in labeled.Item.Select((x, index) => KeyValuePair.Create(index, KeyValuePair.Create(x, (count - x) / Math.Max(count / GroupFactor, 1)))) .OrderBy(p => p.Value.Value).ThenBy(p => p.Value.Key)) { Assert.False(pOuter.Value.Value < prev.Value.Value); Assert.False(pOuter.Value.Value == prev.Value.Value && pOuter.Key < prev.Key, "" + prev + "_" + pOuter); prev = pOuter; } } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(Sources))] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(UnorderedSources))] public static void StableSort_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { StableSort(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void StableSort_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count) { var prev = KeyValuePair.Create(0, KeyValuePair.Create(0, 0)); Assert.All(labeled.Item.Select((x, index) => KeyValuePair.Create(index, KeyValuePair.Create(x, (count - x) / Math.Max(count / GroupFactor, 1)))) .OrderBy(p => p.Value.Value).ThenBy(p => p.Value.Key).ToList(), pOuter => { Assert.False(pOuter.Value.Value < prev.Value.Value); Assert.False(pOuter.Value.Value == prev.Value.Value && pOuter.Key < prev.Key, "" + prev + "_" + pOuter); prev = pOuter; }); } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(Sources))] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(UnorderedSources))] public static void StableSort_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { StableSort_NotPipelined(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void StableSort_Descending(Labeled<ParallelQuery<int>> labeled, int count) { var prev = KeyValuePair.Create(int.MaxValue, KeyValuePair.Create(int.MaxValue, int.MaxValue)); foreach (var pOuter in labeled.Item.Select((x, index) => KeyValuePair.Create(index, KeyValuePair.Create(x, (count - x) / Math.Max(count / GroupFactor, 1)))) .OrderByDescending(p => p.Value.Value).ThenByDescending(p => p.Value.Key)) { Assert.False(pOuter.Value.Value > prev.Value.Value); Assert.False(pOuter.Value.Value == prev.Value.Value && pOuter.Key > prev.Key, "" + prev + "_" + pOuter); prev = pOuter; } } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(Sources))] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(UnorderedSources))] public static void StableSort_Descending_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { StableSort_Descending(labeled, count); } [Theory] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(Sources))] [MemberData("Ranges", (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void StableSort_Descending_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count) { var prev = KeyValuePair.Create(int.MaxValue, KeyValuePair.Create(int.MaxValue, int.MaxValue)); Assert.All(labeled.Item.Select((x, index) => KeyValuePair.Create(index, KeyValuePair.Create(x, (count - x) / Math.Max(count / GroupFactor, 1)))) .OrderByDescending(p => p.Value.Value).ThenByDescending(p => p.Value.Key).ToList(), pOuter => { Assert.False(pOuter.Value.Value > prev.Value.Value); Assert.False(pOuter.Value.Value == prev.Value.Value && pOuter.Key > prev.Key, "" + prev + "_" + pOuter); prev = pOuter; }); } [Theory] [OuterLoop] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(Sources))] [MemberData("Ranges", (object)(new int[] { 1024, 1024 * 32 }), MemberType = typeof(UnorderedSources))] public static void StableSort_Descending_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { StableSort_Descending_NotPipelined(labeled, count); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Text.RegularExpressions.Tests { public class RegexMultipleMatchTests { [Fact] public void Matches_MultipleCapturingGroups() { string[] expectedGroupValues = { "abracadabra", "abra", "cad" }; string[] expectedGroupCaptureValues = { "abracad", "abra" }; // Another example - given by Brad Merril in an article on RegularExpressions Regex regex = new Regex(@"(abra(cad)?)+"); string input = "abracadabra1abracadabra2abracadabra3"; Match match = regex.Match(input); while (match.Success) { string expected = "abracadabra"; Assert.Equal(expected, match.Value); Assert.Equal(3, match.Groups.Count); for (int i = 0; i < match.Groups.Count; i++) { Assert.Equal(expectedGroupValues[i], match.Groups[i].Value); if (i == 1) { Assert.Equal(2, match.Groups[i].Captures.Count); for (int j = 0; j < match.Groups[i].Captures.Count; j++) { Assert.Equal(expectedGroupCaptureValues[j], match.Groups[i].Captures[j].Value); } } else if (i == 2) { Assert.Equal(1, match.Groups[i].Captures.Count); Assert.Equal("cad", match.Groups[i].Captures[0].Value); } } Assert.Equal(1, match.Captures.Count); Assert.Equal("abracadabra", match.Captures[0].Value); match = match.NextMatch(); } } public static IEnumerable<object[]> Matches_TestData() { yield return new object[] { "[0-9]", "12345asdfasdfasdfljkhsda67890", RegexOptions.None, new CaptureData[] { new CaptureData("1", 0, 1), new CaptureData("2", 1, 1), new CaptureData("3", 2, 1), new CaptureData("4", 3, 1), new CaptureData("5", 4, 1), new CaptureData("6", 24, 1), new CaptureData("7", 25, 1), new CaptureData("8", 26, 1), new CaptureData("9", 27, 1), new CaptureData("0", 28, 1), } }; yield return new object[] { "[a-z0-9]+", "[token1]? GARBAGEtoken2GARBAGE ;token3!", RegexOptions.None, new CaptureData[] { new CaptureData("token1", 1, 6), new CaptureData("token2", 17, 6), new CaptureData("token3", 32, 6) } }; yield return new object[] { "(abc){2}", " !abcabcasl dkfjasiduf 12343214-//asdfjzpiouxoifzuoxpicvql23r\\` #$3245,2345278 :asdfas & 100% @daeeffga (ryyy27343) poiweurwabcabcasdfalksdhfaiuyoiruqwer{234}/[(132387 + x)]'aaa''?", RegexOptions.None, new CaptureData[] { new CaptureData("abcabc", 2, 6), new CaptureData("abcabc", 125, 6) } }; yield return new object[] { @"foo\d+", "0123456789foo4567890foo1foo 0987", RegexOptions.RightToLeft, new CaptureData[] { new CaptureData("foo1", 20, 4), new CaptureData("foo4567890", 10, 10), } }; yield return new object[] { "[a-z]", "a", RegexOptions.None, new CaptureData[] { new CaptureData("a", 0, 1) } }; yield return new object[] { "[a-z]", "a1bc", RegexOptions.None, new CaptureData[] { new CaptureData("a", 0, 1), new CaptureData("b", 2, 1), new CaptureData("c", 3, 1) } }; // Alternation construct yield return new object[] { "(?(A)A123|C789)", "A123 B456 C789", RegexOptions.None, new CaptureData[] { new CaptureData("A123", 0, 4), new CaptureData("C789", 10, 4), } }; yield return new object[] { "(?(A)A123|C789)", "A123 B456 C789", RegexOptions.None, new CaptureData[] { new CaptureData("A123", 0, 4), new CaptureData("C789", 10, 4), } }; } [Theory] [MemberData(nameof(Matches_TestData))] public void Matches(string pattern, string input, RegexOptions options, CaptureData[] expected) { if (options == RegexOptions.None) { Regex regexBasic = new Regex(pattern); VerifyMatches(regexBasic.Matches(input), expected); VerifyMatches(regexBasic.Match(input), expected); VerifyMatches(Regex.Matches(input, pattern), expected); VerifyMatches(Regex.Match(input, pattern), expected); } Regex regexAdvanced = new Regex(pattern, options); VerifyMatches(regexAdvanced.Matches(input), expected); VerifyMatches(regexAdvanced.Match(input), expected); VerifyMatches(Regex.Matches(input, pattern, options), expected); VerifyMatches(Regex.Match(input, pattern, options), expected); } public static void VerifyMatches(Match match, CaptureData[] expected) { for (int i = 0; match.Success; i++, match = match.NextMatch()) { VerifyMatch(match, expected[i]); } } public static void VerifyMatches(MatchCollection matches, CaptureData[] expected) { Assert.Equal(expected.Length, matches.Count); for (int i = 0; i < matches.Count; i++) { VerifyMatch(matches[i], expected[i]); } } public static void VerifyMatch(Match match, CaptureData expected) { Assert.True(match.Success); Assert.Equal(expected.Value, match.Value); Assert.Equal(expected.Index, match.Index); Assert.Equal(expected.Length, match.Length); Assert.Equal(expected.Value, match.Groups[0].Value); Assert.Equal(expected.Index, match.Groups[0].Index); Assert.Equal(expected.Length, match.Groups[0].Length); Assert.Equal(1, match.Captures.Count); Assert.Equal(expected.Value, match.Captures[0].Value); Assert.Equal(expected.Index, match.Captures[0].Index); Assert.Equal(expected.Length, match.Captures[0].Length); } [Fact] public void Matches_Invalid() { // Input is null Assert.Throws<ArgumentNullException>("input", () => Regex.Matches(null, "pattern")); Assert.Throws<ArgumentNullException>("input", () => Regex.Matches(null, "pattern", RegexOptions.None)); Assert.Throws<ArgumentNullException>("input", () => Regex.Matches(null, "pattern", RegexOptions.None, TimeSpan.FromSeconds(1))); Assert.Throws<ArgumentNullException>("input", () => new Regex("pattern").Matches(null)); Assert.Throws<ArgumentNullException>("input", () => new Regex("pattern").Matches(null, 0)); // Pattern is null Assert.Throws<ArgumentNullException>("pattern", () => Regex.Matches("input", null)); Assert.Throws<ArgumentNullException>("pattern", () => Regex.Matches("input", null, RegexOptions.None)); Assert.Throws<ArgumentNullException>("pattern", () => Regex.Matches("input", null, RegexOptions.None, TimeSpan.FromSeconds(1))); // Options are invalid Assert.Throws<ArgumentOutOfRangeException>("options", () => Regex.Matches("input", "pattern", (RegexOptions)(-1))); Assert.Throws<ArgumentOutOfRangeException>("options", () => Regex.Matches("input", "pattern", (RegexOptions)(-1), TimeSpan.FromSeconds(1))); Assert.Throws<ArgumentOutOfRangeException>("options", () => Regex.Matches("input", "pattern", (RegexOptions)0x400)); Assert.Throws<ArgumentOutOfRangeException>("options", () => Regex.Matches("input", "pattern", (RegexOptions)0x400, TimeSpan.FromSeconds(1))); // MatchTimeout is invalid Assert.Throws<ArgumentOutOfRangeException>("matchTimeout", () => Regex.Matches("input", "pattern", RegexOptions.None, TimeSpan.Zero)); Assert.Throws<ArgumentOutOfRangeException>("matchTimeout", () => Regex.Matches("input", "pattern", RegexOptions.None, TimeSpan.Zero)); // Start is invalid Assert.Throws<ArgumentOutOfRangeException>("startat", () => new Regex("pattern").Matches("input", -1)); Assert.Throws<ArgumentOutOfRangeException>("startat", () => new Regex("pattern").Matches("input", 6)); } [Fact] public void NextMatch_EmptyMatch_ReturnsEmptyMatch() { Assert.Same(Match.Empty, Match.Empty.NextMatch()); } } }