context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.IO; using UnityEditor; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Editor { public class TextureCombinerWindow : EditorWindow { private enum Channel { Red = 0, Green = 1, Blue = 2, Alpha = 3, RGBAverage = 4 } private enum TextureFormat { TGA = 0, PNG = 1, JPG = 2 } private static readonly string[] textureExtensions = new string[] { "tga", "png", "jpg" }; private const float defaultUniformValue = -0.01f; private Texture2D metallicMap; private Channel metallicMapChannel = Channel.Red; private float metallicUniform = defaultUniformValue; private Texture2D occlusionMap; private Channel occlusionMapChannel = Channel.Green; private float occlusionUniform = defaultUniformValue; private Texture2D emissionMap; private Channel emissionMapChannel = Channel.RGBAverage; private float emissionUniform = defaultUniformValue; private Texture2D smoothnessMap; private Channel smoothnessMapChannel = Channel.Alpha; private float smoothnessUniform = defaultUniformValue; private Material standardMaterial; private TextureFormat textureFormat = TextureFormat.TGA; private const string StandardShaderName = "Standard"; private const string StandardRoughnessShaderName = "Standard (Roughness setup)"; private const string StandardSpecularShaderName = "Standard (Specular setup)"; [MenuItem("Mixed Reality/Toolkit/Utilities/Texture Combiner")] private static void ShowWindow() { TextureCombinerWindow window = GetWindow<TextureCombinerWindow>(); window.titleContent = new GUIContent("Texture Combiner"); window.minSize = new Vector2(380.0f, 700.0f); window.Show(); } private void OnGUI() { GUILayout.Label("Import", EditorStyles.boldLabel); GUI.enabled = metallicUniform < 0.0f; metallicMap = (Texture2D)EditorGUILayout.ObjectField("Metallic Map", metallicMap, typeof(Texture2D), false); metallicMapChannel = (Channel)EditorGUILayout.EnumPopup("Input Channel", metallicMapChannel); GUI.enabled = true; metallicUniform = EditorGUILayout.Slider(new GUIContent("Metallic Uniform"), metallicUniform, defaultUniformValue, 1.0f); GUILayout.Box("Output Channel: Red", EditorStyles.helpBox, System.Array.Empty<GUILayoutOption>()); EditorGUILayout.Separator(); GUI.enabled = occlusionUniform < 0.0f; occlusionMap = (Texture2D)EditorGUILayout.ObjectField("Occlusion Map", occlusionMap, typeof(Texture2D), false); occlusionMapChannel = (Channel)EditorGUILayout.EnumPopup("Input Channel", occlusionMapChannel); GUI.enabled = true; occlusionUniform = EditorGUILayout.Slider(new GUIContent("Occlusion Uniform"), occlusionUniform, defaultUniformValue, 1.0f); GUILayout.Box("Output Channel: Green", EditorStyles.helpBox, System.Array.Empty<GUILayoutOption>()); EditorGUILayout.Separator(); GUI.enabled = emissionUniform < 0.0f; emissionMap = (Texture2D)EditorGUILayout.ObjectField("Emission Map", emissionMap, typeof(Texture2D), false); emissionMapChannel = (Channel)EditorGUILayout.EnumPopup("Input Channel", emissionMapChannel); GUI.enabled = true; emissionUniform = EditorGUILayout.Slider(new GUIContent("Emission Uniform"), emissionUniform, defaultUniformValue, 1.0f); GUILayout.Box("Output Channel: Blue", EditorStyles.helpBox, System.Array.Empty<GUILayoutOption>()); EditorGUILayout.Separator(); GUI.enabled = smoothnessUniform < 0.0f; smoothnessMap = (Texture2D)EditorGUILayout.ObjectField("Smoothness Map", smoothnessMap, typeof(Texture2D), false); smoothnessMapChannel = (Channel)EditorGUILayout.EnumPopup("Input Channel", smoothnessMapChannel); GUI.enabled = true; smoothnessUniform = EditorGUILayout.Slider(new GUIContent("Smoothness Uniform"), smoothnessUniform, defaultUniformValue, 1.0f); GUILayout.Box("Output Channel: Alpha", EditorStyles.helpBox, System.Array.Empty<GUILayoutOption>()); EditorGUILayout.Separator(); standardMaterial = (Material)EditorGUILayout.ObjectField("Standard Material", standardMaterial, typeof(Material), false); GUI.enabled = standardMaterial != null && IsUnityStandardMaterial(standardMaterial); if (GUILayout.Button("Auto-populate from Standard Material")) { Autopopulate(); } GUI.enabled = CanSave(); EditorGUILayout.Separator(); GUILayout.Label("Export", EditorStyles.boldLabel); textureFormat = (TextureFormat)EditorGUILayout.EnumPopup("Texture Format", textureFormat); if (GUILayout.Button("Save Channel Map")) { Save(); } GUILayout.Box("Metallic (Red), Occlusion (Green), Emission (Blue), Smoothness (Alpha)", EditorStyles.helpBox, System.Array.Empty<GUILayoutOption>()); } private void Autopopulate() { metallicUniform = defaultUniformValue; occlusionUniform = defaultUniformValue; emissionUniform = defaultUniformValue; smoothnessUniform = defaultUniformValue; occlusionMap = (Texture2D)standardMaterial.GetTexture("_OcclusionMap"); occlusionMapChannel = occlusionMap != null ? Channel.Green : occlusionMapChannel; emissionMap = (Texture2D)standardMaterial.GetTexture("_EmissionMap"); emissionMapChannel = emissionMap != null ? Channel.RGBAverage : emissionMapChannel; if (standardMaterial.shader.name == StandardShaderName) { metallicMap = (Texture2D)standardMaterial.GetTexture("_MetallicGlossMap"); metallicMapChannel = metallicMap != null ? Channel.Red : metallicMapChannel; smoothnessMap = ((int)standardMaterial.GetFloat("_SmoothnessTextureChannel") == 0) ? metallicMap : (Texture2D)standardMaterial.GetTexture("_MainTex"); smoothnessMapChannel = smoothnessMap != null ? Channel.Alpha : smoothnessMapChannel; } else if (standardMaterial.shader.name == StandardRoughnessShaderName) { metallicMap = (Texture2D)standardMaterial.GetTexture("_MetallicGlossMap"); metallicMapChannel = metallicMap != null ? Channel.Red : metallicMapChannel; smoothnessMap = (Texture2D)standardMaterial.GetTexture("_SpecGlossMap"); smoothnessMapChannel = smoothnessMap != null ? Channel.Red : smoothnessMapChannel; } else { smoothnessMap = ((int)standardMaterial.GetFloat("_SmoothnessTextureChannel") == 0) ? (Texture2D)standardMaterial.GetTexture("_SpecGlossMap") : (Texture2D)standardMaterial.GetTexture("_MainTex"); smoothnessMapChannel = smoothnessMap != null ? Channel.Alpha : smoothnessMapChannel; } } private void Save() { int width; int height; Texture[] textures = new Texture[] { metallicMap, occlusionMap, emissionMap, smoothnessMap }; CalculateChannelMapSize(textures, out width, out height); Texture2D channelMap = new Texture2D(width, height); RenderTexture renderTexture = RenderTexture.GetTemporary(width, height, 0, RenderTextureFormat.Default, RenderTextureReadWrite.Linear); // Use the GPU to pack the various texture maps into a single texture. Material channelPacker = new Material(Shader.Find("Hidden/ChannelPacker")); channelPacker.SetTexture("_MetallicMap", metallicMap); channelPacker.SetInt("_MetallicMapChannel", (int)metallicMapChannel); channelPacker.SetFloat("_MetallicUniform", metallicUniform); channelPacker.SetTexture("_OcclusionMap", occlusionMap); channelPacker.SetInt("_OcclusionMapChannel", (int)occlusionMapChannel); channelPacker.SetFloat("_OcclusionUniform", occlusionUniform); channelPacker.SetTexture("_EmissionMap", emissionMap); channelPacker.SetInt("_EmissionMapChannel", (int)emissionMapChannel); channelPacker.SetFloat("_EmissionUniform", emissionUniform); channelPacker.SetTexture("_SmoothnessMap", smoothnessMap); channelPacker.SetInt("_SmoothnessMapChannel", (int)smoothnessMapChannel); channelPacker.SetFloat("_SmoothnessUniform", smoothnessUniform); Graphics.Blit(null, renderTexture, channelPacker); DestroyImmediate(channelPacker); // Save the last render texture to a texture. RenderTexture previous = RenderTexture.active; RenderTexture.active = renderTexture; channelMap.ReadPixels(new Rect(0.0f, 0.0f, width, height), 0, 0); channelMap.Apply(); RenderTexture.active = previous; RenderTexture.ReleaseTemporary(renderTexture); // Save the texture to disk. string filename = string.Format("{0}{1}.{2}", GetChannelMapName(textures), "_Channel", textureExtensions[(int)textureFormat]); string path = EditorUtility.SaveFilePanel("Save Channel Map", "", filename, textureExtensions[(int)textureFormat]); if (path.Length != 0) { byte[] textureData = null; switch (textureFormat) { case TextureFormat.TGA: textureData = channelMap.EncodeToTGA(); break; case TextureFormat.PNG: textureData = channelMap.EncodeToPNG(); break; case TextureFormat.JPG: textureData = channelMap.EncodeToJPG(); break; } if (textureData != null) { File.WriteAllBytes(path, textureData); Debug.LogFormat("Saved channel map to: {0}", path); AssetDatabase.Refresh(); } } } private bool CanSave() { return metallicMap != null || occlusionMap != null || emissionMap != null || smoothnessMap != null || metallicUniform >= 0.0f || occlusionUniform >= 0.0f || emissionUniform >= 0.0f || smoothnessUniform >= 0.0f; } private static bool IsUnityStandardMaterial(Material material) { if (material != null) { if (material.shader.name == StandardShaderName || material.shader.name == StandardRoughnessShaderName || material.shader.name == StandardSpecularShaderName) { return true; } } return false; } private static string GetChannelMapName(Texture[] textures) { // Use the first named texture as the channel map name. foreach (Texture texture in textures) { if (texture != null && !string.IsNullOrEmpty(texture.name)) { return texture.name; } } return string.Empty; } private static void CalculateChannelMapSize(Texture[] textures, out int width, out int height) { width = 4; height = 4; // Find the max extents of all texture maps. foreach (Texture texture in textures) { width = texture != null ? Mathf.Max(texture.width, width) : width; height = texture != null ? Mathf.Max(texture.height, height) : height; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.MSBuild { /// <summary> /// A map of projects that can be optionally used with <see cref="MSBuildProjectLoader.LoadProjectInfoAsync"/> when loading a /// project into a custom <see cref="Workspace"/>. To use, pass <see cref="Workspace.CurrentSolution"/> to <see cref="Create(Solution)"/>. /// </summary> public class ProjectMap { /// <summary> /// A map of project path to <see cref="ProjectId"/>s. Note that there can be multiple <see cref="ProjectId"/>s per project path /// if the project is multi-targeted -- one for each target framework. /// </summary> private readonly Dictionary<string, HashSet<ProjectId>> _projectPathToProjectIdsMap; /// <summary> /// A map of project path to <see cref="ProjectInfo"/>s. Note that there can be multiple <see cref="ProjectId"/>s per project path /// if the project is multi-targeted -- one for each target framework. /// </summary> private readonly Dictionary<string, ImmutableArray<ProjectInfo>> _projectPathToProjectInfosMap; /// <summary> /// A map of <see cref="ProjectId"/> to the output file of the project (if any). /// </summary> private readonly Dictionary<ProjectId, string> _projectIdToOutputFilePathMap; /// <summary> /// A map of <see cref="ProjectId"/> to the output ref file of the project (if any). /// </summary> private readonly Dictionary<ProjectId, string> _projectIdToOutputRefFilePathMap; private ProjectMap() { _projectPathToProjectIdsMap = new Dictionary<string, HashSet<ProjectId>>(PathUtilities.Comparer); _projectPathToProjectInfosMap = new Dictionary<string, ImmutableArray<ProjectInfo>>(PathUtilities.Comparer); _projectIdToOutputFilePathMap = new Dictionary<ProjectId, string>(); _projectIdToOutputRefFilePathMap = new Dictionary<ProjectId, string>(); } /// <summary> /// Create an empty <see cref="ProjectMap"/>. /// </summary> public static ProjectMap Create() => new(); /// <summary> /// Create a <see cref="ProjectMap"/> populated with the given <see cref="Solution"/>. /// </summary> /// <param name="solution">The <see cref="Solution"/> to populate the new <see cref="ProjectMap"/> with.</param> /// <returns></returns> public static ProjectMap Create(Solution solution) { var projectMap = new ProjectMap(); foreach (var project in solution.Projects) { projectMap.Add(project); } return projectMap; } /// <summary> /// Add a <see cref="Project"/> to this <see cref="ProjectMap"/>. /// </summary> /// <param name="project">The <see cref="Project"/> to add to this <see cref="ProjectMap"/>.</param> public void Add(Project project) { Add(project.Id, project.FilePath, project.OutputFilePath, project.OutputRefFilePath); AddProjectInfo(project.State.ProjectInfo); } private void Add(ProjectId projectId, string? projectPath, string? outputFilePath, string? outputRefFilePath) { if (!RoslynString.IsNullOrEmpty(projectPath)) { _projectPathToProjectIdsMap.MultiAdd(projectPath, projectId); } if (!RoslynString.IsNullOrEmpty(outputFilePath)) { _projectIdToOutputFilePathMap.Add(projectId, outputFilePath); } if (!RoslynString.IsNullOrEmpty(outputRefFilePath)) { _projectIdToOutputRefFilePathMap.Add(projectId, outputRefFilePath); } } internal void AddProjectInfo(ProjectInfo projectInfo) { var projectFilePath = projectInfo.FilePath; if (RoslynString.IsNullOrEmpty(projectFilePath)) { throw new ArgumentException(WorkspaceMSBuildResources.Project_does_not_have_a_path); } if (!_projectPathToProjectInfosMap.TryGetValue(projectFilePath, out var projectInfos)) { projectInfos = ImmutableArray<ProjectInfo>.Empty; } if (projectInfos.Contains(pi => pi.Id == projectInfo.Id)) { throw new ArgumentException(WorkspaceMSBuildResources.Project_already_added); } projectInfos = projectInfos.Add(projectInfo); _projectPathToProjectInfosMap[projectFilePath] = projectInfos; } private ProjectId CreateProjectId(string? projectPath, string? outputFilePath, string? outputRefFilePath) { var newProjectId = ProjectId.CreateNewId(debugName: projectPath); Add(newProjectId, projectPath, outputFilePath, outputRefFilePath); return newProjectId; } internal ProjectId GetOrCreateProjectId(string projectPath) { if (!_projectPathToProjectIdsMap.TryGetValue(projectPath, out var projectIds)) { projectIds = new HashSet<ProjectId>(); _projectPathToProjectIdsMap.Add(projectPath, projectIds); } return projectIds.Count == 1 ? projectIds.Single() : CreateProjectId(projectPath, outputFilePath: null, outputRefFilePath: null); } internal ProjectId GetOrCreateProjectId(ProjectFileInfo projectFileInfo) { var projectPath = projectFileInfo.FilePath; var outputFilePath = projectFileInfo.OutputFilePath; var outputRefFilePath = projectFileInfo.OutputRefFilePath; if (projectPath is not null && TryGetIdsByProjectPath(projectPath, out var projectIds)) { if (TryFindOutputFileRefPathInProjectIdSet(outputRefFilePath, projectIds, out var projectId) || TryFindOutputFilePathInProjectIdSet(outputFilePath, projectIds, out projectId)) { return projectId; } } return CreateProjectId(projectPath, outputFilePath, outputRefFilePath); } private bool TryFindOutputFileRefPathInProjectIdSet(string? outputRefFilePath, HashSet<ProjectId> set, [NotNullWhen(true)] out ProjectId? result) => TryFindPathInProjectIdSet(outputRefFilePath, GetOutputRefFilePathById, set, out result); private bool TryFindOutputFilePathInProjectIdSet(string? outputFilePath, HashSet<ProjectId> set, [NotNullWhen(true)] out ProjectId? result) => TryFindPathInProjectIdSet(outputFilePath, GetOutputFilePathById, set, out result); private static bool TryFindPathInProjectIdSet(string? path, Func<ProjectId, string?> getPathById, HashSet<ProjectId> set, [NotNullWhen(true)] out ProjectId? result) { if (!RoslynString.IsNullOrEmpty(path)) { foreach (var id in set) { var p = getPathById(id); if (PathUtilities.Comparer.Equals(p, path)) { result = id; return true; } } } result = null; return false; } internal string? GetOutputRefFilePathById(ProjectId projectId) => TryGetOutputRefFilePathById(projectId, out var path) ? path : null; internal string? GetOutputFilePathById(ProjectId projectId) => TryGetOutputFilePathById(projectId, out var path) ? path : null; internal bool TryGetIdsByProjectPath(string projectPath, [NotNullWhen(true)] out HashSet<ProjectId>? ids) => _projectPathToProjectIdsMap.TryGetValue(projectPath, out ids); internal bool TryGetOutputFilePathById(ProjectId id, [NotNullWhen(true)] out string? outputFilePath) => _projectIdToOutputFilePathMap.TryGetValue(id, out outputFilePath); internal bool TryGetOutputRefFilePathById(ProjectId id, [NotNullWhen(true)] out string? outputRefFilePath) => _projectIdToOutputRefFilePathMap.TryGetValue(id, out outputRefFilePath); internal bool TryGetProjectInfosByProjectPath(string projectPath, out ImmutableArray<ProjectInfo> projectInfos) => _projectPathToProjectInfosMap.TryGetValue(projectPath, out projectInfos); } }
// // 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.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; using Microsoft.WindowsAzure.Management.Compute; using Microsoft.WindowsAzure.Management.Compute.Models; namespace Microsoft.WindowsAzure.Management.Compute { /// <summary> /// Operations for managing service certificates for your subscription. /// (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee795178.aspx for /// more information) /// </summary> internal partial class ServiceCertificateOperations : IServiceOperations<ComputeManagementClient>, Microsoft.WindowsAzure.Management.Compute.IServiceCertificateOperations { /// <summary> /// Initializes a new instance of the ServiceCertificateOperations /// class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ServiceCertificateOperations(ComputeManagementClient client) { this._client = client; } private ComputeManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.Compute.ComputeManagementClient. /// </summary> public ComputeManagementClient Client { get { return this._client; } } /// <summary> /// The Begin Creating Service Certificate operation adds a certificate /// to a hosted service. This operation is an asynchronous operation. /// To determine whether the management service has finished /// processing the request, call Get Operation Status. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460817.aspx /// for more information) /// </summary> /// <param name='serviceName'> /// Required. The DNS prefix name of your service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Begin Creating Service /// Certificate operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async System.Threading.Tasks.Task<OperationResponse> BeginCreatingAsync(string serviceName, ServiceCertificateCreateParameters parameters, CancellationToken cancellationToken) { // Validate if (serviceName == null) { throw new ArgumentNullException("serviceName"); } // TODO: Validate serviceName is a valid DNS name. if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Data == null) { throw new ArgumentNullException("parameters.Data"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "BeginCreatingAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/hostedservices/" + serviceName.Trim() + "/certificates"; 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("x-ms-version", "2014-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement certificateFileElement = new XElement(XName.Get("CertificateFile", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(certificateFileElement); XElement dataElement = new XElement(XName.Get("Data", "http://schemas.microsoft.com/windowsazure")); dataElement.Value = Convert.ToBase64String(parameters.Data); certificateFileElement.Add(dataElement); XElement certificateFormatElement = new XElement(XName.Get("CertificateFormat", "http://schemas.microsoft.com/windowsazure")); certificateFormatElement.Value = ComputeManagementClient.CertificateFormatToString(parameters.CertificateFormat); certificateFileElement.Add(certificateFormatElement); if (parameters.Password != null) { XElement passwordElement = new XElement(XName.Get("Password", "http://schemas.microsoft.com/windowsazure")); passwordElement.Value = parameters.Password; certificateFileElement.Add(passwordElement); } requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.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) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result OperationResponse result = null; result = new OperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Begin Deleting Service Certificate operation deletes a service /// certificate from the certificate store of a hosted service. This /// operation is an asynchronous operation. To determine whether the /// management service has finished processing the request, call Get /// Operation Status. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460803.aspx /// for more information) /// </summary> /// <param name='parameters'> /// Required. Parameters supplied to the Begin Deleting Service /// Certificate operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async System.Threading.Tasks.Task<OperationResponse> BeginDeletingAsync(ServiceCertificateDeleteParameters parameters, CancellationToken cancellationToken) { // Validate if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.ServiceName == null) { throw new ArgumentNullException("parameters.ServiceName"); } // TODO: Validate parameters.ServiceName is a valid DNS name. if (parameters.Thumbprint == null) { throw new ArgumentNullException("parameters.Thumbprint"); } if (parameters.ThumbprintAlgorithm == null) { throw new ArgumentNullException("parameters.ThumbprintAlgorithm"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "BeginDeletingAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/hostedservices/" + parameters.ServiceName.Trim() + "/certificates/" + parameters.ThumbprintAlgorithm.Trim() + "-" + parameters.Thumbprint.Trim(); 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("x-ms-version", "2014-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.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) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result OperationResponse result = null; result = new OperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Create Service Certificate operation adds a certificate to a /// hosted service. This operation is an asynchronous operation. To /// determine whether the management service has finished processing /// the request, call Get Operation Status. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460817.aspx /// for more information) /// </summary> /// <param name='serviceName'> /// Required. The DNS prefix name of your service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Create Service Certificate /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public async System.Threading.Tasks.Task<OperationStatusResponse> CreateAsync(string serviceName, ServiceCertificateCreateParameters parameters, CancellationToken cancellationToken) { ComputeManagementClient client = this.Client; bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "CreateAsync", tracingParameters); } try { if (shouldTrace) { client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId)); } cancellationToken.ThrowIfCancellationRequested(); OperationResponse response = await client.ServiceCertificates.BeginCreatingAsync(serviceName, parameters, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); int 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.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); delayInSeconds = 30; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { Tracing.Exit(invocationId, result); } if (result.Status != OperationStatus.Succeeded) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.ErrorCode = result.Error.Code; ex.ErrorMessage = result.Error.Message; if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } } return result; } finally { if (client != null && shouldTrace) { client.Dispose(); } } } /// <summary> /// The Delete Service Certificate operation deletes a service /// certificate from the certificate store of a hosted service. This /// operation is an asynchronous operation. To determine whether the /// management service has finished processing the request, call Get /// Operation Status. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460803.aspx /// for more information) /// </summary> /// <param name='parameters'> /// Required. Parameters supplied to the Delete Service Certificate /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public async System.Threading.Tasks.Task<OperationStatusResponse> DeleteAsync(ServiceCertificateDeleteParameters parameters, CancellationToken cancellationToken) { ComputeManagementClient client = this.Client; bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "DeleteAsync", tracingParameters); } try { if (shouldTrace) { client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId)); } cancellationToken.ThrowIfCancellationRequested(); OperationResponse response = await client.ServiceCertificates.BeginDeletingAsync(parameters, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); int 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.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); delayInSeconds = 30; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { Tracing.Exit(invocationId, result); } if (result.Status != OperationStatus.Succeeded) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.ErrorCode = result.Error.Code; ex.ErrorMessage = result.Error.Message; if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } } return result; } finally { if (client != null && shouldTrace) { client.Dispose(); } } } /// <summary> /// The Get Service Certificate operation returns the public data for /// the specified X.509 certificate associated with a hosted service. /// (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460792.aspx /// for more information) /// </summary> /// <param name='parameters'> /// Required. Parameters supplied to the Get Service Certificate /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Get Service Certificate operation response. /// </returns> public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Compute.Models.ServiceCertificateGetResponse> GetAsync(ServiceCertificateGetParameters parameters, CancellationToken cancellationToken) { // Validate if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.ServiceName == null) { throw new ArgumentNullException("parameters.ServiceName"); } // TODO: Validate parameters.ServiceName is a valid DNS name. if (parameters.Thumbprint == null) { throw new ArgumentNullException("parameters.Thumbprint"); } if (parameters.ThumbprintAlgorithm == null) { throw new ArgumentNullException("parameters.ThumbprintAlgorithm"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/hostedservices/" + parameters.ServiceName.Trim() + "/certificates/" + parameters.ThumbprintAlgorithm.Trim() + "-" + parameters.Thumbprint.Trim(); 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-version", "2014-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.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) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result ServiceCertificateGetResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServiceCertificateGetResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement certificateElement = responseDoc.Element(XName.Get("Certificate", "http://schemas.microsoft.com/windowsazure")); if (certificateElement != null) { XElement dataElement = certificateElement.Element(XName.Get("Data", "http://schemas.microsoft.com/windowsazure")); if (dataElement != null) { byte[] dataInstance = Convert.FromBase64String(dataElement.Value); result.Data = dataInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The List Service Certificates operation lists all of the service /// certificates associated with the specified hosted service. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154105.aspx /// for more information) /// </summary> /// <param name='serviceName'> /// Required. The DNS prefix name of your hosted service. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Service Certificates operation response. /// </returns> public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Compute.Models.ServiceCertificateListResponse> ListAsync(string serviceName, CancellationToken cancellationToken) { // Validate if (serviceName == null) { throw new ArgumentNullException("serviceName"); } // TODO: Validate serviceName is a valid DNS name. // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceName", serviceName); Tracing.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/hostedservices/" + serviceName.Trim() + "/certificates"; 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-version", "2014-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.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) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result ServiceCertificateListResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServiceCertificateListResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement certificatesSequenceElement = responseDoc.Element(XName.Get("Certificates", "http://schemas.microsoft.com/windowsazure")); if (certificatesSequenceElement != null) { foreach (XElement certificatesElement in certificatesSequenceElement.Elements(XName.Get("Certificate", "http://schemas.microsoft.com/windowsazure"))) { ServiceCertificateListResponse.Certificate certificateInstance = new ServiceCertificateListResponse.Certificate(); result.Certificates.Add(certificateInstance); XElement certificateUrlElement = certificatesElement.Element(XName.Get("CertificateUrl", "http://schemas.microsoft.com/windowsazure")); if (certificateUrlElement != null) { Uri certificateUrlInstance = TypeConversion.TryParseUri(certificateUrlElement.Value); certificateInstance.CertificateUri = certificateUrlInstance; } XElement thumbprintElement = certificatesElement.Element(XName.Get("Thumbprint", "http://schemas.microsoft.com/windowsazure")); if (thumbprintElement != null) { string thumbprintInstance = thumbprintElement.Value; certificateInstance.Thumbprint = thumbprintInstance; } XElement thumbprintAlgorithmElement = certificatesElement.Element(XName.Get("ThumbprintAlgorithm", "http://schemas.microsoft.com/windowsazure")); if (thumbprintAlgorithmElement != null) { string thumbprintAlgorithmInstance = thumbprintAlgorithmElement.Value; certificateInstance.ThumbprintAlgorithm = thumbprintAlgorithmInstance; } XElement dataElement = certificatesElement.Element(XName.Get("Data", "http://schemas.microsoft.com/windowsazure")); if (dataElement != null) { byte[] dataInstance = Convert.FromBase64String(dataElement.Value); certificateInstance.Data = dataInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute; using EditorBrowsableState = System.ComponentModel.EditorBrowsableState; using Internal.Runtime.CompilerServices; #pragma warning disable 0809 //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)' #pragma warning disable SA1121 // explicitly using type aliases instead of built-in types #if BIT64 using nuint = System.UInt64; #else using nuint = System.UInt32; #endif namespace System { /// <summary> /// Span represents a contiguous region of arbitrary memory. Unlike arrays, it can point to either managed /// or native memory, or to memory allocated on the stack. It is type- and memory-safe. /// </summary> [DebuggerTypeProxy(typeof(SpanDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] [NonVersionable] public readonly ref struct Span<T> { /// <summary>A byref or a native ptr.</summary> internal readonly ByReference<T> _pointer; /// <summary>The number of elements this Span contains.</summary> private readonly int _length; /// <summary> /// Creates a new span over the entirety of the target array. /// </summary> /// <param name="array">The target array.</param> /// <remarks>Returns default when <paramref name="array"/> is null.</remarks> /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span(T[]? array) { if (array == null) { this = default; return; // returns default } if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) ThrowHelper.ThrowArrayTypeMismatchException(); _pointer = new ByReference<T>(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData())); _length = array.Length; } /// <summary> /// Creates a new span over the portion of the target array beginning /// at 'start' index and ending at 'end' index (exclusive). /// </summary> /// <param name="array">The target array.</param> /// <param name="start">The index at which to begin the span.</param> /// <param name="length">The number of items in the span.</param> /// <remarks>Returns default when <paramref name="array"/> is null.</remarks> /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in the range (&lt;0 or &gt;Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span(T[]? array, int start, int length) { if (array == null) { if (start != 0 || length != 0) ThrowHelper.ThrowArgumentOutOfRangeException(); this = default; return; // returns default } if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) ThrowHelper.ThrowArrayTypeMismatchException(); #if BIT64 // See comment in Span<T>.Slice for how this works. if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)array.Length) ThrowHelper.ThrowArgumentOutOfRangeException(); #else if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(); #endif _pointer = new ByReference<T>(ref Unsafe.Add(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()), start)); _length = length; } /// <summary> /// Creates a new span over the target unmanaged buffer. Clearly this /// is quite dangerous, because we are creating arbitrarily typed T's /// out of a void*-typed block of memory. And the length is not checked. /// But if this creation is correct, then all subsequent uses are correct. /// </summary> /// <param name="pointer">An unmanaged pointer to memory.</param> /// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param> /// <exception cref="System.ArgumentException"> /// Thrown when <typeparamref name="T"/> is reference type or contains pointers and hence cannot be stored in unmanaged memory. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="length"/> is negative. /// </exception> [CLSCompliant(false)] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe Span(void* pointer, int length) { if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); if (length < 0) ThrowHelper.ThrowArgumentOutOfRangeException(); _pointer = new ByReference<T>(ref Unsafe.As<byte, T>(ref *(byte*)pointer)); _length = length; } // Constructor for internal use only. [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Span(ref T ptr, int length) { Debug.Assert(length >= 0); _pointer = new ByReference<T>(ref ptr); _length = length; } /// <summary> /// Returns a reference to specified element of the Span. /// </summary> /// <param name="index"></param> /// <returns></returns> /// <exception cref="System.IndexOutOfRangeException"> /// Thrown when index less than 0 or index greater than or equal to Length /// </exception> public ref T this[int index] { [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] get { if ((uint)index >= (uint)_length) ThrowHelper.ThrowIndexOutOfRangeException(); return ref Unsafe.Add(ref _pointer.Value, index); } } /// <summary> /// The number of items in the span. /// </summary> public int Length { [NonVersionable] get => _length; } /// <summary> /// Returns true if Length is 0. /// </summary> public bool IsEmpty { [NonVersionable] get => 0 >= (uint)_length; // Workaround for https://github.com/dotnet/coreclr/issues/19620 } /// <summary> /// Returns false if left and right point at the same memory and have the same length. Note that /// this does *not* check to see if the *contents* are equal. /// </summary> public static bool operator !=(Span<T> left, Span<T> right) => !(left == right); /// <summary> /// This method is not supported as spans cannot be boxed. To compare two spans, use operator==. /// <exception cref="System.NotSupportedException"> /// Always thrown by this method. /// </exception> /// </summary> [Obsolete("Equals() on Span will always throw an exception. Use == instead.")] [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => throw new NotSupportedException(SR.NotSupported_CannotCallEqualsOnSpan); /// <summary> /// This method is not supported as spans cannot be boxed. /// <exception cref="System.NotSupportedException"> /// Always thrown by this method. /// </exception> /// </summary> [Obsolete("GetHashCode() on Span will always throw an exception.")] [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => throw new NotSupportedException(SR.NotSupported_CannotCallGetHashCodeOnSpan); /// <summary> /// Defines an implicit conversion of an array to a <see cref="Span{T}"/> /// </summary> public static implicit operator Span<T>(T[]? array) => new Span<T>(array); /// <summary> /// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Span{T}"/> /// </summary> public static implicit operator Span<T>(ArraySegment<T> segment) => new Span<T>(segment.Array, segment.Offset, segment.Count); /// <summary> /// Returns an empty <see cref="Span{T}"/> /// </summary> public static Span<T> Empty => default; /// <summary>Gets an enumerator for this span.</summary> public Enumerator GetEnumerator() => new Enumerator(this); /// <summary>Enumerates the elements of a <see cref="Span{T}"/>.</summary> public ref struct Enumerator { /// <summary>The span being enumerated.</summary> private readonly Span<T> _span; /// <summary>The next index to yield.</summary> private int _index; /// <summary>Initialize the enumerator.</summary> /// <param name="span">The span to enumerate.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Enumerator(Span<T> span) { _span = span; _index = -1; } /// <summary>Advances the enumerator to the next element of the span.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool MoveNext() { int index = _index + 1; if (index < _span.Length) { _index = index; return true; } return false; } /// <summary>Gets the element at the current position of the enumerator.</summary> public ref T Current { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => ref _span[_index]; } } /// <summary> /// Returns a reference to the 0th element of the Span. If the Span is empty, returns null reference. /// It can be used for pinning and is required to support the use of span within a fixed statement. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public ref T GetPinnableReference() { // Ensure that the native code has just one forward branch that is predicted-not-taken. ref T ret = ref Unsafe.NullRef<T>(); if (_length != 0) ret = ref _pointer.Value; return ref ret; } /// <summary> /// Clears the contents of this span. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Clear() { if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) { SpanHelpers.ClearWithReferences(ref Unsafe.As<T, IntPtr>(ref _pointer.Value), (nuint)_length * (nuint)(Unsafe.SizeOf<T>() / sizeof(nuint))); } else { SpanHelpers.ClearWithoutReferences(ref Unsafe.As<T, byte>(ref _pointer.Value), (nuint)_length * (nuint)Unsafe.SizeOf<T>()); } } /// <summary> /// Fills the contents of this span with the given value. /// </summary> public void Fill(T value) { if (Unsafe.SizeOf<T>() == 1) { uint length = (uint)_length; if (length == 0) return; T tmp = value; // Avoid taking address of the "value" argument. It would regress performance of the loop below. Unsafe.InitBlockUnaligned(ref Unsafe.As<T, byte>(ref _pointer.Value), Unsafe.As<T, byte>(ref tmp), length); } else { // Do all math as nuint to avoid unnecessary 64->32->64 bit integer truncations nuint length = (uint)_length; if (length == 0) return; ref T r = ref _pointer.Value; // TODO: Create block fill for value types of power of two sizes e.g. 2,4,8,16 nuint elementSize = (uint)Unsafe.SizeOf<T>(); nuint i = 0; for (; i < (length & ~(nuint)7); i += 8) { Unsafe.AddByteOffset<T>(ref r, (i + 0) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 1) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 2) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 3) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 4) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 5) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 6) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 7) * elementSize) = value; } if (i < (length & ~(nuint)3)) { Unsafe.AddByteOffset<T>(ref r, (i + 0) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 1) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 2) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 3) * elementSize) = value; i += 4; } for (; i < length; i++) { Unsafe.AddByteOffset<T>(ref r, i * elementSize) = value; } } } /// <summary> /// Copies the contents of this span into destination span. If the source /// and destinations overlap, this method behaves as if the original values in /// a temporary location before the destination is overwritten. /// </summary> /// <param name="destination">The span to copy items into.</param> /// <exception cref="System.ArgumentException"> /// Thrown when the destination Span is shorter than the source Span. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void CopyTo(Span<T> destination) { // Using "if (!TryCopyTo(...))" results in two branches: one for the length // check, and one for the result of TryCopyTo. Since these checks are equivalent, // we can optimize by performing the check once ourselves then calling Memmove directly. if ((uint)_length <= (uint)destination.Length) { Buffer.Memmove(ref destination._pointer.Value, ref _pointer.Value, (nuint)_length); } else { ThrowHelper.ThrowArgumentException_DestinationTooShort(); } } /// <summary> /// Copies the contents of this span into destination span. If the source /// and destinations overlap, this method behaves as if the original values in /// a temporary location before the destination is overwritten. /// </summary> /// <param name="destination">The span to copy items into.</param> /// <returns>If the destination span is shorter than the source span, this method /// return false and no data is written to the destination.</returns> public bool TryCopyTo(Span<T> destination) { bool retVal = false; if ((uint)_length <= (uint)destination.Length) { Buffer.Memmove(ref destination._pointer.Value, ref _pointer.Value, (nuint)_length); retVal = true; } return retVal; } /// <summary> /// Returns true if left and right point at the same memory and have the same length. Note that /// this does *not* check to see if the *contents* are equal. /// </summary> public static bool operator ==(Span<T> left, Span<T> right) => left._length == right._length && Unsafe.AreSame<T>(ref left._pointer.Value, ref right._pointer.Value); /// <summary> /// Defines an implicit conversion of a <see cref="Span{T}"/> to a <see cref="ReadOnlySpan{T}"/> /// </summary> public static implicit operator ReadOnlySpan<T>(Span<T> span) => new ReadOnlySpan<T>(ref span._pointer.Value, span._length); /// <summary> /// For <see cref="Span{Char}"/>, returns a new instance of string that represents the characters pointed to by the span. /// Otherwise, returns a <see cref="string"/> with the name of the type and the number of elements. /// </summary> public override string ToString() { if (typeof(T) == typeof(char)) { return new string(new ReadOnlySpan<char>(ref Unsafe.As<T, char>(ref _pointer.Value), _length)); } #if FEATURE_UTF8STRING else if (typeof(T) == typeof(Char8)) { // TODO_UTF8STRING: Call into optimized transcoding routine when it's available. return Encoding.UTF8.GetString(new ReadOnlySpan<byte>(ref Unsafe.As<T, byte>(ref _pointer.Value), _length)); } #endif // FEATURE_UTF8STRING return string.Format("System.Span<{0}>[{1}]", typeof(T).Name, _length); } /// <summary> /// Forms a slice out of the given span, beginning at 'start'. /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> index is not in range (&lt;0 or &gt;Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<T> Slice(int start) { if ((uint)start > (uint)_length) ThrowHelper.ThrowArgumentOutOfRangeException(); return new Span<T>(ref Unsafe.Add(ref _pointer.Value, start), _length - start); } /// <summary> /// Forms a slice out of the given span, beginning at 'start', of given length /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <param name="length">The desired length for the slice (exclusive).</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in range (&lt;0 or &gt;Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<T> Slice(int start, int length) { #if BIT64 // Since start and length are both 32-bit, their sum can be computed across a 64-bit domain // without loss of fidelity. The cast to uint before the cast to ulong ensures that the // extension from 32- to 64-bit is zero-extending rather than sign-extending. The end result // of this is that if either input is negative or if the input sum overflows past Int32.MaxValue, // that information is captured correctly in the comparison against the backing _length field. // We don't use this same mechanism in a 32-bit process due to the overhead of 64-bit arithmetic. if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)_length) ThrowHelper.ThrowArgumentOutOfRangeException(); #else if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(); #endif return new Span<T>(ref Unsafe.Add(ref _pointer.Value, start), length); } /// <summary> /// Copies the contents of this span into a new array. This heap /// allocates, so should generally be avoided, however it is sometimes /// necessary to bridge the gap with APIs written in terms of arrays. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public T[] ToArray() { if (_length == 0) return Array.Empty<T>(); var destination = new T[_length]; Buffer.Memmove(ref Unsafe.As<byte, T>(ref destination.GetRawSzArrayData()), ref _pointer.Value, (nuint)_length); return destination; } } }
namespace SampleApp { partial class FolderBrowser { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.cboxGrid = new System.Windows.Forms.ComboBox(); this.cbLines = new System.Windows.Forms.CheckBox(); this.label1 = new System.Windows.Forms.Label(); this._treeView = new Aga.Controls.Tree.TreeViewAdv(); this.treeColumn1 = new Aga.Controls.Tree.TreeColumn(); this.treeColumn2 = new Aga.Controls.Tree.TreeColumn(); this.treeColumn3 = new Aga.Controls.Tree.TreeColumn(); this.nodeCheckBox1 = new Aga.Controls.Tree.NodeControls.NodeCheckBox(); this._icon = new Aga.Controls.Tree.NodeControls.NodeStateIcon(); this._name = new Aga.Controls.Tree.NodeControls.NodeTextBox(); this._size = new Aga.Controls.Tree.NodeControls.NodeTextBox(); this._date = new Aga.Controls.Tree.NodeControls.NodeTextBox(); this.SuspendLayout(); // // cboxGrid // this.cboxGrid.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.cboxGrid.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboxGrid.FormattingEnabled = true; this.cboxGrid.Location = new System.Drawing.Point(338, 303); this.cboxGrid.Name = "cboxGrid"; this.cboxGrid.Size = new System.Drawing.Size(192, 21); this.cboxGrid.TabIndex = 1; this.cboxGrid.SelectedIndexChanged += new System.EventHandler(this.cboxGrid_SelectedIndexChanged); // // cbLines // this.cbLines.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.cbLines.AutoSize = true; this.cbLines.Location = new System.Drawing.Point(3, 305); this.cbLines.Name = "cbLines"; this.cbLines.Size = new System.Drawing.Size(81, 17); this.cbLines.TabIndex = 3; this.cbLines.Text = "Show Lines"; this.cbLines.UseVisualStyleBackColor = true; this.cbLines.CheckedChanged += new System.EventHandler(this.cbLines_CheckedChanged); // // label1 // this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(257, 306); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(75, 13); this.label1.TabIndex = 4; this.label1.Text = "Grid Line Style"; // // _treeView // this._treeView.AllowColumnReorder = true; this._treeView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this._treeView.AutoRowHeight = true; this._treeView.BackColor = System.Drawing.SystemColors.Window; this._treeView.ColumnHeaderHeight = 21; this._treeView.Columns.Add(this.treeColumn1); this._treeView.Columns.Add(this.treeColumn2); this._treeView.Columns.Add(this.treeColumn3); this._treeView.Cursor = System.Windows.Forms.Cursors.Default; this._treeView.DefaultToolTipProvider = null; this._treeView.DragDropMarkColor = System.Drawing.Color.Black; this._treeView.FullRowSelect = true; this._treeView.GridLineStyle = ((Aga.Controls.Tree.GridLineStyle)((Aga.Controls.Tree.GridLineStyle.Horizontal | Aga.Controls.Tree.GridLineStyle.Vertical))); this._treeView.LineColor = System.Drawing.SystemColors.ControlDark; this._treeView.LoadOnDemand = true; this._treeView.Location = new System.Drawing.Point(0, 0); this._treeView.Model = null; this._treeView.Name = "_treeView"; this._treeView.NodeControls.Add(this.nodeCheckBox1); this._treeView.NodeControls.Add(this._icon); this._treeView.NodeControls.Add(this._name); this._treeView.NodeControls.Add(this._size); this._treeView.NodeControls.Add(this._date); this._treeView.SelectedNode = null; this._treeView.ShowNodeToolTips = true; this._treeView.Size = new System.Drawing.Size(533, 298); this._treeView.TabIndex = 0; this._treeView.UseColumns = true; this._treeView.NodeMouseDoubleClick += new System.EventHandler<Aga.Controls.Tree.TreeNodeAdvMouseEventArgs>(this._treeView_NodeMouseDoubleClick); this._treeView.ColumnClicked += new System.EventHandler<Aga.Controls.Tree.TreeColumnEventArgs>(this._treeView_ColumnClicked); this._treeView.MouseClick += new System.Windows.Forms.MouseEventHandler(this._treeView_MouseClick); // // treeColumn1 // this.treeColumn1.Header = "Name"; this.treeColumn1.SortOrder = System.Windows.Forms.SortOrder.None; this.treeColumn1.TooltipText = "File name"; this.treeColumn1.Width = 250; // // treeColumn2 // this.treeColumn2.Header = "Size"; this.treeColumn2.SortOrder = System.Windows.Forms.SortOrder.None; this.treeColumn2.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.treeColumn2.TooltipText = "File size"; this.treeColumn2.Width = 100; // // treeColumn3 // this.treeColumn3.Header = "Date"; this.treeColumn3.SortOrder = System.Windows.Forms.SortOrder.None; this.treeColumn3.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; this.treeColumn3.TooltipText = "File date"; this.treeColumn3.Width = 150; // // nodeCheckBox1 // this.nodeCheckBox1.DataPropertyName = "IsChecked"; this.nodeCheckBox1.LeftMargin = 0; this.nodeCheckBox1.ParentColumn = this.treeColumn1; // // _icon // this._icon.DataPropertyName = "Icon"; this._icon.LeftMargin = 1; this._icon.ParentColumn = this.treeColumn1; this._icon.ScaleMode = Aga.Controls.Tree.ImageScaleMode.Clip; // // _name // this._name.DataPropertyName = "Name"; this._name.IncrementalSearchEnabled = true; this._name.LeftMargin = 3; this._name.ParentColumn = this.treeColumn1; this._name.Trimming = System.Drawing.StringTrimming.EllipsisCharacter; this._name.UseCompatibleTextRendering = true; // // _size // this._size.DataPropertyName = "Size"; this._size.IncrementalSearchEnabled = true; this._size.LeftMargin = 3; this._size.ParentColumn = this.treeColumn2; this._size.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // _date // this._date.DataPropertyName = "Date"; this._date.IncrementalSearchEnabled = true; this._date.LeftMargin = 3; this._date.ParentColumn = this.treeColumn3; this._date.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; // // FolderBrowser // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.label1); this.Controls.Add(this.cbLines); this.Controls.Add(this.cboxGrid); this.Controls.Add(this._treeView); this.Name = "FolderBrowser"; this.Size = new System.Drawing.Size(533, 327); this.ResumeLayout(false); this.PerformLayout(); } #endregion private Aga.Controls.Tree.TreeViewAdv _treeView; private Aga.Controls.Tree.NodeControls.NodeStateIcon _icon; private Aga.Controls.Tree.NodeControls.NodeTextBox _name; private Aga.Controls.Tree.NodeControls.NodeTextBox _size; private Aga.Controls.Tree.NodeControls.NodeTextBox _date; private Aga.Controls.Tree.NodeControls.NodeCheckBox nodeCheckBox1; private Aga.Controls.Tree.TreeColumn treeColumn1; private Aga.Controls.Tree.TreeColumn treeColumn2; private Aga.Controls.Tree.TreeColumn treeColumn3; private System.Windows.Forms.ComboBox cboxGrid; private System.Windows.Forms.CheckBox cbLines; private System.Windows.Forms.Label label1; } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections; using System.Globalization; using System.Reflection; using System.Xml; using Ctrip.Log4.Appender; using Ctrip.Log4.Util; using Ctrip.Log4.Core; using Ctrip.Log4.ObjectRenderer; namespace Ctrip.Log4.Repository.Hierarchy { /// <summary> /// Initializes the Ctrip environment using an XML DOM. /// </summary> /// <remarks> /// <para> /// Configures a <see cref="Hierarchy"/> using an XML DOM. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public class XmlHierarchyConfigurator { private enum ConfigUpdateMode { Merge, Overwrite } #region Public Instance Constructors /// <summary> /// Construct the configurator for a hierarchy /// </summary> /// <param name="hierarchy">The hierarchy to build.</param> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="XmlHierarchyConfigurator" /> class /// with the specified <see cref="Hierarchy" />. /// </para> /// </remarks> public XmlHierarchyConfigurator(Hierarchy hierarchy) { m_hierarchy = hierarchy; m_appenderBag = new Hashtable(); } #endregion Public Instance Constructors #region Public Instance Methods /// <summary> /// Configure the hierarchy by parsing a DOM tree of XML elements. /// </summary> /// <param name="element">The root element to parse.</param> /// <remarks> /// <para> /// Configure the hierarchy by parsing a DOM tree of XML elements. /// </para> /// </remarks> public void Configure(XmlElement element) { if (element == null || m_hierarchy == null) { return; } string rootElementName = element.LocalName; if (rootElementName != CONFIGURATION_TAG) { LogLog.Error(declaringType, "Xml element is - not a <" + CONFIGURATION_TAG + "> element."); return; } if (!LogLog.EmitInternalMessages) { // Look for a emitDebug attribute to enable internal debug string emitDebugAttribute = element.GetAttribute(EMIT_INTERNAL_DEBUG_ATTR); LogLog.Debug(declaringType, EMIT_INTERNAL_DEBUG_ATTR + " attribute [" + emitDebugAttribute + "]."); if (emitDebugAttribute.Length > 0 && emitDebugAttribute != "null") { LogLog.EmitInternalMessages = OptionConverter.ToBoolean(emitDebugAttribute, true); } else { LogLog.Debug(declaringType, "Ignoring " + EMIT_INTERNAL_DEBUG_ATTR + " attribute."); } } if (!LogLog.InternalDebugging) { // Look for a debug attribute to enable internal debug string debugAttribute = element.GetAttribute(INTERNAL_DEBUG_ATTR); LogLog.Debug(declaringType, INTERNAL_DEBUG_ATTR+" attribute [" + debugAttribute + "]."); if (debugAttribute.Length>0 && debugAttribute != "null") { LogLog.InternalDebugging = OptionConverter.ToBoolean(debugAttribute, true); } else { LogLog.Debug(declaringType, "Ignoring " + INTERNAL_DEBUG_ATTR + " attribute."); } string confDebug = element.GetAttribute(CONFIG_DEBUG_ATTR); if (confDebug.Length>0 && confDebug != "null") { LogLog.Warn(declaringType, "The \"" + CONFIG_DEBUG_ATTR + "\" attribute is deprecated."); LogLog.Warn(declaringType, "Use the \"" + INTERNAL_DEBUG_ATTR + "\" attribute instead."); LogLog.InternalDebugging = OptionConverter.ToBoolean(confDebug, true); } } // Default mode is merge ConfigUpdateMode configUpdateMode = ConfigUpdateMode.Merge; // Look for the config update attribute string configUpdateModeAttribute = element.GetAttribute(CONFIG_UPDATE_MODE_ATTR); if (configUpdateModeAttribute != null && configUpdateModeAttribute.Length > 0) { // Parse the attribute try { configUpdateMode = (ConfigUpdateMode)OptionConverter.ConvertStringTo(typeof(ConfigUpdateMode), configUpdateModeAttribute); } catch { LogLog.Error(declaringType, "Invalid " + CONFIG_UPDATE_MODE_ATTR + " attribute value [" + configUpdateModeAttribute + "]"); } } // IMPL: The IFormatProvider argument to Enum.ToString() is deprecated in .NET 2.0 LogLog.Debug(declaringType, "Configuration update mode [" + configUpdateMode.ToString() + "]."); // Only reset configuration if overwrite flag specified if (configUpdateMode == ConfigUpdateMode.Overwrite) { // Reset to original unset configuration m_hierarchy.ResetConfiguration(); LogLog.Debug(declaringType, "Configuration reset before reading config."); } /* Building Appender objects, placing them in a local namespace for future reference */ /* Process all the top level elements */ foreach (XmlNode currentNode in element.ChildNodes) { if (currentNode.NodeType == XmlNodeType.Element) { XmlElement currentElement = (XmlElement)currentNode; if (currentElement.LocalName == LOGGER_TAG) { ParseLogger(currentElement); } else if (currentElement.LocalName == CATEGORY_TAG) { // TODO: deprecated use of category ParseLogger(currentElement); } else if (currentElement.LocalName == ROOT_TAG) { ParseRoot(currentElement); } else if (currentElement.LocalName == RENDERER_TAG) { ParseRenderer(currentElement); } else if (currentElement.LocalName == APPENDER_TAG) { // We ignore appenders in this pass. They will // be found and loaded if they are referenced. } else { // Read the param tags and set properties on the hierarchy SetParameter(currentElement, m_hierarchy); } } } // Lastly set the hierarchy threshold string thresholdStr = element.GetAttribute(THRESHOLD_ATTR); LogLog.Debug(declaringType, "Hierarchy Threshold [" + thresholdStr + "]"); if (thresholdStr.Length > 0 && thresholdStr != "null") { Level thresholdLevel = (Level) ConvertStringTo(typeof(Level), thresholdStr); if (thresholdLevel != null) { m_hierarchy.Threshold = thresholdLevel; } else { LogLog.Warn(declaringType, "Unable to set hierarchy threshold using value [" + thresholdStr + "] (with acceptable conversion types)"); } } // Done reading config } #endregion Public Instance Methods #region Protected Instance Methods /// <summary> /// Parse appenders by IDREF. /// </summary> /// <param name="appenderRef">The appender ref element.</param> /// <returns>The instance of the appender that the ref refers to.</returns> /// <remarks> /// <para> /// Parse an XML element that represents an appender and return /// the appender. /// </para> /// </remarks> protected IAppender FindAppenderByReference(XmlElement appenderRef) { string appenderName = appenderRef.GetAttribute(REF_ATTR); IAppender appender = (IAppender)m_appenderBag[appenderName]; if (appender != null) { return appender; } else { // Find the element with that id XmlElement element = null; if (appenderName != null && appenderName.Length > 0) { foreach (XmlElement curAppenderElement in appenderRef.OwnerDocument.GetElementsByTagName(APPENDER_TAG)) { if (curAppenderElement.GetAttribute("name") == appenderName) { element = curAppenderElement; break; } } } if (element == null) { LogLog.Error(declaringType, "XmlHierarchyConfigurator: No appender named [" + appenderName + "] could be found."); return null; } else { appender = ParseAppender(element); if (appender != null) { m_appenderBag[appenderName] = appender; } return appender; } } } /// <summary> /// Parses an appender element. /// </summary> /// <param name="appenderElement">The appender element.</param> /// <returns>The appender instance or <c>null</c> when parsing failed.</returns> /// <remarks> /// <para> /// Parse an XML element that represents an appender and return /// the appender instance. /// </para> /// </remarks> protected IAppender ParseAppender(XmlElement appenderElement) { string appenderName = appenderElement.GetAttribute(NAME_ATTR); string typeName = appenderElement.GetAttribute(TYPE_ATTR); LogLog.Debug(declaringType, "Loading Appender [" + appenderName + "] type: [" + typeName + "]"); try { IAppender appender = (IAppender)Activator.CreateInstance(SystemInfo.GetTypeFromString(typeName, true, true)); appender.Name = appenderName; foreach (XmlNode currentNode in appenderElement.ChildNodes) { /* We're only interested in Elements */ if (currentNode.NodeType == XmlNodeType.Element) { XmlElement currentElement = (XmlElement)currentNode; // Look for the appender ref tag if (currentElement.LocalName == APPENDER_REF_TAG) { string refName = currentElement.GetAttribute(REF_ATTR); IAppenderAttachable appenderContainer = appender as IAppenderAttachable; if (appenderContainer != null) { LogLog.Debug(declaringType, "Attaching appender named [" + refName + "] to appender named [" + appender.Name + "]."); IAppender referencedAppender = FindAppenderByReference(currentElement); if (referencedAppender != null) { appenderContainer.AddAppender(referencedAppender); } } else { LogLog.Error(declaringType, "Requesting attachment of appender named ["+refName+ "] to appender named [" + appender.Name + "] which does not implement Ctrip.Log4.Core.IAppenderAttachable."); } } else { // For all other tags we use standard set param method SetParameter(currentElement, appender); } } } IOptionHandler optionHandler = appender as IOptionHandler; if (optionHandler != null) { optionHandler.ActivateOptions(); } LogLog.Debug(declaringType, "reated Appender [" + appenderName + "]"); return appender; } catch (Exception ex) { // Yes, it's ugly. But all exceptions point to the same problem: we can't create an Appender LogLog.Error(declaringType, "Could not create Appender [" + appenderName + "] of type [" + typeName + "]. Reported error follows.", ex); return null; } } /// <summary> /// Parses a logger element. /// </summary> /// <param name="loggerElement">The logger element.</param> /// <remarks> /// <para> /// Parse an XML element that represents a logger. /// </para> /// </remarks> protected void ParseLogger(XmlElement loggerElement) { // Create a new Ctrip.Logger object from the <logger> element. string loggerName = loggerElement.GetAttribute(NAME_ATTR); LogLog.Debug(declaringType, "Retrieving an instance of Ctrip.Log4.Repository.Logger for logger [" + loggerName + "]."); Logger log = m_hierarchy.GetLogger(loggerName) as Logger; // Setting up a logger needs to be an atomic operation, in order // to protect potential log operations while logger // configuration is in progress. lock(log) { bool additivity = OptionConverter.ToBoolean(loggerElement.GetAttribute(ADDITIVITY_ATTR), true); LogLog.Debug(declaringType, "Setting [" + log.Name + "] additivity to [" + additivity + "]."); log.Additivity = additivity; ParseChildrenOfLoggerElement(loggerElement, log, false); } } /// <summary> /// Parses the root logger element. /// </summary> /// <param name="rootElement">The root element.</param> /// <remarks> /// <para> /// Parse an XML element that represents the root logger. /// </para> /// </remarks> protected void ParseRoot(XmlElement rootElement) { Logger root = m_hierarchy.Root; // logger configuration needs to be atomic lock(root) { ParseChildrenOfLoggerElement(rootElement, root, true); } } /// <summary> /// Parses the children of a logger element. /// </summary> /// <param name="catElement">The category element.</param> /// <param name="log">The logger instance.</param> /// <param name="isRoot">Flag to indicate if the logger is the root logger.</param> /// <remarks> /// <para> /// Parse the child elements of a &lt;logger&gt; element. /// </para> /// </remarks> protected void ParseChildrenOfLoggerElement(XmlElement catElement, Logger log, bool isRoot) { // Remove all existing appenders from log. They will be // reconstructed if need be. log.RemoveAllAppenders(); foreach (XmlNode currentNode in catElement.ChildNodes) { if (currentNode.NodeType == XmlNodeType.Element) { XmlElement currentElement = (XmlElement) currentNode; if (currentElement.LocalName == APPENDER_REF_TAG) { IAppender appender = FindAppenderByReference(currentElement); string refName = currentElement.GetAttribute(REF_ATTR); if (appender != null) { LogLog.Debug(declaringType, "Adding appender named [" + refName + "] to logger [" + log.Name + "]."); log.AddAppender(appender); } else { LogLog.Error(declaringType, "Appender named [" + refName + "] not found."); } } else if (currentElement.LocalName == LEVEL_TAG || currentElement.LocalName == PRIORITY_TAG) { ParseLevel(currentElement, log, isRoot); } else { SetParameter(currentElement, log); } } } IOptionHandler optionHandler = log as IOptionHandler; if (optionHandler != null) { optionHandler.ActivateOptions(); } } /// <summary> /// Parses an object renderer. /// </summary> /// <param name="element">The renderer element.</param> /// <remarks> /// <para> /// Parse an XML element that represents a renderer. /// </para> /// </remarks> protected void ParseRenderer(XmlElement element) { string renderingClassName = element.GetAttribute(RENDERING_TYPE_ATTR); string renderedClassName = element.GetAttribute(RENDERED_TYPE_ATTR); LogLog.Debug(declaringType, "Rendering class [" + renderingClassName + "], Rendered class [" + renderedClassName + "]."); IObjectRenderer renderer = (IObjectRenderer)OptionConverter.InstantiateByClassName(renderingClassName, typeof(IObjectRenderer), null); if (renderer == null) { LogLog.Error(declaringType, "Could not instantiate renderer [" + renderingClassName + "]."); return; } else { try { m_hierarchy.RendererMap.Put(SystemInfo.GetTypeFromString(renderedClassName, true, true), renderer); } catch(Exception e) { LogLog.Error(declaringType, "Could not find class [" + renderedClassName + "].", e); } } } /// <summary> /// Parses a level element. /// </summary> /// <param name="element">The level element.</param> /// <param name="log">The logger object to set the level on.</param> /// <param name="isRoot">Flag to indicate if the logger is the root logger.</param> /// <remarks> /// <para> /// Parse an XML element that represents a level. /// </para> /// </remarks> protected void ParseLevel(XmlElement element, Logger log, bool isRoot) { string loggerName = log.Name; if (isRoot) { loggerName = "root"; } string levelStr = element.GetAttribute(VALUE_ATTR); LogLog.Debug(declaringType, "Logger [" + loggerName + "] Level string is [" + levelStr + "]."); if (INHERITED == levelStr) { if (isRoot) { LogLog.Error(declaringType, "Root level cannot be inherited. Ignoring directive."); } else { LogLog.Debug(declaringType, "Logger [" + loggerName + "] level set to inherit from parent."); log.Level = null; } } else { log.Level = log.Hierarchy.LevelMap[levelStr]; if (log.Level == null) { LogLog.Error(declaringType, "Undefined level [" + levelStr + "] on Logger [" + loggerName + "]."); } else { LogLog.Debug(declaringType, "Logger [" + loggerName + "] level set to [name=\"" + log.Level.Name + "\",value=" + log.Level.Value + "]."); } } } /// <summary> /// Sets a parameter on an object. /// </summary> /// <param name="element">The parameter element.</param> /// <param name="target">The object to set the parameter on.</param> /// <remarks> /// The parameter name must correspond to a writable property /// on the object. The value of the parameter is a string, /// therefore this function will attempt to set a string /// property first. If unable to set a string property it /// will inspect the property and its argument type. It will /// attempt to call a static method called <c>Parse</c> on the /// type of the property. This method will take a single /// string argument and return a value that can be used to /// set the property. /// </remarks> protected void SetParameter(XmlElement element, object target) { // Get the property name string name = element.GetAttribute(NAME_ATTR); // If the name attribute does not exist then use the name of the element if (element.LocalName != PARAM_TAG || name == null || name.Length == 0) { name = element.LocalName; } // Look for the property on the target object Type targetType = target.GetType(); Type propertyType = null; PropertyInfo propInfo = null; MethodInfo methInfo = null; // Try to find a writable property propInfo = targetType.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.IgnoreCase); if (propInfo != null && propInfo.CanWrite) { // found a property propertyType = propInfo.PropertyType; } else { propInfo = null; // look for a method with the signature Add<property>(type) methInfo = FindMethodInfo(targetType, name); if (methInfo != null) { propertyType = methInfo.GetParameters()[0].ParameterType; } } if (propertyType == null) { LogLog.Error(declaringType, "XmlHierarchyConfigurator: Cannot find Property [" + name + "] to set object on [" + target.ToString() + "]"); } else { string propertyValue = null; if (element.GetAttributeNode(VALUE_ATTR) != null) { propertyValue = element.GetAttribute(VALUE_ATTR); } else if (element.HasChildNodes) { // Concatenate the CDATA and Text nodes together foreach(XmlNode childNode in element.ChildNodes) { if (childNode.NodeType == XmlNodeType.CDATA || childNode.NodeType == XmlNodeType.Text) { if (propertyValue == null) { propertyValue = childNode.InnerText; } else { propertyValue += childNode.InnerText; } } } } if(propertyValue != null) { #if !NETCF try { // Expand environment variables in the string. propertyValue = OptionConverter.SubstituteVariables(propertyValue, Environment.GetEnvironmentVariables()); } catch(System.Security.SecurityException) { // This security exception will occur if the caller does not have // unrestricted environment permission. If this occurs the expansion // will be skipped with the following warning message. LogLog.Debug(declaringType, "Security exception while trying to expand environment variables. Error Ignored. No Expansion."); } #endif Type parsedObjectConversionTargetType = null; // Check if a specific subtype is specified on the element using the 'type' attribute string subTypeString = element.GetAttribute(TYPE_ATTR); if (subTypeString != null && subTypeString.Length > 0) { // Read the explicit subtype try { Type subType = SystemInfo.GetTypeFromString(subTypeString, true, true); LogLog.Debug(declaringType, "Parameter ["+name+"] specified subtype ["+subType.FullName+"]"); if (!propertyType.IsAssignableFrom(subType)) { // Check if there is an appropriate type converter if (OptionConverter.CanConvertTypeTo(subType, propertyType)) { // Must re-convert to the real property type parsedObjectConversionTargetType = propertyType; // Use sub type as intermediary type propertyType = subType; } else { LogLog.Error(declaringType, "subtype ["+subType.FullName+"] set on ["+name+"] is not a subclass of property type ["+propertyType.FullName+"] and there are no acceptable type conversions."); } } else { // The subtype specified is found and is actually a subtype of the property // type, therefore we can switch to using this type. propertyType = subType; } } catch(Exception ex) { LogLog.Error(declaringType, "Failed to find type ["+subTypeString+"] set on ["+name+"]", ex); } } // Now try to convert the string value to an acceptable type // to pass to this property. object convertedValue = ConvertStringTo(propertyType, propertyValue); // Check if we need to do an additional conversion if (convertedValue != null && parsedObjectConversionTargetType != null) { LogLog.Debug(declaringType, "Performing additional conversion of value from [" + convertedValue.GetType().Name + "] to [" + parsedObjectConversionTargetType.Name + "]"); convertedValue = OptionConverter.ConvertTypeTo(convertedValue, parsedObjectConversionTargetType); } if (convertedValue != null) { if (propInfo != null) { // Got a converted result LogLog.Debug(declaringType, "Setting Property [" + propInfo.Name + "] to " + convertedValue.GetType().Name + " value [" + convertedValue.ToString() + "]"); try { // Pass to the property propInfo.SetValue(target, convertedValue, BindingFlags.SetProperty, null, null, CultureInfo.InvariantCulture); } catch(TargetInvocationException targetInvocationEx) { LogLog.Error(declaringType, "Failed to set parameter [" + propInfo.Name + "] on object [" + target + "] using value [" + convertedValue + "]", targetInvocationEx.InnerException); } } else if (methInfo != null) { // Got a converted result LogLog.Debug(declaringType, "Setting Collection Property [" + methInfo.Name + "] to " + convertedValue.GetType().Name + " value [" + convertedValue.ToString() + "]"); try { // Pass to the property methInfo.Invoke(target, BindingFlags.InvokeMethod, null, new object[] {convertedValue}, CultureInfo.InvariantCulture); } catch(TargetInvocationException targetInvocationEx) { LogLog.Error(declaringType, "Failed to set parameter [" + name + "] on object [" + target + "] using value [" + convertedValue + "]", targetInvocationEx.InnerException); } } } else { LogLog.Warn(declaringType, "Unable to set property [" + name + "] on object [" + target + "] using value [" + propertyValue + "] (with acceptable conversion types)"); } } else { object createdObject = null; if (propertyType == typeof(string) && !HasAttributesOrElements(element)) { // If the property is a string and the element is empty (no attributes // or child elements) then we special case the object value to an empty string. // This is necessary because while the String is a class it does not have // a default constructor that creates an empty string, which is the behavior // we are trying to simulate and would be expected from CreateObjectFromXml createdObject = ""; } else { // No value specified Type defaultObjectType = null; if (IsTypeConstructible(propertyType)) { defaultObjectType = propertyType; } createdObject = CreateObjectFromXml(element, defaultObjectType, propertyType); } if (createdObject == null) { LogLog.Error(declaringType, "Failed to create object to set param: "+name); } else { if (propInfo != null) { // Got a converted result LogLog.Debug(declaringType, "Setting Property ["+ propInfo.Name +"] to object ["+ createdObject +"]"); try { // Pass to the property propInfo.SetValue(target, createdObject, BindingFlags.SetProperty, null, null, CultureInfo.InvariantCulture); } catch(TargetInvocationException targetInvocationEx) { LogLog.Error(declaringType, "Failed to set parameter [" + propInfo.Name + "] on object [" + target + "] using value [" + createdObject + "]", targetInvocationEx.InnerException); } } else if (methInfo != null) { // Got a converted result LogLog.Debug(declaringType, "Setting Collection Property ["+ methInfo.Name +"] to object ["+ createdObject +"]"); try { // Pass to the property methInfo.Invoke(target, BindingFlags.InvokeMethod, null, new object[] {createdObject}, CultureInfo.InvariantCulture); } catch(TargetInvocationException targetInvocationEx) { LogLog.Error(declaringType, "Failed to set parameter [" + methInfo.Name + "] on object [" + target + "] using value [" + createdObject + "]", targetInvocationEx.InnerException); } } } } } } /// <summary> /// Test if an element has no attributes or child elements /// </summary> /// <param name="element">the element to inspect</param> /// <returns><c>true</c> if the element has any attributes or child elements, <c>false</c> otherwise</returns> private bool HasAttributesOrElements(XmlElement element) { foreach(XmlNode node in element.ChildNodes) { if (node.NodeType == XmlNodeType.Attribute || node.NodeType == XmlNodeType.Element) { return true; } } return false; } /// <summary> /// Test if a <see cref="Type"/> is constructible with <c>Activator.CreateInstance</c>. /// </summary> /// <param name="type">the type to inspect</param> /// <returns><c>true</c> if the type is creatable using a default constructor, <c>false</c> otherwise</returns> private static bool IsTypeConstructible(Type type) { if (type.IsClass && !type.IsAbstract) { ConstructorInfo defaultConstructor = type.GetConstructor(new Type[0]); if (defaultConstructor != null && !defaultConstructor.IsAbstract && !defaultConstructor.IsPrivate) { return true; } } return false; } /// <summary> /// Look for a method on the <paramref name="targetType"/> that matches the <paramref name="name"/> supplied /// </summary> /// <param name="targetType">the type that has the method</param> /// <param name="name">the name of the method</param> /// <returns>the method info found</returns> /// <remarks> /// <para> /// The method must be a public instance method on the <paramref name="targetType"/>. /// The method must be named <paramref name="name"/> or "Add" followed by <paramref name="name"/>. /// The method must take a single parameter. /// </para> /// </remarks> private MethodInfo FindMethodInfo(Type targetType, string name) { string requiredMethodNameA = name; string requiredMethodNameB = "Add" + name; MethodInfo[] methods = targetType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach(MethodInfo methInfo in methods) { if (!methInfo.IsStatic) { if (string.Compare(methInfo.Name, requiredMethodNameA, true, System.Globalization.CultureInfo.InvariantCulture) == 0 || string.Compare(methInfo.Name, requiredMethodNameB, true, System.Globalization.CultureInfo.InvariantCulture) == 0) { // Found matching method name // Look for version with one arg only System.Reflection.ParameterInfo[] methParams = methInfo.GetParameters(); if (methParams.Length == 1) { return methInfo; } } } } return null; } /// <summary> /// Converts a string value to a target type. /// </summary> /// <param name="type">The type of object to convert the string to.</param> /// <param name="value">The string value to use as the value of the object.</param> /// <returns> /// <para> /// An object of type <paramref name="type"/> with value <paramref name="value"/> or /// <c>null</c> when the conversion could not be performed. /// </para> /// </returns> protected object ConvertStringTo(Type type, string value) { // Hack to allow use of Level in property if (typeof(Level) == type) { // Property wants a level Level levelValue = m_hierarchy.LevelMap[value]; if (levelValue == null) { LogLog.Error(declaringType, "XmlHierarchyConfigurator: Unknown Level Specified ["+ value +"]"); } return levelValue; } return OptionConverter.ConvertStringTo(type, value); } /// <summary> /// Creates an object as specified in XML. /// </summary> /// <param name="element">The XML element that contains the definition of the object.</param> /// <param name="defaultTargetType">The object type to use if not explicitly specified.</param> /// <param name="typeConstraint">The type that the returned object must be or must inherit from.</param> /// <returns>The object or <c>null</c></returns> /// <remarks> /// <para> /// Parse an XML element and create an object instance based on the configuration /// data. /// </para> /// <para> /// The type of the instance may be specified in the XML. If not /// specified then the <paramref name="defaultTargetType"/> is used /// as the type. However the type is specified it must support the /// <paramref name="typeConstraint"/> type. /// </para> /// </remarks> protected object CreateObjectFromXml(XmlElement element, Type defaultTargetType, Type typeConstraint) { Type objectType = null; // Get the object type string objectTypeString = element.GetAttribute(TYPE_ATTR); if (objectTypeString == null || objectTypeString.Length == 0) { if (defaultTargetType == null) { LogLog.Error(declaringType, "Object type not specified. Cannot create object of type ["+typeConstraint.FullName+"]. Missing Value or Type."); return null; } else { // Use the default object type objectType = defaultTargetType; } } else { // Read the explicit object type try { objectType = SystemInfo.GetTypeFromString(objectTypeString, true, true); } catch(Exception ex) { LogLog.Error(declaringType, "Failed to find type ["+objectTypeString+"]", ex); return null; } } bool requiresConversion = false; // Got the object type. Check that it meets the typeConstraint if (typeConstraint != null) { if (!typeConstraint.IsAssignableFrom(objectType)) { // Check if there is an appropriate type converter if (OptionConverter.CanConvertTypeTo(objectType, typeConstraint)) { requiresConversion = true; } else { LogLog.Error(declaringType, "Object type ["+objectType.FullName+"] is not assignable to type ["+typeConstraint.FullName+"]. There are no acceptable type conversions."); return null; } } } // Create using the default constructor object createdObject = null; try { createdObject = Activator.CreateInstance(objectType); } catch(Exception createInstanceEx) { LogLog.Error(declaringType, "XmlHierarchyConfigurator: Failed to construct object of type [" + objectType.FullName + "] Exception: "+createInstanceEx.ToString()); } // Set any params on object foreach (XmlNode currentNode in element.ChildNodes) { if (currentNode.NodeType == XmlNodeType.Element) { SetParameter((XmlElement)currentNode, createdObject); } } // Check if we need to call ActivateOptions IOptionHandler optionHandler = createdObject as IOptionHandler; if (optionHandler != null) { optionHandler.ActivateOptions(); } // Ok object should be initialized if (requiresConversion) { // Convert the object type return OptionConverter.ConvertTypeTo(createdObject, typeConstraint); } else { // The object is of the correct type return createdObject; } } #endregion Protected Instance Methods #region Private Constants // String constants used while parsing the XML data private const string CONFIGURATION_TAG = "Ctrip"; private const string RENDERER_TAG = "renderer"; private const string APPENDER_TAG = "appender"; private const string APPENDER_REF_TAG = "appender-ref"; private const string PARAM_TAG = "param"; // TODO: Deprecate use of category tags private const string CATEGORY_TAG = "category"; // TODO: Deprecate use of priority tag private const string PRIORITY_TAG = "priority"; private const string LOGGER_TAG = "logger"; private const string NAME_ATTR = "name"; private const string TYPE_ATTR = "type"; private const string VALUE_ATTR = "value"; private const string ROOT_TAG = "root"; private const string LEVEL_TAG = "level"; private const string REF_ATTR = "ref"; private const string ADDITIVITY_ATTR = "additivity"; private const string THRESHOLD_ATTR = "threshold"; private const string CONFIG_DEBUG_ATTR = "configDebug"; private const string INTERNAL_DEBUG_ATTR = "debug"; private const string EMIT_INTERNAL_DEBUG_ATTR = "emitDebug"; private const string CONFIG_UPDATE_MODE_ATTR = "update"; private const string RENDERING_TYPE_ATTR = "renderingClass"; private const string RENDERED_TYPE_ATTR = "renderedClass"; // flag used on the level element private const string INHERITED = "inherited"; #endregion Private Constants #region Private Instance Fields /// <summary> /// key: appenderName, value: appender. /// </summary> private Hashtable m_appenderBag; /// <summary> /// The Hierarchy being configured. /// </summary> private readonly Hierarchy m_hierarchy; #endregion Private Instance Fields #region Private Static Fields /// <summary> /// The fully qualified type of the XmlHierarchyConfigurator class. /// </summary> /// <remarks> /// Used by the internal logger to record the Type of the /// log message. /// </remarks> private readonly static Type declaringType = typeof(XmlHierarchyConfigurator); #endregion Private Static Fields } }
//--------------------------------------------------------------------------- // // <copyright file="Point3DKeyFrameCollection.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // This file was generated, please do not edit it directly. // // Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information. // //--------------------------------------------------------------------------- using MS.Internal; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Windows.Media.Animation; using System.Windows.Media.Media3D; namespace System.Windows.Media.Animation { /// <summary> /// This collection is used in conjunction with a KeyFramePoint3DAnimation /// to animate a Point3D property value along a set of key frames. /// </summary> public class Point3DKeyFrameCollection : Freezable, IList { #region Data private List<Point3DKeyFrame> _keyFrames; private static Point3DKeyFrameCollection s_emptyCollection; #endregion #region Constructors /// <Summary> /// Creates a new Point3DKeyFrameCollection. /// </Summary> public Point3DKeyFrameCollection() : base() { _keyFrames = new List< Point3DKeyFrame>(2); } #endregion #region Static Methods /// <summary> /// An empty Point3DKeyFrameCollection. /// </summary> public static Point3DKeyFrameCollection Empty { get { if (s_emptyCollection == null) { Point3DKeyFrameCollection emptyCollection = new Point3DKeyFrameCollection(); emptyCollection._keyFrames = new List< Point3DKeyFrame>(0); emptyCollection.Freeze(); s_emptyCollection = emptyCollection; } return s_emptyCollection; } } #endregion #region Freezable /// <summary> /// Creates a freezable copy of this Point3DKeyFrameCollection. /// </summary> /// <returns>The copy</returns> public new Point3DKeyFrameCollection Clone() { return (Point3DKeyFrameCollection)base.Clone(); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>. /// </summary> /// <returns>The new Freezable.</returns> protected override Freezable CreateInstanceCore() { return new Point3DKeyFrameCollection(); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CloneCore(System.Windows.Freezable)">Freezable.CloneCore</see>. /// </summary> protected override void CloneCore(Freezable sourceFreezable) { Point3DKeyFrameCollection sourceCollection = (Point3DKeyFrameCollection) sourceFreezable; base.CloneCore(sourceFreezable); int count = sourceCollection._keyFrames.Count; _keyFrames = new List< Point3DKeyFrame>(count); for (int i = 0; i < count; i++) { Point3DKeyFrame keyFrame = (Point3DKeyFrame)sourceCollection._keyFrames[i].Clone(); _keyFrames.Add(keyFrame); OnFreezablePropertyChanged(null, keyFrame); } } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CloneCurrentValueCore(System.Windows.Freezable)">Freezable.CloneCurrentValueCore</see>. /// </summary> protected override void CloneCurrentValueCore(Freezable sourceFreezable) { Point3DKeyFrameCollection sourceCollection = (Point3DKeyFrameCollection) sourceFreezable; base.CloneCurrentValueCore(sourceFreezable); int count = sourceCollection._keyFrames.Count; _keyFrames = new List< Point3DKeyFrame>(count); for (int i = 0; i < count; i++) { Point3DKeyFrame keyFrame = (Point3DKeyFrame)sourceCollection._keyFrames[i].CloneCurrentValue(); _keyFrames.Add(keyFrame); OnFreezablePropertyChanged(null, keyFrame); } } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.GetAsFrozenCore(System.Windows.Freezable)">Freezable.GetAsFrozenCore</see>. /// </summary> protected override void GetAsFrozenCore(Freezable sourceFreezable) { Point3DKeyFrameCollection sourceCollection = (Point3DKeyFrameCollection) sourceFreezable; base.GetAsFrozenCore(sourceFreezable); int count = sourceCollection._keyFrames.Count; _keyFrames = new List< Point3DKeyFrame>(count); for (int i = 0; i < count; i++) { Point3DKeyFrame keyFrame = (Point3DKeyFrame)sourceCollection._keyFrames[i].GetAsFrozen(); _keyFrames.Add(keyFrame); OnFreezablePropertyChanged(null, keyFrame); } } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.GetCurrentValueAsFrozenCore(System.Windows.Freezable)">Freezable.GetCurrentValueAsFrozenCore</see>. /// </summary> protected override void GetCurrentValueAsFrozenCore(Freezable sourceFreezable) { Point3DKeyFrameCollection sourceCollection = (Point3DKeyFrameCollection) sourceFreezable; base.GetCurrentValueAsFrozenCore(sourceFreezable); int count = sourceCollection._keyFrames.Count; _keyFrames = new List< Point3DKeyFrame>(count); for (int i = 0; i < count; i++) { Point3DKeyFrame keyFrame = (Point3DKeyFrame)sourceCollection._keyFrames[i].GetCurrentValueAsFrozen(); _keyFrames.Add(keyFrame); OnFreezablePropertyChanged(null, keyFrame); } } /// <summary> /// /// </summary> protected override bool FreezeCore(bool isChecking) { bool canFreeze = base.FreezeCore(isChecking); for (int i = 0; i < _keyFrames.Count && canFreeze; i++) { canFreeze &= Freezable.Freeze(_keyFrames[i], isChecking); } return canFreeze; } #endregion #region IEnumerable /// <summary> /// Returns an enumerator of the Point3DKeyFrames in the collection. /// </summary> public IEnumerator GetEnumerator() { ReadPreamble(); return _keyFrames.GetEnumerator(); } #endregion #region ICollection /// <summary> /// Returns the number of Point3DKeyFrames in the collection. /// </summary> public int Count { get { ReadPreamble(); return _keyFrames.Count; } } /// <summary> /// See <see cref="System.Collections.ICollection.IsSynchronized">ICollection.IsSynchronized</see>. /// </summary> public bool IsSynchronized { get { ReadPreamble(); return (IsFrozen || Dispatcher != null); } } /// <summary> /// See <see cref="System.Collections.ICollection.SyncRoot">ICollection.SyncRoot</see>. /// </summary> public object SyncRoot { get { ReadPreamble(); return ((ICollection)_keyFrames).SyncRoot; } } /// <summary> /// Copies all of the Point3DKeyFrames in the collection to an /// array. /// </summary> void ICollection.CopyTo(Array array, int index) { ReadPreamble(); ((ICollection)_keyFrames).CopyTo(array, index); } /// <summary> /// Copies all of the Point3DKeyFrames in the collection to an /// array of Point3DKeyFrames. /// </summary> public void CopyTo(Point3DKeyFrame[] array, int index) { ReadPreamble(); _keyFrames.CopyTo(array, index); } #endregion #region IList /// <summary> /// Adds a Point3DKeyFrame to the collection. /// </summary> int IList.Add(object keyFrame) { return Add((Point3DKeyFrame)keyFrame); } /// <summary> /// Adds a Point3DKeyFrame to the collection. /// </summary> public int Add(Point3DKeyFrame keyFrame) { if (keyFrame == null) { throw new ArgumentNullException("keyFrame"); } WritePreamble(); OnFreezablePropertyChanged(null, keyFrame); _keyFrames.Add(keyFrame); WritePostscript(); return _keyFrames.Count - 1; } /// <summary> /// Removes all Point3DKeyFrames from the collection. /// </summary> public void Clear() { WritePreamble(); if (_keyFrames.Count > 0) { for (int i = 0; i < _keyFrames.Count; i++) { OnFreezablePropertyChanged(_keyFrames[i], null); } _keyFrames.Clear(); WritePostscript(); } } /// <summary> /// Returns true of the collection contains the given Point3DKeyFrame. /// </summary> bool IList.Contains(object keyFrame) { return Contains((Point3DKeyFrame)keyFrame); } /// <summary> /// Returns true of the collection contains the given Point3DKeyFrame. /// </summary> public bool Contains(Point3DKeyFrame keyFrame) { ReadPreamble(); return _keyFrames.Contains(keyFrame); } /// <summary> /// Returns the index of a given Point3DKeyFrame in the collection. /// </summary> int IList.IndexOf(object keyFrame) { return IndexOf((Point3DKeyFrame)keyFrame); } /// <summary> /// Returns the index of a given Point3DKeyFrame in the collection. /// </summary> public int IndexOf(Point3DKeyFrame keyFrame) { ReadPreamble(); return _keyFrames.IndexOf(keyFrame); } /// <summary> /// Inserts a Point3DKeyFrame into a specific location in the collection. /// </summary> void IList.Insert(int index, object keyFrame) { Insert(index, (Point3DKeyFrame)keyFrame); } /// <summary> /// Inserts a Point3DKeyFrame into a specific location in the collection. /// </summary> public void Insert(int index, Point3DKeyFrame keyFrame) { if (keyFrame == null) { throw new ArgumentNullException("keyFrame"); } WritePreamble(); OnFreezablePropertyChanged(null, keyFrame); _keyFrames.Insert(index, keyFrame); WritePostscript(); } /// <summary> /// Returns true if the collection is frozen. /// </summary> public bool IsFixedSize { get { ReadPreamble(); return IsFrozen; } } /// <summary> /// Returns true if the collection is frozen. /// </summary> public bool IsReadOnly { get { ReadPreamble(); return IsFrozen; } } /// <summary> /// Removes a Point3DKeyFrame from the collection. /// </summary> void IList.Remove(object keyFrame) { Remove((Point3DKeyFrame)keyFrame); } /// <summary> /// Removes a Point3DKeyFrame from the collection. /// </summary> public void Remove(Point3DKeyFrame keyFrame) { WritePreamble(); if (_keyFrames.Contains(keyFrame)) { OnFreezablePropertyChanged(keyFrame, null); _keyFrames.Remove(keyFrame); WritePostscript(); } } /// <summary> /// Removes the Point3DKeyFrame at the specified index from the collection. /// </summary> public void RemoveAt(int index) { WritePreamble(); OnFreezablePropertyChanged(_keyFrames[index], null); _keyFrames.RemoveAt(index); WritePostscript(); } /// <summary> /// Gets or sets the Point3DKeyFrame at a given index. /// </summary> object IList.this[int index] { get { return this[index]; } set { this[index] = (Point3DKeyFrame)value; } } /// <summary> /// Gets or sets the Point3DKeyFrame at a given index. /// </summary> public Point3DKeyFrame this[int index] { get { ReadPreamble(); return _keyFrames[index]; } set { if (value == null) { throw new ArgumentNullException(String.Format(CultureInfo.InvariantCulture, "Point3DKeyFrameCollection[{0}]", index)); } WritePreamble(); if (value != _keyFrames[index]) { OnFreezablePropertyChanged(_keyFrames[index], value); _keyFrames[index] = value; Debug.Assert(_keyFrames[index] != null); WritePostscript(); } } } #endregion } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using osu.Framework.Utils; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Types; using osuTK; #nullable enable namespace osu.Game.Rulesets.Catch.Objects { /// <summary> /// Represents the path of a juice stream. /// <para> /// A <see cref="JuiceStream"/> holds a legacy <see cref="SliderPath"/> as the representation of the path. /// However, the <see cref="SliderPath"/> representation is difficult to work with. /// This <see cref="JuiceStreamPath"/> represents the path in a more convenient way, a polyline connecting list of <see cref="JuiceStreamPathVertex"/>s. /// </para> /// <para> /// The path can be regarded as a function from the closed interval <c>[Vertices[0].Distance, Vertices[^1].Distance]</c> to the x position, given by <see cref="PositionAtDistance"/>. /// To ensure the path is convertible to a <see cref="SliderPath"/>, the slope of the function must not be more than <c>1</c> everywhere, /// and this slope condition is always maintained as an invariant. /// </para> /// </summary> public class JuiceStreamPath { /// <summary> /// The height of legacy osu!standard playfield. /// The sliders converted by <see cref="ConvertToSliderPath"/> are vertically contained in this height. /// </summary> internal const float OSU_PLAYFIELD_HEIGHT = 384; /// <summary> /// The list of vertices of the path, which is represented as a polyline connecting the vertices. /// </summary> public IReadOnlyList<JuiceStreamPathVertex> Vertices => vertices; /// <summary> /// The current version number. /// This starts from <c>1</c> and incremented whenever this <see cref="JuiceStreamPath"/> is modified. /// </summary> public int InvalidationID { get; private set; } = 1; /// <summary> /// The difference between first vertex's <see cref="JuiceStreamPathVertex.Distance"/> and last vertex's <see cref="JuiceStreamPathVertex.Distance"/>. /// </summary> public double Distance => vertices[^1].Distance - vertices[0].Distance; /// <remarks> /// This list should always be non-empty. /// </remarks> private readonly List<JuiceStreamPathVertex> vertices = new List<JuiceStreamPathVertex> { new JuiceStreamPathVertex() }; /// <summary> /// Compute the x-position of the path at the given <paramref name="distance"/>. /// </summary> /// <remarks> /// When the given distance is outside of the path, the x position at the corresponding endpoint is returned, /// </remarks> public float PositionAtDistance(double distance) { int index = vertexIndexAtDistance(distance); return positionAtDistance(distance, index); } /// <summary> /// Remove all vertices of this path, then add a new vertex <c>(0, 0)</c>. /// </summary> public void Clear() { vertices.Clear(); vertices.Add(new JuiceStreamPathVertex()); invalidate(); } /// <summary> /// Insert a vertex at given <paramref name="distance"/>. /// The <see cref="PositionAtDistance"/> is used as the position of the new vertex. /// Thus, the set of points of the path is not changed (up to floating-point precision). /// </summary> /// <returns>The index of the new vertex.</returns> public int InsertVertex(double distance) { if (!double.IsFinite(distance)) throw new ArgumentOutOfRangeException(nameof(distance)); int index = vertexIndexAtDistance(distance); float x = positionAtDistance(distance, index); vertices.Insert(index, new JuiceStreamPathVertex(distance, x)); invalidate(); return index; } /// <summary> /// Move the vertex of given <paramref name="index"/> to the given position <paramref name="newX"/>. /// When the distances between vertices are too small for the new vertex positions, the adjacent vertices are moved towards <paramref name="newX"/>. /// </summary> public void SetVertexPosition(int index, float newX) { if (index < 0 || index >= vertices.Count) throw new ArgumentOutOfRangeException(nameof(index)); if (!float.IsFinite(newX)) throw new ArgumentOutOfRangeException(nameof(newX)); var newVertex = new JuiceStreamPathVertex(vertices[index].Distance, newX); for (int i = index - 1; i >= 0 && !canConnect(vertices[i], newVertex); i--) { float clampedX = clampToConnectablePosition(newVertex, vertices[i]); vertices[i] = new JuiceStreamPathVertex(vertices[i].Distance, clampedX); } for (int i = index + 1; i < vertices.Count; i++) { float clampedX = clampToConnectablePosition(newVertex, vertices[i]); vertices[i] = new JuiceStreamPathVertex(vertices[i].Distance, clampedX); } vertices[index] = newVertex; invalidate(); } /// <summary> /// Add a new vertex at given <paramref name="distance"/> and position. /// Adjacent vertices are moved when necessary in the same way as <see cref="SetVertexPosition"/>. /// </summary> public void Add(double distance, float x) { int index = InsertVertex(distance); SetVertexPosition(index, x); } /// <summary> /// Remove all vertices that satisfy the given <paramref name="predicate"/>. /// </summary> /// <remarks> /// If all vertices are removed, a new vertex <c>(0, 0)</c> is added. /// </remarks> /// <param name="predicate">The predicate to determine whether a vertex should be removed given the vertex and its index in the path.</param> /// <returns>The number of removed vertices.</returns> public int RemoveVertices(Func<JuiceStreamPathVertex, int, bool> predicate) { int index = 0; int removeCount = vertices.RemoveAll(vertex => predicate(vertex, index++)); if (vertices.Count == 0) vertices.Add(new JuiceStreamPathVertex()); if (removeCount != 0) invalidate(); return removeCount; } /// <summary> /// Recreate this path by using difference set of vertices at given distances. /// In addition to the given <paramref name="sampleDistances"/>, the first vertex and the last vertex are always added to the new path. /// New vertices use the positions on the original path. Thus, <see cref="PositionAtDistance"/>s at <paramref name="sampleDistances"/> are preserved. /// </summary> public void ResampleVertices(IEnumerable<double> sampleDistances) { var sampledVertices = new List<JuiceStreamPathVertex>(); foreach (double distance in sampleDistances) { if (!double.IsFinite(distance)) throw new ArgumentOutOfRangeException(nameof(sampleDistances)); double clampedDistance = Math.Clamp(distance, vertices[0].Distance, vertices[^1].Distance); float x = PositionAtDistance(clampedDistance); sampledVertices.Add(new JuiceStreamPathVertex(clampedDistance, x)); } sampledVertices.Sort(); // The first vertex and the last vertex are always used in the result. vertices.RemoveRange(1, vertices.Count - (vertices.Count == 1 ? 1 : 2)); vertices.InsertRange(1, sampledVertices); invalidate(); } /// <summary> /// Convert a <see cref="SliderPath"/> to list of vertices and write the result to this <see cref="JuiceStreamPath"/>. /// </summary> /// <remarks> /// Duplicated vertices are automatically removed. /// </remarks> public void ConvertFromSliderPath(SliderPath sliderPath) { var sliderPathVertices = new List<Vector2>(); sliderPath.GetPathToProgress(sliderPathVertices, 0, 1); double distance = 0; vertices.Clear(); vertices.Add(new JuiceStreamPathVertex(0, sliderPathVertices.FirstOrDefault().X)); for (int i = 1; i < sliderPathVertices.Count; i++) { distance += Vector2.Distance(sliderPathVertices[i - 1], sliderPathVertices[i]); if (!Precision.AlmostEquals(vertices[^1].Distance, distance)) vertices.Add(new JuiceStreamPathVertex(distance, sliderPathVertices[i].X)); } invalidate(); } /// <summary> /// Convert the path of this <see cref="JuiceStreamPath"/> to a <see cref="SliderPath"/> and write the result to <paramref name="sliderPath"/>. /// The resulting slider is "folded" to make it vertically contained in the playfield `(0..<see cref="OSU_PLAYFIELD_HEIGHT"/>)` assuming the slider start position is <paramref name="sliderStartY"/>. /// </summary> public void ConvertToSliderPath(SliderPath sliderPath, float sliderStartY) { const float margin = 1; // Note: these two variables and `sliderPath` are modified by the local functions. double currentDistance = 0; Vector2 lastPosition = new Vector2(vertices[0].X, 0); sliderPath.ControlPoints.Clear(); sliderPath.ControlPoints.Add(new PathControlPoint(lastPosition)); for (int i = 1; i < vertices.Count; i++) { sliderPath.ControlPoints[^1].Type = PathType.Linear; float deltaX = vertices[i].X - lastPosition.X; double length = vertices[i].Distance - currentDistance; // Should satisfy `deltaX^2 + deltaY^2 = length^2`. // By invariants, the expression inside the `sqrt` is (almost) non-negative. double deltaY = Math.Sqrt(Math.Max(0, length * length - (double)deltaX * deltaX)); // When `deltaY` is small, one segment is always enough. // This case is handled separately to prevent divide-by-zero. if (deltaY <= OSU_PLAYFIELD_HEIGHT / 2 - margin) { float nextX = vertices[i].X; float nextY = (float)(lastPosition.Y + getYDirection() * deltaY); addControlPoint(nextX, nextY); continue; } // When `deltaY` is large or when the slider velocity is fast, the segment must be partitioned to subsegments to stay in bounds. for (double currentProgress = 0; currentProgress < deltaY;) { double nextProgress = Math.Min(currentProgress + getMaxDeltaY(), deltaY); float nextX = (float)(vertices[i - 1].X + nextProgress / deltaY * deltaX); float nextY = (float)(lastPosition.Y + getYDirection() * (nextProgress - currentProgress)); addControlPoint(nextX, nextY); currentProgress = nextProgress; } } int getYDirection() { float lastSliderY = sliderStartY + lastPosition.Y; return lastSliderY < OSU_PLAYFIELD_HEIGHT / 2 ? 1 : -1; } float getMaxDeltaY() { float lastSliderY = sliderStartY + lastPosition.Y; return Math.Max(lastSliderY, OSU_PLAYFIELD_HEIGHT - lastSliderY) - margin; } void addControlPoint(float nextX, float nextY) { Vector2 nextPosition = new Vector2(nextX, nextY); sliderPath.ControlPoints.Add(new PathControlPoint(nextPosition)); currentDistance += Vector2.Distance(lastPosition, nextPosition); lastPosition = nextPosition; } } /// <summary> /// Find the index at which a new vertex with <paramref name="distance"/> can be inserted. /// </summary> private int vertexIndexAtDistance(double distance) { // The position of `(distance, Infinity)` is uniquely determined because infinite positions are not allowed. int i = vertices.BinarySearch(new JuiceStreamPathVertex(distance, float.PositiveInfinity)); return i < 0 ? ~i : i; } /// <summary> /// Compute the position at the given <paramref name="distance"/>, assuming <paramref name="index"/> is the vertex index returned by <see cref="vertexIndexAtDistance"/>. /// </summary> private float positionAtDistance(double distance, int index) { if (index <= 0) return vertices[0].X; if (index >= vertices.Count) return vertices[^1].X; double length = vertices[index].Distance - vertices[index - 1].Distance; if (Precision.AlmostEquals(length, 0)) return vertices[index].X; float deltaX = vertices[index].X - vertices[index - 1].X; return (float)(vertices[index - 1].X + deltaX * ((distance - vertices[index - 1].Distance) / length)); } /// <summary> /// Check the two vertices can connected directly while satisfying the slope condition. /// </summary> private bool canConnect(JuiceStreamPathVertex vertex1, JuiceStreamPathVertex vertex2, float allowance = 0) { double xDistance = Math.Abs((double)vertex2.X - vertex1.X); float length = (float)Math.Abs(vertex2.Distance - vertex1.Distance); return xDistance <= length + allowance; } /// <summary> /// Move the position of <paramref name="movableVertex"/> towards the position of <paramref name="fixedVertex"/> /// until the vertex pair satisfies the condition <see cref="canConnect"/>. /// </summary> /// <returns>The resulting position of <paramref name="movableVertex"/>.</returns> private float clampToConnectablePosition(JuiceStreamPathVertex fixedVertex, JuiceStreamPathVertex movableVertex) { float length = (float)Math.Abs(movableVertex.Distance - fixedVertex.Distance); return Math.Clamp(movableVertex.X, fixedVertex.X - length, fixedVertex.X + length); } private void invalidate() => InvalidationID++; } }
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using ReaderException = com.google.zxing.ReaderException; using BitSource = com.google.zxing.common.BitSource; using DecoderResult = com.google.zxing.common.DecoderResult; using System.Collections.Generic; namespace com.google.zxing.datamatrix.decoder { /// <summary> <p>Data Matrix Codes can encode text as bits in one of several modes, and can use multiple modes /// in one Data Matrix Code. This class decodes the bits back into text.</p> /// /// <p>See ISO 16022:2006, 5.2.1 - 5.2.9.2</p> /// /// </summary> /// <author> bbrown@google.com (Brian Brown) /// </author> /// <author> Sean Owen /// </author> /// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source /// </author> sealed class DecodedBitStreamParser { /// <summary> See ISO 16022:2006, Annex C Table C.1 /// The C40 Basic Character Set (*'s used for placeholders for the shift values) /// </summary> //UPGRADE_NOTE: Final was removed from the declaration of 'C40_BASIC_SET_CHARS'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" private static readonly char[] C40_BASIC_SET_CHARS = new char[]{'*', '*', '*', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; //UPGRADE_NOTE: Final was removed from the declaration of 'C40_SHIFT2_SET_CHARS'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" private static readonly char[] C40_SHIFT2_SET_CHARS = new char[]{'!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_'}; /// <summary> See ISO 16022:2006, Annex C Table C.2 /// The Text Basic Character Set (*'s used for placeholders for the shift values) /// </summary> //UPGRADE_NOTE: Final was removed from the declaration of 'TEXT_BASIC_SET_CHARS'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" private static readonly char[] TEXT_BASIC_SET_CHARS = new char[]{'*', '*', '*', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; private static char[] TEXT_SHIFT3_SET_CHARS = new char[]{'\'', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '{', '|', '}', '~', (char) 127}; private const int PAD_ENCODE = 0; // Not really an encoding private const int ASCII_ENCODE = 1; private const int C40_ENCODE = 2; private const int TEXT_ENCODE = 3; private const int ANSIX12_ENCODE = 4; private const int EDIFACT_ENCODE = 5; private const int BASE256_ENCODE = 6; private DecodedBitStreamParser() { } internal static DecoderResult decode(sbyte[] bytes) { BitSource bits = new BitSource(bytes); System.Text.StringBuilder result = new System.Text.StringBuilder(100); System.Text.StringBuilder resultTrailer = new System.Text.StringBuilder(0); List<object> byteSegments = new List<object>(); int mode = ASCII_ENCODE; do { if (mode == ASCII_ENCODE) { mode = decodeAsciiSegment(bits, result, resultTrailer); } else { switch (mode) { case C40_ENCODE: decodeC40Segment(bits, result); break; case TEXT_ENCODE: decodeTextSegment(bits, result); break; case ANSIX12_ENCODE: decodeAnsiX12Segment(bits, result); break; case EDIFACT_ENCODE: decodeEdifactSegment(bits, result); break; case BASE256_ENCODE: decodeBase256Segment(bits, result, byteSegments); break; default: throw ReaderException.Instance; } mode = ASCII_ENCODE; } } while (mode != PAD_ENCODE && bits.available() > 0); if (resultTrailer.Length > 0) { result.Append(resultTrailer.ToString()); } return new DecoderResult(bytes, result.ToString(), (byteSegments.Count == 0)?null:byteSegments, null); } /// <summary> See ISO 16022:2006, 5.2.3 and Annex C, Table C.2</summary> private static int decodeAsciiSegment(BitSource bits, System.Text.StringBuilder result, System.Text.StringBuilder resultTrailer) { bool upperShift = false; do { int oneByte = bits.readBits(8); if (oneByte == 0) { throw ReaderException.Instance; } else if (oneByte <= 128) { // ASCII data (ASCII value + 1) oneByte = upperShift?(oneByte + 128):oneByte; upperShift = false; result.Append((char) (oneByte - 1)); return ASCII_ENCODE; } else if (oneByte == 129) { // Pad return PAD_ENCODE; } else if (oneByte <= 229) { // 2-digit data 00-99 (Numeric Value + 130) int value_Renamed = oneByte - 130; if (value_Renamed < 10) { // padd with '0' for single digit values result.Append('0'); } result.Append(value_Renamed); } else if (oneByte == 230) { // Latch to C40 encodation return C40_ENCODE; } else if (oneByte == 231) { // Latch to Base 256 encodation return BASE256_ENCODE; } else if (oneByte == 232) { // FNC1 //throw ReaderException.getInstance(); // Ignore this symbol for now } else if (oneByte == 233) { // Structured Append //throw ReaderException.getInstance(); // Ignore this symbol for now } else if (oneByte == 234) { // Reader Programming //throw ReaderException.getInstance(); // Ignore this symbol for now } else if (oneByte == 235) { // Upper Shift (shift to Extended ASCII) upperShift = true; } else if (oneByte == 236) { // 05 Macro result.Append("[)>\u001E05\u001D"); resultTrailer.Insert(0, "\u001E\u0004"); } else if (oneByte == 237) { // 06 Macro result.Append("[)>\u001E06\u001D"); resultTrailer.Insert(0, "\u001E\u0004"); } else if (oneByte == 238) { // Latch to ANSI X12 encodation return ANSIX12_ENCODE; } else if (oneByte == 239) { // Latch to Text encodation return TEXT_ENCODE; } else if (oneByte == 240) { // Latch to EDIFACT encodation return EDIFACT_ENCODE; } else if (oneByte == 241) { // ECI Character // TODO(bbrown): I think we need to support ECI //throw ReaderException.getInstance(); // Ignore this symbol for now } else if (oneByte >= 242) { // Not to be used in ASCII encodation throw ReaderException.Instance; } } while (bits.available() > 0); return ASCII_ENCODE; } /// <summary> See ISO 16022:2006, 5.2.5 and Annex C, Table C.1</summary> private static void decodeC40Segment(BitSource bits, System.Text.StringBuilder result) { // Three C40 values are encoded in a 16-bit value as // (1600 * C1) + (40 * C2) + C3 + 1 // TODO(bbrown): The Upper Shift with C40 doesn't work in the 4 value scenario all the time bool upperShift = false; int[] cValues = new int[3]; do { // If there is only one byte left then it will be encoded as ASCII if (bits.available() == 8) { return ; } int firstByte = bits.readBits(8); if (firstByte == 254) { // Unlatch codeword return ; } parseTwoBytes(firstByte, bits.readBits(8), cValues); int shift = 0; for (int i = 0; i < 3; i++) { int cValue = cValues[i]; switch (shift) { case 0: if (cValue < 3) { shift = cValue + 1; } else { if (upperShift) { result.Append((char) (C40_BASIC_SET_CHARS[cValue] + 128)); upperShift = false; } else { result.Append(C40_BASIC_SET_CHARS[cValue]); } } break; case 1: if (upperShift) { result.Append((char) (cValue + 128)); upperShift = false; } else { result.Append(cValue); } shift = 0; break; case 2: if (cValue < 27) { if (upperShift) { result.Append((char) (C40_SHIFT2_SET_CHARS[cValue] + 128)); upperShift = false; } else { result.Append(C40_SHIFT2_SET_CHARS[cValue]); } } else if (cValue == 27) { // FNC1 throw ReaderException.Instance; } else if (cValue == 30) { // Upper Shift upperShift = true; } else { throw ReaderException.Instance; } shift = 0; break; case 3: if (upperShift) { result.Append((char) (cValue + 224)); upperShift = false; } else { result.Append((char) (cValue + 96)); } shift = 0; break; default: throw ReaderException.Instance; } } } while (bits.available() > 0); } /// <summary> See ISO 16022:2006, 5.2.6 and Annex C, Table C.2</summary> private static void decodeTextSegment(BitSource bits, System.Text.StringBuilder result) { // Three Text values are encoded in a 16-bit value as // (1600 * C1) + (40 * C2) + C3 + 1 // TODO(bbrown): The Upper Shift with Text doesn't work in the 4 value scenario all the time bool upperShift = false; int[] cValues = new int[3]; do { // If there is only one byte left then it will be encoded as ASCII if (bits.available() == 8) { return ; } int firstByte = bits.readBits(8); if (firstByte == 254) { // Unlatch codeword return ; } parseTwoBytes(firstByte, bits.readBits(8), cValues); int shift = 0; for (int i = 0; i < 3; i++) { int cValue = cValues[i]; switch (shift) { case 0: if (cValue < 3) { shift = cValue + 1; } else { if (upperShift) { result.Append((char) (TEXT_BASIC_SET_CHARS[cValue] + 128)); upperShift = false; } else { result.Append(TEXT_BASIC_SET_CHARS[cValue]); } } break; case 1: if (upperShift) { result.Append((char) (cValue + 128)); upperShift = false; } else { result.Append(cValue); } shift = 0; break; case 2: // Shift 2 for Text is the same encoding as C40 if (cValue < 27) { if (upperShift) { result.Append((char) (C40_SHIFT2_SET_CHARS[cValue] + 128)); upperShift = false; } else { result.Append(C40_SHIFT2_SET_CHARS[cValue]); } } else if (cValue == 27) { // FNC1 throw ReaderException.Instance; } else if (cValue == 30) { // Upper Shift upperShift = true; } else { throw ReaderException.Instance; } shift = 0; break; case 3: if (upperShift) { result.Append((char) (TEXT_SHIFT3_SET_CHARS[cValue] + 128)); upperShift = false; } else { result.Append(TEXT_SHIFT3_SET_CHARS[cValue]); } shift = 0; break; default: throw ReaderException.Instance; } } } while (bits.available() > 0); } /// <summary> See ISO 16022:2006, 5.2.7</summary> private static void decodeAnsiX12Segment(BitSource bits, System.Text.StringBuilder result) { // Three ANSI X12 values are encoded in a 16-bit value as // (1600 * C1) + (40 * C2) + C3 + 1 int[] cValues = new int[3]; do { // If there is only one byte left then it will be encoded as ASCII if (bits.available() == 8) { return ; } int firstByte = bits.readBits(8); if (firstByte == 254) { // Unlatch codeword return ; } parseTwoBytes(firstByte, bits.readBits(8), cValues); for (int i = 0; i < 3; i++) { int cValue = cValues[i]; if (cValue == 0) { // X12 segment terminator <CR> result.Append('\r'); } else if (cValue == 1) { // X12 segment separator * result.Append('*'); } else if (cValue == 2) { // X12 sub-element separator > result.Append('>'); } else if (cValue == 3) { // space result.Append(' '); } else if (cValue < 14) { // 0 - 9 result.Append((char) (cValue + 44)); } else if (cValue < 40) { // A - Z result.Append((char) (cValue + 51)); } else { throw ReaderException.Instance; } } } while (bits.available() > 0); } private static void parseTwoBytes(int firstByte, int secondByte, int[] result) { int fullBitValue = (firstByte << 8) + secondByte - 1; int temp = fullBitValue / 1600; result[0] = temp; fullBitValue -= temp * 1600; temp = fullBitValue / 40; result[1] = temp; result[2] = fullBitValue - temp * 40; } /// <summary> See ISO 16022:2006, 5.2.8 and Annex C Table C.3</summary> private static void decodeEdifactSegment(BitSource bits, System.Text.StringBuilder result) { bool unlatch = false; do { // If there is only two or less bytes left then it will be encoded as ASCII if (bits.available() <= 16) { return ; } for (int i = 0; i < 4; i++) { int edifactValue = bits.readBits(6); // Check for the unlatch character if (edifactValue == 0x2B67) { // 011111 unlatch = true; // If we encounter the unlatch code then continue reading because the Codeword triple // is padded with 0's } if (!unlatch) { if ((edifactValue & 32) == 0) { // no 1 in the leading (6th) bit edifactValue |= 64; // Add a leading 01 to the 6 bit binary value } result.Append(edifactValue); } } } while (!unlatch && bits.available() > 0); } /// <summary> See ISO 16022:2006, 5.2.9 and Annex B, B.2</summary> private static void decodeBase256Segment(BitSource bits, System.Text.StringBuilder result, List<object> byteSegments) { // Figure out how long the Base 256 Segment is. int d1 = bits.readBits(8); int count; if (d1 == 0) { // Read the remainder of the symbol count = bits.available() / 8; } else if (d1 < 250) { count = d1; } else { count = 250 * (d1 - 249) + bits.readBits(8); } sbyte[] bytes = new sbyte[count]; for (int i = 0; i < count; i++) { bytes[i] = unrandomize255State(bits.readBits(8), i); } byteSegments.Add(SupportClass.ToByteArray(bytes)); try { //UPGRADE_TODO: The differences in the Format of parameters for constructor 'java.lang.String.String' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'" result.Append(System.Text.Encoding.GetEncoding("ISO8859_1").GetString(SupportClass.ToByteArray(bytes))); } catch (System.IO.IOException uee) { //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" throw new System.Exception("Platform does not support required encoding: " + uee); } } /// <summary> See ISO 16022:2006, Annex B, B.2</summary> private static sbyte unrandomize255State(int randomizedBase256Codeword, int base256CodewordPosition) { int pseudoRandomNumber = ((149 * base256CodewordPosition) % 255) + 1; int tempVariable = randomizedBase256Codeword - pseudoRandomNumber; return (sbyte) (tempVariable >= 0?tempVariable:(tempVariable + 256)); } } }
using AWTY; using System; using System.Reactive.Disposables; namespace ConsoleDownloader { /// <summary> /// A single-line progress bar displayed on the console. /// </summary> class ConsoleProgressBar : IObserver<ProgressData<long>> { /// <summary> /// Maximum number of characters in a progress title. /// </summary> const int MaxTitleChars = 10; /// <summary> /// The starting column of the bar. /// </summary> const int BarStart = MaxTitleChars + 3; // = ": [" /// <summary> /// The size, in characters, of the bar. /// </summary> const int BarSize = 50; /// <summary> /// The starting column of the bar. /// </summary> const int BarEnd = BarStart + BarSize; /// <summary> /// The starting column of the percentage displayed on the end of the bar. /// </summary> const int PercentageStart = BarEnd + 2; // = "] " /// <summary> /// The ending column of the percentage displayed on the end of the bar. /// </summary> const int PercentageEnd = PercentageStart + 6; // = "] 100%" /// <summary> /// The progress bar title. /// </summary> readonly string _title; /// <summary> /// The line on which the progress bar is displayed. /// </summary> readonly int _line; /// <summary> /// Create a new console progress bar on the current line. /// </summary> /// <param name="title"> /// The progress bar title. /// </param> public ConsoleProgressBar(string title) : this(title, Console.CursorTop) { } /// <summary> /// Create a new progress bar. /// </summary> /// <param name="title"> /// The progress bar title. /// </param> /// <param name="line"> /// The line on which the progress bar is displayed. /// </param> public ConsoleProgressBar(string title, int line) { if (String.IsNullOrWhiteSpace(title)) throw new ArgumentException("Must supply a valid progress bar title.", nameof(title)); if (line < 0) throw new ArgumentOutOfRangeException(nameof(line), line, "Line cannot be less than 0."); _title = title; if (_title.Length > MaxTitleChars) _title = _title.Substring(0, MaxTitleChars); _line = line; using (Line(_line)) { Console.WriteLine("{0}: [{1}]", _title.PadRight(MaxTitleChars), new String(' ', BarSize) ); } } /// <summary> /// Called when the next progress value is available. /// </summary> /// <param name="value"> /// The progress value. /// </param> void IObserver<ProgressData<long>>.OnNext(ProgressData<long> value) { using (Position(_line, BarStart)) { Console.Write(new String('#', value.PercentComplete / 2)); } using (Position(_line, PercentageStart)) { Console.Write("{0}%", value.PercentComplete); } } /// <summary> /// Called when the progress sequence is completed. /// </summary> void IObserver<ProgressData<long>>.OnCompleted() { using (Position(_line, BarStart - 1 /* Overwrite "[" */)) { Console.Write("Complete.".PadRight(PercentageEnd - BarStart)); } } /// <summary> /// Called when the progress source encounters an error. /// </summary> /// <param name="error"> /// An <see cref="Exception"/> representing the error. /// </param> void IObserver<ProgressData<long>>.OnError(Exception error) { using (Position(_line, 0)) using (Color(ConsoleColor.Red)) { Console.Write(error.Message); } } /// <summary> /// Move to the specified line in the console. /// </summary> /// <param name="line"> /// The (0-based) target line number. /// </param> /// <returns> /// An <see cref="IDisposable"/> that returns to the original position when disposed. /// </returns> static IDisposable Line(int line) { return Position(line, column: 0); } /// <summary> /// Move to the specified position in the console. /// </summary> /// <param name="line"> /// The (0-based) target line number. /// </param> /// <param name="column"> /// The (0-based) target column number. /// </param> /// <returns> /// An <see cref="IDisposable"/> that returns to the original position when disposed. /// </returns> static IDisposable Position(int line, int column) { int previousLine = Console.CursorTop; int previousColumn = Console.CursorLeft; if (line == previousLine && column == previousColumn) return Disposable.Empty; Console.SetCursorPosition(left: column, top: line); return Disposable.Create(() => { Console.SetCursorPosition(left: previousColumn, top: previousLine); }); } /// <summary> /// Switch the console foreground to the specified colour. /// </summary> /// <param name="color"> /// The target foreground colour. /// </param> /// <returns> /// An <see cref="IDisposable"/> that returns to the original foreground colour when disposed. /// </returns> static IDisposable Color(ConsoleColor color) { ConsoleColor previousColor = Console.ForegroundColor; Console.ForegroundColor = color; return Disposable.Create( () => Console.ForegroundColor = previousColor ); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Web.UI.WebControls.FormView.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Web.UI.WebControls { public partial class FormView : CompositeDataBoundControl, System.Web.UI.IDataItemContainer, System.Web.UI.INamingContainer, System.Web.UI.IPostBackEventHandler, IPostBackContainer, IDataBoundItemControl, IDataBoundControl, System.Web.UI.IRenderOuterTableControl { #region Methods and constructors public void ChangeMode(FormViewMode newMode) { } protected override int CreateChildControls(System.Collections.IEnumerable dataSource, bool dataBinding) { return default(int); } protected override Style CreateControlStyle() { return default(Style); } protected override System.Web.UI.DataSourceSelectArguments CreateDataSourceSelectArguments() { return default(System.Web.UI.DataSourceSelectArguments); } protected virtual new FormViewRow CreateRow(int itemIndex, DataControlRowType rowType, DataControlRowState rowState) { return default(FormViewRow); } protected virtual new Table CreateTable() { return default(Table); } public sealed override void DataBind() { } public virtual new void DeleteItem() { } protected override void EnsureDataBound() { } protected virtual new void ExtractRowValues(System.Collections.Specialized.IOrderedDictionary fieldValues, bool includeKeys) { } public FormView() { } protected virtual new void InitializePager(FormViewRow row, PagedDataSource pagedDataSource) { } protected virtual new void InitializeRow(FormViewRow row) { } public virtual new void InsertItem(bool causesValidation) { } public virtual new bool IsBindableType(Type type) { return default(bool); } protected internal override void LoadControlState(Object savedState) { } protected override void LoadViewState(Object savedState) { } protected internal virtual new string ModifiedOuterTableStylePropertyName() { return default(string); } protected override bool OnBubbleEvent(Object source, EventArgs e) { return default(bool); } protected internal override void OnInit(EventArgs e) { } protected virtual new void OnItemCommand(FormViewCommandEventArgs e) { } protected virtual new void OnItemCreated(EventArgs e) { } protected virtual new void OnItemDeleted(FormViewDeletedEventArgs e) { } protected virtual new void OnItemDeleting(FormViewDeleteEventArgs e) { } protected virtual new void OnItemInserted(FormViewInsertedEventArgs e) { } protected virtual new void OnItemInserting(FormViewInsertEventArgs e) { } protected virtual new void OnItemUpdated(FormViewUpdatedEventArgs e) { } protected virtual new void OnItemUpdating(FormViewUpdateEventArgs e) { } protected virtual new void OnModeChanged(EventArgs e) { } protected virtual new void OnModeChanging(FormViewModeEventArgs e) { } protected virtual new void OnPageIndexChanged(EventArgs e) { } protected virtual new void OnPageIndexChanging(FormViewPageEventArgs e) { } protected internal override void PerformDataBinding(System.Collections.IEnumerable data) { } protected internal virtual new void PrepareControlHierarchy() { } protected virtual new void RaisePostBackEvent(string eventArgument) { } protected internal override void Render(System.Web.UI.HtmlTextWriter writer) { } protected internal override Object SaveControlState() { return default(Object); } protected override Object SaveViewState() { return default(Object); } public void SetPageIndex(int index) { } void System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(string eventArgument) { } System.Web.UI.PostBackOptions System.Web.UI.WebControls.IPostBackContainer.GetPostBackOptions(IButtonControl buttonControl) { return default(System.Web.UI.PostBackOptions); } protected override void TrackViewState() { } public virtual new void UpdateItem(bool causesValidation) { } #endregion #region Properties and indexers public virtual new bool AllowPaging { get { return default(bool); } set { } } public virtual new string BackImageUrl { get { return default(string); } set { } } public virtual new FormViewRow BottomPagerRow { get { return default(FormViewRow); } } public virtual new string Caption { get { return default(string); } set { } } public virtual new TableCaptionAlign CaptionAlign { get { return default(TableCaptionAlign); } set { } } public virtual new int CellPadding { get { return default(int); } set { } } public virtual new int CellSpacing { get { return default(int); } set { } } public FormViewMode CurrentMode { get { return default(FormViewMode); } } public virtual new Object DataItem { get { return default(Object); } } public int DataItemCount { get { return default(int); } } public virtual new int DataItemIndex { get { return default(int); } } public virtual new DataKey DataKey { get { return default(DataKey); } } public virtual new string[] DataKeyNames { get { return default(string[]); } set { } } public virtual new FormViewMode DefaultMode { get { return default(FormViewMode); } set { } } public virtual new System.Web.UI.ITemplate EditItemTemplate { get { return default(System.Web.UI.ITemplate); } set { } } public TableItemStyle EditRowStyle { get { return default(TableItemStyle); } } public TableItemStyle EmptyDataRowStyle { get { return default(TableItemStyle); } } public virtual new System.Web.UI.ITemplate EmptyDataTemplate { get { return default(System.Web.UI.ITemplate); } set { } } public virtual new string EmptyDataText { get { return default(string); } set { } } public virtual new bool EnableModelValidation { get { return default(bool); } set { } } public virtual new FormViewRow FooterRow { get { return default(FormViewRow); } } public TableItemStyle FooterStyle { get { return default(TableItemStyle); } } public virtual new System.Web.UI.ITemplate FooterTemplate { get { return default(System.Web.UI.ITemplate); } set { } } public virtual new string FooterText { get { return default(string); } set { } } public virtual new GridLines GridLines { get { return default(GridLines); } set { } } public virtual new FormViewRow HeaderRow { get { return default(FormViewRow); } } public TableItemStyle HeaderStyle { get { return default(TableItemStyle); } } public virtual new System.Web.UI.ITemplate HeaderTemplate { get { return default(System.Web.UI.ITemplate); } set { } } public virtual new string HeaderText { get { return default(string); } set { } } public virtual new HorizontalAlign HorizontalAlign { get { return default(HorizontalAlign); } set { } } public virtual new System.Web.UI.ITemplate InsertItemTemplate { get { return default(System.Web.UI.ITemplate); } set { } } public TableItemStyle InsertRowStyle { get { return default(TableItemStyle); } } public virtual new System.Web.UI.ITemplate ItemTemplate { get { return default(System.Web.UI.ITemplate); } set { } } public virtual new int PageCount { get { return default(int); } } public virtual new int PageIndex { get { return default(int); } set { } } public virtual new PagerSettings PagerSettings { get { return default(PagerSettings); } } public TableItemStyle PagerStyle { get { return default(TableItemStyle); } } public virtual new System.Web.UI.ITemplate PagerTemplate { get { return default(System.Web.UI.ITemplate); } set { } } public virtual new bool RenderOuterTable { get { return default(bool); } set { } } public virtual new FormViewRow Row { get { return default(FormViewRow); } } public TableItemStyle RowStyle { get { return default(TableItemStyle); } } public Object SelectedValue { get { return default(Object); } } int System.Web.UI.IDataItemContainer.DataItemIndex { get { return default(int); } } int System.Web.UI.IDataItemContainer.DisplayIndex { get { return default(int); } } string[] System.Web.UI.WebControls.IDataBoundControl.DataKeyNames { get { return default(string[]); } set { } } string System.Web.UI.WebControls.IDataBoundControl.DataMember { get { return default(string); } set { } } Object System.Web.UI.WebControls.IDataBoundControl.DataSource { get { return default(Object); } set { } } string System.Web.UI.WebControls.IDataBoundControl.DataSourceID { get { return default(string); } set { } } System.Web.UI.IDataSource System.Web.UI.WebControls.IDataBoundControl.DataSourceObject { get { return default(System.Web.UI.IDataSource); } } System.Web.UI.WebControls.DataKey System.Web.UI.WebControls.IDataBoundItemControl.DataKey { get { return default(System.Web.UI.WebControls.DataKey); } } DataBoundControlMode System.Web.UI.WebControls.IDataBoundItemControl.Mode { get { return default(DataBoundControlMode); } } protected override System.Web.UI.HtmlTextWriterTag TagKey { get { return default(System.Web.UI.HtmlTextWriterTag); } } public virtual new FormViewRow TopPagerRow { get { return default(FormViewRow); } } #endregion #region Events public event FormViewCommandEventHandler ItemCommand { add { } remove { } } public event EventHandler ItemCreated { add { } remove { } } public event FormViewDeletedEventHandler ItemDeleted { add { } remove { } } public event FormViewDeleteEventHandler ItemDeleting { add { } remove { } } public event FormViewInsertedEventHandler ItemInserted { add { } remove { } } public event FormViewInsertEventHandler ItemInserting { add { } remove { } } public event FormViewUpdatedEventHandler ItemUpdated { add { } remove { } } public event FormViewUpdateEventHandler ItemUpdating { add { } remove { } } public event EventHandler ModeChanged { add { } remove { } } public event FormViewModeEventHandler ModeChanging { add { } remove { } } public event EventHandler PageIndexChanged { add { } remove { } } public event FormViewPageEventHandler PageIndexChanging { add { } remove { } } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace PropertyManager.Web.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
/* * Copyright (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 log4net; using NDesk.Options; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver { /// <summary> /// This module loads and saves OpenSimulator inventory archives /// </summary> public class InventoryArchiverModule : IRegionModule, IInventoryArchiverModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public string Name { get { return "Inventory Archiver Module"; } } public bool IsSharedModule { get { return true; } } /// <value> /// Enable or disable checking whether the iar user is actually logged in /// </value> public bool DisablePresenceChecks { get; set; } public event InventoryArchiveSaved OnInventoryArchiveSaved; /// <summary> /// The file to load and save inventory if no filename has been specified /// </summary> protected const string DEFAULT_INV_BACKUP_FILENAME = "user-inventory.iar"; /// <value> /// Pending save completions initiated from the console /// </value> protected List<Guid> m_pendingConsoleSaves = new List<Guid>(); /// <value> /// All scenes that this module knows about /// </value> private Dictionary<UUID, Scene> m_scenes = new Dictionary<UUID, Scene>(); private Scene m_aScene; public InventoryArchiverModule() {} public InventoryArchiverModule(bool disablePresenceChecks) { DisablePresenceChecks = disablePresenceChecks; } public void Initialise(Scene scene, IConfigSource source) { if (m_scenes.Count == 0) { scene.RegisterModuleInterface<IInventoryArchiverModule>(this); OnInventoryArchiveSaved += SaveInvConsoleCommandCompleted; scene.AddCommand( this, "load iar", "load iar <first> <last> <inventory path> <password> [<IAR path>]", //"load iar [--merge] <first> <last> <inventory path> <password> [<IAR path>]", "Load user inventory archive (IAR).", //"--merge is an option which merges the loaded IAR with existing inventory folders where possible, rather than always creating new ones" //+ "<first> is user's first name." + Environment.NewLine "<first> is user's first name." + Environment.NewLine + "<last> is user's last name." + Environment.NewLine + "<inventory path> is the path inside the user's inventory where the IAR should be loaded." + Environment.NewLine + "<password> is the user's password." + Environment.NewLine + "<IAR path> is the filesystem path or URI from which to load the IAR." + string.Format(" If this is not given then the filename {0} in the current directory is used", DEFAULT_INV_BACKUP_FILENAME), HandleLoadInvConsoleCommand); scene.AddCommand( this, "save iar", "save iar <first> <last> <inventory path> <password> [<IAR path>]", "Save user inventory archive (IAR).", "<first> is the user's first name." + Environment.NewLine + "<last> is the user's last name." + Environment.NewLine + "<inventory path> is the path inside the user's inventory for the folder/item to be saved." + Environment.NewLine + "<IAR path> is the filesystem path at which to save the IAR." + string.Format(" If this is not given then the filename {0} in the current directory is used", DEFAULT_INV_BACKUP_FILENAME), HandleSaveInvConsoleCommand); m_aScene = scene; } m_scenes[scene.RegionInfo.RegionID] = scene; } public void PostInitialise() {} public void Close() {} /// <summary> /// Trigger the inventory archive saved event. /// </summary> protected internal void TriggerInventoryArchiveSaved( Guid id, bool succeeded, UserAccount userInfo, string invPath, Stream saveStream, Exception reportedException) { InventoryArchiveSaved handlerInventoryArchiveSaved = OnInventoryArchiveSaved; if (handlerInventoryArchiveSaved != null) handlerInventoryArchiveSaved(id, succeeded, userInfo, invPath, saveStream, reportedException); } public bool ArchiveInventory( Guid id, string firstName, string lastName, string invPath, string pass, Stream saveStream) { return ArchiveInventory(id, firstName, lastName, invPath, pass, saveStream, new Dictionary<string, object>()); } public bool ArchiveInventory( Guid id, string firstName, string lastName, string invPath, string pass, Stream saveStream, Dictionary<string, object> options) { if (m_scenes.Count > 0) { UserAccount userInfo = GetUserInfo(firstName, lastName, pass); if (userInfo != null) { if (CheckPresence(userInfo.PrincipalID)) { try { new InventoryArchiveWriteRequest(id, this, m_aScene, userInfo, invPath, saveStream).Execute(); } catch (EntryPointNotFoundException e) { m_log.ErrorFormat( "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + "If you've manually installed Mono, have you appropriately updated zlib1g as well?"); m_log.Error(e); return false; } return true; } else { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator", userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID); } } } return false; } public bool ArchiveInventory( Guid id, string firstName, string lastName, string invPath, string pass, string savePath, Dictionary<string, object> options) { if (m_scenes.Count > 0) { UserAccount userInfo = GetUserInfo(firstName, lastName, pass); if (userInfo != null) { if (CheckPresence(userInfo.PrincipalID)) { try { new InventoryArchiveWriteRequest(id, this, m_aScene, userInfo, invPath, savePath).Execute(); } catch (EntryPointNotFoundException e) { m_log.ErrorFormat( "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + "If you've manually installed Mono, have you appropriately updated zlib1g as well?"); m_log.Error(e); return false; } return true; } else { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator", userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID); } } } return false; } public bool DearchiveInventory(string firstName, string lastName, string invPath, string pass, Stream loadStream) { return DearchiveInventory(firstName, lastName, invPath, pass, loadStream, new Dictionary<string, object>()); } public bool DearchiveInventory( string firstName, string lastName, string invPath, string pass, Stream loadStream, Dictionary<string, object> options) { if (m_scenes.Count > 0) { UserAccount userInfo = GetUserInfo(firstName, lastName, pass); if (userInfo != null) { if (CheckPresence(userInfo.PrincipalID)) { InventoryArchiveReadRequest request; try { request = new InventoryArchiveReadRequest(m_aScene, userInfo, invPath, loadStream); } catch (EntryPointNotFoundException e) { m_log.ErrorFormat( "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + "If you've manually installed Mono, have you appropriately updated zlib1g as well?"); m_log.Error(e); return false; } UpdateClientWithLoadedNodes(userInfo, request.Execute()); return true; } else { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator", userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID); } } } return false; } public bool DearchiveInventory( string firstName, string lastName, string invPath, string pass, string loadPath, Dictionary<string, object> options) { if (m_scenes.Count > 0) { UserAccount userInfo = GetUserInfo(firstName, lastName, pass); if (userInfo != null) { if (CheckPresence(userInfo.PrincipalID)) { InventoryArchiveReadRequest request; try { request = new InventoryArchiveReadRequest(m_aScene, userInfo, invPath, loadPath); } catch (EntryPointNotFoundException e) { m_log.ErrorFormat( "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + "If you've manually installed Mono, have you appropriately updated zlib1g as well?"); m_log.Error(e); return false; } UpdateClientWithLoadedNodes(userInfo, request.Execute()); return true; } else { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: User {0} {1} {2} not logged in to this region simulator", userInfo.FirstName, userInfo.LastName, userInfo.PrincipalID); } } } return false; } /// <summary> /// Load inventory from an inventory file archive /// </summary> /// <param name="cmdparams"></param> protected void HandleLoadInvConsoleCommand(string module, string[] cmdparams) { m_log.Info("[INVENTORY ARCHIVER]: PLEASE NOTE THAT THIS FACILITY IS EXPERIMENTAL. BUG REPORTS WELCOME."); Dictionary<string, object> options = new Dictionary<string, object>(); OptionSet optionSet = new OptionSet().Add("m|merge", delegate (string v) { options["merge"] = v != null; }); List<string> mainParams = optionSet.Parse(cmdparams); if (mainParams.Count < 6) { m_log.Error( "[INVENTORY ARCHIVER]: usage is load iar <first name> <last name> <inventory path> <user password> [<load file path>]"); return; } string firstName = mainParams[2]; string lastName = mainParams[3]; string invPath = mainParams[4]; string pass = mainParams[5]; string loadPath = (mainParams.Count > 6 ? mainParams[6] : DEFAULT_INV_BACKUP_FILENAME); m_log.InfoFormat( "[INVENTORY ARCHIVER]: Loading archive {0} to inventory path {1} for {2} {3}", loadPath, invPath, firstName, lastName); if (DearchiveInventory(firstName, lastName, invPath, pass, loadPath, options)) m_log.InfoFormat( "[INVENTORY ARCHIVER]: Loaded archive {0} for {1} {2}", loadPath, firstName, lastName); } /// <summary> /// Save inventory to a file archive /// </summary> /// <param name="cmdparams"></param> protected void HandleSaveInvConsoleCommand(string module, string[] cmdparams) { if (cmdparams.Length < 6) { m_log.Error( "[INVENTORY ARCHIVER]: usage is save iar <first name> <last name> <inventory path> <user password> [<save file path>]"); return; } m_log.Info("[INVENTORY ARCHIVER]: PLEASE NOTE THAT THIS FACILITY IS EXPERIMENTAL. BUG REPORTS WELCOME."); string firstName = cmdparams[2]; string lastName = cmdparams[3]; string invPath = cmdparams[4]; string pass = cmdparams[5]; string savePath = (cmdparams.Length > 6 ? cmdparams[6] : DEFAULT_INV_BACKUP_FILENAME); m_log.InfoFormat( "[INVENTORY ARCHIVER]: Saving archive {0} using inventory path {1} for {2} {3}", savePath, invPath, firstName, lastName); Guid id = Guid.NewGuid(); ArchiveInventory(id, firstName, lastName, invPath, pass, savePath, new Dictionary<string, object>()); lock (m_pendingConsoleSaves) m_pendingConsoleSaves.Add(id); } private void SaveInvConsoleCommandCompleted( Guid id, bool succeeded, UserAccount userInfo, string invPath, Stream saveStream, Exception reportedException) { lock (m_pendingConsoleSaves) { if (m_pendingConsoleSaves.Contains(id)) m_pendingConsoleSaves.Remove(id); else return; } if (succeeded) { m_log.InfoFormat("[INVENTORY ARCHIVER]: Saved archive for {0} {1}", userInfo.FirstName, userInfo.LastName); } else { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: Archive save for {0} {1} failed - {2}", userInfo.FirstName, userInfo.LastName, reportedException.Message); } } /// <summary> /// Get user information for the given name. /// </summary> /// <param name="firstName"></param> /// <param name="lastName"></param> /// <param name="pass">User password</param> /// <returns></returns> protected UserAccount GetUserInfo(string firstName, string lastName, string pass) { UserAccount account = m_aScene.UserAccountService.GetUserAccount(m_aScene.RegionInfo.ScopeID, firstName, lastName); if (null == account) { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: Failed to find user info for {0} {1}", firstName, lastName); return null; } try { string encpass = Util.Md5Hash(pass); if (m_aScene.AuthenticationService.Authenticate(account.PrincipalID, encpass, 1) != string.Empty) { return account; } else { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: Password for user {0} {1} incorrect. Please try again.", firstName, lastName); return null; } } catch (Exception e) { m_log.ErrorFormat("[INVENTORY ARCHIVER]: Could not authenticate password, {0}", e.Message); return null; } } /// <summary> /// Notify the client of loaded nodes if they are logged in /// </summary> /// <param name="loadedNodes">Can be empty. In which case, nothing happens</param> private void UpdateClientWithLoadedNodes(UserAccount userInfo, List<InventoryNodeBase> loadedNodes) { if (loadedNodes.Count == 0) return; foreach (Scene scene in m_scenes.Values) { ScenePresence user = scene.GetScenePresence(userInfo.PrincipalID); if (user != null && !user.IsChildAgent) { foreach (InventoryNodeBase node in loadedNodes) { // m_log.DebugFormat( // "[INVENTORY ARCHIVER]: Notifying {0} of loaded inventory node {1}", // user.Name, node.Name); user.ControllingClient.SendBulkUpdateInventory(node); } break; } } } /// <summary> /// Check if the given user is present in any of the scenes. /// </summary> /// <param name="userId">The user to check</param> /// <returns>true if the user is in any of the scenes, false otherwise</returns> protected bool CheckPresence(UUID userId) { if (DisablePresenceChecks) return true; foreach (Scene scene in m_scenes.Values) { ScenePresence p; if ((p = scene.GetScenePresence(userId)) != null) { p.ControllingClient.SendAgentAlertMessage("Inventory operation has been started", false); return true; } } return false; } } }
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System.Security; namespace NLog.Internal.FileAppenders { using System; using System.IO; using System.Runtime.InteropServices; using NLog.Common; using NLog.Internal; /// <summary> /// Base class for optimized file appenders. /// </summary> [SecuritySafeCritical] internal abstract class BaseFileAppender : IDisposable { private readonly Random random = new Random(); /// <summary> /// Initializes a new instance of the <see cref="BaseFileAppender" /> class. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="createParameters">The create parameters.</param> public BaseFileAppender(string fileName, ICreateFileParameters createParameters) { this.CreateFileParameters = createParameters; this.FileName = fileName; this.OpenTime = DateTime.UtcNow; // to be consistent with timeToKill in FileTarget.AutoClosingTimerCallback this.LastWriteTime = DateTime.MinValue; } /// <summary> /// Gets the path of the file, including file extension. /// </summary> /// <value>The name of the file.</value> public string FileName { get; private set; } /// <summary> /// Gets the file creation time. /// </summary> /// <value>The file creation time. DateTime value must be of UTC kind.</value> public DateTime CreationTime { get; private set; } /// <summary> /// Gets the open time of the file. /// </summary> /// <value>The open time. DateTime value must be of UTC kind.</value> public DateTime OpenTime { get; private set; } /// <summary> /// Gets the last write time. /// </summary> /// <value>The time the file was last written to. DateTime value must be of UTC kind.</value> public DateTime LastWriteTime { get; private set; } /// <summary> /// Gets the file creation parameters. /// </summary> /// <value>The file creation parameters.</value> public ICreateFileParameters CreateFileParameters { get; private set; } /// <summary> /// Writes the specified bytes. /// </summary> /// <param name="bytes">The bytes.</param> public abstract void Write(byte[] bytes); /// <summary> /// Writes the specified bytes. /// </summary> /// <param name="bytes">The byte array to write.</param> /// <param name="offset">The offset in the byte array to start writing from.</param> /// <param name="count">The number of bytes to write.</param> public abstract void Write(byte[] bytes, int offset, int count); /// <summary> /// Flushes this instance. /// </summary> public abstract void Flush(); /// <summary> /// Closes this instance. /// </summary> public abstract void Close(); /// <summary> /// Gets the file info. /// </summary> /// <returns>The file characteristics, if the file information was retrieved successfully, otherwise null.</returns> public abstract FileCharacteristics GetFileCharacteristics(); /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing">True to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (disposing) { this.Close(); } } /// <summary> /// Updates the last write time of the file. /// </summary> protected void FileTouched() { FileTouched(DateTime.UtcNow); } /// <summary> /// Updates the last write time of the file to the specified date. /// </summary> /// <param name="dateTime">Date and time when the last write occurred in UTC.</param> protected void FileTouched(DateTime dateTime) { this.LastWriteTime = dateTime; } /// <summary> /// Creates the file stream. /// </summary> /// <param name="allowFileSharedWriting">If set to <c>true</c> sets the file stream to allow shared writing.</param> /// <returns>A <see cref="FileStream"/> object which can be used to write to the file.</returns> protected FileStream CreateFileStream(bool allowFileSharedWriting) { int currentDelay = this.CreateFileParameters.ConcurrentWriteAttemptDelay; InternalLogger.Trace("Opening {0} with allowFileSharedWriting={1}", this.FileName, allowFileSharedWriting.ToString()); for (int i = 0; i < this.CreateFileParameters.ConcurrentWriteAttempts; ++i) { try { try { return this.TryCreateFileStream(allowFileSharedWriting); } catch (DirectoryNotFoundException) { if (!this.CreateFileParameters.CreateDirs) { throw; } Directory.CreateDirectory(Path.GetDirectoryName(this.FileName)); return this.TryCreateFileStream(allowFileSharedWriting); } } catch (IOException) { if (!this.CreateFileParameters.ConcurrentWrites || i + 1 == this.CreateFileParameters.ConcurrentWriteAttempts) { throw; // rethrow } int actualDelay = this.random.Next(currentDelay); InternalLogger.Warn("Attempt #{0} to open {1} failed. Sleeping for {2}ms", i.AsString(), this.FileName, actualDelay.AsString()); currentDelay *= 2; System.Threading.Thread.Sleep(actualDelay); } } throw new InvalidOperationException("Should not be reached."); } #if !SILVERLIGHT && !MONO && !__IOS__ && !__ANDROID__ [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Objects are disposed elsewhere")] private FileStream WindowsCreateFile(string fileName, bool allowFileSharedWriting) { int fileShare = Win32FileNativeMethods.FILE_SHARE_READ; if (allowFileSharedWriting) { fileShare |= Win32FileNativeMethods.FILE_SHARE_WRITE; } if (this.CreateFileParameters.EnableFileDelete && PlatformDetector.CurrentOS != RuntimeOS.Windows) { fileShare |= Win32FileNativeMethods.FILE_SHARE_DELETE; } Microsoft.Win32.SafeHandles.SafeFileHandle handle = null; FileStream fileStream = null; try { handle = Win32FileNativeMethods.CreateFile( fileName, Win32FileNativeMethods.FileAccess.GenericWrite | Win32FileNativeMethods.FileAccess.GenericRead, fileShare, IntPtr.Zero, Win32FileNativeMethods.CreationDisposition.OpenAlways, this.CreateFileParameters.FileAttributes, IntPtr.Zero); if (handle.IsInvalid) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } #if!SILVERLIGHT && !MONO && !__IOS__ && !__ANDROID__ && NET4_5 // TODO: Beware there be dragons here, every time we create a file stream, it creates a byte array the size of the buffersize. // TODO: in MS .NET implementation, the file stream does write to its internal buffer if you are writing something that is bigger than its buffer size, // So, to prevent allocations, we set the buffer to 1, since then it will just write whats in the incoming buffer and not allocate a buffer if (this.CreateFileParameters.PoolingEnabled) { fileStream = new FileStream(handle, FileAccess.ReadWrite, 1); } else { fileStream = new FileStream(handle, FileAccess.ReadWrite, this.CreateFileParameters.BufferSize); } #else fileStream = new FileStream(handle, FileAccess.Write, this.CreateFileParameters.BufferSize); #endif fileStream.Seek(0, SeekOrigin.End); return fileStream; } catch { if (fileStream != null) fileStream.Dispose(); if ((handle != null) && (!handle.IsClosed)) handle.Close(); throw; } } #endif private FileStream TryCreateFileStream(bool allowFileSharedWriting) { UpdateCreationTime(); #if !SILVERLIGHT && !MONO && !__IOS__ && !__ANDROID__ try { if (!this.CreateFileParameters.ForceManaged && PlatformDetector.IsDesktopWin32) { return this.WindowsCreateFile(this.FileName, allowFileSharedWriting); } } catch (SecurityException) { InternalLogger.Debug("Could not use native Windows create file, falling back to managed filestream"); } #endif FileShare fileShare = allowFileSharedWriting ? FileShare.ReadWrite : FileShare.Read; if (this.CreateFileParameters.EnableFileDelete && PlatformDetector.CurrentOS != RuntimeOS.Windows) { fileShare |= FileShare.Delete; } // TODO: Beware there be dragons here, every time we create a file stream, it creates a byte array the size of the buffersize. // TODO: in MS .NET implementation, the file stream does write to its internal buffer if you are writing something that is bigger than its buffer size, // So, to prevent allocations, we might as well set the buffer to 0, since then it will just write whats in the incoming buffer // Possibly find out if we could do something about it, so that it does not create #if!SILVERLIGHT && !MONO && !__IOS__ && !__ANDROID__ && NET4_5 return new FileStream( this.FileName, FileMode.Append, FileAccess.ReadWrite, fileShare, 1); #else return new FileStream( this.FileName, FileMode.Append, FileAccess.Write, fileShare, this.CreateFileParameters.BufferSize); #endif } private void UpdateCreationTime() { if (File.Exists(this.FileName)) { if (this.CreationTime == default(DateTime)) { #if !SILVERLIGHT this.CreationTime = File.GetCreationTimeUtc(this.FileName); #else this.CreationTime = File.GetCreationTime(this.FileName); #endif } } else { File.Create(this.FileName).Dispose(); #if !SILVERLIGHT this.CreationTime = DateTime.UtcNow; // Set the file's creation time to avoid being thwarted by Windows' Tunneling capabilities (https://support.microsoft.com/en-us/kb/172190). File.SetCreationTimeUtc(this.FileName, this.CreationTime); #else this.CreationTime = File.GetCreationTime(this.FileName); #endif } } } }
/******************************************************************************************** Copyright (c) Microsoft Corporation All rights reserved. Microsoft Public License: This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software. 1. Definitions The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law. A "contribution" is the original software, or any additions or changes to the software. A "contributor" is any person that distributes its contribution under this license. "Licensed patents" are a contributor's patent claims that read directly on its contribution. 2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create. (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software. 3. Conditions and Limitations (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically. (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software. (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license. (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. ********************************************************************************************/ using System; using System.Reflection; using System.Globalization; using System.Resources; using System.Threading; namespace Microsoft.VisualStudio.Project.Samples.CustomProject { /// <summary> /// This class represent resource storage and management functionality. /// </summary> internal sealed class Resources { #region Constants internal const string Application = "Application"; internal const string ApplicationCaption = "ApplicationCaption"; internal const string GeneralCaption = "GeneralCaption"; internal const string AssemblyName = "AssemblyName"; internal const string AssemblyNameDescription = "AssemblyNameDescription"; internal const string OutputType = "OutputType"; internal const string OutputTypeDescription = "OutputTypeDescription"; internal const string DefaultNamespace = "DefaultNamespace"; internal const string DefaultNamespaceDescription = "DefaultNamespaceDescription"; internal const string StartupObject = "StartupObject"; internal const string StartupObjectDescription = "StartupObjectDescription"; internal const string ApplicationIcon = "ApplicationIcon"; internal const string ApplicationIconDescription = "ApplicationIconDescription"; internal const string Project = "Project"; internal const string ProjectFile = "ProjectFile"; internal const string ProjectFileDescription = "ProjectFileDescription"; internal const string ProjectFolder = "ProjectFolder"; internal const string ProjectFolderDescription = "ProjectFolderDescription"; internal const string OutputFile = "OutputFile"; internal const string OutputFileDescription = "OutputFileDescription"; internal const string TargetFrameworkMoniker = "TargetFrameworkMoniker"; internal const string TargetFrameworkMonikerDescription = "TargetFrameworkMonikerDescription"; internal const string NestedProjectFileAssemblyFilter = "NestedProjectFileAssemblyFilter"; //internal const string MsgFailedToLoadTemplateFile = "Failed to add template file to project"; #endregion Constants #region Fields private static Resources loader; private ResourceManager resourceManager; private static Object internalSyncObjectInstance; #endregion Fields #region Constructors /// <summary> /// Internal explicitly defined default constructor. /// </summary> internal Resources() { resourceManager = new System.Resources.ResourceManager("Microsoft.VisualStudio.Project.Samples.CustomProject.Resources", Assembly.GetExecutingAssembly()); } #endregion Constructors #region Properties /// <summary> /// Gets the internal sync. object. /// </summary> private static Object InternalSyncObject { get { if(internalSyncObjectInstance == null) { Object o = new Object(); Interlocked.CompareExchange(ref internalSyncObjectInstance, o, null); } return internalSyncObjectInstance; } } /// <summary> /// Gets information about a specific culture. /// </summary> private static CultureInfo Culture { get { return null/*use ResourceManager default, CultureInfo.CurrentUICulture*/; } } /// <summary> /// Gets convenient access to culture-specific resources at runtime. /// </summary> public static ResourceManager ResourceManager { get { return GetLoader().resourceManager; } } #endregion Properties #region Public Implementation /// <summary> /// Provide access to resource string value. /// </summary> /// <param name="name">Received string name.</param> /// <param name="args">Arguments for the String.Format method.</param> /// <returns>Returns resources string value or null if error occured.</returns> public static string GetString(string name, params object[] args) { Resources resourcesInstance = GetLoader(); if(resourcesInstance == null) { return null; } string res = resourcesInstance.resourceManager.GetString(name, Resources.Culture); if(args != null && args.Length > 0) { return String.Format(CultureInfo.CurrentCulture, res, args); } else { return res; } } /// <summary> /// Provide access to resource string value. /// </summary> /// <param name="name">Received string name.</param> /// <returns>Returns resources string value or null if error occured.</returns> public static string GetString(string name) { Resources resourcesInstance = GetLoader(); if(resourcesInstance == null) { return null; } return resourcesInstance.resourceManager.GetString(name, Resources.Culture); } /// <summary> /// Provide access to resource object value. /// </summary> /// <param name="name">Received object name.</param> /// <returns>Returns resources object value or null if error occured.</returns> public static object GetObject(string name) { Resources resourcesInstance = GetLoader(); if(resourcesInstance == null) { return null; } return resourcesInstance.resourceManager.GetObject(name, Resources.Culture); } #endregion Methods #region Private Implementation private static Resources GetLoader() { if(loader == null) { lock(InternalSyncObject) { if(loader == null) { loader = new Resources(); } } } return loader; } #endregion } }
//------------------------------------------- // FontDialog.cs (c) 2006 by Charles Petzold //------------------------------------------- using System; using System.Collections.Generic; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Globalization; namespace Petzold.ChooseFont { public class FontDialog : Window { TextBoxWithLister boxFamily, boxStyle, boxWeight, boxStretch, boxSize; Label lblDisplay; bool isUpdateSuppressed = true; // Public properties. public Typeface Typeface { set { if (boxFamily.Contains(value.FontFamily)) boxFamily.SelectedItem = value.FontFamily; else boxFamily.SelectedIndex = 0; if (boxStyle.Contains(value.Style)) boxStyle.SelectedItem = value.Style; else boxStyle.SelectedIndex = 0; if (boxWeight.Contains(value.Weight)) boxWeight.SelectedItem = value.Weight; else boxWeight.SelectedIndex = 0; if (boxStretch.Contains(value.Stretch)) boxStretch.SelectedItem = value.Stretch; else boxStretch.SelectedIndex = 0; } get { return new Typeface((FontFamily)boxFamily.SelectedItem, (FontStyle)boxStyle.SelectedItem, (FontWeight)boxWeight.SelectedItem, (FontStretch)boxStretch.SelectedItem); } } public double FaceSize { set { double size = 0.75 * value; boxSize.Text = size.ToString(CultureInfo.InvariantCulture); if (!boxSize.Contains(size)) boxSize.Insert(0, size); boxSize.SelectedItem = size; } get { double size; if (!Double.TryParse(boxSize.Text, out size)) size = 8.25; return size / 0.75; } } // Constructor. public FontDialog() { Title = "Font"; ShowInTaskbar = false; WindowStyle = WindowStyle.ToolWindow; WindowStartupLocation = WindowStartupLocation.CenterOwner; SizeToContent = SizeToContent.WidthAndHeight; ResizeMode = ResizeMode.NoResize; // Create three-row Grid as content of window. Grid gridMain = new Grid(); Content = gridMain; // This row is for the TextBoxWithLister controls. RowDefinition rowdef = new RowDefinition(); rowdef.Height = new GridLength(200, GridUnitType.Pixel); gridMain.RowDefinitions.Add(rowdef); // This row is for the sample text. rowdef = new RowDefinition(); rowdef.Height = new GridLength(150, GridUnitType.Pixel); gridMain.RowDefinitions.Add(rowdef); // This row is for the buttons. rowdef = new RowDefinition(); rowdef.Height = GridLength.Auto; gridMain.RowDefinitions.Add(rowdef); // One column in main Grid. ColumnDefinition coldef = new ColumnDefinition(); coldef.Width = new GridLength(650, GridUnitType.Pixel); gridMain.ColumnDefinitions.Add(coldef); // Create two-row, five-column Grid for TextBoxWithLister controls. Grid gridBoxes = new Grid(); gridMain.Children.Add(gridBoxes); // This row is for the labels. rowdef = new RowDefinition(); rowdef.Height = GridLength.Auto; gridBoxes.RowDefinitions.Add(rowdef); // This row is for the EditBoxWithLister controls. rowdef = new RowDefinition(); rowdef.Height = new GridLength(100, GridUnitType.Star); gridBoxes.RowDefinitions.Add(rowdef); // First column is FontFamily. coldef = new ColumnDefinition(); coldef.Width = new GridLength(175, GridUnitType.Star); gridBoxes.ColumnDefinitions.Add(coldef); // Second column is FontStyle. coldef = new ColumnDefinition(); coldef.Width = new GridLength(100, GridUnitType.Star); gridBoxes.ColumnDefinitions.Add(coldef); // Third column is FontWeight. coldef = new ColumnDefinition(); coldef.Width = new GridLength(100, GridUnitType.Star); gridBoxes.ColumnDefinitions.Add(coldef); // Fourth column is FontStretch. coldef = new ColumnDefinition(); coldef.Width = new GridLength(100, GridUnitType.Star); gridBoxes.ColumnDefinitions.Add(coldef); // Fifth column is Size. coldef = new ColumnDefinition(); coldef.Width = new GridLength(75, GridUnitType.Star); gridBoxes.ColumnDefinitions.Add(coldef); // Create FontFamily labels and TextBoxWithLister controls. Label lbl = new Label(); lbl.Content = "Font Family"; lbl.Margin = new Thickness(12, 12, 12, 0); gridBoxes.Children.Add(lbl); Grid.SetRow(lbl, 0); Grid.SetColumn(lbl, 0); boxFamily = new TextBoxWithLister(); boxFamily.IsReadOnly = true; boxFamily.Margin = new Thickness(12, 0, 12, 12); gridBoxes.Children.Add(boxFamily); Grid.SetRow(boxFamily, 1); Grid.SetColumn(boxFamily, 0); // Create FontStyle labels and TextBoxWithLister controls. lbl = new Label(); lbl.Content = "Style"; lbl.Margin = new Thickness(12, 12, 12, 0); gridBoxes.Children.Add(lbl); Grid.SetRow(lbl, 0); Grid.SetColumn(lbl, 1); boxStyle = new TextBoxWithLister(); boxStyle.IsReadOnly = true; boxStyle.Margin = new Thickness(12, 0, 12, 12); gridBoxes.Children.Add(boxStyle); Grid.SetRow(boxStyle, 1); Grid.SetColumn(boxStyle, 1); // Create FontWeight labels and TextBoxWithLister controls. lbl = new Label(); lbl.Content = "Weight"; lbl.Margin = new Thickness(12, 12, 12, 0); gridBoxes.Children.Add(lbl); Grid.SetRow(lbl, 0); Grid.SetColumn(lbl, 2); boxWeight = new TextBoxWithLister(); boxWeight.IsReadOnly = true; boxWeight.Margin = new Thickness(12, 0, 12, 12); gridBoxes.Children.Add(boxWeight); Grid.SetRow(boxWeight, 1); Grid.SetColumn(boxWeight, 2); // Create FontStretch labels and TextBoxWithLister controls. lbl = new Label(); lbl.Content = "Stretch"; lbl.Margin = new Thickness(12, 12, 12, 0); gridBoxes.Children.Add(lbl); Grid.SetRow(lbl, 0); Grid.SetColumn(lbl, 3); boxStretch = new TextBoxWithLister(); boxStretch.IsReadOnly = true; boxStretch.Margin = new Thickness(12, 0, 12, 12); gridBoxes.Children.Add(boxStretch); Grid.SetRow(boxStretch, 1); Grid.SetColumn(boxStretch, 3); // Create Size labels and TextBoxWithLister controls. lbl = new Label(); lbl.Content = "Size"; lbl.Margin = new Thickness(12, 12, 12, 0); gridBoxes.Children.Add(lbl); Grid.SetRow(lbl, 0); Grid.SetColumn(lbl, 4); boxSize = new TextBoxWithLister(); boxSize.Margin = new Thickness(12, 0, 12, 12); gridBoxes.Children.Add(boxSize); Grid.SetRow(boxSize, 1); Grid.SetColumn(boxSize, 4); // Create Label to display sample text. lblDisplay = new Label(); lblDisplay.Content = "AaBbCc XxYzZz 012345"; lblDisplay.HorizontalContentAlignment = HorizontalAlignment.Center; lblDisplay.VerticalContentAlignment = VerticalAlignment.Center; gridMain.Children.Add(lblDisplay); Grid.SetRow(lblDisplay, 1); // Create five-column Grid for Buttons. Grid gridButtons = new Grid(); gridMain.Children.Add(gridButtons); Grid.SetRow(gridButtons, 2); for (int i = 0; i < 5; i++) gridButtons.ColumnDefinitions.Add(new ColumnDefinition()); // OK button. Button btn = new Button(); btn.Content = "OK"; btn.IsDefault = true; btn.HorizontalAlignment = HorizontalAlignment.Center; btn.MinWidth = 60; btn.Margin = new Thickness(12); btn.Click += OkOnClick; gridButtons.Children.Add(btn); Grid.SetColumn(btn, 1); // Cancel button. btn = new Button(); btn.Content = "Cancel"; btn.IsCancel = true; btn.HorizontalAlignment = HorizontalAlignment.Center; btn.MinWidth = 60; btn.Margin = new Thickness(12); gridButtons.Children.Add(btn); Grid.SetColumn(btn, 3); // Initialize FontFamily box with system font families. foreach (FontFamily fam in Fonts.SystemFontFamilies) boxFamily.Add(fam); // Initialize FontSize box. double[] ptsizes = new double[] { 8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 72 }; foreach (double ptsize in ptsizes) boxSize.Add(ptsize); // Set event handlers. boxFamily.SelectionChanged += FamilyOnSelectionChanged; boxStyle.SelectionChanged += StyleOnSelectionChanged; boxWeight.SelectionChanged += StyleOnSelectionChanged; boxStretch.SelectionChanged += StyleOnSelectionChanged; boxSize.TextChanged += SizeOnTextChanged; // Initialize selected values based on Window properties. // (These will probably be overridden when properties are set.) Typeface = new Typeface(FontFamily, FontStyle, FontWeight, FontStretch); FaceSize = FontSize; // Set keyboard focus. boxFamily.Focus(); // Allow updates to the sample text. isUpdateSuppressed = false; UpdateSample(); } // Event handler for SelectionChanged in FontFamily box. void FamilyOnSelectionChanged(object sender, EventArgs args) { // Get selected FontFamily. FontFamily fntfam = (FontFamily)boxFamily.SelectedItem; // Save previous Style, Weight, Stretch. // These should only be null when this method is called for the // first time. FontStyle? fntstyPrevious = (FontStyle?)boxStyle.SelectedItem; FontWeight? fntwtPrevious = (FontWeight?)boxWeight.SelectedItem; FontStretch? fntstrPrevious = (FontStretch?)boxStretch.SelectedItem; // Turn off Sample display. isUpdateSuppressed = true; // Clear Style, Weight, and Stretch boxes. boxStyle.Clear(); boxWeight.Clear(); boxStretch.Clear(); // Loop through typefaces in selected FontFamily. foreach (FamilyTypeface ftf in fntfam.FamilyTypefaces) { // Put Style in boxStyle (Normal always at top). if (!boxStyle.Contains(ftf.Style)) { if (ftf.Style == FontStyles.Normal) boxStyle.Insert(0, ftf.Style); else boxStyle.Add(ftf.Style); } // Put Weight in boxWeight (Normal always at top). if (!boxWeight.Contains(ftf.Weight)) { if (ftf.Weight == FontWeights.Normal) boxWeight.Insert(0, ftf.Weight); else boxWeight.Add(ftf.Weight); } // Put Stretch in boxStretch (Normal always at top). if (!boxStretch.Contains(ftf.Stretch)) { if (ftf.Stretch == FontStretches.Normal) boxStretch.Insert(0, ftf.Stretch); else boxStretch.Add(ftf.Stretch); } } // Set selected item in boxStyle. if (boxStyle.Contains(fntstyPrevious)) boxStyle.SelectedItem = fntstyPrevious; else boxStyle.SelectedIndex = 0; // Set selected item in boxWeight. if (boxWeight.Contains(fntwtPrevious)) boxWeight.SelectedItem = fntwtPrevious; else boxWeight.SelectedIndex = 0; // Set selected item in boxStretch. if (boxStretch.Contains(fntstrPrevious)) boxStretch.SelectedItem = fntstrPrevious; else boxStretch.SelectedIndex = 0; // Resume Sample update and update the Sample. isUpdateSuppressed = false; UpdateSample(); } // Event handler for SelectionChanged in Style, Weight, Stretch boxes. void StyleOnSelectionChanged(object sender, EventArgs args) { UpdateSample(); } // Event handler for TextChanged in Size box. void SizeOnTextChanged(object sender, TextChangedEventArgs args) { UpdateSample(); } // Update the Sample text. void UpdateSample() { if (isUpdateSuppressed) return; lblDisplay.FontFamily = (FontFamily)boxFamily.SelectedItem; lblDisplay.FontStyle = (FontStyle)boxStyle.SelectedItem; lblDisplay.FontWeight = (FontWeight)boxWeight.SelectedItem; lblDisplay.FontStretch = (FontStretch)boxStretch.SelectedItem; double size; if (!Double.TryParse(boxSize.Text, out size)) size = 8.25; lblDisplay.FontSize = size / 0.75; } // OK button terminates dialog box. void OkOnClick(object sender, RoutedEventArgs args) { DialogResult = true; } } }
namespace NRepository.Core.Query { using NRepository.Core.Events; using NRepository.Core.Query.Specification; using NRepository.Core.Utilities; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; public abstract class QueryRepositoryBase : IQueryRepository, IDisposable { private bool disposed; protected QueryRepositoryBase() : this(new DefaultQueryEventHandlers(), new DefaultQueryInterceptor()) { } protected QueryRepositoryBase(IQueryEventHandler queryEventHandlers) : this(queryEventHandlers, new DefaultQueryInterceptor()) { } protected QueryRepositoryBase(IQueryInterceptor queryInterceptor) : this(new DefaultQueryEventHandlers(), queryInterceptor) { } protected QueryRepositoryBase(IQueryEventHandler queryEventHandlers, IQueryInterceptor queryInterceptor) { Check.NotNull(queryEventHandlers, "queryEventHandlers"); Check.NotNull(queryInterceptor, "queryInterceptor"); QueryEventHandler = queryEventHandlers; QueryInterceptor = queryInterceptor; } ~QueryRepositoryBase() { Dispose(false); } public object ObjectContext { get; protected set; } protected IQueryInterceptor QueryInterceptor { get; set; } protected IQueryEventHandler QueryEventHandler { get; set; } public abstract IQueryable<T> GetQueryableEntities<T>(object additionalQueryData) where T : class; public virtual T GetEntity<T>(IQueryStrategy queryStrategy, bool throwExceptionIfZeroOrManyFound, object additionalQueryData = null) where T : class { Check.NotNull(queryStrategy, "queryStrategy"); queryStrategy.QueryableRepository = this; var allResults = queryStrategy.GetQueryableEntities<T>(additionalQueryData).Take(2).AsEnumerable(); QueryEventHandler.RepositoryQueriedEventHandler.Handle(new SimpleRepositoryQueryEvent( this, queryStrategy, additionalQueryData, throwExceptionIfZeroOrManyFound)); if (allResults.Count() != 1 && throwExceptionIfZeroOrManyFound) { var rowsFound = allResults.Count(); throw new EntitySearchRepositoryException(rowsFound, typeof(T).Name, queryStrategy); } var result = allResults.FirstOrDefault(); return result; } public IQueryable<T> GetEntities<T>(IQueryStrategy queryStrategy, object additionalQueryData = null) where T : class { Check.NotNull(queryStrategy, "queryStrategy"); queryStrategy.QueryableRepository = this; QueryEventHandler.RepositoryQueriedEventHandler.Handle(new SimpleRepositoryQueryEvent( this, queryStrategy, additionalQueryData)); var result = queryStrategy.GetQueryableEntities<T>(additionalQueryData); return result; } public T GetEntity<T>(params Expression<Func<T, bool>>[] predicates) where T : class { Check.NotNull(predicates, "predicates"); return GetEntity<T>(predicates.Select(predicate => new ExpressionSpecificationQueryStrategy<T>(predicate)).ToArray()); } public T GetEntity<T>(params IQueryStrategy[] queryStrategies) where T : class { Check.NotNull(queryStrategies, "queryStrategies"); return GetEntity<T>(new AggregateQueryStrategy(queryStrategies), true); } public T GetEntity<T>(Expression<Func<T, bool>> predicate, bool throwExceptionIfZeroOrManyFound) where T : class { Check.NotNull(predicate, "predicate"); return GetEntity<T>(new ExpressionSpecificationQueryStrategy<T>(predicate), throwExceptionIfZeroOrManyFound); } public T GetEntity<T>(Expression<Func<T, bool>> predicate, IQueryStrategy queryStrategy, bool throwExceptionIfZeroOrManyFound) where T : class { Check.NotNull(predicate, "predicate"); Check.NotNull(queryStrategy, "queryStrategy"); return GetEntity<T>(new ExpressionSpecificationQueryStrategy<T>(predicate), queryStrategy, throwExceptionIfZeroOrManyFound); } public T GetEntity<T>(Expression<Func<T, bool>> predicate, params IQueryStrategy[] queryStrategies) where T : class { Check.NotNull(predicate, "predicate"); Check.NotNull(queryStrategies, "queryStrategies"); var aggQueryStrategy = new AggregateQueryStrategy(new ExpressionSpecificationQueryStrategy<T>(predicate)); aggQueryStrategy.AddRange(queryStrategies); return GetEntity<T>(aggQueryStrategy, true); } public T GetEntity<T>(IQueryStrategy queryStrategy, IQueryStrategy queryStrategy2, bool throwExceptionIfZeroOrManyFound) where T : class { Check.NotNull(queryStrategy, "queryStrategy"); Check.NotNull(queryStrategy2, "queryStrategy2"); return GetEntity<T>(new AggregateQueryStrategy(queryStrategy, queryStrategy2), throwExceptionIfZeroOrManyFound); } public T GetEntity<T>(IQueryStrategy queryStrategy, IQueryStrategy queryStrategy2, IQueryStrategy queryStrategy3, bool throwExceptionIfZeroOrManyFound) where T : class { Check.NotNull(queryStrategy, "queryStrategy"); Check.NotNull(queryStrategy2, "queryStrategy2"); Check.NotNull(queryStrategy3, "queryStrategy3"); return GetEntity<T>(new AggregateQueryStrategy(queryStrategy, queryStrategy2, queryStrategy3), throwExceptionIfZeroOrManyFound); } public T GetEntity<T>(IQueryStrategy queryStrategy, IQueryStrategy queryStrategy2, IQueryStrategy queryStrategy3, IQueryStrategy queryStrategy4, bool throwExceptionIfZeroOrManyFound) where T : class { Check.NotNull(queryStrategy, "queryStrategy"); Check.NotNull(queryStrategy2, "queryStrategy2"); Check.NotNull(queryStrategy3, "queryStrategy3"); Check.NotNull(queryStrategy4, "queryStrategy4"); return GetEntity<T>(new AggregateQueryStrategy(queryStrategy, queryStrategy2, queryStrategy3, queryStrategy4), throwExceptionIfZeroOrManyFound); } public T GetEntity<T>(Expression<Func<T, bool>> predicate, IQueryStrategy queryStrategy, IQueryStrategy queryStrategy2, bool throwExceptionIfZeroOrManyFound) where T : class { Check.NotNull(predicate, "predicate"); Check.NotNull(queryStrategy, "queryStrategy"); Check.NotNull(queryStrategy2, "queryStrategy2"); return GetEntity<T>( new AggregateQueryStrategy(new ExpressionSpecificationQueryStrategy<T>(predicate), queryStrategy, queryStrategy2), throwExceptionIfZeroOrManyFound); } public T GetEntity<T>(Expression<Func<T, bool>> predicate, IQueryStrategy queryStrategy, IQueryStrategy queryStrategy2, IQueryStrategy queryStrategy3, bool throwExceptionIfZeroOrManyFound) where T : class { Check.NotNull(predicate, "predicate"); Check.NotNull(queryStrategy, "queryStrategy"); Check.NotNull(queryStrategy2, "queryStrategy2"); Check.NotNull(queryStrategy3, "queryStrategy3"); return GetEntity<T>( new AggregateQueryStrategy(new ExpressionSpecificationQueryStrategy<T>(predicate), queryStrategy, queryStrategy2, queryStrategy3), throwExceptionIfZeroOrManyFound); } public T GetEntity<T>(Expression<Func<T, bool>> predicate, IQueryStrategy queryStrategy, IQueryStrategy queryStrategy2, IQueryStrategy queryStrategy3, IQueryStrategy queryStrategy4, bool throwExceptionIfZeroOrManyFound) where T : class { Check.NotNull(predicate, "predicate"); Check.NotNull(queryStrategy, "queryStrategy"); Check.NotNull(queryStrategy2, "queryStrategy2"); Check.NotNull(queryStrategy3, "queryStrategy3"); Check.NotNull(queryStrategy4, "queryStrategy4"); return GetEntity<T>( new AggregateQueryStrategy(new ExpressionSpecificationQueryStrategy<T>(predicate), queryStrategy, queryStrategy2, queryStrategy3, queryStrategy4), throwExceptionIfZeroOrManyFound); } public IQueryable<T> GetEntities<T>() where T : class { return GetEntities<T>(new DefaultQueryStrategy()); } public IQueryable<T> GetEntities<T>(params IQueryStrategy[] queryStrategy) where T : class { Check.NotNull(queryStrategy, "queryStrategy"); return GetEntities<T>(new AggregateQueryStrategy(queryStrategy)); } public IQueryable<T> GetEntities<T>(Expression<Func<T, bool>> predicate) where T : class { Check.NotNull(predicate, "predicate"); return GetEntities<T>(new ExpressionSpecificationQueryStrategy<T>(predicate)); } public IQueryable<T> GetEntities<T>(Expression<Func<T, bool>> predicate, params IQueryStrategy[] queryStrategies) where T : class { Check.NotNull(predicate, "predicate"); Check.NotNull(queryStrategies, "queryStrategies"); var aggregateQueryStrategy = new AggregateQueryStrategy(new ExpressionSpecificationQueryStrategy<T>(predicate)); aggregateQueryStrategy.AddRange(queryStrategies); return GetEntities<T>(aggregateQueryStrategy); } public async Task<T> GetEntityAsync<T>(params Expression<Func<T, bool>>[] predicates) where T : class { Check.NotNull(predicates, "predicates"); return await Task.Run(() => GetEntity<T>(predicates)); } public async Task<T> GetEntityAsync<T>(params IQueryStrategy[] queryStrategies) where T : class { Check.NotNull(queryStrategies, "queryStrategies"); return await Task.Run(() => GetEntity<T>(queryStrategies)); } public async Task<T> GetEntityAsync<T>(Expression<Func<T, bool>> predicate, bool throwExceptionIfZeroOrManyFound) where T : class { Check.NotNull(predicate, "predicate"); return await Task.Run(() => GetEntity<T>(predicate, throwExceptionIfZeroOrManyFound)); } public async Task<T> GetEntityAsync<T>(Expression<Func<T, bool>> predicate, IQueryStrategy queryStrategy, bool throwExceptionIfZeroOrManyFound) where T : class { Check.NotNull(predicate, "predicate"); Check.NotNull(queryStrategy, "queryStrategy"); return await Task.Run(() => GetEntity<T>(predicate, queryStrategy, throwExceptionIfZeroOrManyFound)); } public async Task<T> GetEntityAsync<T>(Expression<Func<T, bool>> predicate, params IQueryStrategy[] queryStrategies) where T : class { Check.NotNull(predicate, "predicate"); Check.NotNull(queryStrategies, "queryStrategies"); return await Task.Run(() => GetEntity<T>(predicate, queryStrategies)); } public async Task<T> GetEntityAsync<T>(IQueryStrategy queryStrategy, IQueryStrategy queryStrategy2, bool throwExceptionIfZeroOrManyFound) where T : class { Check.NotNull(queryStrategy, "queryStrategy"); Check.NotNull(queryStrategy2, "queryStrategy2"); return await Task.Run(() => GetEntity<T>(queryStrategy, queryStrategy2, throwExceptionIfZeroOrManyFound)); } public async Task<T> GetEntityAsync<T>(IQueryStrategy queryStrategy, IQueryStrategy queryStrategy2, IQueryStrategy queryStrategy3, bool throwExceptionIfZeroOrManyFound) where T : class { Check.NotNull(queryStrategy, "queryStrategy"); Check.NotNull(queryStrategy2, "queryStrategy2"); Check.NotNull(queryStrategy3, "queryStrategy3"); return await Task.Run(() => GetEntity<T>(queryStrategy, queryStrategy2, queryStrategy3, throwExceptionIfZeroOrManyFound)); } public async Task<T> GetEntityAsync<T>(IQueryStrategy queryStrategy, IQueryStrategy queryStrategy2, IQueryStrategy queryStrategy3, IQueryStrategy queryStrategy4, bool throwExceptionIfZeroOrManyFound) where T : class { Check.NotNull(queryStrategy, "queryStrategy"); Check.NotNull(queryStrategy2, "queryStrategy2"); Check.NotNull(queryStrategy3, "queryStrategy3"); Check.NotNull(queryStrategy4, "queryStrategy4"); return await Task.Run(() => GetEntity<T>(queryStrategy, queryStrategy2, queryStrategy3, queryStrategy4, throwExceptionIfZeroOrManyFound)); } public async Task<T> GetEntityAsync<T>(Expression<Func<T, bool>> predicate, IQueryStrategy queryStrategy, IQueryStrategy queryStrategy2, bool throwExceptionIfZeroOrManyFound) where T : class { Check.NotNull(predicate, "predicate"); Check.NotNull(queryStrategy, "queryStrategy"); Check.NotNull(queryStrategy2, "queryStrategy2"); return await Task.Run(() => GetEntity<T>(predicate, queryStrategy, queryStrategy2, throwExceptionIfZeroOrManyFound)); } public async Task<T> GetEntityAsync<T>(Expression<Func<T, bool>> predicate, IQueryStrategy queryStrategy, IQueryStrategy queryStrategy2, IQueryStrategy queryStrategy3, bool throwExceptionIfZeroOrManyFound) where T : class { Check.NotNull(predicate, "predicate"); Check.NotNull(queryStrategy, "queryStrategy"); Check.NotNull(queryStrategy2, "queryStrategy2"); Check.NotNull(queryStrategy3, "queryStrategy3"); return await Task.Run(() => GetEntity<T>(predicate, queryStrategy, queryStrategy2, queryStrategy3, throwExceptionIfZeroOrManyFound)); } public async Task<T> GetEntityAsync<T>(Expression<Func<T, bool>> predicate, IQueryStrategy queryStrategy, IQueryStrategy queryStrategy2, IQueryStrategy queryStrategy3, IQueryStrategy queryStrategy4, bool throwExceptionIfZeroOrManyFound) where T : class { Check.NotNull(predicate, "predicate"); Check.NotNull(queryStrategy, "queryStrategy"); Check.NotNull(queryStrategy2, "queryStrategy2"); Check.NotNull(queryStrategy3, "queryStrategy3"); Check.NotNull(queryStrategy4, "queryStrategy4"); return await Task.Run(() => GetEntity<T>(predicate, queryStrategy, queryStrategy2, queryStrategy3, queryStrategy4, throwExceptionIfZeroOrManyFound)); } public async Task<List<T>> GetEntitiesAsync<T>() where T : class { return await Task.Run(() => GetEntities<T>().ToList()); } public async Task<List<T>> GetEntitiesAsync<T>(params IQueryStrategy[] queryStrategy) where T : class { Check.NotNull(queryStrategy, "queryStrategy"); return await Task.Run(() => GetEntities<T>(queryStrategy).ToList()); } public async Task<List<T>> GetEntitiesAsync<T>(Expression<Func<T, bool>> predicate) where T : class { Check.NotNull(predicate, "predicate"); return await Task.Run(() => GetEntities<T>(predicate).ToList()); } public async Task<List<T>> GetEntitiesAsync<T>(Expression<Func<T, bool>> predicate, params IQueryStrategy[] queryStrategies) where T : class { Check.NotNull(predicate, "predicate"); Check.NotNull(queryStrategies, "queryStrategies"); return await Task.Run(() => GetEntities<T>(predicate, queryStrategies).ToList()); } public async Task<T> GetEntityAsync<T>(IQueryStrategy queryStrategy, bool throwExceptionIfZeroOrManyFound) where T : class { Check.NotNull(queryStrategy, "queryStrategy"); return await Task.Run(() => GetEntity<T>(queryStrategy, throwExceptionIfZeroOrManyFound)); } public IQueryable<T> GetEntities<T>(params Expression<Func<T, bool>>[] predicates) where T : class { Check.NotNull(predicates, "predicates"); return GetEntities<T>(new AggregateQueryStrategy(predicates.Select(predicate => new ExpressionSpecificationQueryStrategy<T>(predicate)).ToArray())); } public async Task<List<T>> GetEntitiesAsync<T>(params Expression<Func<T, bool>>[] predicates) where T : class { Check.NotNull(predicates, "predicates"); return await Task.Run(() => GetEntities<T>(predicates).ToList()); } public async Task<T> GetEntityAsync<T>(IQueryStrategy queryStrategy, bool throwExceptionIfZeroOrManyFound, object additionalQueryData = null) where T : class { return await Task.Run(() => GetEntity<T>(queryStrategy, throwExceptionIfZeroOrManyFound, additionalQueryData)); } public async Task<List<T>> GetEntitiesAsync<T>(IQueryStrategy queryStrategy, object additionalQueryData = null) where T : class { return await Task.Run(() => GetEntities<T>(queryStrategy, additionalQueryData).ToList()); } [ExcludeFromCodeCoverage] public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } [ExcludeFromCodeCoverage] protected virtual void Dispose(bool disposing) { if (disposed) return; disposed = true; if (disposing) { if (ObjectContext != null && ObjectContext is IDisposable) { ((IDisposable)ObjectContext).Dispose(); } ObjectContext = null; } } public virtual void RaiseEvent<T>(T evnt) where T : class, IRepositoryQueryEvent { var addedEvent = evnt as RepositoryQueryEvent; QueryEventHandler.RepositoryQueriedEventHandler.Handle(addedEvent); } } }
// 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! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V10.Services { /// <summary>Settings for <see cref="AdGroupAssetServiceClient"/> instances.</summary> public sealed partial class AdGroupAssetServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="AdGroupAssetServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="AdGroupAssetServiceSettings"/>.</returns> public static AdGroupAssetServiceSettings GetDefault() => new AdGroupAssetServiceSettings(); /// <summary>Constructs a new <see cref="AdGroupAssetServiceSettings"/> object with default settings.</summary> public AdGroupAssetServiceSettings() { } private AdGroupAssetServiceSettings(AdGroupAssetServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); MutateAdGroupAssetsSettings = existing.MutateAdGroupAssetsSettings; OnCopy(existing); } partial void OnCopy(AdGroupAssetServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>AdGroupAssetServiceClient.MutateAdGroupAssets</c> and /// <c>AdGroupAssetServiceClient.MutateAdGroupAssetsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings MutateAdGroupAssetsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="AdGroupAssetServiceSettings"/> object.</returns> public AdGroupAssetServiceSettings Clone() => new AdGroupAssetServiceSettings(this); } /// <summary> /// Builder class for <see cref="AdGroupAssetServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class AdGroupAssetServiceClientBuilder : gaxgrpc::ClientBuilderBase<AdGroupAssetServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public AdGroupAssetServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public AdGroupAssetServiceClientBuilder() { UseJwtAccessWithScopes = AdGroupAssetServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref AdGroupAssetServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AdGroupAssetServiceClient> task); /// <summary>Builds the resulting client.</summary> public override AdGroupAssetServiceClient Build() { AdGroupAssetServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<AdGroupAssetServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<AdGroupAssetServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private AdGroupAssetServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return AdGroupAssetServiceClient.Create(callInvoker, Settings); } private async stt::Task<AdGroupAssetServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return AdGroupAssetServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => AdGroupAssetServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => AdGroupAssetServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => AdGroupAssetServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>AdGroupAssetService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage ad group assets. /// </remarks> public abstract partial class AdGroupAssetServiceClient { /// <summary> /// The default endpoint for the AdGroupAssetService service, which is a host of "googleads.googleapis.com" and /// a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default AdGroupAssetService scopes.</summary> /// <remarks> /// The default AdGroupAssetService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="AdGroupAssetServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use /// <see cref="AdGroupAssetServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="AdGroupAssetServiceClient"/>.</returns> public static stt::Task<AdGroupAssetServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new AdGroupAssetServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="AdGroupAssetServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use /// <see cref="AdGroupAssetServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="AdGroupAssetServiceClient"/>.</returns> public static AdGroupAssetServiceClient Create() => new AdGroupAssetServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="AdGroupAssetServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="AdGroupAssetServiceSettings"/>.</param> /// <returns>The created <see cref="AdGroupAssetServiceClient"/>.</returns> internal static AdGroupAssetServiceClient Create(grpccore::CallInvoker callInvoker, AdGroupAssetServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } AdGroupAssetService.AdGroupAssetServiceClient grpcClient = new AdGroupAssetService.AdGroupAssetServiceClient(callInvoker); return new AdGroupAssetServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC AdGroupAssetService client</summary> public virtual AdGroupAssetService.AdGroupAssetServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes ad group assets. Operation statuses are /// returned. /// /// List of thrown errors: /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [NotAllowlistedError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateAdGroupAssetsResponse MutateAdGroupAssets(MutateAdGroupAssetsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes ad group assets. Operation statuses are /// returned. /// /// List of thrown errors: /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [NotAllowlistedError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateAdGroupAssetsResponse> MutateAdGroupAssetsAsync(MutateAdGroupAssetsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes ad group assets. Operation statuses are /// returned. /// /// List of thrown errors: /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [NotAllowlistedError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateAdGroupAssetsResponse> MutateAdGroupAssetsAsync(MutateAdGroupAssetsRequest request, st::CancellationToken cancellationToken) => MutateAdGroupAssetsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes ad group assets. Operation statuses are /// returned. /// /// List of thrown errors: /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [NotAllowlistedError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose ad group assets are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual ad group assets. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateAdGroupAssetsResponse MutateAdGroupAssets(string customerId, scg::IEnumerable<AdGroupAssetOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateAdGroupAssets(new MutateAdGroupAssetsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes ad group assets. Operation statuses are /// returned. /// /// List of thrown errors: /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [NotAllowlistedError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose ad group assets are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual ad group assets. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateAdGroupAssetsResponse> MutateAdGroupAssetsAsync(string customerId, scg::IEnumerable<AdGroupAssetOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateAdGroupAssetsAsync(new MutateAdGroupAssetsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes ad group assets. Operation statuses are /// returned. /// /// List of thrown errors: /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [NotAllowlistedError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose ad group assets are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual ad group assets. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateAdGroupAssetsResponse> MutateAdGroupAssetsAsync(string customerId, scg::IEnumerable<AdGroupAssetOperation> operations, st::CancellationToken cancellationToken) => MutateAdGroupAssetsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>AdGroupAssetService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage ad group assets. /// </remarks> public sealed partial class AdGroupAssetServiceClientImpl : AdGroupAssetServiceClient { private readonly gaxgrpc::ApiCall<MutateAdGroupAssetsRequest, MutateAdGroupAssetsResponse> _callMutateAdGroupAssets; /// <summary> /// Constructs a client wrapper for the AdGroupAssetService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="AdGroupAssetServiceSettings"/> used within this client.</param> public AdGroupAssetServiceClientImpl(AdGroupAssetService.AdGroupAssetServiceClient grpcClient, AdGroupAssetServiceSettings settings) { GrpcClient = grpcClient; AdGroupAssetServiceSettings effectiveSettings = settings ?? AdGroupAssetServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callMutateAdGroupAssets = clientHelper.BuildApiCall<MutateAdGroupAssetsRequest, MutateAdGroupAssetsResponse>(grpcClient.MutateAdGroupAssetsAsync, grpcClient.MutateAdGroupAssets, effectiveSettings.MutateAdGroupAssetsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateAdGroupAssets); Modify_MutateAdGroupAssetsApiCall(ref _callMutateAdGroupAssets); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_MutateAdGroupAssetsApiCall(ref gaxgrpc::ApiCall<MutateAdGroupAssetsRequest, MutateAdGroupAssetsResponse> call); partial void OnConstruction(AdGroupAssetService.AdGroupAssetServiceClient grpcClient, AdGroupAssetServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC AdGroupAssetService client</summary> public override AdGroupAssetService.AdGroupAssetServiceClient GrpcClient { get; } partial void Modify_MutateAdGroupAssetsRequest(ref MutateAdGroupAssetsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Creates, updates, or removes ad group assets. Operation statuses are /// returned. /// /// List of thrown errors: /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [NotAllowlistedError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override MutateAdGroupAssetsResponse MutateAdGroupAssets(MutateAdGroupAssetsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateAdGroupAssetsRequest(ref request, ref callSettings); return _callMutateAdGroupAssets.Sync(request, callSettings); } /// <summary> /// Creates, updates, or removes ad group assets. Operation statuses are /// returned. /// /// List of thrown errors: /// [AssetLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [NotAllowlistedError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<MutateAdGroupAssetsResponse> MutateAdGroupAssetsAsync(MutateAdGroupAssetsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateAdGroupAssetsRequest(ref request, ref callSettings); return _callMutateAdGroupAssets.Async(request, callSettings); } } }
new SimGroup(AssetBrowserPreviewCache); //AssetBrowser.addToolbarButton function AssetBrowser::addToolbarButton(%this) { %filename = expandFilename("tools/gui/images/iconOpen"); %button = new GuiBitmapButtonCtrl() { canSaveDynamicFields = "0"; internalName = AssetBrowserBtn; Enabled = "1"; isContainer = "0"; Profile = "ToolsGuiButtonProfile"; HorizSizing = "right"; VertSizing = "bottom"; position = "180 0"; Extent = "25 19"; MinExtent = "8 2"; canSave = "1"; Visible = "1"; Command = "AssetBrowser.ShowDialog();"; tooltipprofile = "ToolsGuiToolTipProfile"; ToolTip = "Asset Browser"; hovertime = "750"; bitmap = %filename; bitmapMode = "Centered"; buttonType = "PushButton"; groupNum = "0"; useMouseEvents = "0"; }; ToolsToolbarArray.add(%button); EWToolsToolbar.setExtent((25 + 8) * (ToolsToolbarArray.getCount()) + 12 SPC "33"); } // function AssetBrowser::onAdd(%this) { %this.isReImportingAsset = false; } function AssetBrowser::onWake(%this) { %this.importAssetNewListArray = new ArrayObject(); %this.importAssetUnprocessedListArray = new ArrayObject(); %this.importAssetFinalListArray = new ArrayObject(); } //Drag-Drop functionality function AssetBrowser::selectAsset( %this, %asset ) { if(AssetBrowser.selectCallback !$= "") { // The callback function should be ready to intake the returned material //eval("materialEd_previewMaterial." @ %propertyField @ " = " @ %value @ ";"); if( AssetBrowser.returnType $= "name" ) { eval( "" @ AssetBrowser.selectCallback @ "(" @ %name @ ");"); } else { %command = "" @ AssetBrowser.selectCallback @ "(\"" @ %asset @ "\");"; eval(%command); } } else { //try just setting the asset %this.changeAsset(); } Inspector.refresh(); AssetBrowser.hideDialog(); } function AssetBrowser::showDialog( %this, %AssetTypeFilter, %selectCallback, %targetObj, %fieldName, %returnType) { // Set the select callback AssetBrowser.selectCallback = %selectCallback; AssetBrowser.returnType = %returnType; AssetBrowser.assetTypeFilter = %AssetTypeFilter; AssetBrowser.fieldTargetObject = %targetObj; AssetBrowser.fieldTargetName = %fieldName; Canvas.add(AssetBrowser); AssetBrowser.setVisible(1); AssetBrowserWindow.setVisible(1); AssetBrowserWindow.selectWindow(); if(%selectCallback $= "") { //we're not in selection mode, so just hide the select button %this-->SelectButton.setHidden(true); } else { %this-->SelectButton.setHidden(false); } //AssetBrowser_importAssetWindow.setVisible(0); //AssetBrowser_importAssetConfigWindow.setVisible(0); AssetBrowser.loadFilters(); } function AssetBrowser::hideDialog( %this ) { AssetBrowser.setVisible(1); AssetBrowserWindow.setVisible(1); Canvas.popDialog(AssetBrowser_addModule); Canvas.popDialog(ImportAssetWindow); Canvas.popDialog(AssetBrowser); } function AssetBrowser::buildPreviewArray( %this, %asset, %moduleName ) { %assetDesc = AssetDatabase.acquireAsset(%asset); %assetName = AssetDatabase.getAssetName(%asset); %previewImage = "core/art/warnmat"; AssetPreviewArray.empty(); // it may seem goofy why the checkbox can't be instanciated inside the container // reason being its because we need to store the checkbox ctrl in order to make changes // on it later in the function. %previewSize = "80 80"; %previewBounds = 20; %assetType = AssetDatabase.getAssetType(%asset); %container = new GuiControl(){ profile = "ToolsGuiDefaultProfile"; Position = "0 0"; Extent = %previewSize.x + %previewBounds SPC %previewSize.y + %previewBounds + 24; HorizSizing = "right"; VertSizing = "bottom"; isContainer = "1"; assetName = %assetName; moduleName = %moduleName; assetType = %assetType; }; %tooltip = %assetName; if(%assetType $= "ShapeAsset") { %previewButton = new GuiObjectView() { className = "AssetPreviewControl"; internalName = %matName; HorizSizing = "right"; VertSizing = "bottom"; Profile = "ToolsGuiDefaultProfile"; position = "7 4"; extent = %previewSize; MinExtent = "8 8"; canSave = "1"; Visible = "1"; tooltipprofile = "ToolsGuiToolTipProfile"; hovertime = "1000"; Margin = "0 0 0 0"; Padding = "0 0 0 0"; AnchorTop = "1"; AnchorBottom = "0"; AnchorLeft = "1"; AnchorRight = "0"; renderMissionArea = "0"; GizmoProfile = "GlobalGizmoProfile"; cameraZRot = "0"; forceFOV = "0"; gridColor = "0 0 0 0"; renderNodes = "0"; renderObjBox = "0"; renderMounts = "0"; renderColMeshes = "0"; selectedNode = "-1"; sunDiffuse = "255 255 255 255"; sunAmbient = "180 180 180 255"; timeScale = "1.0"; fixedDetail = "0"; orbitNode = "0"; new GuiBitmapButtonCtrl() { HorizSizing = "right"; VertSizing = "bottom"; profile = "ToolsGuiButtonProfile"; position = "0 0"; extent = %previewSize; Variable = ""; buttonType = "ToggleButton"; bitmap = "tools/materialEditor/gui/cubemapBtnBorder"; groupNum = "0"; text = ""; }; }; %assetQuery = new AssetQuery(); %numAssetsFound = AssetDatabase.findAllAssets(%assetQuery); for( %i=0; %i < %numAssetsFound; %i++) { %assetId = %assetQuery.getAsset(%i); %name = AssetDatabase.getAssetName(%assetId); if(%name $= %assetName) { %asset = AssetDatabase.acquireAsset(%assetId); %previewButton.setModel(%asset.fileName); //%previewButton.refreshShape(); //%previewButton.currentDL = 0; //%previewButton.fitToShape(); break; } } } else { if(%assetType $= "ComponentAsset") { %assetPath = "data/" @ %moduleName @ "/components/" @ %assetName @ ".cs"; %doubleClickCommand = "EditorOpenFileInTorsion( "@%assetPath@", 0 );"; %previewImage = "tools/assetBrowser/art/componentIcon"; %assetFriendlyName = %assetDesc.friendlyName; %assetDesc = %assetDesc.description; %tooltip = %assetFriendlyName @ "\n" @ %assetDesc; } else if(%assetType $= "GameObjectAsset") { %assetPath = "data/" @ %moduleName @ "/gameObjects/" @ %assetName @ ".cs"; %doubleClickCommand = "EditorOpenFileInTorsion( "@%assetPath@", 0 );"; %previewImage = "tools/assetBrowser/art/gameObjectIcon"; %tooltip = %assetDesc.gameObjectName; } else if(%assetType $= "ImageAsset") { //nab the image and use it for the preview %assetQuery = new AssetQuery(); %numAssetsFound = AssetDatabase.findAllAssets(%assetQuery); for( %i=0; %i < %numAssetsFound; %i++) { %assetId = %assetQuery.getAsset(%i); %name = AssetDatabase.getAssetName(%assetId); if(%name $= %assetName) { %asset = AssetDatabase.acquireAsset(%assetId); %previewImage = %asset.imageFile; break; } } } else if(%assetType $= "StateMachineAsset") { %previewImage = "tools/assetBrowser/art/stateMachineIcon"; } else if(%assetType $= "SoundAsset") { %previewImage = "tools/assetBrowser/art/soundIcon"; } else if(%assetType $= "LevelAsset") { %previewImage = "tools/assetBrowser/art/levelIcon"; } else if(%assetType $= "PostEffectAsset") { %previewImage = "tools/assetBrowser/art/postEffectIcon"; } else if(%assetType $= "GUIAsset") { %previewImage = "tools/assetBrowser/art/guiIcon"; } else if(%assetType $= "ScriptAsset") { if(%assetDesc.isServerSide) %previewImage = "tools/assetBrowser/art/serverScriptIcon"; else %previewImage = "tools/assetBrowser/art/clientScriptIcon"; } else if(%assetType $= "MaterialAsset") { %previewImage = ""; //nab the image and use it for the preview %assetQuery = new AssetQuery(); %numAssetsFound = AssetDatabase.findAllAssets(%assetQuery); for( %i=0; %i < %numAssetsFound; %i++) { %assetId = %assetQuery.getAsset(%i); %name = AssetDatabase.getAssetName(%assetId); if(%name $= %assetName) { %asset = AssetDatabase.acquireAsset(%assetId); %previewImage = %asset.materialDefinitionName.diffuseMap[0]; break; } } if(%previewImage $= "") %previewImage = "tools/assetBrowser/art/materialIcon"; } if(%assetType $= "ShapeAnimationAsset") { %previewImage = "tools/assetBrowser/art/animationIcon"; } %previewButton = new GuiBitmapButtonCtrl() { className = "AssetPreviewControl"; internalName = %assetName; HorizSizing = "right"; VertSizing = "bottom"; profile = "ToolsGuiButtonProfile"; position = "10 4"; extent = %previewSize; buttonType = "PushButton"; bitmap = %previewImage; Command = ""; text = ""; useStates = false; new GuiBitmapButtonCtrl() { HorizSizing = "right"; VertSizing = "bottom"; profile = "ToolsGuiButtonProfile"; position = "0 0"; extent = %previewSize; Variable = ""; buttonType = "toggleButton"; bitmap = "tools/materialEditor/gui/cubemapBtnBorder"; groupNum = "0"; text = ""; }; }; } %previewBorder = new GuiButtonCtrl(){ class = "AssetPreviewButton"; internalName = %assetName@"Border"; HorizSizing = "right"; VertSizing = "bottom"; profile = "ToolsGuiThumbHighlightButtonProfile"; position = "0 0"; extent = %previewSize.x + %previewBounds SPC %previewSize.y + 24; Variable = ""; buttonType = "radioButton"; tooltip = %tooltip; Command = "AssetBrowser.updateSelection( $ThisControl.getParent().assetName, $ThisControl.getParent().moduleName );"; altCommand = %doubleClickCommand; groupNum = "0"; useMouseEvents = true; text = ""; icon = %previewImage; }; %previewNameCtrl = new GuiTextEditCtrl(){ position = 0 SPC %previewSize.y + %previewBounds - 16; profile = ToolsGuiTextEditCenterProfile; extent = %previewSize.x + %previewBounds SPC 16; text = %assetName; originalAssetName = %assetName; //special internal field used in renaming assets internalName = "AssetNameLabel"; class = "AssetNameField"; active = false; }; %container.add(%previewButton); %container.add(%previewBorder); %container.add(%previewNameCtrl); // add to the gui control array AssetBrowser-->materialSelection.add(%container); // add to the array object for reference later AssetPreviewArray.add( %previewButton, %previewImage ); } function AssetBrowser::loadImages( %this, %materialNum ) { // this will save us from spinning our wheels in case we don't exist /*if( !AssetBrowser.visible ) return; // this schedule is here to dynamically load images %previewButton = AssetPreviewArray.getKey(%materialNum); %previewImage = AssetPreviewArray.getValue(%materialNum); if(%previewButton.getClassName() !$= "GuiObjectView") { %previewButton.setBitmap(%previewImage); %previewButton.setText(""); } %materialNum++; /*if( %materialNum < AssetPreviewArray.count() ) { %tempSchedule = %this.schedule(64, "loadImages", %materialNum); MatEdScheduleArray.add( %tempSchedule, %materialNum ); }*/ } function AssetBrowser::loadFilters( %this ) { AssetBrowser-->filterTree.clear(); AssetBrowser-->filterTree.buildIconTable(":tools/classIcons/prefab"); AssetBrowser-->filterTree.insertItem(0, "Assets"); //First, build our our list of active modules %modulesList = ModuleDatabase.findModules(true); for(%i=0; %i < getWordCount(%modulesList); %i++) { %moduleName = getWord(%modulesList, %i).ModuleId; %moduleItemId = AssetBrowser-->filterTree.findItemByName(%moduleName); if(%moduleItemId == 0) %moduleItemId = AssetBrowser-->filterTree.insertItem(1, %moduleName, "", "", 1, 1); } //Next, go through and list the asset categories %assetQuery = new AssetQuery(); %numAssetsFound = AssetDatabase.findAllAssets(%assetQuery); for( %i=0; %i < %numAssetsFound; %i++) { %assetId = %assetQuery.getAsset(%i); //first, get the asset's module, as our major categories %module = AssetDatabase.getAssetModule(%assetId); %moduleName = %module.moduleId; //These are core, native-level components, so we're not going to be messing with this module at all, skip it if(%moduleName $= "CoreComponentsModule") continue; //first, see if this module Module is listed already %moduleItemId = AssetBrowser-->filterTree.findItemByName(%moduleName); if(%moduleItemId == 0) %moduleItemId = AssetBrowser-->filterTree.insertItem(1, %moduleName, "", "", 1, 1); %assetType = AssetDatabase.getAssetCategory(%assetId); if(%assetType $= "") { %assetType = AssetDatabase.getAssetType(%assetId); if(%assetType $= "") %assetType = "Misc"; } if(AssetBrowser.assetTypeFilter !$= "" && AssetBrowser.assetTypeFilter !$= %assetType) continue; %assetTypeId = AssetBrowser-->filterTree.findChildItemByName(%moduleItemId, %assetType); if(%assetTypeId == 0) %assetTypeId = AssetBrowser-->filterTree.insertItem(%moduleItemId, %assetType); } AssetBrowser-->filterTree.buildVisibleTree(true); //special handling for selections if(AssetBrowser.newModuleId !$= "") { AssetBrowser-->filterTree.clearSelection(); %newModuleItem = AssetBrowser-->filterTree.findItemByName(AssetBrowser.newModuleId); AssetBrowser-->filterTree.selectItem(%newModuleItem); AssetBrowser.newModuleId = ""; } %selectedItem = AssetBrowser-->filterTree.getSelectedItem(); AssetBrowser-->filterTree.scrollVisibleByObjectId(%selectedItem); } // create category and update current material if there is one function AssetBrowser::createFilter( %this, %filter ) { if( %filter $= %existingFilters ) { MessageBoxOK( "Error", "Can not create blank filter."); return; } for( %i = AssetBrowser.staticFilterObjects; %i < AssetBrowser-->filterArray.getCount() ; %i++ ) { %existingFilters = AssetBrowser-->filterArray.getObject(%i).getObject(0).filter; if( %filter $= %existingFilters ) { MessageBoxOK( "Error", "Can not create two filters of the same name."); return; } } %container = new GuiControl(){ profile = "ToolsGuiDefaultProfile"; Position = "0 0"; Extent = "128 18"; HorizSizing = "right"; VertSizing = "bottom"; isContainer = "1"; new GuiCheckBoxCtrl(){ Profile = "ToolsGuiCheckBoxListProfile"; position = "5 1"; Extent = "118 18"; Command = ""; groupNum = "0"; buttonType = "ToggleButton"; text = %filter @ " ( " @ MaterialFilterAllArray.countKey(%filter) @ " )"; filter = %filter; Command = "AssetBrowser.preloadFilter();"; }; }; AssetBrowser-->filterArray.add( %container ); // if selection exists, lets reselect it to refresh it if( isObject(AssetBrowser.selectedMaterial) ) AssetBrowser.updateSelection( AssetBrowser.selectedMaterial, AssetBrowser.selectedPreviewImagePath ); // material category text field to blank AssetBrowser_addFilterWindow-->tagName.setText(""); } function AssetBrowser::updateSelection( %this, %asset, %moduleName ) { // the material selector will visually update per material information // after we move away from the material. eg: if we remove a field from the material, // the empty checkbox will still be there until you move fro and to the material again %isAssetBorder = 0; eval("%isAssetBorder = isObject(AssetBrowser-->"@%asset@"Border);"); if( %isAssetBorder ) { eval( "AssetBrowser-->"@%asset@"Border.setStateOn(1);"); } %isAssetBorderPrevious = 0; eval("%isAssetBorderPrevious = isObject(AssetBrowser-->"@%this.prevSelectedMaterialHL@"Border);"); if( %isAssetBorderPrevious ) { eval( "AssetBrowser-->"@%this.prevSelectedMaterialHL@"Border.setStateOn(0);"); } AssetBrowser.selectedMaterial = %asset; AssetBrowser.selectedAsset = %moduleName@":"@%asset; AssetBrowser.selectedAssetDef = AssetDatabase.acquireAsset(AssetBrowser.selectedAsset); //AssetBrowser.selectedPreviewImagePath = %previewImagePath; %this.prevSelectedMaterialHL = %asset; } // //needs to be deleted with the persistence manager and needs to be blanked out of the matmanager //also need to update instances... i guess which is the tricky part.... function AssetBrowser::showDeleteDialog( %this ) { %material = AssetBrowser.selectedMaterial; %secondFilter = "MaterialFilterMappedArray"; %secondFilterName = "Mapped"; for( %i = 0; %i < MaterialFilterUnmappedArray.count(); %i++ ) { if( MaterialFilterUnmappedArray.getValue(%i) $= %material ) { %secondFilter = "MaterialFilterUnmappedArray"; %secondFilterName = "Unmapped"; break; } } if( isObject( %material ) ) { MessageBoxYesNoCancel("Delete Material?", "Are you sure you want to delete<br><br>" @ %material.getName() @ "<br><br> Material deletion won't take affect until the engine is quit.", "AssetBrowser.deleteMaterial( " @ %material @ ", " @ %secondFilter @ ", " @ %secondFilterName @" );", "", "" ); } } function AssetBrowser::deleteMaterial( %this, %materialName, %secondFilter, %secondFilterName ) { if( !isObject( %materialName ) ) return; for( %i = 0; %i <= MaterialFilterAllArray.countValue( %materialName ); %i++) { %index = MaterialFilterAllArray.getIndexFromValue( %materialName ); MaterialFilterAllArray.erase( %index ); } MaterialFilterAllArrayCheckbox.setText("All ( " @ MaterialFilterAllArray.count() - 1 @ " ) "); %checkbox = %secondFilter @ "Checkbox"; for( %k = 0; %k <= %secondFilter.countValue( %materialName ); %k++) { %index = %secondFilter.getIndexFromValue( %materialName ); %secondFilter.erase( %index ); } %checkbox.setText( %secondFilterName @ " ( " @ %secondFilter.count() - 1 @ " ) "); for( %i = 0; %materialName.getFieldValue("materialTag" @ %i) !$= ""; %i++ ) { %materialTag = %materialName.getFieldValue("materialTag" @ %i); for( %j = AssetBrowser.staticFilterObjects; %j < AssetBrowser-->filterArray.getCount() ; %j++ ) { if( %materialTag $= AssetBrowser-->filterArray.getObject(%j).getObject(0).filter ) { %count = getWord( AssetBrowser-->filterArray.getObject(%j).getObject(0).getText(), 2 ); %count--; AssetBrowser-->filterArray.getObject(%j).getObject(0).setText( %materialTag @ " ( "@ %count @ " )"); } } } UnlistedMaterials.add( "unlistedMaterials", %materialName ); if( %materialName.getFilename() !$= "" && %materialName.getFilename() !$= "tools/gui/AssetBrowser.ed.gui" && %materialName.getFilename() !$= "tools/materialEditor/scripts/materialEditor.ed.cs" ) { AssetBrowserPerMan.removeObjectFromFile(%materialName); AssetBrowserPerMan.saveDirty(); } AssetBrowser.preloadFilter(); } function AssetBrowser::thumbnailCountUpdate(%this) { $Pref::AssetBrowser::ThumbnailCountIndex = AssetBrowser-->materialPreviewCountPopup.getSelected(); AssetBrowser.LoadFilter( AssetBrowser.currentFilter, AssetBrowser.currentStaticFilter ); } function AssetBrowser::toggleTagFilterPopup(%this) { if(TagFilterWindow.visible) TagFilterWindow.visible = false; else TagFilterWindow.visible = true; return; %assetQuery = new AssetQuery(); %numAssetsFound = AssetDatabase.findAllAssets(%assetQuery); for( %i=0; %i < %numAssetsFound; %i++) { %assetId = %assetQuery.getAsset(%i); //first, get the asset's module, as our major categories %module = AssetDatabase.getAssetModule(%assetId); %moduleName = %module.moduleId; //check that we don't re-add it %moduleItemId = AssetBrowser-->filterTree.findItemByName(%moduleName); if(%moduleItemId == -1 || %moduleItemId == 0) %moduleItemId = AssetBrowser-->filterTree.insertItem(1, %module.moduleId, "", "", 1, 1); //now, add the asset's category %assetType = AssetDatabase.getAssetCategory(%assetId); %checkBox = new GuiCheckBoxCtrl() { canSaveDynamicFields = "0"; isContainer = "0"; Profile = "ToolsGuiCheckBoxListProfile"; HorizSizing = "right"; VertSizing = "bottom"; Position = "0 0"; Extent = (%textLength * 4) @ " 18"; MinExtent = "8 2"; canSave = "1"; Visible = "1"; Variable = %var; tooltipprofile = "ToolsGuiToolTipProfile"; hovertime = "1000"; text = %text; groupNum = "-1"; buttonType = "ToggleButton"; useMouseEvents = "0"; useInactiveState = "0"; Command = %cmd; }; TagFilterList.add(%checkBox); } } function AssetBrowser::changeAsset(%this) { //alright, we've selectd an asset for a field, so time to set it! %cmd = %this.fieldTargetObject @ "." @ %this.fieldTargetName @ "=\"" @ %this.selectedAsset @ "\";"; echo("Changing asset via the " @ %cmd @ " command"); eval(%cmd); } function AssetBrowser::reImportAsset(%this) { //Find out what type it is %assetDef = AssetDatabase.acquireAsset(EditAssetPopup.assetId); %assetType = AssetDatabase.getAssetType(EditAssetPopup.assetId); if(%assetType $= "ShapeAsset" || %assetType $= "ImageAsset" || %assetType $= "SoundAsset") { AssetBrowser.isAssetReImport = true; AssetBrowser.reImportingAssetId = EditAssetPopup.assetId; AssetBrowser.onBeginDropFiles(); AssetBrowser.onDropFile(%assetDef.originalFilePath); AssetBrowser.onEndDropFiles(); %module = AssetDatabase.getAssetModule(EditAssetPopup.assetId); //get the selected module data ImportAssetModuleList.setText(%module.ModuleId); } } //------------------------------------------------------------------------------ function AssetPreviewButton::onRightClick(%this) { AssetBrowser.selectedAssetPreview = %this.getParent(); EditAssetPopup.assetId = %this.getParent().moduleName @ ":" @ %this.getParent().assetName; %assetType = %this.getParent().assetType; //Do some enabling/disabling of options depending on asset type EditAssetPopup.enableItem(0, true); EditAssetPopup.enableItem(7, true); //Is it an editable type? if(%assetType $= "ImageAsset" || %assetType $= "GameObjectAsset" || %assetType $= "SoundAsset") { EditAssetPopup.enableItem(0, false); } //Is it an importable type? if(%assetType $= "GameObjectAsset" || %assetType $= "ComponentAsset" || %assetType $= "GUIAsset" || %assetType $= "LevelAsset" || %assetType $= "MaterialAsset" || %assetType $= "ParticleAsset" || %assetType $= "PostEffectAsset" || %assetType $= "ScriptAsset" || %assetType $= "StateMachineAsset") { EditAssetPopup.enableItem(7, false); } EditAssetPopup.showPopup(Canvas); } function AssetListPanel::onRightMouseDown(%this) { AddNewAssetPopup.showPopup(Canvas); } //------------------------------------------------------------------------------ function AssetBrowser::refreshPreviews(%this) { AssetBrowserFilterTree.onSelect(AssetBrowser.selectedItem); } function AssetBrowserFilterTree::onSelect(%this, %itemId) { if(%itemId == 1) //can't select root return; //Make sure we have an actual module selected! %parentId = %this.getParentItem(%itemId); if(%parentId != 1) AssetBrowser.selectedModule = %this.getItemText(%parentId);//looks like we have one of the categories selected, not the module. Nab the parent so we have the correct thing! else AssetBrowser.selectedModule = %this.getItemText(%itemId); AssetBrowser.selectedItem = %itemId; //alright, we have a module or sub-filter selected, so now build our asset list based on that filter! echo("Asset Browser Filter Tree selected filter #:" @ %itemId); // manage schedule array properly if(!isObject(MatEdScheduleArray)) new ArrayObject(MatEdScheduleArray); // if we select another list... delete all schedules that were created by // previous load for( %i = 0; %i < MatEdScheduleArray.count(); %i++ ) cancel(MatEdScheduleArray.getKey(%i)); // we have to empty out the list; so when we create new schedules, these dont linger MatEdScheduleArray.empty(); // manage preview array if(!isObject(AssetPreviewArray)) new ArrayObject(AssetPreviewArray); // we have to empty out the list; so when we create new guicontrols, these dont linger AssetPreviewArray.empty(); AssetBrowser-->materialSelection.deleteAllObjects(); //AssetBrowser-->materialPreviewPagesStack.deleteAllObjects(); %assetArray = new ArrayObject(); //First, Query for our assets %assetQuery = new AssetQuery(); %numAssetsFound = AssetDatabase.findAllAssets(%assetQuery); //module name per our selected filter: %moduleItemId = %this.getParentItem(%itemId); //check if we've selected a Module if(%moduleItemId == 1) { %FilterModuleName = %this.getItemText(%itemId); } else { %FilterModuleName = %this.getItemText(%moduleItemId); } //now, we'll iterate through, and find the assets that are in this module, and this category for( %i=0; %i < %numAssetsFound; %i++) { %assetId = %assetQuery.getAsset(%i); //first, get the asset's module, as our major categories %module = AssetDatabase.getAssetModule(%assetId); %moduleName = %module.moduleId; if(%FilterModuleName $= %moduleName) { //it's good, so test that the category is right! %assetType = AssetDatabase.getAssetCategory(%assetId); if(%assetType $= "") { %assetType = AssetDatabase.getAssetType(%assetId); } if(%this.getItemText(%itemId) $= %assetType || (%assetType $= "" && %this.getItemText(%itemId) $= "Misc") || %moduleItemId == 1) { //stop adding after previewsPerPage is hit %assetName = AssetDatabase.getAssetName(%assetId); %searchText = AssetBrowserSearchFilter.getText(); if(%searchText !$= "\c2Filter...") { if(strstr(strlwr(%assetName), strlwr(%searchText)) != -1) %assetArray.add( %moduleName, %assetId); } else { //got it. %assetArray.add( %moduleName, %assetId ); } } } } AssetBrowser.currentPreviewPage = 0; AssetBrowser.totalPages = 1; for(%i=0; %i < %assetArray.count(); %i++) AssetBrowser.buildPreviewArray( %assetArray.getValue(%i), %assetArray.getKey(%i) ); AssetBrowser.loadImages( 0 ); } function AssetBrowserFilterTree::onRightMouseDown(%this, %itemId) { if( %this.getSelectedItemsCount() > 0 && %itemId != 1) { //AddNewAssetPopup.showPopup(Canvas); //We have something clicked, so figure out if it's a sub-filter or a module filter, then push the correct //popup menu if(%this.getParentItem(%itemId) == 1) { //yep, module, push the all-inclusive popup EditModulePopup.showPopup(Canvas); //also set the module value for creation info AssetBrowser.selectedModule = %this.getItemText(%itemId); } else { //get the parent, and thus our module %moduleId = %this.getParentItem(%itemId); //set the module value for creation info AssetBrowser.selectedModule = %this.getItemText(%moduleId); if(%this.getItemText(%itemId) $= "ComponentAsset") { AddNewComponentAssetPopup.showPopup(Canvas); //Canvas.popDialog(AssetBrowser_newComponentAsset); //AssetBrowser_newComponentAsset-->AssetBrowserModuleList.setText(AssetBrowser.selectedModule); } else { } } } else if( %this.getSelectedItemsCount() > 0 && %itemId == 1) { AddNewModulePopup.showPopup(Canvas); } } // // function AssetBrowserSearchFilterText::onWake( %this ) { /*%filter = %this.treeView.getFilterText(); if( %filter $= "" ) %this.setText( "\c2Filter..." ); else %this.setText( %filter );*/ } //------------------------------------------------------------------------------ function AssetBrowserSearchFilterText::onGainFirstResponder( %this ) { %this.selectAllText(); } //--------------------------------------------------------------------------------------------- // When Enter is pressed in the filter text control, pass along the text of the control // as the treeview's filter. function AssetBrowserSearchFilterText::onReturn( %this ) { %text = %this.getText(); if( %text $= "" ) %this.reset(); else { //%this.treeView.setFilterText( %text ); %curItem = AssetBrowserFilterTree.getSelectedItem(); AssetBrowserFilterTree.onSelect(%curItem); } } //--------------------------------------------------------------------------------------------- function AssetBrowserSearchFilterText::reset( %this ) { %this.setText( "\c2Filter..." ); //%this.treeView.clearFilterText(); %curItem = AssetBrowserFilterTree.getSelectedItem(); AssetBrowserFilterTree.onSelect(%curItem); } //--------------------------------------------------------------------------------------------- function AssetBrowserSearchFilterText::onClick( %this ) { %this.textCtrl.reset(); } // // // function AssetBrowser::reloadModules(%this) { ModuleDatabase.unloadGroup("Game"); %modulesList = ModuleDatabase.findModules(); %count = getWordCount(%modulesList); for(%i=0; %i < %count; %i++) { %moduleId = getWord(%modulesList, %i).ModuleId; ModuleDatabase.unloadExplicit(%moduleId); } ModuleDatabase.scanModules(); %modulesList = ModuleDatabase.findModules(); %count = getWordCount(%modulesList); for(%i=0; %i < %count; %i++) { %moduleId = getWord(%modulesList, %i).ModuleId; ModuleDatabase.loadExplicit(%moduleId); } //ModuleDatabase.loadGroup("Game"); } // function AssetPreviewButton::onMouseDragged(%this) { %payload = new GuiBitmapButtonCtrl(); %payload.assignFieldsFrom( %this ); %payload.className = "AssetPreviewControl"; %payload.position = "0 0"; %payload.dragSourceControl = %this; %payload.bitmap = %this.icon; %payload.extent.x /= 2; %payload.extent.y /= 2; %xOffset = getWord( %payload.extent, 0 ) / 2; %yOffset = getWord( %payload.extent, 1 ) / 2; // Compute the initial position of the GuiDragAndDrop control on the cavas based on the current // mouse cursor position. %cursorpos = Canvas.getCursorPos(); %xPos = getWord( %cursorpos, 0 ) - %xOffset; %yPos = getWord( %cursorpos, 1 ) - %yOffset; if(!isObject(EditorDragAndDropLayer)) { new GuiControl(EditorDragAndDropLayer) { position = "0 0"; extent = Canvas.extent; }; } // Create the drag control. %ctrl = new GuiDragAndDropControl() { canSaveDynamicFields = "0"; Profile = "GuiSolidDefaultProfile"; HorizSizing = "right"; VertSizing = "bottom"; Position = %xPos SPC %yPos; extent = %payload.extent; MinExtent = "4 4"; canSave = "1"; Visible = "1"; hovertime = "1000"; // Let the GuiDragAndDropControl delete itself on mouse-up. When the drag is aborted, // this not only deletes the drag control but also our payload. deleteOnMouseUp = true; useWholeCanvas = true; // To differentiate drags, use the namespace hierarchy to classify them. // This will allow a color swatch drag to tell itself apart from a file drag, for example. class = "AssetPreviewControlType_AssetDrop"; }; // Add the temporary color swatch to the drag control as the payload. %ctrl.add( %payload ); // Start drag by adding the drag control to the canvas and then calling startDragging(). //Canvas.getContent().add( %ctrl ); EditorDragAndDropLayer.add(%ctrl); Canvas.pushDialog(EditorDragAndDropLayer); %ctrl.startDragging( %xOffset, %yOffset ); } function AssetPreviewButton::onControlDragCancelled(%this) { Canvas.popDialog(EditorDragAndDropLayer); } function AssetPreviewButton::onControlDropped( %this, %payload, %position ) { Canvas.popDialog(EditorDragAndDropLayer); // Make sure this is a color swatch drag operation. if( !%payload.parentGroup.isInNamespaceHierarchy( "AssetPreviewControlType_AssetDrop" ) ) return; // If dropped on same button whence we came from, // do nothing. if( %payload.dragSourceControl == %this ) return; // If a swatch button control is dropped onto this control, // copy it's color. if( %payload.isMemberOfClass( "AssetPreviewButton" ) ) { // If the swatch button is part of a color-type inspector field, // remember the inspector field so we can later set the color // through it. if( %this.parentGroup.isMemberOfClass( "GuiInspectorTypeColorI" ) ) %this.parentGroup.apply( ColorFloatToInt( %payload.color ) ); else if( %this.parentGroup.isMemberOfClass( "GuiInspectorTypeColorF" ) ) %this.parentGroup.apply( %payload.color ); else %this.setColor( %payload.color ); } } function EWorldEditor::onControlDropped( %this, %payload, %position ) { Canvas.popDialog(EditorDragAndDropLayer); // Make sure this is a color swatch drag operation. if( !%payload.parentGroup.isInNamespaceHierarchy( "AssetPreviewControlType_AssetDrop" ) ) return; // If dropped on same button whence we came from, // do nothing. if( %payload.dragSourceControl == %this ) return; %assetType = %payload.dragSourceControl.parentGroup.assetType; %pos = EWCreatorWindow.getCreateObjectPosition(); //LocalClientConnection.camera.position; %module = %payload.dragSourceControl.parentGroup.moduleName; %asset = %payload.dragSourceControl.parentGroup.assetName; if(%assetType $= "ImageAsset") { echo("DROPPED AN IMAGE ON THE EDITOR WINDOW!"); } else if(%assetType $= "ShapeAsset") { echo("DROPPED A SHAPE ON THE EDITOR WINDOW!"); %newEntity = new Entity() { position = %pos; new MeshComponent() { MeshAsset = %module @ ":" @ %asset; }; //new CollisionComponent(){}; }; MissionGroup.add(%newEntity); EWorldEditor.clearSelection(); EWorldEditor.selectObject(%newEntity); } else if(%assetType $= "MaterialAsset") { echo("DROPPED A MATERIAL ON THE EDITOR WINDOW!"); } else if(%assetType $= "GameObjectAsset") { echo("DROPPED A GAME OBJECT ON THE EDITOR WINDOW!"); %GO = spawnGameObject(%asset, true); %pos = EWCreatorWindow.getCreateObjectPosition(); //LocalClientConnection.camera.position; %GO.position = %pos; EWorldEditor.clearSelection(); EWorldEditor.selectObject(%GO); } else if(%assetType $= "ComponentAsset") { %newEntity = new Entity() { position = %pos; }; %assetDef = AssetDatabase.acquireAsset(%module @ ":" @ %asset); if(%assetDef.componentClass $= "Component") eval("$tmpVar = new " @ %assetDef.componentClass @ "() { class = " @ %assetDef.componentName @ "; }; %newEntity.add($tmpVar);"); else eval("$tmpVar = new " @ %assetDef.componentClass @ "() {}; %newEntity.add($tmpVar);"); MissionGroup.add(%newEntity); EWorldEditor.clearSelection(); EWorldEditor.selectObject(%newEntity); } else if(%assetType $= "ScriptAsset") //do we want to do it this way? { %newEntity = new Entity() { position = %pos; class = %asset; }; MissionGroup.add(%newEntity); EWorldEditor.clearSelection(); EWorldEditor.selectObject(%newEntity); } EWorldEditor.isDirty = true; } function GuiInspectorTypeShapeAssetPtr::onControlDropped( %this, %payload, %position ) { Canvas.popDialog(EditorDragAndDropLayer); // Make sure this is a color swatch drag operation. if( !%payload.parentGroup.isInNamespaceHierarchy( "AssetPreviewControlType_AssetDrop" ) ) return; %assetType = %payload.dragSourceControl.parentGroup.assetType; if(%assetType $= "ShapeAsset") { echo("DROPPED A SHAPE ON A SHAPE ASSET COMPONENT FIELD!"); %module = %payload.dragSourceControl.parentGroup.moduleName; %asset = %payload.dragSourceControl.parentGroup.assetName; %targetComponent = %this.ComponentOwner; %targetComponent.MeshAsset = %module @ ":" @ %asset; //Inspector.refresh(); } EWorldEditor.isDirty= true; } function GuiInspectorTypeImageAssetPtr::onControlDropped( %this, %payload, %position ) { Canvas.popDialog(EditorDragAndDropLayer); // Make sure this is a color swatch drag operation. if( !%payload.parentGroup.isInNamespaceHierarchy( "AssetPreviewControlType_AssetDrop" ) ) return; %assetType = %payload.dragSourceControl.parentGroup.assetType; if(%assetType $= "ImageAsset") { echo("DROPPED A IMAGE ON AN IMAGE ASSET COMPONENT FIELD!"); } EWorldEditor.isDirty = true; } function GuiInspectorTypeMaterialAssetPtr::onControlDropped( %this, %payload, %position ) { Canvas.popDialog(EditorDragAndDropLayer); // Make sure this is a color swatch drag operation. if( !%payload.parentGroup.isInNamespaceHierarchy( "AssetPreviewControlType_AssetDrop" ) ) return; %assetType = %payload.dragSourceControl.parentGroup.assetType; if(%assetType $= "MaterialAsset") { echo("DROPPED A MATERIAL ON A MATERIAL ASSET COMPONENT FIELD!"); } EWorldEditor.isDirty = true; } function AssetBrowserFilterTree::onControlDropped( %this, %payload, %position ) { Canvas.popDialog(EditorDragAndDropLayer); if( !%payload.parentGroup.isInNamespaceHierarchy( "AssetPreviewControlType_AssetDrop" ) ) return; %assetType = %payload.dragSourceControl.parentGroup.assetType; %assetName = %payload.dragSourceControl.parentGroup.assetName; %moduleName = %payload.dragSourceControl.parentGroup.moduleName; echo("DROPPED A " @ %assetType @ " ON THE ASSET BROWSER NAVIGATION TREE!"); %item = %this.getItemAtPosition(%position); echo("DROPPED IT ON ITEM " @ %item); %parent = %this.getParentItem(%item); if(%parent == 1) { //we're a module entry, cool %targetModuleName = %this.getItemText(%item); echo("DROPPED IT ON MODULE " @ %targetModuleName); if(%moduleName !$= %targetModuleName) { //we're trying to move the asset to a different module! MessageBoxYesNo( "Move Asset", "Do you wish to move asset " @ %assetName @ " to module " @ %targetModuleName @ "?", "AssetBrowser.moveAsset("@%assetName@", "@%targetModuleName@");", ""); } } }
/* * 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 Nini.Config; using log4net; using System; using System.Reflection; using System.IO; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Serialization; using System.Collections.Generic; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; using OpenMetaverse; namespace OpenSim.Server.Handlers.Grid { public class GridServerPostHandler : BaseStreamHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IGridService m_GridService; public GridServerPostHandler(IGridService service) : base("POST", "/grid") { m_GridService = service; } public override byte[] Handle(string path, Stream requestData, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { StreamReader sr = new StreamReader(requestData); string body = sr.ReadToEnd(); sr.Close(); body = body.Trim(); //m_log.DebugFormat("[XXX]: query String: {0}", body); try { Dictionary<string, string> request = ServerUtils.ParseQueryString(body); if (!request.ContainsKey("METHOD")) return FailureResult(); string method = request["METHOD"]; switch (method) { case "register": return Register(request); case "deregister": return Deregister(request); case "get_neighbours": return GetNeighbours(request); case "get_region_by_uuid": return GetRegionByUUID(request); case "get_region_by_position": return GetRegionByPosition(request); case "get_region_by_name": return GetRegionByName(request); case "get_regions_by_name": return GetRegionsByName(request); case "get_region_range": return GetRegionRange(request); } m_log.DebugFormat("[GRID HANDLER]: unknown method {0} request {1}", method.Length, method); } catch (Exception e) { m_log.DebugFormat("[GRID HANDLER]: Exception {0}", e); } return FailureResult(); } #region Method-specific handlers byte[] Register(Dictionary<string, string> request) { UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"], out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to register region"); int versionNumberMin = 0, versionNumberMax = 0; if (request.ContainsKey("VERSIONMIN")) Int32.TryParse(request["VERSIONMIN"], out versionNumberMin); else m_log.WarnFormat("[GRID HANDLER]: no minimum protocol version in request to register region"); if (request.ContainsKey("VERSIONMAX")) Int32.TryParse(request["VERSIONMAX"], out versionNumberMax); else m_log.WarnFormat("[GRID HANDLER]: no maximum protocol version in request to register region"); // Check the protocol version if ((versionNumberMin > ProtocolVersions.ServerProtocolVersionMax && versionNumberMax < ProtocolVersions.ServerProtocolVersionMax)) { // Can't do, there is no overlap in the acceptable ranges return FailureResult(); } Dictionary<string, object> rinfoData = new Dictionary<string, object>(); GridRegion rinfo = null; try { foreach (KeyValuePair<string, string> kvp in request) rinfoData[kvp.Key] = kvp.Value; rinfo = new GridRegion(rinfoData); } catch (Exception e) { m_log.DebugFormat("[GRID HANDLER]: exception unpacking region data: {0}", e); } bool result = false; if (rinfo != null) result = m_GridService.RegisterRegion(scopeID, rinfo); if (result) return SuccessResult(); else return FailureResult(); } byte[] Deregister(Dictionary<string, string> request) { UUID regionID = UUID.Zero; if (request["REGIONID"] != null) UUID.TryParse(request["REGIONID"], out regionID); else m_log.WarnFormat("[GRID HANDLER]: no regionID in request to deregister region"); bool result = m_GridService.DeregisterRegion(regionID); if (result) return SuccessResult(); else return FailureResult(); } byte[] GetNeighbours(Dictionary<string, string> request) { UUID scopeID = UUID.Zero; if (request["SCOPEID"] != null) UUID.TryParse(request["SCOPEID"], out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get neighbours"); UUID regionID = UUID.Zero; if (request["REGIONID"] != null) UUID.TryParse(request["REGIONID"], out regionID); else m_log.WarnFormat("[GRID HANDLER]: no regionID in request to get neighbours"); List<GridRegion> rinfos = m_GridService.GetNeighbours(scopeID, regionID); //m_log.DebugFormat("[GRID HANDLER]: neighbours for region {0}: {1}", regionID, rinfos.Count); Dictionary<string, object> result = new Dictionary<string, object>(); if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0))) result["result"] = "null"; else { int i = 0; foreach (GridRegion rinfo in rinfos) { Dictionary<string, object> rinfoDict = rinfo.ToKeyValuePairs(); result["region" + i] = rinfoDict; i++; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); UTF8Encoding encoding = new UTF8Encoding(); return encoding.GetBytes(xmlString); } byte[] GetRegionByUUID(Dictionary<string, string> request) { UUID scopeID = UUID.Zero; if (request["SCOPEID"] != null) UUID.TryParse(request["SCOPEID"], out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get neighbours"); UUID regionID = UUID.Zero; if (request["REGIONID"] != null) UUID.TryParse(request["REGIONID"], out regionID); else m_log.WarnFormat("[GRID HANDLER]: no regionID in request to get neighbours"); GridRegion rinfo = m_GridService.GetRegionByUUID(scopeID, regionID); //m_log.DebugFormat("[GRID HANDLER]: neighbours for region {0}: {1}", regionID, rinfos.Count); Dictionary<string, object> result = new Dictionary<string, object>(); if (rinfo == null) result["result"] = "null"; else result["result"] = rinfo.ToKeyValuePairs(); string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); UTF8Encoding encoding = new UTF8Encoding(); return encoding.GetBytes(xmlString); } byte[] GetRegionByPosition(Dictionary<string, string> request) { UUID scopeID = UUID.Zero; if (request["SCOPEID"] != null) UUID.TryParse(request["SCOPEID"], out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get region by position"); int x = 0, y = 0; if (request["X"] != null) Int32.TryParse(request["X"], out x); else m_log.WarnFormat("[GRID HANDLER]: no X in request to get region by position"); if (request["Y"] != null) Int32.TryParse(request["Y"], out y); else m_log.WarnFormat("[GRID HANDLER]: no Y in request to get region by position"); GridRegion rinfo = m_GridService.GetRegionByPosition(scopeID, x, y); //m_log.DebugFormat("[GRID HANDLER]: neighbours for region {0}: {1}", regionID, rinfos.Count); Dictionary<string, object> result = new Dictionary<string, object>(); if (rinfo == null) result["result"] = "null"; else result["result"] = rinfo.ToKeyValuePairs(); string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); UTF8Encoding encoding = new UTF8Encoding(); return encoding.GetBytes(xmlString); } byte[] GetRegionByName(Dictionary<string, string> request) { UUID scopeID = UUID.Zero; if (request["SCOPEID"] != null) UUID.TryParse(request["SCOPEID"], out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get region by name"); string regionName = string.Empty; if (request["NAME"] != null) regionName = request["NAME"]; else m_log.WarnFormat("[GRID HANDLER]: no name in request to get region by name"); GridRegion rinfo = m_GridService.GetRegionByName(scopeID, regionName); //m_log.DebugFormat("[GRID HANDLER]: neighbours for region {0}: {1}", regionID, rinfos.Count); Dictionary<string, object> result = new Dictionary<string, object>(); if (rinfo == null) result["result"] = "null"; else result["result"] = rinfo.ToKeyValuePairs(); string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); UTF8Encoding encoding = new UTF8Encoding(); return encoding.GetBytes(xmlString); } byte[] GetRegionsByName(Dictionary<string, string> request) { UUID scopeID = UUID.Zero; if (request["SCOPEID"] != null) UUID.TryParse(request["SCOPEID"], out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get regions by name"); string regionName = string.Empty; if (request["NAME"] != null) regionName = request["NAME"]; else m_log.WarnFormat("[GRID HANDLER]: no NAME in request to get regions by name"); int max = 0; if (request["MAX"] != null) Int32.TryParse(request["MAX"], out max); else m_log.WarnFormat("[GRID HANDLER]: no MAX in request to get regions by name"); List<GridRegion> rinfos = m_GridService.GetRegionsByName(scopeID, regionName, max); //m_log.DebugFormat("[GRID HANDLER]: neighbours for region {0}: {1}", regionID, rinfos.Count); Dictionary<string, object> result = new Dictionary<string, object>(); if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0))) result["result"] = "null"; else { int i = 0; foreach (GridRegion rinfo in rinfos) { Dictionary<string, object> rinfoDict = rinfo.ToKeyValuePairs(); result["region" + i] = rinfoDict; i++; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); UTF8Encoding encoding = new UTF8Encoding(); return encoding.GetBytes(xmlString); } byte[] GetRegionRange(Dictionary<string, string> request) { //m_log.DebugFormat("[GRID HANDLER]: GetRegionRange"); UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"], out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get region range"); int xmin = 0, xmax = 0, ymin = 0, ymax = 0; if (request.ContainsKey("XMIN")) Int32.TryParse(request["XMIN"], out xmin); else m_log.WarnFormat("[GRID HANDLER]: no XMIN in request to get region range"); if (request.ContainsKey("XMAX")) Int32.TryParse(request["XMAX"], out xmax); else m_log.WarnFormat("[GRID HANDLER]: no XMAX in request to get region range"); if (request.ContainsKey("YMIN")) Int32.TryParse(request["YMIN"], out ymin); else m_log.WarnFormat("[GRID HANDLER]: no YMIN in request to get region range"); if (request.ContainsKey("YMAX")) Int32.TryParse(request["YMAX"], out ymax); else m_log.WarnFormat("[GRID HANDLER]: no YMAX in request to get region range"); List<GridRegion> rinfos = m_GridService.GetRegionRange(scopeID, xmin, xmax, ymin, ymax); Dictionary<string, object> result = new Dictionary<string, object>(); if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0))) result["result"] = "null"; else { int i = 0; foreach (GridRegion rinfo in rinfos) { Dictionary<string, object> rinfoDict = rinfo.ToKeyValuePairs(); result["region" + i] = rinfoDict; i++; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); UTF8Encoding encoding = new UTF8Encoding(); return encoding.GetBytes(xmlString); } #endregion #region Misc private byte[] SuccessResult() { XmlDocument doc = new XmlDocument(); XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); doc.AppendChild(xmlnode); XmlElement rootElement = doc.CreateElement("", "ServerResponse", ""); doc.AppendChild(rootElement); XmlElement result = doc.CreateElement("", "Result", ""); result.AppendChild(doc.CreateTextNode("Success")); rootElement.AppendChild(result); return DocToBytes(doc); } private byte[] FailureResult() { XmlDocument doc = new XmlDocument(); XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); doc.AppendChild(xmlnode); XmlElement rootElement = doc.CreateElement("", "ServerResponse", ""); doc.AppendChild(rootElement); XmlElement result = doc.CreateElement("", "Result", ""); result.AppendChild(doc.CreateTextNode("Failure")); rootElement.AppendChild(result); return DocToBytes(doc); } private byte[] DocToBytes(XmlDocument doc) { MemoryStream ms = new MemoryStream(); XmlTextWriter xw = new XmlTextWriter(ms, null); xw.Formatting = Formatting.Indented; doc.WriteTo(xw); xw.Flush(); return ms.ToArray(); } #endregion } }
// // This file is part of the game Voxalia, created by FreneticXYZ. // This code is Copyright (C) 2016 FreneticXYZ under the terms of the MIT license. // See README.md or LICENSE.txt for contents of the MIT license. // If these are not available, see https://opensource.org/licenses/MIT // using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; namespace Voxalia.Shared { /// <summary> /// Contains the list of all block paint colors. Colors can be reused for other things. /// </summary> public static class Colors { public static Color WHITE = Color.FromArgb(255, 255, 255); public static Color BLACK = Color.FromArgb(7, 7, 7); public static Color GREEN = Color.FromArgb(0, 255, 0); public static Color BLUE = Color.FromArgb(0, 0, 255); public static Color RED = Color.FromArgb(255, 0, 0); public static Color MAGENTA = Color.FromArgb(255, 0, 255); public static Color YELLOW = Color.FromArgb(255, 255, 0); public static Color CYAN = Color.FromArgb(0, 255, 255); public static Color DARK_GREEN = Color.FromArgb(0, 128, 0); public static Color DARK_BLUE = Color.FromArgb(0, 0, 128); public static Color DARK_RED = Color.FromArgb(128, 0, 0); public static Color LIGHT_GREEN = Color.FromArgb(128, 255, 128); public static Color LIGHT_BLUE = Color.FromArgb(128, 128, 255); public static Color LIGHT_RED = Color.FromArgb(255, 128, 128); public static Color GRAY = Color.FromArgb(128, 128, 128); public static Color LIGHT_GRAY = Color.FromArgb(192, 192, 192); public static Color DARK_GRAY = Color.FromArgb(64, 64, 64); public static Color DARK_MAGENTA = Color.FromArgb(128, 0, 128); public static Color DARK_YELLOW = Color.FromArgb(128, 128, 0); public static Color DARK_CYAN = Color.FromArgb(0, 128, 128); public static Color LIGHT_MAGENTA = Color.FromArgb(255, 128, 255); public static Color LIGHT_YELLOW = Color.FromArgb(255, 255, 128); public static Color LIGHT_CYAN = Color.FromArgb(128, 255, 255); public static Color ORANGE = Color.FromArgb(255, 128, 0); public static Color BROWN = Color.FromArgb(128, 64, 0); public static Color PURPLE = Color.FromArgb(128, 0, 255); public static Color PINK = Color.FromArgb(255, 128, 255); public static Color LIME = Color.FromArgb(128, 255, 0); public static Color SKY_BLUE = Color.FromArgb(0, 128, 255); public static Color VERY_DARK_GRAY = Color.FromArgb(32, 32, 32); public static Color TRANSPARENT_GREEN = Color.FromArgb(127, 0, 255, 0); public static Color TRANSPARENT_BLUE = Color.FromArgb(127, 0, 0, 255); public static Color TRANSPARENT_RED = Color.FromArgb(127, 255, 0, 0); public static Color TRANSPARENT_MAGENTA = Color.FromArgb(127, 255, 0, 255); public static Color TRANSPARENT_YELLOW = Color.FromArgb(127, 255, 255, 0); public static Color TRANSPARENT_CYAN = Color.FromArgb(127, 0, 255, 255); public static Color SLIGHTLY_TRANSPARENT = Color.FromArgb(191, 255, 255, 255); public static Color TRANSPARENT = Color.FromArgb(127, 255, 255, 255); public static Color VERY_TRANSPARENT = Color.FromArgb(63, 255, 255, 255); public static Color LIGHT_STROBE_GREEN = Color.FromArgb(2, 255, 0, 255); public static Color LIGHT_STROBE_BLUE = Color.FromArgb(2, 255, 255, 0); public static Color LIGHT_STROBE_RED = Color.FromArgb(2, 0, 255, 255); public static Color LIGHT_STROBE_MAGENTA = Color.FromArgb(2, 0, 255, 0); public static Color LIGHT_STROBE_YELLOW = Color.FromArgb(2, 0, 0, 255); public static Color LIGHT_STROBE_CYAN = Color.FromArgb(2, 255, 0, 0); public static Color STROBE_WHITE = Color.FromArgb(0, 255, 255, 255); public static Color STROBE_GREEN = Color.FromArgb(0, 0, 255, 0); public static Color STROBE_BLUE = Color.FromArgb(0, 0, 0, 255); public static Color STROBE_RED = Color.FromArgb(0, 255, 0, 0); public static Color STROBE_MAGENTA = Color.FromArgb(0, 255, 0, 255); public static Color STROBE_YELLOW = Color.FromArgb(0, 255, 255, 0); public static Color STROBE_CYAN = Color.FromArgb(0, 0, 255, 255); public static Color MAGIC = Color.FromArgb(0, 0, 0, 0); public static Color OLD_MAGIC = Color.FromArgb(0, 127, 0, 0); public static Color RAINBOW = Color.FromArgb(0, 127, 0, 127); public static Color BLUR = Color.FromArgb(0, 0, 127, 0); public static Color CRACKS = Color.FromArgb(0, 127, 127, 127); public static Color INVERT = Color.FromArgb(0, 127, 127, 145); public static Color SHINE = Color.FromArgb(0, 145, 127, 127); public static Dictionary<string, byte> KnownColorNames = new Dictionary<string, byte>(); public static Color[] KnownColorsArray = new Color[64]; public static string[] KnownColorNamesArray = new string[64]; public static double AlphaForByte(byte input) { if (input >= TRANS1 && input < TRANS_BASE || input == TRANS_BASE + 1) { return 0.5; } else if (input == TRANS_BASE) { return 0.75; } else if (input == TRANS2) { return 0.25; } return 1.0; } public static Color ForByte(byte input) { int baseinp = input; return KnownColorsArray[baseinp]; } public static string NameForByte(byte input) { int baseinp = input; return KnownColorNamesArray[baseinp]; } public static byte ForName(string name) { byte val; if (byte.TryParse(name, out val)) { return val; } name = name.ToUpperInvariant(); if (KnownColorNames.TryGetValue(name, out val)) { return val; } return 0; } static int inc = 0; public static int TRANS1; public static int TRANS2; public static int TRANS_BASE; public static int M_BLUR; static int Register(string name, Color col) { KnownColorNames.Add(name, (byte)inc); KnownColorNamesArray[inc] = name; KnownColorsArray[inc] = col; return inc++; } static Colors() { Register("WHITE", WHITE); Register("BLACK", BLACK); Register("GREEN", GREEN); Register("BLUE", BLUE); Register("RED", RED); Register("MAGENTA", MAGENTA); Register("YELLOW", YELLOW); Register("CYAN", CYAN); Register("DARK_GREEN", DARK_GREEN); Register("DARK_BLUE", DARK_BLUE); Register("DARK_RED", DARK_RED); Register("LIGHT_GREEN", LIGHT_GREEN); Register("LIGHT_BLUE", LIGHT_BLUE); Register("LIGHT_RED", LIGHT_RED); Register("GRAY", GRAY); Register("LIGHT_GRAY", LIGHT_GRAY); Register("DARK_GRAY", DARK_GRAY); Register("DARK_MAGENTA", DARK_MAGENTA); Register("DARK_YELLOW", DARK_YELLOW); Register("DARK_CYAN", DARK_CYAN); Register("LIGHT_MAGENTA", LIGHT_MAGENTA); Register("LIGHT_YELLOW", LIGHT_YELLOW); Register("LIGHT_CYAN", LIGHT_CYAN); Register("ORANGE", ORANGE); Register("BROWN", BROWN); Register("PURPLE", PURPLE); Register("PINK", PINK); Register("LIME", LIME); Register("SKY_BLUE", SKY_BLUE); Register("VERY_DARK_GRAY", VERY_DARK_GRAY); Register("PLACEHOLDER_5", WHITE); Register("PLACEHOLDER_4", WHITE); Register("PLACEHOLDER_3", WHITE); Register("PLACEHOLDER_2", WHITE); Register("PLACEHOLDER_1", WHITE); TRANS1 = Register("TRANSPARENT_GREEN", TRANSPARENT_GREEN); Register("TRANSPARENT_BLUE", TRANSPARENT_BLUE); Register("TRANSPARENT_RED", TRANSPARENT_RED); Register("TRANSPARENT_MAGENTA", TRANSPARENT_MAGENTA); Register("TRANSPARENT_YELLOW", TRANSPARENT_YELLOW); Register("TRANSPARENT_CYAN", TRANSPARENT_CYAN); TRANS_BASE = Register("SLIGHTLY_TRANSPARENT", SLIGHTLY_TRANSPARENT); Register("TRANSPARENT", TRANSPARENT); TRANS2 = Register("VERY_TRANSPARENT", VERY_TRANSPARENT); Register("LIGHT_STROBE_GREEN", LIGHT_STROBE_GREEN); Register("LIGHT_STROBE_BLUE", LIGHT_STROBE_BLUE); Register("LIGHT_STROBE_RED", LIGHT_STROBE_RED); Register("LIGHT_STROBE_YELLOW", LIGHT_STROBE_YELLOW); Register("LIGHT_STROBE_MAGENTA", LIGHT_STROBE_MAGENTA); Register("LIGHT_STROBE_CYAN", LIGHT_STROBE_CYAN); Register("STROBE_WHITE", STROBE_WHITE); Register("STROBE_GREEN", STROBE_GREEN); Register("STROBE_BLUE", STROBE_BLUE); Register("STROBE_RED", STROBE_RED); Register("STROBE_YELLOW", STROBE_YELLOW); Register("STROBE_MAGENTA", STROBE_MAGENTA); Register("STROBE_CYAN", STROBE_CYAN); Register("MAGIC", MAGIC); Register("OLD_MAGIC", OLD_MAGIC); Register("RAINBOW", RAINBOW); M_BLUR = Register("BLUR", BLUR); Register("CRACKS", CRACKS); Register("INVERT", INVERT); Register("SHINE", SHINE); } } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using CslaGenerator.Metadata; using CslaGenerator.Util; using CslaGenerator.Templates; namespace CslaGenerator { /// <summary> /// Summary description for GeneratorForm. /// </summary> public class GeneratorForm : System.Windows.Forms.Form { private System.Windows.Forms.CheckBox chkActiveObjects; private System.Windows.Forms.CheckBox chkBackUpOldSource; private System.Windows.Forms.CheckBox chkSeparateNamespaces; private System.Windows.Forms.CheckBox chkGenerateStoredProcedures; private System.Windows.Forms.Label label1; private System.Windows.Forms.CheckBox chkSpOneFile; private System.Windows.Forms.ComboBox cboTarget; private System.Windows.Forms.CheckBox chkSeparateBaseClasses; private System.Windows.Forms.Button btnGenerate; private System.Windows.Forms.CheckedListBox clbObjects; private System.Windows.Forms.Label label2; private System.Windows.Forms.ToolTip toolTip1; private System.Windows.Forms.ProgressBar progressBar1; private System.Windows.Forms.TextBox txtOutput; private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage tabGeneration; private System.Windows.Forms.TabPage tabOutPut; private System.Windows.Forms.CheckBox chkSave; private System.Windows.Forms.MenuItem mnuAll; private System.Windows.Forms.MenuItem mnuNone; private System.Windows.Forms.ContextMenu selectionMenu; private System.Windows.Forms.Button cmdClose; private CheckBox chkUseDotDesignerFileNameConvention; private System.ComponentModel.IContainer components; #region Constructors public GeneratorForm(CslaGeneratorUnit unit) { // // Required for Windows Form Designer support // InitializeComponent(); _unit = unit; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #endregion #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(GeneratorForm)); this.chkActiveObjects = new System.Windows.Forms.CheckBox(); this.chkBackUpOldSource = new System.Windows.Forms.CheckBox(); this.chkSeparateNamespaces = new System.Windows.Forms.CheckBox(); this.cboTarget = new System.Windows.Forms.ComboBox(); this.chkGenerateStoredProcedures = new System.Windows.Forms.CheckBox(); this.chkSpOneFile = new System.Windows.Forms.CheckBox(); this.label1 = new System.Windows.Forms.Label(); this.chkSeparateBaseClasses = new System.Windows.Forms.CheckBox(); this.btnGenerate = new System.Windows.Forms.Button(); this.clbObjects = new System.Windows.Forms.CheckedListBox(); this.selectionMenu = new System.Windows.Forms.ContextMenu(); this.mnuAll = new System.Windows.Forms.MenuItem(); this.mnuNone = new System.Windows.Forms.MenuItem(); this.label2 = new System.Windows.Forms.Label(); this.toolTip1 = new System.Windows.Forms.ToolTip(this.components); this.chkSave = new System.Windows.Forms.CheckBox(); this.progressBar1 = new System.Windows.Forms.ProgressBar(); this.txtOutput = new System.Windows.Forms.TextBox(); this.tabControl1 = new System.Windows.Forms.TabControl(); this.tabGeneration = new System.Windows.Forms.TabPage(); this.chkUseDotDesignerFileNameConvention = new System.Windows.Forms.CheckBox(); this.tabOutPut = new System.Windows.Forms.TabPage(); this.cmdClose = new System.Windows.Forms.Button(); this.tabControl1.SuspendLayout(); this.tabGeneration.SuspendLayout(); this.tabOutPut.SuspendLayout(); this.SuspendLayout(); // // chkActiveObjects // this.chkActiveObjects.Location = new System.Drawing.Point(9, 68); this.chkActiveObjects.Name = "chkActiveObjects"; this.chkActiveObjects.Size = new System.Drawing.Size(224, 24); this.chkActiveObjects.TabIndex = 0; this.chkActiveObjects.Text = "Generate Active Objects Code"; this.toolTip1.SetToolTip(this.chkActiveObjects, "If checked it will output ActiveObjects code instead of plain CSLA."); // // chkBackUpOldSource // this.chkBackUpOldSource.Location = new System.Drawing.Point(9, 98); this.chkBackUpOldSource.Name = "chkBackUpOldSource"; this.chkBackUpOldSource.Size = new System.Drawing.Size(216, 24); this.chkBackUpOldSource.TabIndex = 1; this.chkBackUpOldSource.Text = "BackUp old source files"; this.toolTip1.SetToolTip(this.chkBackUpOldSource, "Replaced files will be backed up as \"<filename>.old\""); // // chkSeparateNamespaces // this.chkSeparateNamespaces.Location = new System.Drawing.Point(9, 186); this.chkSeparateNamespaces.Name = "chkSeparateNamespaces"; this.chkSeparateNamespaces.Size = new System.Drawing.Size(272, 24); this.chkSeparateNamespaces.TabIndex = 2; this.chkSeparateNamespaces.Text = "Separate Namespaces in folders"; this.toolTip1.SetToolTip(this.chkSeparateNamespaces, "Generated codes is distributed in folders according to their namespaces."); // // cboTarget // this.cboTarget.Location = new System.Drawing.Point(128, 36); this.cboTarget.Name = "cboTarget"; this.cboTarget.Size = new System.Drawing.Size(144, 26); this.cboTarget.TabIndex = 3; this.cboTarget.Text = "cboTarget"; // // chkGenerateStoredProcedures // this.chkGenerateStoredProcedures.Location = new System.Drawing.Point(9, 216); this.chkGenerateStoredProcedures.Name = "chkGenerateStoredProcedures"; this.chkGenerateStoredProcedures.Size = new System.Drawing.Size(272, 24); this.chkGenerateStoredProcedures.TabIndex = 5; this.chkGenerateStoredProcedures.Text = "Generate Stored Procedures"; this.toolTip1.SetToolTip(this.chkGenerateStoredProcedures, "Check this if you want to generate stored procedures for the objects that can gen" + "erate them."); // // chkSpOneFile // this.chkSpOneFile.Location = new System.Drawing.Point(9, 246); this.chkSpOneFile.Name = "chkSpOneFile"; this.chkSpOneFile.Size = new System.Drawing.Size(264, 24); this.chkSpOneFile.TabIndex = 6; this.chkSpOneFile.Text = "Generate only one SP file per object"; this.toolTip1.SetToolTip(this.chkSpOneFile, "Check this if you want to create only one file that contains all the generated st" + "ored procedures for the business object"); // // label1 // this.label1.Location = new System.Drawing.Point(5, 38); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(128, 24); this.label1.TabIndex = 7; this.label1.Text = "Target Framework:"; // // chkSeparateBaseClasses // this.chkSeparateBaseClasses.Location = new System.Drawing.Point(9, 156); this.chkSeparateBaseClasses.Name = "chkSeparateBaseClasses"; this.chkSeparateBaseClasses.Size = new System.Drawing.Size(248, 24); this.chkSeparateBaseClasses.TabIndex = 8; this.chkSeparateBaseClasses.Text = "Separate base classes in a folder"; this.toolTip1.SetToolTip(this.chkSeparateBaseClasses, "Generated code goes to \"<output path>\\Base\""); // // btnGenerate // this.btnGenerate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnGenerate.Location = new System.Drawing.Point(456, 329); this.btnGenerate.Name = "btnGenerate"; this.btnGenerate.Size = new System.Drawing.Size(88, 32); this.btnGenerate.TabIndex = 9; this.btnGenerate.Text = "&Generate"; this.btnGenerate.Click += new System.EventHandler(this.btnGenerate_Click); // // clbObjects // this.clbObjects.CheckOnClick = true; this.clbObjects.ContextMenu = this.selectionMenu; this.clbObjects.Location = new System.Drawing.Point(315, 38); this.clbObjects.Name = "clbObjects"; this.clbObjects.Size = new System.Drawing.Size(296, 238); this.clbObjects.TabIndex = 10; this.clbObjects.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler(this.clbObjects_ItemCheck); // // selectionMenu // this.selectionMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.mnuAll, this.mnuNone}); // // mnuAll // this.mnuAll.Index = 0; this.mnuAll.Text = "Select All"; this.mnuAll.Click += new System.EventHandler(this.mnuAll_Click); // // mnuNone // this.mnuNone.Index = 1; this.mnuNone.Text = "Select None"; this.mnuNone.Click += new System.EventHandler(this.mnuNone_Click); // // label2 // this.label2.Location = new System.Drawing.Point(312, 16); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(152, 24); this.label2.TabIndex = 11; this.label2.Text = "Objects to generate:"; // // chkSave // this.chkSave.Checked = true; this.chkSave.CheckState = System.Windows.Forms.CheckState.Checked; this.chkSave.Font = new System.Drawing.Font("Trebuchet MS", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.chkSave.Location = new System.Drawing.Point(8, 14); this.chkSave.Name = "chkSave"; this.chkSave.Size = new System.Drawing.Size(272, 21); this.chkSave.TabIndex = 12; this.chkSave.Text = "Save project before generating"; this.toolTip1.SetToolTip(this.chkSave, "This is enabled by default every time you open the generation form."); // // progressBar1 // this.progressBar1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.progressBar1.Location = new System.Drawing.Point(16, 329); this.progressBar1.Name = "progressBar1"; this.progressBar1.Size = new System.Drawing.Size(432, 32); this.progressBar1.TabIndex = 12; // // txtOutput // this.txtOutput.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtOutput.Location = new System.Drawing.Point(15, 8); this.txtOutput.Multiline = true; this.txtOutput.Name = "txtOutput"; this.txtOutput.ScrollBars = System.Windows.Forms.ScrollBars.Both; this.txtOutput.Size = new System.Drawing.Size(590, 267); this.txtOutput.TabIndex = 14; // // tabControl1 // this.tabControl1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tabControl1.Controls.Add(this.tabGeneration); this.tabControl1.Controls.Add(this.tabOutPut); this.tabControl1.Location = new System.Drawing.Point(8, 8); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(624, 315); this.tabControl1.TabIndex = 15; // // tabGeneration // this.tabGeneration.Controls.Add(this.chkUseDotDesignerFileNameConvention); this.tabGeneration.Controls.Add(this.chkSave); this.tabGeneration.Controls.Add(this.chkActiveObjects); this.tabGeneration.Controls.Add(this.chkBackUpOldSource); this.tabGeneration.Controls.Add(this.chkSeparateNamespaces); this.tabGeneration.Controls.Add(this.cboTarget); this.tabGeneration.Controls.Add(this.chkGenerateStoredProcedures); this.tabGeneration.Controls.Add(this.chkSpOneFile); this.tabGeneration.Controls.Add(this.label1); this.tabGeneration.Controls.Add(this.chkSeparateBaseClasses); this.tabGeneration.Controls.Add(this.clbObjects); this.tabGeneration.Controls.Add(this.label2); this.tabGeneration.Location = new System.Drawing.Point(4, 27); this.tabGeneration.Name = "tabGeneration"; this.tabGeneration.Size = new System.Drawing.Size(616, 284); this.tabGeneration.TabIndex = 0; this.tabGeneration.Text = "Generation Parameters"; // // chkUseDotDesignerFileNameConvention // this.chkUseDotDesignerFileNameConvention.AutoSize = true; this.chkUseDotDesignerFileNameConvention.Location = new System.Drawing.Point(9, 128); this.chkUseDotDesignerFileNameConvention.Name = "chkUseDotDesignerFileNameConvention"; this.chkUseDotDesignerFileNameConvention.Size = new System.Drawing.Size(198, 22); this.chkUseDotDesignerFileNameConvention.TabIndex = 14; this.chkUseDotDesignerFileNameConvention.Text = "Use \".Designer\" in file names"; this.chkUseDotDesignerFileNameConvention.UseVisualStyleBackColor = true; // // tabOutPut // this.tabOutPut.Controls.Add(this.txtOutput); this.tabOutPut.Location = new System.Drawing.Point(4, 27); this.tabOutPut.Name = "tabOutPut"; this.tabOutPut.Size = new System.Drawing.Size(616, 284); this.tabOutPut.TabIndex = 1; this.tabOutPut.Text = "Output"; // // cmdClose // this.cmdClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.cmdClose.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cmdClose.Location = new System.Drawing.Point(552, 329); this.cmdClose.Name = "cmdClose"; this.cmdClose.Size = new System.Drawing.Size(80, 32); this.cmdClose.TabIndex = 16; this.cmdClose.Text = "&Close"; // // GeneratorForm // this.AutoScaleBaseSize = new System.Drawing.Size(6, 16); this.CancelButton = this.cmdClose; this.ClientSize = new System.Drawing.Size(642, 369); this.Controls.Add(this.cmdClose); this.Controls.Add(this.tabControl1); this.Controls.Add(this.progressBar1); this.Controls.Add(this.btnGenerate); this.Font = new System.Drawing.Font("Trebuchet MS", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.Name = "GeneratorForm"; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "CSLA Object Generator v1.0"; this.Load += new System.EventHandler(this.GeneratorForm_Load); this.tabControl1.ResumeLayout(false); this.tabGeneration.ResumeLayout(false); this.tabGeneration.PerformLayout(); this.tabOutPut.ResumeLayout(false); this.tabOutPut.PerformLayout(); this.ResumeLayout(false); } #endregion private CslaGeneratorUnit _unit; private CodeGenerator _generatorInstance; private bool _generating=false; public event EventHandler RequestSave; #region OnRequestSave /// <summary> /// Triggers the RequestSave event. /// </summary> public virtual void OnRequestSave(EventArgs ea) { if (RequestSave != null) RequestSave(this, ea); } #endregion #region properties... //private CodeGenerator GeneratorInstance1 //{ // get // { // if (_generatorInstance == null) // { // _generatorInstance = new CodeGenerator(_unit.TargetDirectory); // _generatorInstance.Step +=new CslaGenerator.Templates.CodeGenerator.GenerationInformationDelegate(_generatorInstance_Step); // _generatorInstance.Finilized += new EventHandler(_generatorInstance_Finilized); // _generatorInstance.GenerationInformation += new CslaGenerator.Templates.CodeGenerator.GenerationInformationDelegate(_generatorInstance_GenerationInformation); // } // return _generatorInstance; // } //} #endregion #region event handlers... private void btnGenerate_Click(object sender, System.EventArgs e) { btnGenerate.Enabled=false; if (!_generating) { SaveInfo(); if (chkSave.Checked) { try { OnRequestSave(new EventArgs()); } catch (Exception ex) { DialogResult dr; dr = MessageBox.Show("The project failed to save. Would you like to continue anyway?" + Environment.NewLine + Environment.NewLine + "Exception Details:" + Environment.NewLine + ex.Message, "Cslagen", MessageBoxButtons.YesNo, MessageBoxIcon.Error); if (dr == DialogResult.No) { btnGenerate.Enabled = true; return; } } } try { System.Threading.Thread thd; System.Threading.ThreadStart start = new System.Threading.ThreadStart(Start); thd = new System.Threading.Thread(start); btnGenerate.Text = "&Abort"; txtOutput.Clear(); progressBar1.Maximum = clbObjects.CheckedItems.Count; tabControl1.SelectedIndex = 1; cmdClose.Enabled = false; thd.Start(); } catch (Exception ex) { MessageBox.Show("Error Generating Code:" + Environment.NewLine + Environment.NewLine + ex.Message); } } else { this._generatorInstance.Abort(); } } private void clbObjects_ItemCheck(object sender, System.Windows.Forms.ItemCheckEventArgs e) { CslaObjectInfo item = (CslaObjectInfo)clbObjects.Items[e.Index]; item.Generate = (e.NewValue == CheckState.Checked) ? true : false; } private void GeneratorForm_Load(object sender, System.EventArgs e) { foreach (string str in Enum.GetNames(typeof(TargetFramework))) { cboTarget.Items.Add(str); } LoadInfo(); LoadObjects(); clbObjects.Focus(); } private void mnuAll_Click(object sender, System.EventArgs e) { for (int i = 0; i < clbObjects.Items.Count; i++) { clbObjects.SetItemChecked(i,true); } } private void mnuNone_Click(object sender, System.EventArgs e) { for (int i = 0; i < clbObjects.Items.Count; i++) { clbObjects.SetItemChecked(i,false); } } #endregion #region Thread Safe Handlers delegate void MessageDelegate(string message); private void _generatorInstance_Step(string e) { this.Invoke(new MessageDelegate(DoStep), new object[] {e}); } private void _generatorInstance_Finilized(object sender, EventArgs e) { this.Invoke(new MethodInvoker(DoFinalize)); } private void _generatorInstance_GenerationInformation(string e) { this.Invoke(new MessageDelegate(DisplayInfo), new object[] {e}); } #endregion #region Private Methods void Start() { int index = 0; CslaObjectInfo[] GenerateObjects = new CslaObjectInfo[clbObjects.CheckedItems.Count]; foreach (CslaObjectInfo obj in clbObjects.CheckedItems) { GenerateObjects[index] = obj; index++; } string targetDir = _unit.TargetDirectory; if (targetDir.StartsWith(".") || targetDir.StartsWith("..")) { targetDir = targetDir + @"\" + targetDir; } _generatorInstance = new CodeGenerator(targetDir); _generatorInstance.Step += new CslaGenerator.Templates.CodeGenerator.GenerationInformationDelegate(_generatorInstance_Step); _generatorInstance.Finilized += new EventHandler(_generatorInstance_Finilized); _generatorInstance.GenerationInformation += new CslaGenerator.Templates.CodeGenerator.GenerationInformationDelegate(_generatorInstance_GenerationInformation); _generatorInstance.GenerateProject(_unit, GeneratorController.Current.CurrentFilePath); } void DoStep(string objectName) { txtOutput.AppendText(new String('=',70) + Environment.NewLine + objectName + ":" + Environment.NewLine); if (_generating) progressBar1.Value++; else progressBar1.Value = progressBar1.Minimum; _generating=true; btnGenerate.Enabled=true; } void DoFinalize() { txtOutput.AppendText(Environment.NewLine + "Done!"); progressBar1.Value=progressBar1.Maximum; _generating=false; btnGenerate.Text = "&Generate"; btnGenerate.Enabled=true; cmdClose.Enabled = true; _generatorInstance.Step -= new CslaGenerator.Templates.CodeGenerator.GenerationInformationDelegate(_generatorInstance_Step); _generatorInstance.Finilized -= new EventHandler(_generatorInstance_Finilized); _generatorInstance.GenerationInformation -= new CslaGenerator.Templates.CodeGenerator.GenerationInformationDelegate(_generatorInstance_GenerationInformation); _generatorInstance = null; } void DisplayInfo(string msg) { txtOutput.AppendText(msg + Environment.NewLine); txtOutput.SelectionStart= txtOutput.Text.Length; } void LoadObjects() { foreach (CslaObjectInfo obj in _unit.CslaObjects) { clbObjects.Items.Add(obj, obj.Generate); } } void LoadInfo() { GenerationParameters p = _unit.GenerationParams; cboTarget.SelectedItem = p.TargetFramework.ToString(); chkActiveObjects.Checked = p.ActiveObjects; chkBackUpOldSource.Checked = p.BackupOldSource; chkGenerateStoredProcedures.Checked = p.GenerateSprocs; chkSpOneFile.Checked = p.OneSpFilePerObject; chkSeparateBaseClasses.Checked = p.SeparateBaseClasses; chkSeparateNamespaces.Checked = p.SeparateNamespaces; chkUseDotDesignerFileNameConvention.Checked = p.UseDotDesignerFileNameConvention; } void SaveInfo() { GenerationParameters p = _unit.GenerationParams; p.TargetFramework = (TargetFramework)Enum.Parse(typeof(TargetFramework),(string)cboTarget.SelectedItem); p.ActiveObjects = chkActiveObjects.Checked; p.BackupOldSource = chkBackUpOldSource.Checked; p.GenerateSprocs = chkGenerateStoredProcedures.Checked; p.OneSpFilePerObject = chkSpOneFile.Checked; p.SeparateBaseClasses = chkSeparateBaseClasses.Checked; p.SeparateNamespaces = chkSeparateNamespaces.Checked; p.UseDotDesignerFileNameConvention = chkUseDotDesignerFileNameConvention.Checked; } #endregion } }
// ----- // GNU General Public License // The Forex Professional Analyzer 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 3 of the License, or (at your option) any later version. // The Forex Professional Analyzer 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. // ----- using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Configuration; namespace fxpa { public class FxpaBase { //TransportIntegrationServer _server; /// <summary> /// This includes all component types grouped. /// </summary> List<IFxpaBaseCompoent> _components = new List<IFxpaBaseCompoent>(); public ReadOnlyCollection<IFxpaBaseCompoent> Components { get { lock (this) { return _components.AsReadOnly(); } } } //List<TransportInfo> _sourcesUpdatesSubscribers = new List<TransportInfo>(); SettingsBase _settings; public SettingsBase Settings { get { lock (this) { return _settings; } } } public delegate void ActiveComponentUpdateDelegate(IFxpaBaseCompoent component, bool added); public event ActiveComponentUpdateDelegate ActiveComponentUpdateEvent; Uri _platformUri; public Uri PlatformUri { get { lock (this) { return _platformUri; } } } string name; public string Name { get { return name; } set { name = value; } } //private bool _singleThreadOnly ; /// <summary> /// /// </summary> public FxpaBase() //: base("Platform", false) { // TracerHelper.Tracer = new Tracer(); // TracerHelper.TraceEntry(); //Arbiter arbiter = new Arbiter("Platform"); ////ArbiterTraceHelper.TracingEnabled = false; //arbiter.AddClient(this); name = "FxpaBase"; //_messageFilter = new MessageFilter(true); //_singleThreadOnly = false; } public bool Initialize(SettingsBase settings) { //SystemMonitor.CheckThrow(_settings == null, "Platform already initialized."); // TracerHelper.TraceEntry(); lock (this) { _settings = settings; ActiveComponentUpdateEvent += new ActiveComponentUpdateDelegate(Platform_ActiveComponentUpdateEvent); _platformUri = new Uri((string)settings["FxpaUriAddress"]); //_server = new TransportIntegrationServer(_platformUri); //Arbiter.AddClient(_server); } return true; } public bool UnInitialize() { // TracerHelper.TraceEntry(); lock (this) { //this.SendRespondingToMany(_sourcesUpdatesSubscribers, new SourcesSubscriptionTerminatedMessage()); //_sourcesUpdatesSubscribers.Clear(); while (_components.Count > 0) {// Cycling this way, since a component might be removing other components. IFxpaBaseCompoent component = this._components[0]; if (component.IsInitialized) { UnInitializeComponent(component); } _components.Remove(component); } //this.Arbiter.Dispose(); } return true; } public TComponentType[] GetComponents<TComponentType>() // where ComponentType : IPlatformComponent, // all in here are IPlatformComponent but searching is not always by that criteria { List<TComponentType> result = new List<TComponentType>(); foreach (IFxpaBaseCompoent component in _components) { Type componentType = component.GetType(); if (typeof(TComponentType).IsInterface) {// Interface checking is different. List<Type> interfaces = new List<Type>(componentType.GetInterfaces()); if (interfaces.Contains(typeof(TComponentType))) { result.Add((TComponentType)component); } } else {// Normal class check. if (componentType == typeof(TComponentType) || componentType.IsSubclassOf(typeof(TComponentType))) { result.Add((TComponentType)component); } } } return result.ToArray(); } /// <summary> /// Prepare the object for operation. Access to this allows externals to use the 2 step component registration process. /// </summary> public bool InitializeComponent(IFxpaBaseCompoent component) { // TracerHelper.Trace(component.Name); //Arbiter.AddClient(component); //if (component.IsInitialized == false && component.Initialize(this) == false) //{ // Arbiter.RemoveClient(component); // return false; //} component.Initialize(this); return true; } /// <summary> /// Bring down the object from operation. Access to this allows externals to use the 2 step component registration process. /// </summary> public bool UnInitializeComponent(IFxpaBaseCompoent component) { // TracerHelper.Trace(component.Name); component.UnInitialize(); //Arbiter.RemoveClient(component); return true; } void Platform_ActiveComponentUpdateEvent(IFxpaBaseCompoent component, bool isAdded) { // TracerHelper.Trace(component.Name); //if (component is DataSource == false && component is ExecutionSource == false) //{ // return; //} if (component is FxpaSource == false ) { return; } //SourceUpdatedMessage message = new SourceUpdatedMessage(component.SubscriptionClientID, component is DataSource, isAdded); lock (this) { //foreach (TransportInfo info in _sourcesUpdatesSubscribers) //{ // this.SendResponding(info, message); //} } } /// <summary> /// Add the object to the list of active objects and call event to notify all listeners, a new object has been added. /// </summary> /// <param name="component"></param> /// <returns></returns> public bool RegisterComponent(IFxpaBaseCompoent component) { // TracerHelper.Trace(component.Name); if (InitializeComponent(component) == false) { return false; } lock (this) { if (_components.Contains(component)) { return true; } _components.Add(component); } GeneralHelper.SafeEventRaise(new GeneralHelper.GenericDelegate<IFxpaBaseCompoent, bool>( ActiveComponentUpdateEvent), component, true); return true; } public bool UnRegisterComponent(IFxpaBaseCompoent component) { // TracerHelper.Trace(component.Name); UnInitializeComponent(component); lock (this) { if (_components.Remove(component) == false) { return true; } } if (ActiveComponentUpdateEvent != null) { ActiveComponentUpdateEvent(component, false); } return true; } //[MessageReceiver] //ResultTransportMessage Receive(SubscribeToSourcesMessage message) //{ // lock (this) //{ //if (_sourcesUpdatesSubscribers.Contains(message.TransportInfo) == false) //{ // _sourcesUpdatesSubscribers.Add(message.TransportInfo); //} //foreach (SessionedSource source in GetComponents<DataSource>()) //{ // this.SendResponding(message.TransportInfo, new SourceUpdatedMessage(source.SubscriptionClientID, true, true)); //} //foreach (SessionedSource source in GetComponents<ExecutionSource>()) //{ // this.SendResponding(message.TransportInfo, new SourceUpdatedMessage(source.SubscriptionClientID, false, true)); //} // } // return new ResultTransportMessage(true); //} //[MessageReceiver] //ResultTransportMessage Receive(UnSubscribeToSourcesMessage message) //{ // lock (this) // { // _sourcesUpdatesSubscribers.Remove(message.TransportInfo); // } // if (message.RequestConfirmation == false) // { // return null; // } // return new ResultTransportMessage(true); //} } }
using UnityEngine; namespace UnitySampleAssets.ImageEffects { [ExecuteInEditMode] [AddComponentMenu("Image Effects/Contrast Stretch")] public class ContrastStretchEffect : MonoBehaviour { /// Adaptation speed - percents per frame, if playing at 30FPS. /// Default is 0.02 (2% each 1/30s). public float adaptationSpeed = 0.02f; /// If our scene is really dark (or really bright), we might not want to /// stretch its contrast to the full range. /// limitMinimum=0, limitMaximum=1 is the same as not applying the effect at all. /// limitMinimum=1, limitMaximum=0 is always stretching colors to full range. /// The limit on the minimum luminance (0...1) - we won't go above this. public float limitMinimum = 0.2f; /// The limit on the maximum luminance (0...1) - we won't go below this. public float limitMaximum = 0.6f; // To maintain adaptation levels over time, we need two 1x1 render textures // and ping-pong between them. private RenderTexture[] adaptRenderTex = new RenderTexture[2]; private int curAdaptIndex = 0; // Computes scene luminance (grayscale) image public Shader shaderLum; private Material m_materialLum; protected Material materialLum { get { if (m_materialLum == null) { m_materialLum = new Material(shaderLum); m_materialLum.hideFlags = HideFlags.HideAndDontSave; } return m_materialLum; } } // Reduces size of the image by 2x2, while computing maximum/minimum values. // By repeatedly applying this shader, we reduce the initial luminance image // to 1x1 image with minimum/maximum luminances found. public Shader shaderReduce; private Material m_materialReduce; protected Material materialReduce { get { if (m_materialReduce == null) { m_materialReduce = new Material(shaderReduce); m_materialReduce.hideFlags = HideFlags.HideAndDontSave; } return m_materialReduce; } } // Adaptation shader - gradually "adapts" minimum/maximum luminances, // based on currently adapted 1x1 image and the actual 1x1 image of the current scene. public Shader shaderAdapt; private Material m_materialAdapt; protected Material materialAdapt { get { if (m_materialAdapt == null) { m_materialAdapt = new Material(shaderAdapt); m_materialAdapt.hideFlags = HideFlags.HideAndDontSave; } return m_materialAdapt; } } // Final pass - stretches the color values of the original scene, based on currently // adpated minimum/maximum values. public Shader shaderApply; private Material m_materialApply; protected Material materialApply { get { if (m_materialApply == null) { m_materialApply = new Material(shaderApply); m_materialApply.hideFlags = HideFlags.HideAndDontSave; } return m_materialApply; } } private void Start() { // Disable if we don't support image effects if (!SystemInfo.supportsImageEffects) { enabled = false; return; } if (!shaderAdapt.isSupported || !shaderApply.isSupported || !shaderLum.isSupported || !shaderReduce.isSupported) { enabled = false; return; } } private void OnEnable() { for (int i = 0; i < 2; ++i) { if (!adaptRenderTex[i]) { adaptRenderTex[i] = new RenderTexture(1, 1, 32); adaptRenderTex[i].hideFlags = HideFlags.HideAndDontSave; } } } private void OnDisable() { for (int i = 0; i < 2; ++i) { DestroyImmediate(adaptRenderTex[i]); adaptRenderTex[i] = null; } if (m_materialLum) DestroyImmediate(m_materialLum); if (m_materialReduce) DestroyImmediate(m_materialReduce); if (m_materialAdapt) DestroyImmediate(m_materialAdapt); if (m_materialApply) DestroyImmediate(m_materialApply); } /// Apply the filter private void OnRenderImage(RenderTexture source, RenderTexture destination) { // Blit to smaller RT and convert to luminance on the way const int TEMP_RATIO = 1; // 4x4 smaller RenderTexture rtTempSrc = RenderTexture.GetTemporary(source.width/TEMP_RATIO, source.height/TEMP_RATIO); Graphics.Blit(source, rtTempSrc, materialLum); // Repeatedly reduce this image in size, computing min/max luminance values // In the end we'll have 1x1 image with min/max luminances found. const int FINAL_SIZE = 1; //const int FINAL_SIZE = 1; while (rtTempSrc.width > FINAL_SIZE || rtTempSrc.height > FINAL_SIZE) { const int REDUCE_RATIO = 2; // our shader does 2x2 reduction int destW = rtTempSrc.width/REDUCE_RATIO; if (destW < FINAL_SIZE) destW = FINAL_SIZE; int destH = rtTempSrc.height/REDUCE_RATIO; if (destH < FINAL_SIZE) destH = FINAL_SIZE; RenderTexture rtTempDst = RenderTexture.GetTemporary(destW, destH); Graphics.Blit(rtTempSrc, rtTempDst, materialReduce); // Release old src temporary, and make new temporary the source RenderTexture.ReleaseTemporary(rtTempSrc); rtTempSrc = rtTempDst; } // Update viewer's adaptation level CalculateAdaptation(rtTempSrc); // Apply contrast strech to the original scene, using currently adapted parameters materialApply.SetTexture("_AdaptTex", adaptRenderTex[curAdaptIndex]); Graphics.Blit(source, destination, materialApply); RenderTexture.ReleaseTemporary(rtTempSrc); } /// Helper function to do gradual adaptation to min/max luminances private void CalculateAdaptation(Texture curTexture) { int prevAdaptIndex = curAdaptIndex; curAdaptIndex = (curAdaptIndex + 1)%2; // Adaptation speed is expressed in percents/frame, based on 30FPS. // Calculate the adaptation lerp, based on current FPS. float adaptLerp = 1.0f - Mathf.Pow(1.0f - adaptationSpeed, 30.0f*Time.deltaTime); const float kMinAdaptLerp = 0.01f; adaptLerp = Mathf.Clamp(adaptLerp, kMinAdaptLerp, 1); materialAdapt.SetTexture("_CurTex", curTexture); materialAdapt.SetVector("_AdaptParams", new Vector4( adaptLerp, limitMinimum, limitMaximum, 0.0f )); Graphics.Blit( adaptRenderTex[prevAdaptIndex], adaptRenderTex[curAdaptIndex], materialAdapt); } } }
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // using System; using System.IO; using System.Text; using System.Diagnostics; using System.Collections.Generic; using Autodesk.Revit; using Autodesk.Revit.DB.Events; using Autodesk.Revit.DB; namespace Revit.SDK.Samples.PrintLog.CS { /// <summary> /// This class has four handler methods which will be subscribed to ViewPrint and DocumentPrint events separately, /// It contains other methods which are used to dump related information to log files. /// /// The handler methods will be used to dump designed information to log files when they are /// raised by Print operations(both UI and API). /// /// This class contains two log file handlers m_printLog and m_eventsLog, they will dump information /// to PrintLog.txt and PrintEventsLog.txt separately. /// PrintEventsLog.txt only contains the information of events, like events arguments and sequences. /// The PrintLog.txt contains all information of print, date time stamp and cost time of print are dumped especially. /// </summary> public sealed class EventsReactor { #region Class Member Variables /// <summary> /// This member will be used to reserve document and accordingly timers of current events. /// Because events are registered in controlled application, there are maybe more than one document. /// /// The int value is hash code of document, it's unique for each document. /// The events watches will reserve the start times of ViewPrint and DocumentPrint and then calculate the /// individual and total times for each view and all views. /// /// Note: /// How to identify document, maybe you want to use PathName or Title, but they don't work: /// . PathName is not accessible for newly created document, exception will thrown once you access it. /// . Title may be duplicated if two .rvt with same name were opened. /// /// Though Microsoft says hash code does not guarantee unique return values for different objects. /// (refer to http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx) /// In RevitAPI, hash code can be used for identifying document because API will guarantee the same /// and only one CLI object each time access them. /// </summary> private Dictionary<int, EventsWatches> m_docEventsWatches = null; /// <summary> /// This listener is used to print all required information to print log and it it'll be bound to log file PrintLog.txt. /// It will be added to Trace.Listeners. /// /// Detailed information of print, like: Printer name, views to-be-printed or printed, /// Print times of view and document, will be dumped to that log file. /// By this log file user can easily find the detailed information of print process. /// </summary> private TextWriterTraceListener m_printLog = null; /// <summary> /// This listener is used to monitor the events raising sequences and arguments of events. /// it will be bound to log file PrintEventsLog.txt, it will be added to Trace.Listeners. /// /// This log file will only contain information of event raising sequence, event arguments, etc. /// Any information which is related to time stamp won't be dumped to this file. /// /// This file can be used to check if events work well in different platforms, for example: /// By this sample, if user printed something, Revit journal will record all operation of users, /// meanwhile PrintEventsLog.txt will be generated. If user run the journal in other machine, user will get another /// PrintEventsLog.txt, by comparing the two files user can figure out easily if the two prints work equally. /// </summary> private TextWriterTraceListener m_eventsLog = null; /// <summary> /// Current assembly path /// </summary> String m_assemblyPath = null; #endregion #region Class Constructor Method /// <summary> /// Constructor method /// This method will only initialize the m_docEventsWatches and m_assemblyPath. /// Notice that this method won't open log files. /// </summary> public EventsReactor() { // Members initialization m_docEventsWatches = new Dictionary<int, EventsWatches>(); // // Get assembly path m_assemblyPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); } /// <summary> /// Close log files now /// </summary> public void CloseLogFiles() { // Flush trace and close it Trace.Flush(); Trace.Close(); // // Close listeners Trace.Flush(); if (null != m_printLog) { Trace.Listeners.Remove(m_printLog); m_printLog.Flush(); m_printLog.Close(); } if (null != m_eventsLog) { Trace.Listeners.Remove(m_eventsLog); m_eventsLog.Flush(); m_eventsLog.Close(); } } #endregion #region Class Handler Methods /// <summary> /// Handler method for DocumentPrinting event. /// This method will dump printer name, views to be printed and user name, etc. /// Besides, this handler will reserve the start time of whole print process. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void AppDocumentPrinting(object sender, Autodesk.Revit.DB.Events.DocumentPrintingEventArgs e) { // ensure log files are specified and dump header information SetupLogFiles(); // // Dump environment of print: user name, printer name and project title. DumpPrintEnv(System.Environment.UserName, e.Document.PrintManager.PrinterName, e.Document.Title); // // Start new watch for DocumentPrint Trace.WriteLine(System.Environment.NewLine + "Document Print Start: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); StartNewWatch(e.Document, false); // // Dump the events arguments DumpEventArguments(e); } /// <summary> /// Handler method for ViewPrinting event. /// This method will dump detailed information of view, like view type, id and start start time of print for this view. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void AppViewPrinting(object sender, Autodesk.Revit.DB.Events.ViewPrintingEventArgs e) { // header information Trace.WriteLine(System.Environment.NewLine + "View Print Start: -----------------------------------------------"); // // Start new watch for ViewPrint StartNewWatch(e.Document, true); // // Dump the events arguments DumpEventArguments(e); } /// <summary> /// Handler method for ViewPrinted event. /// This handler will dump information of printed view, like View name, type and end time of print. /// Besides, It will calculate cost time of print for this view. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void AppViewPrinted(object sender, Autodesk.Revit.DB.Events.ViewPrintedEventArgs e) { // header information Trace.WriteLine(System.Environment.NewLine + "View Print End: -------"); // // Stop watch and calculate the cost time StopWatch(e.Document, true); // // Dump the events arguments DumpEventArguments(e); } /// <summary> /// Handler method for DocumentPrinted event. /// This method will dump all views printed and failed views(if any), total for all print. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void AppDocumentPrinted(object sender, Autodesk.Revit.DB.Events.DocumentPrintedEventArgs e) { // header information Trace.WriteLine(System.Environment.NewLine + "Document Print End: <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"); // // Stop watch and calculate the cost time StopWatch(e.Document, false); // // Dump the events arguments DumpEventArguments(e); } #endregion #region Class Implementations /// <summary> /// For singleton consideration, setup log file only when events are raised. /// m_printLog and m_eventsLog will be initialized and added to Trace.Listeners /// PrintLog.txt and PrintEventsLog.txt will be removed if existed. /// </summary> private void SetupLogFiles() { // singleton consideration if (null != m_printLog && null != m_eventsLog) { return; } // // delete existed log files String printLogFile = Path.Combine(m_assemblyPath, "PrintLog.txt"); String printEventsLogFile = Path.Combine(m_assemblyPath, "PrintEventsLog.txt"); if (File.Exists(printLogFile)) { File.Delete(printLogFile); } if (File.Exists(printEventsLogFile)) { File.Delete(printEventsLogFile); } // // Create listeners and add to Trace.Listeners to monitor the string to be emitted m_printLog = new TextWriterTraceListener(printLogFile); m_eventsLog = new TextWriterTraceListener(printEventsLogFile); Trace.Listeners.Add(m_printLog); Trace.Listeners.Add(m_eventsLog); Trace.AutoFlush = true; // set auto flush to ensure the emitted string can be dumped in time } /// <summary> /// Start to dump current date/time and start watch count. /// </summary> /// <param name="curDoc">Current document.</param> /// <param name="isViewWatch">Indicates if current watch is for view or document. /// True means we need to start watch for ViewPrint, else start watch for DocumentPrint.</param> private void StartNewWatch(Document curDoc, bool isViewWatch) { // Just dump current date time to printlog.txt DumpDateTime("Start"); // // Start new watch for view print or document print EventsWatches watches; bool result = m_docEventsWatches.TryGetValue(curDoc.GetHashCode(), out watches); if (!result || null == watches) { watches = new EventsWatches(); m_docEventsWatches.Add(curDoc.GetHashCode(), watches); } // // Start watch for ViewPrint and DocumentPrint if (isViewWatch) { watches.ViewPrintWatch = Stopwatch.StartNew(); } else { watches.DocPrintWatch = Stopwatch.StartNew(); } } /// <summary> /// Stop watch for print and then calculate the time cost, /// Besides, it will dump current date time to PrintLog.txt. /// </summary> /// <param name="curDoc"></param> /// <param name="isViewWatch"></param> private void StopWatch(Document curDoc, bool isViewWatch) { // Just dump current date time to printlog.txt DumpDateTime("End"); // // Calculate the elapse time print for this view EventsWatches watches; bool result = m_docEventsWatches.TryGetValue(curDoc.GetHashCode(), out watches); if (!result) { Trace.Write("Failed to find the watch, time calculation is skipped."); return; } // // Dump the cost time to PrintLog.txt if (isViewWatch) { watches.ViewPrintWatch.Stop(); m_printLog.WriteLine(String.Format("Succeeded to print view, costs {0} ms.", watches.ViewPrintWatch.Elapsed.TotalMilliseconds)); } else { watches.DocPrintWatch.Stop(); m_printLog.WriteLine(String.Format("Succeeded to print document, totally costs {0} ms.", watches.DocPrintWatch.Elapsed.TotalMilliseconds)); } } /// <summary> /// Dump global environment of print: user, printer and project name. /// This only will be dumped to PrintLog.txt. /// </summary> /// <param name="user">User name who prints current document.</param> /// <param name="printer">Printer name.</param> /// <param name="projectName">Current document title.</param> private void DumpPrintEnv(String user, String printer, String projectName) { m_printLog.WriteLine("Start to Print.................................................."); m_printLog.WriteLine(">> Print user: " + user); m_printLog.WriteLine(">> Printer name: " + printer); m_printLog.WriteLine(">> Project name: " + projectName); } /// <summary> /// This method will dump date time to log file, but it will only dump to PrintLog.txt file. /// The date/time stamp should not be dumped to PrintEventsLog.txt. /// </summary> /// <param name="prefix">Prefix string to be dumped to log file.</param> private void DumpDateTime(string prefix) { // ensure log file has been specified SetupLogFiles(); m_printLog.WriteLine(String.Format("{0} Time: {1}", prefix, System.DateTime.Now.ToString())); } /// <summary> /// Dump the events arguments to log files: PrintLog.txt and PrintEventsLog.txt. /// This method will only dump EventArguments of ViewPrint and DocumentPrint, /// that's, 4 event arguments will be handled here: /// . DocumentPrintingEventArgs /// . DocumentPrintedEventArgs /// . ViewPrintingEventArgs /// . ViewPrintedEventArgs /// </summary> /// <param name="eventArgs">Event argument to be dumped. </param> private static void DumpEventArguments(RevitAPIEventArgs eventArgs) { // Dump parameters now: // white space is for align purpose. if (eventArgs.GetType().Equals(typeof(DocumentPrintingEventArgs))) { Trace.WriteLine("DocumentPrintingEventArgs Parameters ------>"); DocumentPrintingEventArgs args = eventArgs as DocumentPrintingEventArgs; Trace.WriteLine(" Event Cancellable : " + args.Cancellable); // cancellable Trace.WriteLine(" Views to be printed : "); // Views DumpViewsInfo(args.Document, args.GetViewElementIds(), " "); } else if (eventArgs.GetType().Equals(typeof(DocumentPrintedEventArgs))) { Trace.WriteLine("DocumentPrintedEventArgs Parameters ------>"); DocumentPrintedEventArgs args = eventArgs as DocumentPrintedEventArgs; Trace.WriteLine(" Event Status : " + args.Status.ToString()); // Status Trace.WriteLine(" Event Cancellable : " + args.Cancellable); // Cancellable // // PrintedViews IList<ElementId> ids = args.GetPrintedViewElementIds(); if (null == ids || 0 == ids.Count) { Trace.WriteLine(" Views been printed: <null>"); } else { Trace.WriteLine(" Views been printed: "); DumpViewsInfo(args.Document, ids, " "); } // // FailedViews ids = args.GetFailedViewElementIds(); if (null == ids || 0 == ids.Count) { Trace.WriteLine(" Views failed: <null>"); } else { Trace.WriteLine(" Views Failed : "); DumpViewsInfo(args.Document, ids, " "); } } else if (eventArgs.GetType().Equals(typeof(ViewPrintingEventArgs))) { Trace.WriteLine("ViewPrintingEventArgs Parameters ------>"); ViewPrintingEventArgs args = eventArgs as ViewPrintingEventArgs; Trace.WriteLine(" Event Cancellable : " + args.Cancellable); // Cancellable Trace.WriteLine(" TotalViews : " + args.TotalViews); // TotalViews Trace.WriteLine(" View Index : " + args.Index); // Index Trace.WriteLine(" View Information :"); // View DumpViewInfo(args.View, " "); } else if (eventArgs.GetType().Equals(typeof(ViewPrintedEventArgs))) { Trace.WriteLine("ViewPrintedEventArgs Parameters ------>"); ViewPrintedEventArgs args = eventArgs as ViewPrintedEventArgs; Trace.WriteLine(" Event Status : " + args.Status); // Cancellable Trace.WriteLine(" TotalViews : " + args.TotalViews); // TotalViews Trace.WriteLine(" View Index : " + args.Index); // Index Trace.WriteLine(" View Information :"); // View DumpViewInfo(args.View, " "); } else { // no handling for other argument } } /// <summary> /// Dump information of views: ViewType, Id and ViewName. /// The information will be dumped to both PrintLog.txt and PrintEventsLog.txt. /// </summary> /// <param name="Document">Current active document.</param> /// <param name="viewIds">Views to be dumped to log files.</param> /// <param name="prefix">Prefix mark for each line dumped to log files.</param> private static void DumpViewsInfo(Document activeDoc, IList<ElementId> viewIds, String prefix) { int index = 0; foreach (ElementId id in viewIds) { View curView = activeDoc.get_Element(id) as View; if (null != curView) { DumpViewInfo(curView, String.Format("{0}#{1}", prefix, index++)); } } } /// <summary> /// Dump information of single view: ViewType and ViewName. /// The information will be dumped to both PrintLog.txt and PrintEventsLog.txt. /// </summary> /// <param name="view">View element to be dumped to log files.</param> /// <param name="prefix">Prefix mark for each line dumped to log files.</param> private static void DumpViewInfo(View view, String prefix) { Trace.WriteLine(String.Format("{0} ViewName: {1}, ViewType: {2}", prefix, view.ViewName, view.ViewType)); } #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.Reflection; using System.Timers; using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using System.Text; using DirFindFlags = OpenMetaverse.DirectoryManager.DirFindFlags; namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "GroupsModule")] public class GroupsModule : ISharedRegionModule, IGroupsModule { /// <summary> /// ; To use this module, you must specify the following in your OpenSim.ini /// [GROUPS] /// Enabled = true /// /// Module = GroupsModule /// NoticesEnabled = true /// DebugEnabled = true /// /// GroupsServicesConnectorModule = XmlRpcGroupsServicesConnector /// XmlRpcServiceURL = http://osflotsam.org/xmlrpc.php /// XmlRpcServiceReadKey = 1234 /// XmlRpcServiceWriteKey = 1234 /// /// MessagingModule = GroupsMessagingModule /// MessagingEnabled = true /// /// ; Disables HTTP Keep-Alive for Groups Module HTTP Requests, work around for /// ; a problem discovered on some Windows based region servers. Only disable /// ; if you see a large number (dozens) of the following Exceptions: /// ; System.Net.WebException: The request was aborted: The request was canceled. /// /// XmlRpcDisableKeepAlive = false /// </summary> private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private List<Scene> m_sceneList = new List<Scene>(); private IMessageTransferModule m_msgTransferModule; private IGroupsMessagingModule m_groupsMessagingModule; private IGroupsServicesConnector m_groupData; // Configuration settings private bool m_groupsEnabled = false; private bool m_groupNoticesEnabled = true; private bool m_debugEnabled = false; private int m_levelGroupCreate = 0; #region Region Module interfaceBase Members public void Initialise(IConfigSource config) { IConfig groupsConfig = config.Configs["Groups"]; if (groupsConfig == null) { // Do not run this module by default. return; } else { m_groupsEnabled = groupsConfig.GetBoolean("Enabled", false); if (!m_groupsEnabled) { return; } if (groupsConfig.GetString("Module", "Default") != Name) { m_groupsEnabled = false; return; } m_log.InfoFormat("[GROUPS]: Initializing {0}", this.Name); m_groupNoticesEnabled = groupsConfig.GetBoolean("NoticesEnabled", true); m_debugEnabled = groupsConfig.GetBoolean("DebugEnabled", false); m_levelGroupCreate = groupsConfig.GetInt("LevelGroupCreate", 0); } } public void AddRegion(Scene scene) { if (m_groupsEnabled) { scene.RegisterModuleInterface<IGroupsModule>(this); scene.AddCommand( "Debug", this, "debug groups verbose", "debug groups verbose <true|false>", "This setting turns on very verbose groups debugging", HandleDebugGroupsVerbose); } } private void HandleDebugGroupsVerbose(object modules, string[] args) { if (args.Length < 4) { MainConsole.Instance.Output("Usage: debug groups verbose <true|false>"); return; } bool verbose = false; if (!bool.TryParse(args[3], out verbose)) { MainConsole.Instance.Output("Usage: debug groups verbose <true|false>"); return; } m_debugEnabled = verbose; MainConsole.Instance.OutputFormat("{0} verbose logging set to {1}", Name, m_debugEnabled); } public void RegionLoaded(Scene scene) { if (!m_groupsEnabled) return; if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); if (m_groupData == null) { m_groupData = scene.RequestModuleInterface<IGroupsServicesConnector>(); // No Groups Service Connector, then nothing works... if (m_groupData == null) { m_groupsEnabled = false; m_log.Error("[GROUPS]: Could not get IGroupsServicesConnector"); Close(); return; } } if (m_msgTransferModule == null) { m_msgTransferModule = scene.RequestModuleInterface<IMessageTransferModule>(); // No message transfer module, no notices, group invites, rejects, ejects, etc if (m_msgTransferModule == null) { m_groupsEnabled = false; m_log.Warn("[GROUPS]: Could not get IMessageTransferModule"); } } if (m_groupsMessagingModule == null) { m_groupsMessagingModule = scene.RequestModuleInterface<IGroupsMessagingModule>(); // No message transfer module, no notices, group invites, rejects, ejects, etc if (m_groupsMessagingModule == null) m_log.Warn("[GROUPS]: Could not get IGroupsMessagingModule"); } lock (m_sceneList) { m_sceneList.Add(scene); } scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnMakeRootAgent += OnMakeRoot; scene.EventManager.OnMakeChildAgent += OnMakeChild; scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage; scene.EventManager.OnClientClosed += OnClientClosed; } public void RemoveRegion(Scene scene) { if (!m_groupsEnabled) return; if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); scene.EventManager.OnNewClient -= OnNewClient; scene.EventManager.OnMakeRootAgent -= OnMakeRoot; scene.EventManager.OnMakeChildAgent -= OnMakeChild; scene.EventManager.OnIncomingInstantMessage -= OnGridInstantMessage; scene.EventManager.OnClientClosed -= OnClientClosed; if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); lock (m_sceneList) { m_sceneList.Remove(scene); } } public void Close() { if (!m_groupsEnabled) return; if (m_debugEnabled) m_log.Debug("[GROUPS]: Shutting down Groups module."); } public Type ReplaceableInterface { get { return null; } } public string Name { get { return "GroupsModule"; } } #endregion #region ISharedRegionModule Members public void PostInitialise() { // NoOp } #endregion #region EventHandlers private void OnMakeRoot(ScenePresence sp) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); sp.ControllingClient.OnUUIDGroupNameRequest += HandleUUIDGroupNameRequest; // Used for Notices and Group Invites/Accept/Reject sp.ControllingClient.OnInstantMessage += OnInstantMessage; // comented out because some viewers no longer suport it // sp.ControllingClient.AddGenericPacketHandler("avatargroupsrequest", AvatarGroupsRequest); // Send out group data update for compatibility. // There might be some problem with the thread we're generating this on but not // doing the update at this time causes problems (Mantis #7920 and #7915) // TODO: move sending this update to a later time in the rootification of the client. if(!sp.haveGroupInformation) SendAgentGroupDataUpdate(sp.ControllingClient, false); } private void OnMakeChild(ScenePresence sp) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); sp.ControllingClient.OnUUIDGroupNameRequest -= HandleUUIDGroupNameRequest; sp.ControllingClient.OnInstantMessage -= OnInstantMessage; } private void OnNewClient(IClientAPI client) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); client.OnAgentDataUpdateRequest += OnAgentDataUpdateRequest; client.OnRequestAvatarProperties += OnRequestAvatarProperties; } /* this should be the right message to ask for other avatars groups private void AvatarGroupsRequest(Object sender, string method, List<String> args) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); if (!(sender is IClientAPI)) return; IClientAPI remoteClient = (IClientAPI)sender; UUID avatarID; UUID.TryParse(args[0], out avatarID); if (avatarID != UUID.Zero) { GroupMembershipData[] avatarGroups = GetProfileListedGroupMemberships(remoteClient, avatarID); remoteClient.SendAvatarGroupsReply(avatarID, avatarGroups); } } */ // this should not be used to send groups memberships, but some viewers do expect it // it does send unnecessary memberships, when viewers just want other properties information private void OnRequestAvatarProperties(IClientAPI remoteClient, UUID avatarID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); GroupMembershipData[] avatarGroups = GetProfileListedGroupMemberships(remoteClient, avatarID); remoteClient.SendAvatarGroupsReply(avatarID, avatarGroups); } private void OnClientClosed(UUID AgentId, Scene scene) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); if (scene == null) return; ScenePresence sp = scene.GetScenePresence(AgentId); IClientAPI client = sp.ControllingClient; if (client != null) { client.OnAgentDataUpdateRequest -= OnAgentDataUpdateRequest; client.OnRequestAvatarProperties -= OnRequestAvatarProperties; // make child possible not called? client.OnUUIDGroupNameRequest -= HandleUUIDGroupNameRequest; client.OnInstantMessage -= OnInstantMessage; } /* lock (m_ActiveClients) { if (m_ActiveClients.ContainsKey(AgentId)) { IClientAPI client = m_ActiveClients[AgentId]; client.OnUUIDGroupNameRequest -= HandleUUIDGroupNameRequest; client.OnAgentDataUpdateRequest -= OnAgentDataUpdateRequest; client.OnDirFindQuery -= OnDirFindQuery; client.OnInstantMessage -= OnInstantMessage; m_ActiveClients.Remove(AgentId); } else { if (m_debugEnabled) m_log.WarnFormat("[GROUPS]: Client closed that wasn't registered here."); } } */ } private void OnAgentDataUpdateRequest(IClientAPI remoteClient, UUID dataForAgentID, UUID sessionID) { // this a private message for own agent only if (dataForAgentID != GetRequestingAgentID(remoteClient)) return; SendAgentGroupDataUpdate(remoteClient, false); // its a info request not a change, so nothing is sent to others // they do get the group title with the avatar object update on arrivel to a region } private void HandleUUIDGroupNameRequest(UUID GroupID, IClientAPI remoteClient) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); string GroupName; GroupRecord group = m_groupData.GetGroupRecord(GetRequestingAgentID(remoteClient), GroupID, null); if (group != null) { GroupName = group.GroupName; } else { GroupName = "Unknown"; } remoteClient.SendGroupNameReply(GroupID, GroupName); } private void OnInstantMessage(IClientAPI remoteClient, GridInstantMessage im) { if (m_debugEnabled) m_log.DebugFormat( "[GROUPS]: {0} called for {1}, message type {2}", System.Reflection.MethodBase.GetCurrentMethod().Name, remoteClient.Name, (InstantMessageDialog)im.dialog); // Group invitations if ((im.dialog == (byte)InstantMessageDialog.GroupInvitationAccept) || (im.dialog == (byte)InstantMessageDialog.GroupInvitationDecline)) { UUID inviteID = new UUID(im.imSessionID); GroupInviteInfo inviteInfo = m_groupData.GetAgentToGroupInvite(GetRequestingAgentID(remoteClient), inviteID); if (inviteInfo == null) { if (m_debugEnabled) m_log.WarnFormat("[GROUPS]: Received an Invite IM for an invite that does not exist {0}.", inviteID); return; } if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Invite is for Agent {0} to Group {1}.", inviteInfo.AgentID, inviteInfo.GroupID); UUID fromAgentID = new UUID(im.fromAgentID); if ((inviteInfo != null) && (fromAgentID == inviteInfo.AgentID)) { // Accept if (im.dialog == (byte)InstantMessageDialog.GroupInvitationAccept) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Received an accept invite notice."); // and the sessionid is the role m_groupData.AddAgentToGroup(GetRequestingAgentID(remoteClient), inviteInfo.AgentID, inviteInfo.GroupID, inviteInfo.RoleID); GridInstantMessage msg = new GridInstantMessage(); msg.imSessionID = UUID.Zero.Guid; msg.fromAgentID = UUID.Zero.Guid; msg.toAgentID = inviteInfo.AgentID.Guid; msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); msg.fromAgentName = "Groups"; msg.message = string.Format("You have been added to the group."); msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.MessageBox; msg.fromGroup = false; msg.offline = (byte)0; msg.ParentEstateID = 0; msg.Position = Vector3.Zero; msg.RegionID = UUID.Zero.Guid; msg.binaryBucket = new byte[0]; OutgoingInstantMessage(msg, inviteInfo.AgentID); IClientAPI inviteeClient = GetActiveRootClient(inviteInfo.AgentID); if(inviteeClient !=null) { SendAgentGroupDataUpdate(inviteeClient,true); } m_groupData.RemoveAgentToGroupInvite(GetRequestingAgentID(remoteClient), inviteID); } // Reject if (im.dialog == (byte)InstantMessageDialog.GroupInvitationDecline) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Received a reject invite notice."); m_groupData.RemoveAgentToGroupInvite(GetRequestingAgentID(remoteClient), inviteID); } } } // Group notices if ((im.dialog == (byte)InstantMessageDialog.GroupNotice)) { if (!m_groupNoticesEnabled) { return; } UUID GroupID = new UUID(im.toAgentID); if (m_groupData.GetGroupRecord(GetRequestingAgentID(remoteClient), GroupID, null) != null) { UUID NoticeID = UUID.Random(); string Subject = im.message.Substring(0, im.message.IndexOf('|')); string Message = im.message.Substring(Subject.Length + 1); InventoryItemBase item = null; bool hasAttachment = false; UUID itemID = UUID.Zero; //Assignment to quiet compiler UUID ownerID = UUID.Zero; //Assignment to quiet compiler byte[] bucket; if (im.binaryBucket.Length >= 1 && im.binaryBucket[0] > 0) { string binBucket = OpenMetaverse.Utils.BytesToString(im.binaryBucket); binBucket = binBucket.Remove(0, 14).Trim(); OSDMap binBucketOSD = (OSDMap)OSDParser.DeserializeLLSDXml(binBucket); if (binBucketOSD is OSD) { OSDMap binBucketMap = (OSDMap)binBucketOSD; itemID = binBucketMap["item_id"].AsUUID(); ownerID = binBucketMap["owner_id"].AsUUID(); //Attempt to get the details of the attached item. //If sender doesn't own the attachment, the item //variable will be set to null and attachment will //not be included with the group notice. Scene scene = (Scene)remoteClient.Scene; item = scene.InventoryService.GetItem(ownerID, itemID); if (item != null) { //Got item details so include the attachment. hasAttachment = true; } } else { m_log.DebugFormat("[Groups]: Received OSD with unexpected type: {0}", binBucketOSD.GetType()); } } if (hasAttachment) { //Bucket contains information about attachment. // //Byte offset and description of bucket data: //0: 1 byte indicating if attachment is present //1: 1 byte indicating the type of attachment //2: 16 bytes - Group UUID //18: 16 bytes - UUID of the attachment owner //34: 16 bytes - UUID of the attachment //50: variable - Name of the attachment //??: NUL byte to terminate the attachment name byte[] name = Encoding.UTF8.GetBytes(item.Name); bucket = new byte[51 + name.Length];//3 bytes, 3 UUIDs, and name bucket[0] = 1; //Has attachment flag bucket[1] = (byte)item.InvType; //Type of Attachment GroupID.ToBytes(bucket, 2); ownerID.ToBytes(bucket, 18); itemID.ToBytes(bucket, 34); name.CopyTo(bucket, 50); } else { bucket = new byte[19]; bucket[0] = 0; //Has attachment flag bucket[1] = 0; //Type of attachment GroupID.ToBytes(bucket, 2); bucket[18] = 0; //NUL terminate name of attachment } m_groupData.AddGroupNotice(GetRequestingAgentID(remoteClient), GroupID, NoticeID, im.fromAgentName, Subject, Message, bucket); if (OnNewGroupNotice != null) { OnNewGroupNotice(GroupID, NoticeID); } if (m_debugEnabled) { foreach (GroupMembersData member in m_groupData.GetGroupMembers(GetRequestingAgentID(remoteClient), GroupID)) { if (m_debugEnabled) { UserAccount targetUser = m_sceneList[0].UserAccountService.GetUserAccount( remoteClient.Scene.RegionInfo.ScopeID, member.AgentID); if (targetUser != null) { m_log.DebugFormat( "[GROUPS]: Prepping group notice {0} for agent: {1} who Accepts Notices ({2})", NoticeID, targetUser.FirstName + " " + targetUser.LastName, member.AcceptNotices); } else { m_log.DebugFormat( "[GROUPS]: Prepping group notice {0} for agent: {1} who Accepts Notices ({2})", NoticeID, member.AgentID, member.AcceptNotices); } } } } GridInstantMessage msg = CreateGroupNoticeIM(UUID.Zero, NoticeID, (byte)OpenMetaverse.InstantMessageDialog.GroupNotice); if (m_groupsMessagingModule != null) m_groupsMessagingModule.SendMessageToGroup( msg, GroupID, remoteClient.AgentId, gmd => gmd.AcceptNotices); } } if (im.dialog == (byte)InstantMessageDialog.GroupNoticeInventoryAccepted) { //Is bucket large enough to hold UUID of the attachment? if (im.binaryBucket.Length < 16) return; UUID noticeID = new UUID(im.imSessionID); if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Requesting notice {0} for {1}", noticeID, remoteClient.AgentId); GroupNoticeInfo notice = m_groupData.GetGroupNotice(GetRequestingAgentID(remoteClient), noticeID); if (notice != null) { UUID giver = new UUID(notice.BinaryBucket, 18); UUID attachmentUUID = new UUID(notice.BinaryBucket, 34); if (m_debugEnabled) m_log.DebugFormat("[Groups]: Giving inventory from {0} to {1}", giver, remoteClient.AgentId); string message; InventoryItemBase itemCopy = ((Scene)(remoteClient.Scene)).GiveInventoryItem(remoteClient.AgentId, giver, attachmentUUID, out message); if (itemCopy == null) { remoteClient.SendAgentAlertMessage(message, false); return; } remoteClient.SendInventoryItemCreateUpdate(itemCopy, 0); } else { if (m_debugEnabled) m_log.DebugFormat( "[GROUPS]: Could not find notice {0} for {1} on GroupNoticeInventoryAccepted.", noticeID, remoteClient.AgentId); } } // Interop, received special 210 code for ejecting a group member // this only works within the comms servers domain, and won't work hypergrid // TODO:FIXME: Use a presence server of some kind to find out where the // client actually is, and try contacting that region directly to notify them, // or provide the notification via xmlrpc update queue if ((im.dialog == 210)) { // This is sent from the region that the ejectee was ejected from // if it's being delivered here, then the ejectee is here // so we need to send local updates to the agent. UUID ejecteeID = new UUID(im.toAgentID); im.imSessionID = UUID.Zero.Guid; im.dialog = (byte)InstantMessageDialog.MessageFromAgent; OutgoingInstantMessage(im, ejecteeID); IClientAPI ejectee = GetActiveRootClient(ejecteeID); if (ejectee != null) { UUID groupID = new UUID(im.imSessionID); ejectee.SendAgentDropGroup(groupID); SendAgentGroupDataUpdate(ejectee,true); } } } private void OnGridInstantMessage(GridInstantMessage msg) { if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Trigger the above event handler OnInstantMessage(null, msg); // If a message from a group arrives here, it may need to be forwarded to a local client if (msg.fromGroup == true) { switch (msg.dialog) { case (byte)InstantMessageDialog.GroupInvitation: case (byte)InstantMessageDialog.GroupNotice: UUID toAgentID = new UUID(msg.toAgentID); IClientAPI localClient = GetActiveRootClient(toAgentID); if (localClient != null) { localClient.SendInstantMessage(msg); } break; } } } #endregion #region IGroupsModule Members public event NewGroupNotice OnNewGroupNotice; public GroupRecord GetGroupRecord(UUID GroupID) { return m_groupData.GetGroupRecord(UUID.Zero, GroupID, null); } public GroupRecord GetGroupRecord(string name) { return m_groupData.GetGroupRecord(UUID.Zero, UUID.Zero, name); } public void ActivateGroup(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); UUID agentID = GetRequestingAgentID(remoteClient); m_groupData.SetAgentActiveGroup(agentID, agentID, groupID); // llClientView does this SendAgentGroupDataUpdate(remoteClient, true); } /// <summary> /// Get the Role Titles for an Agent, for a specific group /// </summary> public List<GroupTitlesData> GroupTitlesRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); List<GroupRolesData> agentRoles = m_groupData.GetAgentGroupRoles(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID); GroupMembershipData agentMembership = m_groupData.GetAgentGroupMembership(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID); List<GroupTitlesData> titles = new List<GroupTitlesData>(); foreach (GroupRolesData role in agentRoles) { GroupTitlesData title = new GroupTitlesData(); title.Name = role.Name; if (agentMembership != null) { title.Selected = agentMembership.ActiveRole == role.RoleID; } title.UUID = role.RoleID; titles.Add(title); } return titles; } public List<GroupMembersData> GroupMembersRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat( "[GROUPS]: GroupMembersRequest called for {0} from client {1}", groupID, remoteClient.Name); List<GroupMembersData> data = m_groupData.GetGroupMembers(GetRequestingAgentID(remoteClient), groupID); if (m_debugEnabled) { foreach (GroupMembersData member in data) { m_log.DebugFormat("[GROUPS]: Member({0}) - IsOwner({1})", member.AgentID, member.IsOwner); } } return data; } public List<GroupRolesData> GroupRoleDataRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); List<GroupRolesData> data = m_groupData.GetGroupRoles(GetRequestingAgentID(remoteClient), groupID); return data; } public List<GroupRoleMembersData> GroupRoleMembersRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); List<GroupRoleMembersData> data = m_groupData.GetGroupRoleMembers(GetRequestingAgentID(remoteClient), groupID); if (m_debugEnabled) { foreach (GroupRoleMembersData member in data) { m_log.DebugFormat("[GROUPS]: Member({0}) - Role({1})", member.MemberID, member.RoleID); } } return data; } public GroupProfileData GroupProfileRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); GroupProfileData profile = new GroupProfileData(); GroupRecord groupInfo = m_groupData.GetGroupRecord(GetRequestingAgentID(remoteClient), groupID, null); if (groupInfo != null) { profile.AllowPublish = groupInfo.AllowPublish; profile.Charter = groupInfo.Charter; profile.FounderID = groupInfo.FounderID; profile.GroupID = groupID; profile.GroupMembershipCount = m_groupData.GetGroupMembers(GetRequestingAgentID(remoteClient), groupID).Count; profile.GroupRolesCount = m_groupData.GetGroupRoles(GetRequestingAgentID(remoteClient), groupID).Count; profile.InsigniaID = groupInfo.GroupPicture; profile.MaturePublish = groupInfo.MaturePublish; profile.MembershipFee = groupInfo.MembershipFee; profile.Money = 0; // TODO: Get this from the currency server? profile.Name = groupInfo.GroupName; profile.OpenEnrollment = groupInfo.OpenEnrollment; profile.OwnerRole = groupInfo.OwnerRoleID; profile.ShowInList = groupInfo.ShowInList; } GroupMembershipData memberInfo = m_groupData.GetAgentGroupMembership(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID); if (memberInfo != null) { profile.MemberTitle = memberInfo.GroupTitle; profile.PowersMask = memberInfo.GroupPowers; } /* this should save xmlrpc calls, but seems to return wrong GroupMembershipCount and GroupRolesCount UUID agent = GetRequestingAgentID(remoteClient); GroupProfileData profile = m_groupData.GetMemberGroupProfile(agent, groupID, agent); */ return profile; } public GroupMembershipData[] GetMembershipData(UUID agentID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); return m_groupData.GetAgentGroupMemberships(UUID.Zero, agentID).ToArray(); } public GroupMembershipData GetMembershipData(UUID groupID, UUID agentID) { if (m_debugEnabled) m_log.DebugFormat( "[GROUPS]: {0} called with groupID={1}, agentID={2}", System.Reflection.MethodBase.GetCurrentMethod().Name, groupID, agentID); return m_groupData.GetAgentGroupMembership(UUID.Zero, agentID, groupID); } public GroupMembershipData GetActiveMembershipData(UUID agentID) { return m_groupData.GetAgentActiveMembership(agentID, agentID); } public void UpdateGroupInfo(IClientAPI remoteClient, UUID groupID, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Note: Permissions checking for modification rights is handled by the Groups Server/Service m_groupData.UpdateGroup(GetRequestingAgentID(remoteClient), groupID, charter, showInList, insigniaID, membershipFee, openEnrollment, allowPublish, maturePublish); } public void SetGroupAcceptNotices(IClientAPI remoteClient, UUID groupID, bool acceptNotices, bool listInProfile) { // Note: Permissions checking for modification rights is handled by the Groups Server/Service if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); m_groupData.SetAgentGroupInfo(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID, acceptNotices, listInProfile); } public UUID CreateGroup(IClientAPI remoteClient, string name, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); GroupRecord groupRecord = m_groupData.GetGroupRecord(GetRequestingAgentID(remoteClient), UUID.Zero, name); if (groupRecord != null) { remoteClient.SendCreateGroupReply(UUID.Zero, false, "A group with the same name already exists."); return UUID.Zero; } // check user level ScenePresence avatar = null; Scene scene = (Scene)remoteClient.Scene; scene.TryGetScenePresence(remoteClient.AgentId, out avatar); if (avatar != null) { if (avatar.GodController.UserLevel < m_levelGroupCreate) { remoteClient.SendCreateGroupReply(UUID.Zero, false, "You have insufficient permissions to create a group."); return UUID.Zero; } } // check funds // is there a money module present ? IMoneyModule money = scene.RequestModuleInterface<IMoneyModule>(); if (money != null && money.GroupCreationCharge > 0) { // do the transaction, that is if the agent has sufficient funds if (!money.AmountCovered(remoteClient.AgentId, money.GroupCreationCharge)) { remoteClient.SendCreateGroupReply(UUID.Zero, false, "You have insufficient funds to create a group."); return UUID.Zero; } money.ApplyCharge(GetRequestingAgentID(remoteClient), money.GroupCreationCharge, MoneyTransactionType.GroupCreate, name); } UUID groupID = m_groupData.CreateGroup(GetRequestingAgentID(remoteClient), name, charter, showInList, insigniaID, membershipFee, openEnrollment, allowPublish, maturePublish, GetRequestingAgentID(remoteClient)); remoteClient.SendCreateGroupReply(groupID, true, "Group created successfully"); // Update the founder with new group information. SendAgentGroupDataUpdate(remoteClient, true); return groupID; } public GroupNoticeData[] GroupNoticesListRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // ToDo: check if agent is a member of group and is allowed to see notices? return m_groupData.GetGroupNotices(GetRequestingAgentID(remoteClient), groupID).ToArray(); } /// <summary> /// Get the title of the agent's current role. /// </summary> public string GetGroupTitle(UUID avatarID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); GroupMembershipData membership = m_groupData.GetAgentActiveMembership(UUID.Zero, avatarID); if (membership != null) { return membership.GroupTitle; } return string.Empty; } /// <summary> /// Change the current Active Group Role for Agent /// </summary> public void GroupTitleUpdate(IClientAPI remoteClient, UUID groupID, UUID titleRoleID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); m_groupData.SetAgentActiveGroupRole(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID, titleRoleID); // TODO: Not sure what all is needed here, but if the active group role change is for the group // the client currently has set active, then we need to do a scene presence update too // if (m_groupData.GetAgentActiveMembership(GetRequestingAgentID(remoteClient)).GroupID == GroupID) SendDataUpdate(remoteClient, true); } public void GroupRoleUpdate(IClientAPI remoteClient, UUID groupID, UUID roleID, string name, string description, string title, ulong powers, byte updateType) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Security Checks are handled in the Groups Service. switch ((OpenMetaverse.GroupRoleUpdate)updateType) { case OpenMetaverse.GroupRoleUpdate.Create: m_groupData.AddGroupRole(GetRequestingAgentID(remoteClient), groupID, UUID.Random(), name, description, title, powers); break; case OpenMetaverse.GroupRoleUpdate.Delete: m_groupData.RemoveGroupRole(GetRequestingAgentID(remoteClient), groupID, roleID); break; case OpenMetaverse.GroupRoleUpdate.UpdateAll: case OpenMetaverse.GroupRoleUpdate.UpdateData: case OpenMetaverse.GroupRoleUpdate.UpdatePowers: if (m_debugEnabled) { GroupPowers gp = (GroupPowers)powers; m_log.DebugFormat("[GROUPS]: Role ({0}) updated with Powers ({1}) ({2})", name, powers.ToString(), gp.ToString()); } m_groupData.UpdateGroupRole(GetRequestingAgentID(remoteClient), groupID, roleID, name, description, title, powers); break; case OpenMetaverse.GroupRoleUpdate.NoUpdate: default: // No Op break; } // TODO: This update really should send out updates for everyone in the role that just got changed. SendAgentGroupDataUpdate(remoteClient, false); } public void GroupRoleChanges(IClientAPI remoteClient, UUID groupID, UUID roleID, UUID memberID, uint changes) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Todo: Security check switch (changes) { case 0: // Add m_groupData.AddAgentToGroupRole(GetRequestingAgentID(remoteClient), memberID, groupID, roleID); break; case 1: // Remove m_groupData.RemoveAgentFromGroupRole(GetRequestingAgentID(remoteClient), memberID, groupID, roleID); break; default: m_log.ErrorFormat("[GROUPS]: {0} does not understand changes == {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, changes); break; } // TODO: This update really should send out updates for everyone in the role that just got changed. SendAgentGroupDataUpdate(remoteClient, false); } public void GroupNoticeRequest(IClientAPI remoteClient, UUID groupNoticeID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); GroupNoticeInfo data = m_groupData.GetGroupNotice(GetRequestingAgentID(remoteClient), groupNoticeID); if (data != null) { GridInstantMessage msg = CreateGroupNoticeIM(remoteClient.AgentId, groupNoticeID, (byte)InstantMessageDialog.GroupNoticeRequested); OutgoingInstantMessage(msg, GetRequestingAgentID(remoteClient)); } } public GridInstantMessage CreateGroupNoticeIM(UUID agentID, UUID groupNoticeID, byte dialog) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); GridInstantMessage msg = new GridInstantMessage(); byte[] bucket; msg.imSessionID = groupNoticeID.Guid; msg.toAgentID = agentID.Guid; msg.dialog = dialog; msg.fromGroup = true; msg.offline = (byte)1; // Allow this message to be stored for offline use msg.ParentEstateID = 0; msg.Position = Vector3.Zero; msg.RegionID = UUID.Zero.Guid; GroupNoticeInfo info = m_groupData.GetGroupNotice(agentID, groupNoticeID); if (info != null) { msg.fromAgentID = info.GroupID.Guid; msg.timestamp = info.noticeData.Timestamp; msg.fromAgentName = info.noticeData.FromName; msg.message = info.noticeData.Subject + "|" + info.Message; if (info.BinaryBucket[0] > 0) { //32 is due to not needing space for two of the UUIDs. //(Don't need UUID of attachment or its owner in IM) //50 offset gets us to start of attachment name. //We are skipping the attachment flag, type, and //the three UUID fields at the start of the bucket. bucket = new byte[info.BinaryBucket.Length-32]; bucket[0] = 1; //Has attachment bucket[1] = info.BinaryBucket[1]; Array.Copy(info.BinaryBucket, 50, bucket, 18, info.BinaryBucket.Length-50); } else { bucket = new byte[19]; bucket[0] = 0; //No attachment bucket[1] = 0; //Attachment type bucket[18] = 0; //NUL terminate name } info.GroupID.ToBytes(bucket, 2); msg.binaryBucket = bucket; } else { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Group Notice {0} not found, composing empty message.", groupNoticeID); msg.fromAgentID = UUID.Zero.Guid; msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); msg.fromAgentName = string.Empty; msg.message = string.Empty; msg.binaryBucket = new byte[0]; } return msg; } public void JoinGroupRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Should check to see if OpenEnrollment, or if there's an outstanding invitation m_groupData.AddAgentToGroup(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID, UUID.Zero); // check funds // is there a money module present ? GroupRecord groupRecord = m_groupData.GetGroupRecord(GetRequestingAgentID(remoteClient), groupID, null); IMoneyModule money = remoteClient.Scene.RequestModuleInterface<IMoneyModule>(); if (money != null && groupRecord.MembershipFee > 0) { // do the transaction, that is if the agent has sufficient funds if (!money.AmountCovered(GetRequestingAgentID(remoteClient), groupRecord.MembershipFee)) { remoteClient.SendCreateGroupReply(UUID.Zero, false, "You have insufficient funds to join the group."); return; } money.ApplyCharge(GetRequestingAgentID(remoteClient), groupRecord.MembershipFee, MoneyTransactionType.GroupJoin, groupRecord.GroupName); } remoteClient.SendJoinGroupReply(groupID, true); SendAgentGroupDataUpdate(remoteClient, true); } public void LeaveGroupRequest(IClientAPI remoteClient, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); m_groupData.RemoveAgentFromGroup(GetRequestingAgentID(remoteClient), GetRequestingAgentID(remoteClient), groupID); remoteClient.SendLeaveGroupReply(groupID, true); remoteClient.SendAgentDropGroup(groupID); // SL sends out notifcations to the group messaging session that the person has left // Should this also update everyone who is in the group? SendAgentGroupDataUpdate(remoteClient, true); } public void EjectGroupMemberRequest(IClientAPI remoteClient, UUID groupID, UUID ejecteeID) { EjectGroupMember(remoteClient, GetRequestingAgentID(remoteClient), groupID, ejecteeID); } public void EjectGroupMember(IClientAPI remoteClient, UUID agentID, UUID groupID, UUID ejecteeID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Todo: Security check? m_groupData.RemoveAgentFromGroup(agentID, ejecteeID, groupID); string agentName; RegionInfo regionInfo; // remoteClient provided or just agentID? if (remoteClient != null) { agentName = remoteClient.Name; regionInfo = remoteClient.Scene.RegionInfo; remoteClient.SendEjectGroupMemberReply(agentID, groupID, true); } else { IClientAPI client = GetActiveClient(agentID); if (client != null) { agentName = client.Name; regionInfo = client.Scene.RegionInfo; client.SendEjectGroupMemberReply(agentID, groupID, true); } else { regionInfo = m_sceneList[0].RegionInfo; UserAccount acc = m_sceneList[0].UserAccountService.GetUserAccount(regionInfo.ScopeID, agentID); if (acc != null) { agentName = acc.FirstName + " " + acc.LastName; } else { agentName = "Unknown member"; } } } GroupRecord groupInfo = m_groupData.GetGroupRecord(agentID, groupID, null); if (groupInfo == null) return; IClientAPI ejecteeClient = GetActiveRootClient(ejecteeID); // Send Message to Ejectee GridInstantMessage msg = new GridInstantMessage(); string ejecteeName = "Unknown member"; // if local send a normal message if(ejecteeClient != null) { msg.imSessionID = UUID.Zero.Guid; msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.MessageFromAgent; // also execute and send update ejecteeClient.SendAgentDropGroup(groupID); SendAgentGroupDataUpdate(ejecteeClient,true); ejecteeName = ejecteeClient.Name; } else // send { // Interop, received special 210 code for ejecting a group member // this only works within the comms servers domain, and won't work hypergrid // TODO:FIXME: Use a presence server of some kind to find out where the // client actually is, and try contacting that region directly to notify them, // or provide the notification via xmlrpc update queue msg.imSessionID = groupInfo.GroupID.Guid; msg.dialog = (byte)210; //interop UserAccount account = m_sceneList[0].UserAccountService.GetUserAccount(regionInfo.ScopeID, ejecteeID); if (account != null) ejecteeName = account.FirstName + " " + account.LastName; } msg.fromAgentID = agentID.Guid; // msg.fromAgentID = info.GroupID; msg.toAgentID = ejecteeID.Guid; //msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); msg.timestamp = 0; msg.fromAgentName = agentName; msg.message = string.Format("You have been ejected from '{1}' by {0}.", agentName, groupInfo.GroupName); // msg.fromGroup = false; msg.offline = (byte)0; msg.ParentEstateID = 0; msg.Position = Vector3.Zero; msg.RegionID = regionInfo.RegionID.Guid; msg.binaryBucket = new byte[0]; OutgoingInstantMessage(msg, ejecteeID); // Message to ejector msg = new GridInstantMessage(); msg.imSessionID = UUID.Zero.Guid; msg.fromAgentID = agentID.Guid; msg.toAgentID = agentID.Guid; msg.timestamp = 0; msg.fromAgentName = agentName; msg.message = string.Format("{2} has been ejected from '{1}' by {0}.", agentName, groupInfo.GroupName, ejecteeName); // msg.dialog = (byte)210; //interop msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.MessageFromAgent; msg.fromGroup = false; msg.offline = (byte)0; msg.ParentEstateID = 0; msg.Position = Vector3.Zero; msg.RegionID = regionInfo.RegionID.Guid; msg.binaryBucket = new byte[0]; OutgoingInstantMessage(msg, agentID); } public void InviteGroupRequest(IClientAPI remoteClient, UUID groupID, UUID invitedAgentID, UUID roleID) { InviteGroup(remoteClient, GetRequestingAgentID(remoteClient), groupID, invitedAgentID, roleID); } public void InviteGroup(IClientAPI remoteClient, UUID agentID, UUID groupID, UUID invitedAgentID, UUID roleID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); string agentName; RegionInfo regionInfo; // remoteClient provided or just agentID? if (remoteClient != null) { agentName = remoteClient.Name; regionInfo = remoteClient.Scene.RegionInfo; } else { IClientAPI client = GetActiveClient(agentID); if (client != null) { agentName = client.Name; regionInfo = client.Scene.RegionInfo; } else { regionInfo = m_sceneList[0].RegionInfo; UserAccount account = m_sceneList[0].UserAccountService.GetUserAccount(regionInfo.ScopeID, agentID); if (account != null) { agentName = account.FirstName + " " + account.LastName; } else { agentName = "Unknown member"; } } } // Todo: Security check, probably also want to send some kind of notification UUID InviteID = UUID.Random(); m_groupData.AddAgentToGroupInvite(agentID, InviteID, groupID, roleID, invitedAgentID); // Check to see if the invite went through, if it did not then it's possible // the remoteClient did not validate or did not have permission to invite. GroupInviteInfo inviteInfo = m_groupData.GetAgentToGroupInvite(agentID, InviteID); if (inviteInfo != null) { if (m_msgTransferModule != null) { Guid inviteUUID = InviteID.Guid; GridInstantMessage msg = new GridInstantMessage(); msg.imSessionID = inviteUUID; // msg.fromAgentID = agentID.Guid; msg.fromAgentID = groupID.Guid; msg.toAgentID = invitedAgentID.Guid; //msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); msg.timestamp = 0; msg.fromAgentName = agentName; msg.message = string.Format("{0} has invited you to join a group. There is no cost to join this group.", agentName); msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.GroupInvitation; msg.fromGroup = true; msg.offline = (byte)0; msg.ParentEstateID = 0; msg.Position = Vector3.Zero; msg.RegionID = regionInfo.RegionID.Guid; msg.binaryBucket = new byte[20]; OutgoingInstantMessage(msg, invitedAgentID); } } } public List<DirGroupsReplyData> FindGroups(IClientAPI remoteClient, string query) { return m_groupData.FindGroups(GetRequestingAgentID(remoteClient), query); } #endregion #region Client/Update Tools private IClientAPI GetActiveRootClient(UUID agentID) { foreach (Scene scene in m_sceneList) { ScenePresence sp = scene.GetScenePresence(agentID); if (sp != null && !sp.IsChildAgent && !sp.IsDeleted) { return sp.ControllingClient; } } return null; } /// <summary> /// Try to find an active IClientAPI reference for agentID giving preference to root connections /// </summary> private IClientAPI GetActiveClient(UUID agentID) { IClientAPI child = null; // Try root avatar first foreach (Scene scene in m_sceneList) { ScenePresence sp = scene.GetScenePresence(agentID); if (sp != null && !sp.IsDeleted) { if (!sp.IsChildAgent) { return sp.ControllingClient; } else { child = sp.ControllingClient; } } } // If we didn't find a root, then just return whichever child we found, or null if none return child; } private void SendScenePresenceUpdate(UUID AgentID, string Title) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Updating scene title for {0} with title: {1}", AgentID, Title); ScenePresence presence = null; foreach (Scene scene in m_sceneList) { presence = scene.GetScenePresence(AgentID); if (presence != null) { if (presence.Grouptitle != Title) { presence.Grouptitle = Title; if (! presence.IsChildAgent) presence.SendAvatarDataToAllAgents(); } } } } public void SendAgentGroupDataUpdate(IClientAPI remoteClient) { SendAgentGroupDataUpdate(remoteClient, true); } /// <summary> /// Tell remoteClient about its agent groups, and optionally send title to others /// </summary> private void SendAgentGroupDataUpdate(IClientAPI remoteClient, bool tellOthers) { if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: {0} called for {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, remoteClient.Name); // NPCs currently don't have a CAPs structure or event queues. There is a strong argument for conveying this information // to them anyway since it makes writing server-side bots a lot easier, but for now we don't do anything. if (remoteClient.SceneAgent.PresenceType == PresenceType.Npc) return; // TODO: All the client update functions need to be reexamined because most do too much and send too much stuff UUID agentID = GetRequestingAgentID(remoteClient); SendDataUpdate(remoteClient, tellOthers); GroupMembershipData[] membershipArray = GetProfileListedGroupMemberships(remoteClient, agentID); remoteClient.UpdateGroupMembership(membershipArray); remoteClient.SendAgentGroupDataUpdate(agentID, membershipArray); } /// <summary> /// Get a list of groups memberships for the agent that are marked "ListInProfile" /// (unless that agent has a godLike aspect, in which case get all groups) /// </summary> /// <param name="dataForAgentID"></param> /// <returns></returns> private GroupMembershipData[] GetProfileListedGroupMemberships(IClientAPI requestingClient, UUID dataForAgentID) { List<GroupMembershipData> membershipData = m_groupData.GetAgentGroupMemberships(requestingClient.AgentId, dataForAgentID); GroupMembershipData[] membershipArray; // cScene and property accessor 'isGod' are in support of the opertions to bypass 'hidden' group attributes for // those with a GodLike aspect. Scene cScene = (Scene)requestingClient.Scene; bool isGod = cScene.Permissions.IsGod(requestingClient.AgentId); if (isGod) { membershipArray = membershipData.ToArray(); } else { if (requestingClient.AgentId != dataForAgentID) { Predicate<GroupMembershipData> showInProfile = delegate(GroupMembershipData membership) { return membership.ListInProfile; }; membershipArray = membershipData.FindAll(showInProfile).ToArray(); } else { membershipArray = membershipData.ToArray(); } } if (m_debugEnabled) { m_log.InfoFormat("[GROUPS]: Get group membership information for {0} requested by {1}", dataForAgentID, requestingClient.AgentId); foreach (GroupMembershipData membership in membershipArray) { m_log.InfoFormat("[GROUPS]: {0} :: {1} - {2} - {3}", dataForAgentID, membership.GroupName, membership.GroupTitle, membership.GroupPowers); } } return membershipArray; } //tell remoteClient about its agent group info, and optionally send title to others private void SendDataUpdate(IClientAPI remoteClient, bool tellOthers) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); UUID activeGroupID = UUID.Zero; string activeGroupTitle = string.Empty; string activeGroupName = string.Empty; ulong activeGroupPowers = (ulong)GroupPowers.None; UUID agentID = GetRequestingAgentID(remoteClient); GroupMembershipData membership = m_groupData.GetAgentActiveMembership(agentID, agentID); if (membership != null) { activeGroupID = membership.GroupID; activeGroupTitle = membership.GroupTitle; activeGroupPowers = membership.GroupPowers; activeGroupName = membership.GroupName; } UserAccount account = m_sceneList[0].UserAccountService.GetUserAccount(remoteClient.Scene.RegionInfo.ScopeID, agentID); string firstname, lastname; if (account != null) { firstname = account.FirstName; lastname = account.LastName; } else { firstname = "Unknown"; lastname = "Unknown"; } remoteClient.SendAgentDataUpdate(agentID, activeGroupID, firstname, lastname, activeGroupPowers, activeGroupName, activeGroupTitle); if (tellOthers) SendScenePresenceUpdate(agentID, activeGroupTitle); ScenePresence sp = (ScenePresence)remoteClient.SceneAgent; if (sp != null) sp.Grouptitle = activeGroupTitle; } #endregion #region IM Backed Processes private void OutgoingInstantMessage(GridInstantMessage msg, UUID msgTo) { if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); IClientAPI localClient = GetActiveRootClient(msgTo); if (localClient != null) { if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: MsgTo ({0}) is local, delivering directly", localClient.Name); localClient.SendInstantMessage(msg); } else if (m_msgTransferModule != null) { if (m_debugEnabled) m_log.InfoFormat("[GROUPS]: MsgTo ({0}) is not local, delivering via TransferModule", msgTo); m_msgTransferModule.SendInstantMessage(msg, delegate(bool success) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS]: Message Sent: {0}", success?"Succeeded":"Failed"); }); } } public void NotifyChange(UUID groupID) { // Notify all group members of a chnge in group roles and/or // permissions // } #endregion private UUID GetRequestingAgentID(IClientAPI client) { UUID requestingAgentID = UUID.Zero; if (client != null) { requestingAgentID = client.AgentId; } return requestingAgentID; } } public class GroupNoticeInfo { public GroupNoticeData noticeData = new GroupNoticeData(); public UUID GroupID = UUID.Zero; public string Message = string.Empty; public byte[] BinaryBucket = new byte[0]; } }
using UnityEngine; using System.Collections; using System.Collections.Generic; /// <summary> /// Will store animation data in the form of one of more <see cref="OTAnimationFrameset" />s. /// </summary> [ExecuteInEditMode] public class OTAnimation : MonoBehaviour { /// <exclude /> public string _name = ""; /// <exclude /> public float _fps = 30; /// <exclude /> public float _duration = 1; /// <summary> /// Array with animation frameset data. /// </summary> /// <remarks> /// An animation consists of one or more animation framesets. This way it is easy to span an /// animation over more than one container. It is even possible to repeat containers and/or use different /// start- and end-frames. /// <br></br><br></br> /// By programmaticly playing only parts of an animation, one could even put all animation sequences in one /// animation object and control manually what sequences will be played. /// </remarks> public OTAnimationFrameset[] framesets; bool registered = false; bool dirtyAnimation = true; Frame[] frames = { }; List<OTContainer> containers = new List<OTContainer>(); bool _isReady = false; float _fps_ = 30; float _duration_ = 1; float _framesetSize = 0; /// <exclude /> protected string _name_ = ""; /// <summary> /// Frames per second /// </summary> public float fps { get { return _fps; } set { _fps = value; Update(); } } /// <summary> /// Duration of this animation /// </summary> public float duration { get { return _duration; } set { _duration = value; Update(); } } /// <summary> /// Animation name for lookup purposes. /// </summary> new public string name { get { return _name; } set { string old = _name; _name = value; gameObject.name = _name; if (OT.isValid) { _name_ = _name; OT.RegisterAnimationLookup(this, old); } } } /// <summary> /// Stores data of a specific animation frame. /// </summary> public struct Frame { /// <summary> /// Frame's container /// </summary> public OTContainer container; /// <summary> /// Frame's container index /// </summary> public int frameIndex; //public Vector2 movement; //public float rotation; //public Vector2 scale; } /// <summary> /// Animation ready indicator. /// </summary> public bool isReady { get { return _isReady; } } /// <exclude /> public OTAnimationFrameset GetFrameset(string pName) { if (pName == "") return null; for (int f = 0; f < framesets.Length; f++) { if (framesets[f].name.ToLower() == pName.ToLower()) return framesets[f]; } return null; } /// <exclude /> public float GetDuration(OTAnimationFrameset frameset) { if (frameset != null) { return (frameset.singleDuration != 0) ? frameset.singleDuration : frameset.frameCount / fps; } else return duration; } /// <summary> /// Number of frames in this animation. /// </summary> public int frameCount { get { return frames.Length; } } /// <summary> /// Get number of frames in this animaation /// </summary> /// <remarks> /// If no <see cref="OTAnimationFrameset" /> is provided the number of frames of the entire animation is returned. If an OTAnimationFrameset is provided /// this method will return the number of frames of that particular frameset. /// </remarks> /// <param name="frameset">Get number of frames of a perticular animation frameset.</param> /// <returns>number of frames</returns> public int GetFrameCount(OTAnimationFrameset frameset) { if (frameset != null) return frameset.frameCount; else return frameCount; } int GetIndex(float time, int direction, OTAnimationFrameset frameset) { int index = 0; int fc = GetFrameCount(frameset); index = (int)Mathf.Floor((float)fc * (time / GetDuration(frameset))); while (index > fc - 1) index -= fc; if (direction == -1) index = fc - 1 - index; return index; } /// <summary> /// Retrieve the animation frame that is active at a specific time. /// </summary> /// <param name="time">Animation time in seconds.</param> /// <param name="direction">Animation direction, 1 = forward, -1 = backward</param> /// <param name="frameset">The animation frameset of which a frame is requested</param> /// <returns>Retrieved animation frame.</returns> public Frame GetFrame(float time, int direction, OTAnimationFrameset frameset) { if (frames.Length == 0) { return new Frame(); } else { if (frameset != null) { return frames[frameset.startIndex+GetIndex(time, direction, frameset)]; } else { return frames[GetIndex(time, direction, null)]; } } } protected void Awake() { #if UNITY_EDITOR if (!Application.isPlaying) UnityEditor.PrefabUtility.RecordPrefabInstancePropertyModifications(this); #endif } // Use this for initialization void Start() { _duration_ = _duration; _fps_ = _fps; _name_ = name; if (name == "") { name = "Animation (id=" + this.gameObject.GetInstanceID() + ")"; #if UNITY_EDITOR if (!Application.isPlaying) UnityEditor.PrefabUtility.RecordPrefabInstancePropertyModifications(this); #endif } RegisterAnimation(); } /// <exclude /> protected Frame[] GetFrames() { List<Frame> frames = new List<Frame>(); if (framesets.Length > 0) { int index = 0; for (int f = 0; f < framesets.Length; f++) { OTAnimationFrameset fs = framesets[f]; fs.startIndex = index; index += fs.frameCount; int[] framesetFrames = fs.frameNumbers; foreach (int frameIndex in framesetFrames) { Frame curFrame = new Frame(); curFrame.container = fs.container; curFrame.frameIndex = frameIndex; frames.Add(curFrame); } } } return frames.ToArray(); } void RegisterAnimation() { if (OT.AnimationByName(name) == null) { OT.RegisterAnimation(this); gameObject.name = name; registered = true; } if (_name_ != name) { OT.RegisterAnimationLookup(this, _name_); _name_ = name; gameObject.name = name; } if (name != gameObject.name) { name = gameObject.name; OT.RegisterAnimationLookup(this, _name_); _name_ = name; #if UNITY_EDITOR if (!Application.isPlaying) UnityEditor.PrefabUtility.RecordPrefabInstancePropertyModifications(this); #endif } } bool Ready() { if (!isReady) { _isReady = true; for (int f = 0; f < framesets.Length; f++) { OTAnimationFrameset fs = framesets[f]; if (fs.container != null && !fs.container.isReady) _isReady = false; } } return _isReady; } void CheckEditorSettings() { if (frameCount == 0 && framesets.Length > 0 && !dirtyAnimation) { dirtyAnimation = true; } if (framesets.Length > 0) { if (_framesetSize != framesets.Length) { _framesetSize = framesets.Length; dirtyAnimation = true; } int _frameCount = 0; for (int f = 0; f < framesets.Length; f++) { OTAnimationFrameset fs = framesets[f]; if (fs.container != null) { if (f <= containers.Count - 1 && containers[f] != fs.container) { dirtyAnimation = true; } if (f <= containers.Count - 1) { if (containers[f] != fs.container) { dirtyAnimation = true; } containers[f] = fs.container; } else { containers.Add(fs.container); dirtyAnimation = true; } if (fs.container!=null) fs._containerName = fs.container.name; if (fs.container.isReady) { if (fs.startFrame < 0) fs.startFrame = 0; else if (fs.startFrame >= fs.container.frameCount) fs.startFrame = fs.container.frameCount - 1; if (fs.endFrame < 0) fs.endFrame = 0; else if (fs.endFrame >= fs.container.frameCount) fs.endFrame = fs.container.frameCount - 1; _frameCount += fs.frameCount; } } else { if (fs._containerName=="") { fs.startFrame = -1; fs.endFrame = -1; } } if (fs.playCount < 1) fs.playCount = 1; } if (frames != null) { if (_frameCount != frames.Length) { dirtyAnimation = true; } } while (framesets.Length < containers.Count) containers.RemoveAt(containers.Count - 1); } } // Update is called once per frame void Update() { if (!OT.isValid || !Ready()) return; if (!registered || !Application.isPlaying) RegisterAnimation(); if (Application.isEditor || OT.dirtyChecks) CheckEditorSettings(); if (dirtyAnimation) { bool isOk = true; for (int f = 0; f < framesets.Length; f++) { OTAnimationFrameset fs = framesets[f]; if (fs.container == null && fs._containerName!="") { OTContainer c = OT.ContainerByName(fs._containerName); if (c!=null && c.isReady) fs.container = c; else { isOk = false; break; } } } if (isOk) { frames = GetFrames(); dirtyAnimation = false; _fps = frames.Length / _duration; _fps_ = _fps; } } if (Application.isEditor || OT.dirtyChecks) { if (_duration > 0) { if (_duration_ != _duration) { _duration_ = _duration; _fps = frames.Length / _duration; _fps_ = _fps; } } if (_fps > 0) { if (_fps_ != _fps) { _fps_ = _fps; _duration = frames.Length / _fps; _duration_ = _duration; } } } } void OnDestroy() { if (OT.isValid) OT.RemoveAnimation(this); } }
using System; using System.Text; using System.Security.Cryptography; using System.IO; using System.Collections.Generic; namespace DarkMultiPlayerCommon { public class Common { //Timeouts in milliseconds public const long HEART_BEAT_INTERVAL = 5000; public const long INITIAL_CONNECTION_TIMEOUT = 5000; public const long CONNECTION_TIMEOUT = 20000; //Any message bigger than 5MB will be invalid public const int MAX_MESSAGE_SIZE = 5242880; //Split messages into 8kb chunks to higher priority messages have more injection points into the TCP stream. public const int SPLIT_MESSAGE_LENGTH = 8192; //Bump this every time there is a network change (Basically, if MessageWriter or MessageReader is touched). public const int PROTOCOL_VERSION = 33; //Program version. This is written in the build scripts. public const string PROGRAM_VERSION = "Custom"; //Compression threshold public const int COMPRESSION_THRESHOLD = 4096; public static string CalculateSHA256Hash(string fileName) { return CalculateSHA256Hash(File.ReadAllBytes(fileName)); } public static string CalculateSHA256Hash(byte[] fileData) { StringBuilder sb = new StringBuilder(); using (SHA256Managed sha = new SHA256Managed()) { byte[] fileHashData = sha.ComputeHash(fileData); //Byte[] to string conversion adapted from MSDN... for (int i = 0; i < fileHashData.Length; i++) { sb.Append(fileHashData[i].ToString("x2")); } } return sb.ToString(); } public static byte[] PrependNetworkFrame(int messageType, byte[] messageData) { byte[] returnBytes; //Get type bytes byte[] typeBytes = BitConverter.GetBytes(messageType); if (BitConverter.IsLittleEndian) { Array.Reverse(typeBytes); } if (messageData == null || messageData.Length == 0) { returnBytes = new byte[8]; typeBytes.CopyTo(returnBytes, 0); } else { //Get length bytes if we have a payload byte[] lengthBytes = BitConverter.GetBytes(messageData.Length); if (BitConverter.IsLittleEndian) { Array.Reverse(lengthBytes); } returnBytes = new byte[8 + messageData.Length]; typeBytes.CopyTo(returnBytes, 0); lengthBytes.CopyTo(returnBytes, 4); messageData.CopyTo(returnBytes, 8); } return returnBytes; } public static string ConvertConfigStringToGUIDString(string configNodeString) { string[] returnString = new string[5]; returnString[0] = configNodeString.Substring(0, 8); returnString[1] = configNodeString.Substring(8, 4); returnString[2] = configNodeString.Substring(12, 4); returnString[3] = configNodeString.Substring(16, 4); returnString[4] = configNodeString.Substring(20); return String.Join("-", returnString); } public static List<string> GetStockParts() { List<string> stockPartList = new List<string>(); stockPartList.Add("StandardCtrlSrf"); stockPartList.Add("CanardController"); stockPartList.Add("noseCone"); stockPartList.Add("AdvancedCanard"); stockPartList.Add("airplaneTail"); stockPartList.Add("deltaWing"); stockPartList.Add("noseConeAdapter"); stockPartList.Add("rocketNoseCone"); stockPartList.Add("smallCtrlSrf"); stockPartList.Add("standardNoseCone"); stockPartList.Add("sweptWing"); stockPartList.Add("tailfin"); stockPartList.Add("wingConnector"); stockPartList.Add("winglet"); stockPartList.Add("R8winglet"); stockPartList.Add("winglet3"); stockPartList.Add("Mark1Cockpit"); stockPartList.Add("Mark2Cockpit"); stockPartList.Add("Mark1-2Pod"); stockPartList.Add("advSasModule"); stockPartList.Add("asasmodule1-2"); stockPartList.Add("avionicsNoseCone"); stockPartList.Add("crewCabin"); stockPartList.Add("cupola"); stockPartList.Add("landerCabinSmall"); stockPartList.Add("mark3Cockpit"); stockPartList.Add("mk1pod"); stockPartList.Add("mk2LanderCabin"); stockPartList.Add("probeCoreCube"); stockPartList.Add("probeCoreHex"); stockPartList.Add("probeCoreOcto"); stockPartList.Add("probeCoreOcto2"); stockPartList.Add("probeCoreSphere"); stockPartList.Add("probeStackLarge"); stockPartList.Add("probeStackSmall"); stockPartList.Add("sasModule"); stockPartList.Add("seatExternalCmd"); stockPartList.Add("rtg"); stockPartList.Add("batteryBank"); stockPartList.Add("batteryBankLarge"); stockPartList.Add("batteryBankMini"); stockPartList.Add("batteryPack"); stockPartList.Add("ksp.r.largeBatteryPack"); stockPartList.Add("largeSolarPanel"); stockPartList.Add("solarPanels1"); stockPartList.Add("solarPanels2"); stockPartList.Add("solarPanels3"); stockPartList.Add("solarPanels4"); stockPartList.Add("solarPanels5"); stockPartList.Add("JetEngine"); stockPartList.Add("engineLargeSkipper"); stockPartList.Add("ionEngine"); stockPartList.Add("liquidEngine"); stockPartList.Add("liquidEngine1-2"); stockPartList.Add("liquidEngine2"); stockPartList.Add("liquidEngine2-2"); stockPartList.Add("liquidEngine3"); stockPartList.Add("liquidEngineMini"); stockPartList.Add("microEngine"); stockPartList.Add("nuclearEngine"); stockPartList.Add("radialEngineMini"); stockPartList.Add("radialLiquidEngine1-2"); stockPartList.Add("sepMotor1"); stockPartList.Add("smallRadialEngine"); stockPartList.Add("solidBooster"); stockPartList.Add("solidBooster1-1"); stockPartList.Add("toroidalAerospike"); stockPartList.Add("turboFanEngine"); stockPartList.Add("MK1Fuselage"); stockPartList.Add("Mk1FuselageStructural"); stockPartList.Add("RCSFuelTank"); stockPartList.Add("RCSTank1-2"); stockPartList.Add("rcsTankMini"); stockPartList.Add("rcsTankRadialLong"); stockPartList.Add("fuelTank"); stockPartList.Add("fuelTank1-2"); stockPartList.Add("fuelTank2-2"); stockPartList.Add("fuelTank3-2"); stockPartList.Add("fuelTank4-2"); stockPartList.Add("fuelTankSmall"); stockPartList.Add("fuelTankSmallFlat"); stockPartList.Add("fuelTank.long"); stockPartList.Add("miniFuelTank"); stockPartList.Add("mk2Fuselage"); stockPartList.Add("mk2SpacePlaneAdapter"); stockPartList.Add("mk3Fuselage"); stockPartList.Add("mk3spacePlaneAdapter"); stockPartList.Add("radialRCSTank"); stockPartList.Add("toroidalFuelTank"); stockPartList.Add("xenonTank"); stockPartList.Add("xenonTankRadial"); stockPartList.Add("adapterLargeSmallBi"); stockPartList.Add("adapterLargeSmallQuad"); stockPartList.Add("adapterLargeSmallTri"); stockPartList.Add("adapterSmallMiniShort"); stockPartList.Add("adapterSmallMiniTall"); stockPartList.Add("nacelleBody"); stockPartList.Add("radialEngineBody"); stockPartList.Add("smallHardpoint"); stockPartList.Add("stationHub"); stockPartList.Add("structuralIBeam1"); stockPartList.Add("structuralIBeam2"); stockPartList.Add("structuralIBeam3"); stockPartList.Add("structuralMiniNode"); stockPartList.Add("structuralPanel1"); stockPartList.Add("structuralPanel2"); stockPartList.Add("structuralPylon"); stockPartList.Add("structuralWing"); stockPartList.Add("strutConnector"); stockPartList.Add("strutCube"); stockPartList.Add("strutOcto"); stockPartList.Add("trussAdapter"); stockPartList.Add("trussPiece1x"); stockPartList.Add("trussPiece3x"); stockPartList.Add("CircularIntake"); stockPartList.Add("landingLeg1"); stockPartList.Add("landingLeg1-2"); stockPartList.Add("RCSBlock"); stockPartList.Add("stackDecoupler"); stockPartList.Add("airScoop"); stockPartList.Add("commDish"); stockPartList.Add("decoupler1-2"); stockPartList.Add("dockingPort1"); stockPartList.Add("dockingPort2"); stockPartList.Add("dockingPort3"); stockPartList.Add("dockingPortLarge"); stockPartList.Add("dockingPortLateral"); stockPartList.Add("fuelLine"); stockPartList.Add("ladder1"); stockPartList.Add("largeAdapter"); stockPartList.Add("largeAdapter2"); stockPartList.Add("launchClamp1"); stockPartList.Add("linearRcs"); stockPartList.Add("longAntenna"); stockPartList.Add("miniLandingLeg"); stockPartList.Add("parachuteDrogue"); stockPartList.Add("parachuteLarge"); stockPartList.Add("parachuteRadial"); stockPartList.Add("parachuteSingle"); stockPartList.Add("radialDecoupler"); stockPartList.Add("radialDecoupler1-2"); stockPartList.Add("radialDecoupler2"); stockPartList.Add("ramAirIntake"); stockPartList.Add("roverBody"); stockPartList.Add("sensorAccelerometer"); stockPartList.Add("sensorBarometer"); stockPartList.Add("sensorGravimeter"); stockPartList.Add("sensorThermometer"); stockPartList.Add("spotLight1"); stockPartList.Add("spotLight2"); stockPartList.Add("stackBiCoupler"); stockPartList.Add("stackDecouplerMini"); stockPartList.Add("stackPoint1"); stockPartList.Add("stackQuadCoupler"); stockPartList.Add("stackSeparator"); stockPartList.Add("stackSeparatorBig"); stockPartList.Add("stackSeparatorMini"); stockPartList.Add("stackTriCoupler"); stockPartList.Add("telescopicLadder"); stockPartList.Add("telescopicLadderBay"); stockPartList.Add("SmallGearBay"); stockPartList.Add("roverWheel1"); stockPartList.Add("roverWheel2"); stockPartList.Add("roverWheel3"); stockPartList.Add("wheelMed"); stockPartList.Add("flag"); stockPartList.Add("kerbalEVA"); stockPartList.Add("mediumDishAntenna"); stockPartList.Add("GooExperiment"); stockPartList.Add("science.module"); stockPartList.Add("RAPIER"); stockPartList.Add("Large.Crewed.Lab"); //0.23.5 parts stockPartList.Add("GrapplingDevice"); stockPartList.Add("LaunchEscapeSystem"); stockPartList.Add("MassiveBooster"); stockPartList.Add("PotatoRoid"); stockPartList.Add("Size2LFB"); stockPartList.Add("Size3AdvancedEngine"); stockPartList.Add("size3Decoupler"); stockPartList.Add("Size3EngineCluster"); stockPartList.Add("Size3LargeTank"); stockPartList.Add("Size3MediumTank"); stockPartList.Add("Size3SmallTank"); stockPartList.Add("Size3to2Adapter"); //0.24 parts stockPartList.Add("omsEngine"); stockPartList.Add("vernierEngine"); //0.25 parts stockPartList.Add("delta.small"); stockPartList.Add("elevon2"); stockPartList.Add("elevon3"); stockPartList.Add("elevon5"); stockPartList.Add("IntakeRadialLong"); stockPartList.Add("MK1IntakeFuselage"); stockPartList.Add("mk2.1m.AdapterLong"); stockPartList.Add("mk2.1m.Bicoupler"); stockPartList.Add("mk2CargoBayL"); stockPartList.Add("mk2CargoBayS"); stockPartList.Add("mk2Cockpit.Inline"); stockPartList.Add("mk2Cockpit.Standard"); stockPartList.Add("mk2CrewCabin"); stockPartList.Add("mk2DockingPort"); stockPartList.Add("mk2DroneCore"); stockPartList.Add("mk2FuselageLongLFO"); stockPartList.Add("mk2FuselageShortLFO"); stockPartList.Add("mk2FuselageShortLiquid"); stockPartList.Add("mk2FuselageShortMono"); stockPartList.Add("shockConeIntake"); stockPartList.Add("structuralWing2"); stockPartList.Add("structuralWing3"); stockPartList.Add("structuralWing4"); stockPartList.Add("sweptWing1"); stockPartList.Add("sweptWing2"); stockPartList.Add("wingConnector2"); stockPartList.Add("wingConnector3"); stockPartList.Add("wingConnector4"); stockPartList.Add("wingConnector5"); stockPartList.Add("wingStrake"); //0.90 parts stockPartList.Add("adapterMk3-Mk2"); stockPartList.Add("adapterMk3-Size2"); stockPartList.Add("adapterMk3-Size2Slant"); stockPartList.Add("adapterSize2-Mk2"); stockPartList.Add("adapterSize2-Size1"); stockPartList.Add("adapterSize2-Size1Slant"); stockPartList.Add("adapterSize3-Mk3"); stockPartList.Add("mk3CargoBayL"); stockPartList.Add("mk3CargoBayM"); stockPartList.Add("mk3CargoBayS"); stockPartList.Add("mk3Cockpit.Shuttle"); stockPartList.Add("mk3CrewCabin"); stockPartList.Add("mk3FuselageLF.100"); stockPartList.Add("mk3FuselageLF.25"); stockPartList.Add("mk3FuselageLF.50"); stockPartList.Add("mk3FuselageLFO.100"); stockPartList.Add("mk3FuselageLFO.25"); stockPartList.Add("mk3FuselageLFO.50"); stockPartList.Add("mk3FuselageMONO"); return stockPartList; } public static string GenerateModFileStringData(string[] requiredFiles, string[] optionalFiles, bool isWhiteList, string[] whitelistBlacklistFiles, string[] partsList) { //This is the same format as KMPModControl.txt. It's a fairly sane format, and it makes sense to remain compatible. StringBuilder sb = new StringBuilder(); //Header stuff sb.AppendLine("#You can comment by starting a line with a #, these are ignored by the server."); sb.AppendLine("#Commenting will NOT work unless the line STARTS with a '#'."); sb.AppendLine("#You can also indent the file with tabs or spaces."); sb.AppendLine("#Sections supported are required-files, optional-files, partslist, resource-blacklist and resource-whitelist."); sb.AppendLine("#The client will be required to have the files found in required-files, and they must match the SHA hash if specified (this is where part mod files and play-altering files should go, like KWRocketry or Ferram Aerospace Research#The client may have the files found in optional-files, but IF they do then they must match the SHA hash (this is where mods that do not affect other players should go, like EditorExtensions or part catalogue managers"); sb.AppendLine("#You cannot use both resource-blacklist AND resource-whitelist in the same file."); sb.AppendLine("#resource-blacklist bans ONLY the files you specify"); sb.AppendLine("#resource-whitelist bans ALL resources except those specified in the resource-whitelist section OR in the SHA sections. A file listed in resource-whitelist will NOT be checked for SHA hash. This is useful if you want a mod that modifies files in its own directory as you play."); sb.AppendLine("#Each section has its own type of formatting. Examples have been given."); sb.AppendLine("#Sections are defined as follows:"); sb.AppendLine(""); //Required section sb.AppendLine("!required-files"); sb.AppendLine("#To generate the SHA256 of a file you can use a utility such as this one: http://hash.online-convert.com/sha256-generator (use the 'hex' string), or use sha256sum on linux."); sb.AppendLine("#File paths are read from inside GameData."); sb.AppendLine("#If there is no SHA256 hash listed here (i.e. blank after the equals sign or no equals sign), SHA matching will not be enforced."); sb.AppendLine("#You may not specify multiple SHAs for the same file. Do not put spaces around equals sign. Follow the example carefully."); sb.AppendLine("#Syntax:"); sb.AppendLine("#[File Path]=[SHA] or [File Path]"); sb.AppendLine("#Example: MechJeb2/Plugins/MechJeb2.dll=B84BB63AE740F0A25DA047E5EDA35B26F6FD5DF019696AC9D6AF8FC3E031F0B9"); sb.AppendLine("#Example: MechJeb2/Plugins/MechJeb2.dll"); foreach (string requiredFile in requiredFiles) { sb.AppendLine(requiredFile); } sb.AppendLine(""); sb.AppendLine(""); sb.AppendLine("!optional-files"); sb.AppendLine("#Formatting for this section is the same as the 'required-files' section"); foreach (string optionalFile in optionalFiles) { sb.AppendLine(optionalFile); } sb.AppendLine(""); sb.AppendLine(""); //Whitelist or blacklist section if (isWhiteList) { sb.AppendLine("!resource-whitelist"); sb.AppendLine("#!resource-blacklist"); } else { sb.AppendLine("!resource-blacklist"); sb.AppendLine("#!resource-whitelist"); } sb.AppendLine("#Only select one of these modes."); sb.AppendLine("#Resource blacklist: clients will be allowed to use any dll's, So long as they are not listed in this section"); sb.AppendLine("#Resource whitelist: clients will only be allowed to use dll's listed here or in the 'required-files' and 'optional-files' sections."); sb.AppendLine("#Syntax:"); sb.AppendLine("#[File Path]"); sb.AppendLine("#Example: MechJeb2/Plugins/MechJeb2.dll"); foreach (string whitelistBlacklistFile in whitelistBlacklistFiles) { sb.AppendLine(whitelistBlacklistFile); } sb.AppendLine(""); sb.AppendLine(""); //Parts section sb.AppendLine("!partslist"); sb.AppendLine("#This is a list of parts to allow users to put on their ships."); sb.AppendLine("#If a part the client has doesn't appear on this list, they can still join the server but not use the part."); sb.AppendLine("#The default stock parts have been added already for you."); sb.AppendLine("#To add a mod part, add the name from the part's .cfg file. The name is the name from the PART{} section, where underscores are replaced with periods."); sb.AppendLine("#[partname]"); sb.AppendLine("#Example: mumech.MJ2.Pod (NOTE: In the part.cfg this MechJeb2 pod is named mumech_MJ2_Pod. The _ have been replaced with .)"); sb.AppendLine("#You can use this application to generate partlists from a KSP installation if you want to add mod parts: http://forum.kerbalspaceprogram.com/threads/57284 "); foreach (string partName in partsList) { sb.AppendLine(partName); } sb.AppendLine(""); return sb.ToString(); } } public enum CraftType { VAB, SPH, SUBASSEMBLY } public enum ClientMessageType { HEARTBEAT, HANDSHAKE_RESPONSE, CHAT_MESSAGE, PLAYER_STATUS, PLAYER_COLOR, SCENARIO_DATA, KERBALS_REQUEST, KERBAL_PROTO, VESSELS_REQUEST, VESSEL_PROTO, VESSEL_UPDATE, VESSEL_REMOVE, CRAFT_LIBRARY, SCREENSHOT_LIBRARY, FLAG_SYNC, SYNC_TIME_REQUEST, PING_REQUEST, MOTD_REQUEST, WARP_CONTROL, LOCK_SYSTEM, MOD_DATA, SPLIT_MESSAGE, CONNECTION_END } public enum ServerMessageType { HEARTBEAT, HANDSHAKE_CHALLANGE, HANDSHAKE_REPLY, SERVER_SETTINGS, CHAT_MESSAGE, PLAYER_STATUS, PLAYER_COLOR, PLAYER_JOIN, PLAYER_DISCONNECT, SCENARIO_DATA, KERBAL_REPLY, KERBAL_COMPLETE, VESSEL_LIST, VESSEL_PROTO, VESSEL_UPDATE, VESSEL_COMPLETE, VESSEL_REMOVE, CRAFT_LIBRARY, SCREENSHOT_LIBRARY, FLAG_SYNC, SET_SUBSPACE, SYNC_TIME_REPLY, PING_REPLY, MOTD_REPLY, WARP_CONTROL, ADMIN_SYSTEM, LOCK_SYSTEM, MOD_DATA, SPLIT_MESSAGE, CONNECTION_END } public enum ConnectionStatus { DISCONNECTED, CONNECTING, CONNECTED } public enum ClientState { DISCONNECTED, CONNECTING, CONNECTED, HANDSHAKING, AUTHENTICATED, TIME_SYNCING, TIME_SYNCED, SYNCING_KERBALS, KERBALS_SYNCED, SYNCING_VESSELS, VESSELS_SYNCED, TIME_LOCKING, TIME_LOCKED, STARTING, RUNNING, DISCONNECTING } public enum WarpMode { MCW_FORCE, MCW_VOTE, MCW_LOWEST, SUBSPACE_SIMPLE, SUBSPACE, NONE } public enum GameMode { SANDBOX, SCIENCE, CAREER } public enum ModControlMode { DISABLED, ENABLED_STOP_INVALID_PART_SYNC, ENABLED_STOP_INVALID_PART_LAUNCH } public enum WarpMessageType { REQUEST_VOTE, REPLY_VOTE, CHANGE_WARP, SET_CONTROLLER, NEW_SUBSPACE, CHANGE_SUBSPACE, RELOCK_SUBSPACE, REPORT_RATE } public enum CraftMessageType { LIST, REQUEST_FILE, RESPOND_FILE, UPLOAD_FILE, ADD_FILE, DELETE_FILE, } public enum ScreenshotMessageType { NOTIFY, SEND_START_NOTIFY, WATCH, SCREENSHOT, } public enum ChatMessageType { LIST, JOIN, LEAVE, CHANNEL_MESSAGE, PRIVATE_MESSAGE, CONSOLE_MESSAGE } public enum AdminMessageType { LIST, ADD, REMOVE, } public enum LockMessageType { LIST, ACQUIRE, RELEASE, } public enum FlagMessageType { LIST, FLAG_DATA, UPLOAD_FILE, DELETE_FILE, } public enum PlayerColorMessageType { LIST, SET, } public class ClientMessage { public bool handled; public ClientMessageType type; public byte[] data; } public class ServerMessage { public ServerMessageType type; public byte[] data; } public class PlayerStatus { public string playerName; public string vesselText; public string statusText; } public class Subspace { public long serverClock; public double planetTime; public float subspaceSpeed; } public enum HandshakeReply : int { HANDSHOOK_SUCCESSFULLY = 0, PROTOCOL_MISMATCH = 1, ALREADY_CONNECTED = 2, RESERVED_NAME = 3, INVALID_KEY = 4, PLAYER_BANNED = 5, SERVER_FULL = 6, NOT_WHITELISTED = 7, INVALID_PLAYERNAME = 98, MALFORMED_HANDSHAKE = 99 } public enum GameDifficulty : int { EASY, NORMAL, MODERATE, HARD, CUSTOM } }
// CatalogStore.cs - Documentation catalog tree model. // // Author: Mike Kestner <mkestner@novell.com> // // Copyright (c) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, // and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS // BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. namespace Monodoc.Widgets { using System; using System.Collections; using System.Runtime.InteropServices; using Gtk; internal class CatalogStore : GLib.Object, TreeModelImplementor { DocNode root_node; public CatalogStore (DocNode root_node) { this.root_node = root_node; } DocNode GetNodeAtPath (TreePath path) { if (path.Indices.Length <= 0 || path.Indices [0] != 0) return null; DocNode result = root_node; for (int i = 1; i < path.Indices.Length; i++) { if (result.ChildCount <= path.Indices[i]) return null; result = result [path.Indices [i]] as DocNode; } return result; } Hashtable node_hash = new Hashtable (); public TreeModelFlags Flags { get { return TreeModelFlags.ItersPersist; } } public int NColumns { get { return 1; } } public GLib.GType GetColumnType (int col) { return GLib.GType.String; } TreeIter IterFromNode (DocNode node) { GCHandle gch; if (node_hash [node] != null) gch = (GCHandle) node_hash [node]; else { gch = GCHandle.Alloc (node); node_hash [node] = gch; node.Changed += new EventHandler (OnNodeChanged); node.ChildAdded += new NodeEventHandler (OnChildAdded); node.ChildRemoved += new NodeEventHandler (OnChildRemoved); } TreeIter result = TreeIter.Zero; result.UserData = (IntPtr) gch; return result; } void OnNodeChanged (object o, EventArgs args) { TreeModelAdapter adapter = new TreeModelAdapter (this); adapter.EmitRowChanged (PathFromNode (o as DocNode), IterFromNode (o as DocNode)); } void OnChildAdded (object o, NodeEventArgs args) { TreeModelAdapter adapter = new TreeModelAdapter (this); adapter.EmitRowInserted (PathFromNode (args.Node), IterFromNode (args.Node)); } void OnChildRemoved (object o, NodeEventArgs args) { TreeModelAdapter adapter = new TreeModelAdapter (this); adapter.EmitRowDeleted (PathFromNode (args.Node)); } internal DocNode NodeFromIter (TreeIter iter) { GCHandle gch = (GCHandle) iter.UserData; return gch.Target as DocNode; } internal TreePath PathFromNode (DocNode node) { if (node == null) return new TreePath (); DocNode work = node; TreePath path = new TreePath (); while (work != root_node) { DocNode parent = work.Parent; path.PrependIndex (parent.IndexOf (work)); work = parent; } path.PrependIndex (0); return path; } public bool GetIter (out TreeIter iter, TreePath path) { if (path == null) throw new ArgumentNullException ("path"); iter = TreeIter.Zero; DocNode node = GetNodeAtPath (path); if (node == null) return false; iter = IterFromNode (node); return true; } public TreePath GetPath (TreeIter iter) { DocNode node = NodeFromIter (iter); if (node == null) throw new ArgumentException ("iter"); return PathFromNode (node); } public void GetValue (TreeIter iter, int col, ref GLib.Value val) { DocNode node = NodeFromIter (iter); if (node == null) return; val = new GLib.Value (node.Caption); } public bool IterNext (ref TreeIter iter) { DocNode node = NodeFromIter (iter); if (node == null || node == root_node) return false; int idx = node.Parent.IndexOf (node) + 1; if (idx < node.Parent.ChildCount) { iter = IterFromNode (node.Parent [idx]); return true; } return false; } public bool IterChildren (out TreeIter child, TreeIter parent) { child = TreeIter.Zero; if (parent.UserData == IntPtr.Zero) { child = IterFromNode (root_node); return true; } DocNode node = NodeFromIter (parent); if (node == null || node.ChildCount <= 0) return false; child = IterFromNode (node [0]); return true; } public bool IterHasChild (TreeIter iter) { DocNode node = NodeFromIter (iter); if (node == null || node.ChildCount <= 0) return false; return true; } public int IterNChildren (TreeIter iter) { if (iter.UserData == IntPtr.Zero) return 1; DocNode node = NodeFromIter (iter); return node == null ? 0 : node.ChildCount; } public bool IterNthChild (out TreeIter child, TreeIter parent, int n) { child = TreeIter.Zero; if (parent.UserData == IntPtr.Zero) { if (n != 0) return false; child = IterFromNode (root_node); return true; } DocNode node = NodeFromIter (parent); if (node == null || node.ChildCount <= n) return false; child = IterFromNode (node [n]); return true; } public bool IterParent (out TreeIter parent, TreeIter child) { parent = TreeIter.Zero; DocNode node = NodeFromIter (child); if (node == null || node == root_node) return false; parent = IterFromNode (node.Parent); return true; } public void RefNode (TreeIter iter) { } public void UnrefNode (TreeIter iter) { } } }
// 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. #pragma warning disable 0420 // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // // // -------------------------------------------------------------------------------------- // // A class that provides a simple, lightweight implementation of lazy initialization, // obviating the need for a developer to implement a custom, thread-safe lazy initialization // solution. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Runtime; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Diagnostics; using System.Runtime.Serialization; using System.Threading; using System.Diagnostics.Contracts; using System.Runtime.ExceptionServices; namespace System { // Lazy<T> is generic, but not all of its state needs to be generic. Avoid creating duplicate // objects per instantiation by putting them here. internal static class LazyHelpers { // Dummy object used as the value of m_threadSafeObj if in PublicationOnly mode. internal static readonly object PUBLICATION_ONLY_SENTINEL = new object(); } /// <summary> /// Provides support for lazy initialization. /// </summary> /// <typeparam name="T">Specifies the type of element being lazily initialized.</typeparam> /// <remarks> /// <para> /// By default, all public and protected members of <see cref="Lazy{T}"/> are thread-safe and may be used /// concurrently from multiple threads. These thread-safety guarantees may be removed optionally and per instance /// using parameters to the type's constructors. /// </para> /// </remarks> [Serializable] [ComVisible(false)] #if !FEATURE_CORECLR [HostProtection(Synchronization = true, ExternalThreading = true)] #endif [DebuggerTypeProxy(typeof(System_LazyDebugView<>))] [DebuggerDisplay("ThreadSafetyMode={Mode}, IsValueCreated={IsValueCreated}, IsValueFaulted={IsValueFaulted}, Value={ValueForDebugDisplay}")] public class Lazy<T> { #region Inner classes /// <summary> /// wrapper class to box the initialized value, this is mainly created to avoid boxing/unboxing the value each time the value is called in case T is /// a value type /// </summary> [Serializable] class Boxed { internal Boxed(T value) { m_value = value; } internal T m_value; } /// <summary> /// Wrapper class to wrap the excpetion thrown by the value factory /// </summary> class LazyInternalExceptionHolder { internal ExceptionDispatchInfo m_edi; internal LazyInternalExceptionHolder(Exception ex) { m_edi = ExceptionDispatchInfo.Capture(ex); } } #endregion // A dummy delegate used as a : // 1- Flag to avoid recursive call to Value in None and ExecutionAndPublication modes in m_valueFactory // 2- Flag to m_threadSafeObj if ExecutionAndPublication mode and the value is known to be initialized static readonly Func<T> ALREADY_INVOKED_SENTINEL = delegate { Contract.Assert(false, "ALREADY_INVOKED_SENTINEL should never be invoked."); return default(T); }; //null --> value is not created //m_value is Boxed --> the value is created, and m_value holds the value //m_value is LazyExceptionHolder --> it holds an exception private object m_boxed; // The factory delegate that returns the value. // In None and ExecutionAndPublication modes, this will be set to ALREADY_INVOKED_SENTINEL as a flag to avoid recursive calls [NonSerialized] private Func<T> m_valueFactory; // null if it is not thread safe mode // LazyHelpers.PUBLICATION_ONLY_SENTINEL if PublicationOnly mode // object if ExecutionAndPublication mode (may be ALREADY_INVOKED_SENTINEL if the value is already initialized) [NonSerialized] private object m_threadSafeObj; /// <summary> /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class that /// uses <typeparamref name="T"/>'s default constructor for lazy initialization. /// </summary> /// <remarks> /// An instance created with this constructor may be used concurrently from multiple threads. /// </remarks> public Lazy() : this(LazyThreadSafetyMode.ExecutionAndPublication) { } /// <summary> /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class that uses a /// specified initialization function. /// </summary> /// <param name="valueFactory"> /// The <see cref="T:System.Func{T}"/> invoked to produce the lazily-initialized value when it is /// needed. /// </param> /// <exception cref="System.ArgumentNullException"><paramref name="valueFactory"/> is a null /// reference (Nothing in Visual Basic).</exception> /// <remarks> /// An instance created with this constructor may be used concurrently from multiple threads. /// </remarks> public Lazy(Func<T> valueFactory) : this(valueFactory, LazyThreadSafetyMode.ExecutionAndPublication) { } /// <summary> /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> /// class that uses <typeparamref name="T"/>'s default constructor and a specified thread-safety mode. /// </summary> /// <param name="isThreadSafe">true if this instance should be usable by multiple threads concurrently; false if the instance will only be used by one thread at a time. /// </param> public Lazy(bool isThreadSafe) : this(isThreadSafe? LazyThreadSafetyMode.ExecutionAndPublication : LazyThreadSafetyMode.None) { } /// <summary> /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> /// class that uses <typeparamref name="T"/>'s default constructor and a specified thread-safety mode. /// </summary> /// <param name="mode">The lazy thread-safety mode mode</param> /// <exception cref="System.ArgumentOutOfRangeException"><paramref name="mode"/> mode contains an invalid valuee</exception> public Lazy(LazyThreadSafetyMode mode) { m_threadSafeObj = GetObjectFromMode(mode); } /// <summary> /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class /// that uses a specified initialization function and a specified thread-safety mode. /// </summary> /// <param name="valueFactory"> /// The <see cref="T:System.Func{T}"/> invoked to produce the lazily-initialized value when it is needed. /// </param> /// <param name="isThreadSafe">true if this instance should be usable by multiple threads concurrently; false if the instance will only be used by one thread at a time. /// </param> /// <exception cref="System.ArgumentNullException"><paramref name="valueFactory"/> is /// a null reference (Nothing in Visual Basic).</exception> public Lazy(Func<T> valueFactory, bool isThreadSafe) : this(valueFactory, isThreadSafe ? LazyThreadSafetyMode.ExecutionAndPublication : LazyThreadSafetyMode.None) { } /// <summary> /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class /// that uses a specified initialization function and a specified thread-safety mode. /// </summary> /// <param name="valueFactory"> /// The <see cref="T:System.Func{T}"/> invoked to produce the lazily-initialized value when it is needed. /// </param> /// <param name="mode">The lazy thread-safety mode.</param> /// <exception cref="System.ArgumentNullException"><paramref name="valueFactory"/> is /// a null reference (Nothing in Visual Basic).</exception> /// <exception cref="System.ArgumentOutOfRangeException"><paramref name="mode"/> mode contains an invalid value.</exception> public Lazy(Func<T> valueFactory, LazyThreadSafetyMode mode) { if (valueFactory == null) throw new ArgumentNullException("valueFactory"); m_threadSafeObj = GetObjectFromMode(mode); m_valueFactory = valueFactory; } /// <summary> /// Static helper function that returns an object based on the given mode. it also throws an exception if the mode is invalid /// </summary> private static object GetObjectFromMode(LazyThreadSafetyMode mode) { if (mode == LazyThreadSafetyMode.ExecutionAndPublication) return new object(); else if (mode == LazyThreadSafetyMode.PublicationOnly) return LazyHelpers.PUBLICATION_ONLY_SENTINEL; else if (mode != LazyThreadSafetyMode.None) throw new ArgumentOutOfRangeException("mode", Environment.GetResourceString("Lazy_ctor_ModeInvalid")); return null; // None mode } /// <summary>Forces initialization during serialization.</summary> /// <param name="context">The StreamingContext for the serialization operation.</param> [OnSerializing] private void OnSerializing(StreamingContext context) { // Force initialization T dummy = Value; } /// <summary>Creates and returns a string representation of this instance.</summary> /// <returns>The result of calling <see cref="System.Object.ToString"/> on the <see /// cref="Value"/>.</returns> /// <exception cref="T:System.NullReferenceException"> /// The <see cref="Value"/> is null. /// </exception> public override string ToString() { return IsValueCreated ? Value.ToString() : Environment.GetResourceString("Lazy_ToString_ValueNotCreated"); } /// <summary>Gets the value of the Lazy&lt;T&gt; for debugging display purposes.</summary> internal T ValueForDebugDisplay { get { if (!IsValueCreated) { return default(T); } return ((Boxed)m_boxed).m_value; } } /// <summary> /// Gets a value indicating whether this instance may be used concurrently from multiple threads. /// </summary> internal LazyThreadSafetyMode Mode { get { if (m_threadSafeObj == null) return LazyThreadSafetyMode.None; if (m_threadSafeObj == (object)LazyHelpers.PUBLICATION_ONLY_SENTINEL) return LazyThreadSafetyMode.PublicationOnly; return LazyThreadSafetyMode.ExecutionAndPublication; } } /// <summary> /// Gets whether the value creation is faulted or not /// </summary> internal bool IsValueFaulted { get { return m_boxed is LazyInternalExceptionHolder; } } /// <summary>Gets a value indicating whether the <see cref="T:System.Lazy{T}"/> has been initialized. /// </summary> /// <value>true if the <see cref="T:System.Lazy{T}"/> instance has been initialized; /// otherwise, false.</value> /// <remarks> /// The initialization of a <see cref="T:System.Lazy{T}"/> instance may result in either /// a value being produced or an exception being thrown. If an exception goes unhandled during initialization, /// <see cref="IsValueCreated"/> will return false. /// </remarks> public bool IsValueCreated { get { return m_boxed != null && m_boxed is Boxed; } } /// <summary>Gets the lazily initialized value of the current <see /// cref="T:System.Threading.Lazy{T}"/>.</summary> /// <value>The lazily initialized value of the current <see /// cref="T:System.Threading.Lazy{T}"/>.</value> /// <exception cref="T:System.MissingMemberException"> /// The <see cref="T:System.Threading.Lazy{T}"/> was initialized to use the default constructor /// of the type being lazily initialized, and that type does not have a public, parameterless constructor. /// </exception> /// <exception cref="T:System.MemberAccessException"> /// The <see cref="T:System.Threading.Lazy{T}"/> was initialized to use the default constructor /// of the type being lazily initialized, and permissions to access the constructor were missing. /// </exception> /// <exception cref="T:System.InvalidOperationException"> /// The <see cref="T:System.Threading.Lazy{T}"/> was constructed with the <see cref="T:System.Threading.LazyThreadSafetyMode.ExecutionAndPublication"/> or /// <see cref="T:System.Threading.LazyThreadSafetyMode.None"/> and the initialization function attempted to access <see cref="Value"/> on this instance. /// </exception> /// <remarks> /// If <see cref="IsValueCreated"/> is false, accessing <see cref="Value"/> will force initialization. /// Please <see cref="System.Threading.LazyThreadSafetyMode"> for more information on how <see cref="T:System.Threading.Lazy{T}"/> will behave if an exception is thrown /// from initialization delegate. /// </remarks> [DebuggerBrowsable(DebuggerBrowsableState.Never)] public T Value { get { Boxed boxed = null; if (m_boxed != null ) { // Do a quick check up front for the fast path. boxed = m_boxed as Boxed; if (boxed != null) { return boxed.m_value; } LazyInternalExceptionHolder exc = m_boxed as LazyInternalExceptionHolder; Contract.Assert(exc != null); exc.m_edi.Throw(); } // Fall through to the slow path. #if !FEATURE_CORECLR // We call NOCTD to abort attempts by the debugger to funceval this property (e.g. on mouseover) // (the debugger proxy is the correct way to look at state/value of this object) Debugger.NotifyOfCrossThreadDependency(); #endif return LazyInitValue(); } } /// <summary> /// local helper method to initialize the value /// </summary> /// <returns>The inititialized T value</returns> private T LazyInitValue() { Boxed boxed = null; LazyThreadSafetyMode mode = Mode; if (mode == LazyThreadSafetyMode.None) { boxed = CreateValue(); m_boxed = boxed; } else if (mode == LazyThreadSafetyMode.PublicationOnly) { boxed = CreateValue(); if (boxed == null || Interlocked.CompareExchange(ref m_boxed, boxed, null) != null) { // If CreateValue returns null, it means another thread successfully invoked the value factory // and stored the result, so we should just take what was stored. If CreateValue returns non-null // but another thread set the value we should just take what was stored. boxed = (Boxed)m_boxed; } else { // We successfully created and stored the value. At this point, the value factory delegate is // no longer needed, and we don't want to hold onto its resources. m_valueFactory = ALREADY_INVOKED_SENTINEL; } } else { object threadSafeObj = Volatile.Read(ref m_threadSafeObj); bool lockTaken = false; try { if (threadSafeObj != (object)ALREADY_INVOKED_SENTINEL) Monitor.Enter(threadSafeObj, ref lockTaken); else Contract.Assert(m_boxed != null); if (m_boxed == null) { boxed = CreateValue(); m_boxed = boxed; Volatile.Write(ref m_threadSafeObj, ALREADY_INVOKED_SENTINEL); } else // got the lock but the value is not null anymore, check if it is created by another thread or faulted and throw if so { boxed = m_boxed as Boxed; if (boxed == null) // it is not Boxed, so it is a LazyInternalExceptionHolder { LazyInternalExceptionHolder exHolder = m_boxed as LazyInternalExceptionHolder; Contract.Assert(exHolder != null); exHolder.m_edi.Throw(); } } } finally { if (lockTaken) Monitor.Exit(threadSafeObj); } } Contract.Assert(boxed != null); return boxed.m_value; } /// <summary>Creates an instance of T using m_valueFactory in case its not null or use reflection to create a new T()</summary> /// <returns>An instance of Boxed.</returns> private Boxed CreateValue() { Boxed boxed = null; LazyThreadSafetyMode mode = Mode; if (m_valueFactory != null) { try { // check for recursion if (mode != LazyThreadSafetyMode.PublicationOnly && m_valueFactory == ALREADY_INVOKED_SENTINEL) throw new InvalidOperationException(Environment.GetResourceString("Lazy_Value_RecursiveCallsToValue")); Func<T> factory = m_valueFactory; if (mode != LazyThreadSafetyMode.PublicationOnly) // only detect recursion on None and ExecutionAndPublication modes { m_valueFactory = ALREADY_INVOKED_SENTINEL; } else if (factory == ALREADY_INVOKED_SENTINEL) { // Another thread raced to successfully invoke the factory. return null; } boxed = new Boxed(factory()); } catch (Exception ex) { if (mode != LazyThreadSafetyMode.PublicationOnly) // don't cache the exception for PublicationOnly mode m_boxed = new LazyInternalExceptionHolder(ex); throw; } } else { try { boxed = new Boxed((T)Activator.CreateInstance(typeof(T))); } catch (System.MissingMethodException) { Exception ex = new System.MissingMemberException(Environment.GetResourceString("Lazy_CreateValue_NoParameterlessCtorForT")); if (mode != LazyThreadSafetyMode.PublicationOnly) // don't cache the exception for PublicationOnly mode m_boxed = new LazyInternalExceptionHolder(ex); throw ex; } } return boxed; } } /// <summary>A debugger view of the Lazy&lt;T&gt; to surface additional debugging properties and /// to ensure that the Lazy&lt;T&gt; does not become initialized if it was not already.</summary> internal sealed class System_LazyDebugView<T> { //The Lazy object being viewed. private readonly Lazy<T> m_lazy; /// <summary>Constructs a new debugger view object for the provided Lazy object.</summary> /// <param name="lazy">A Lazy object to browse in the debugger.</param> public System_LazyDebugView(Lazy<T> lazy) { m_lazy = lazy; } /// <summary>Returns whether the Lazy object is initialized or not.</summary> public bool IsValueCreated { get { return m_lazy.IsValueCreated; } } /// <summary>Returns the value of the Lazy object.</summary> public T Value { get { return m_lazy.ValueForDebugDisplay; } } /// <summary>Returns the execution mode of the Lazy object</summary> public LazyThreadSafetyMode Mode { get { return m_lazy.Mode; } } /// <summary>Returns the execution mode of the Lazy object</summary> public bool IsValueFaulted { get { return m_lazy.IsValueFaulted; } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Kudu.Services.Web.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ActionDescriptor.ReturnType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] [SuppressMessage("Microsoft.WebAPI", "CR4001:DoNotCallProblematicMethodsOnTask", Justification = "The sample generation is done synchronously.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Copyright (c) 2015 Alachisoft // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections; using Alachisoft.NCache.Caching.Exceptions; using Alachisoft.NCache.Caching.Statistics; using Alachisoft.NCache.Common; namespace Alachisoft.NCache.Caching.Topologies.Local { class HashedOverflowCache : IndexedOverflowCache { private int _bucketSize; /// <summary> /// A map that contains key lists against each bucket id. /// </summary> private Hashtable _keyList; /// <summary> /// A map of operation loggers against each bucketId /// </summary> private Hashtable _operationLoggers; private OpLogManager _logMgr; private int _stopLoggingThreshhold = 50; private bool _logEntries; public HashedOverflowCache(IDictionary cacheClasses, CacheBase parentCache, IDictionary properties, ICacheEventsListener listener, CacheRuntimeContext context, bool logEntries) : base(cacheClasses, parentCache, properties, listener, context) { _logMgr = new OpLogManager(logEntries, context); _logEntries = logEntries; } public override int BucketSize { set { _bucketSize = value; } } public override ArrayList GetKeyList(int bucketId, bool startLogging) { if (startLogging) _logMgr.StartLogging(bucketId, LogMode.LogBeforeAfterActualOperation); if (_keyList != null) { if (_keyList.Contains(bucketId)) { Hashtable keyTbl = _keyList[bucketId] as Hashtable; return new ArrayList(keyTbl.Keys); } return null; } return null; } public override Hashtable GetLogTable(ArrayList bucketIds, ref bool isLoggingStopped) { Hashtable result = null; int logCount = 0; IEnumerator ie = bucketIds.GetEnumerator(); while (ie.MoveNext()) { Hashtable tmp = _logMgr.GetLogTable((int)ie.Current); if (tmp != null) { if (result == null) result = tmp; else { ArrayList removed = tmp["removed"] as ArrayList; ArrayList updated = tmp["updated"] as ArrayList; if (removed != null) { ((ArrayList)result["removed"]).AddRange(removed); logCount += removed.Count; } if (updated != null) { ((ArrayList)result["updated"]).AddRange(updated); logCount += updated.Count; } } } } if (logCount < _stopLoggingThreshhold) { isLoggingStopped = true; _logMgr.StopLogging(bucketIds); } else isLoggingStopped = false; return result; } public override void RemoveFromLogTbl(int bucketId) { if (_logMgr != null) _logMgr.RemoveLogger(bucketId); } public override void RemoveBucket(int bucket) { if (Context.NCacheLog.IsInfoEnabled) Context.NCacheLog.Info("HashedCache.RemoveBucket", "removing bucket :" + bucket); //Remove from stats LocalBuckets.Remove(bucket); //Remove actual data of the bucket RemoveBucketData(bucket); //remove operation logger for the bucket from log table if any exists. RemoveFromLogTbl(bucket); } public override void RemoveBucketData(int bucketId) { if (Context.NCacheLog.IsInfoEnabled) Context.NCacheLog.Info("HashedOverflowCache.RemoveBucketData", "removing bucket data:" + bucketId); ArrayList keys = GetKeyList(bucketId, false); if (keys != null) { keys = keys.Clone() as ArrayList; IEnumerator ie = keys.GetEnumerator(); while (ie.MoveNext()) { Remove(ie.Current, ItemRemoveReason.Removed, false, false, null, LockAccessType.IGNORE_LOCK,new OperationContext(OperationContextFieldName.OperationType,OperationContextOperationType.CacheOperation)); } } } public override void UpdateLocalBuckets(ArrayList bucketIds) { IEnumerator ie = bucketIds.GetEnumerator(); while (ie.MoveNext()) { if (LocalBuckets == null) LocalBuckets = new Hashtable(); if (!LocalBuckets.Contains(ie.Current)) { LocalBuckets[ie.Current] = new BucketStatistics(); } } } public override void StartLogging(int bucketId) { if (_logMgr != null) _logMgr.StartLogging(bucketId, LogMode.LogBeforeActualOperation); } private void IncrementBucketStats(string key, int bucketId, long dataSize) { if (_stats.LocalBuckets.Contains(bucketId)) { ((BucketStatistics)_stats.LocalBuckets[bucketId]).Increment(dataSize); } if (_keyList == null) _keyList = new Hashtable(); if (_keyList.Contains(bucketId)) { Hashtable keys = (Hashtable)_keyList[bucketId]; keys[key] = null; } else { Hashtable keys = new Hashtable(); keys[key] = null; _keyList[bucketId] = keys; } } private void DecrementBucketStats(string key, int bucketId, long dataSize) { if (_stats.LocalBuckets.Contains(bucketId)) { ((BucketStatistics)_stats.LocalBuckets[bucketId]).Decrement(dataSize); } if (_keyList != null) { if (_keyList.Contains(bucketId)) { Hashtable keys = (Hashtable)_keyList[bucketId]; keys.Remove(key); if (keys.Count == 0) _keyList.Remove(bucketId); } } } private bool IsBucketTransfered(int bucketId) { return !_logMgr.IsOperationAllowed(bucketId); } private int GetBucketId(string key) { //int hashCode = key.GetHashCode(); int hashCode = AppUtil.GetHashCode(key); int bucketId = hashCode / _bucketSize; if (bucketId < 0) bucketId *= -1; return bucketId; } public override Hashtable LocalBuckets { get { return _stats.LocalBuckets; } set { _stats.LocalBuckets = value; } } public override void AddLoggedData(ArrayList bucketIds) { if (bucketIds != null) { IEnumerator ie = bucketIds.GetEnumerator(); while (ie.MoveNext()) { if (_logMgr != null) { Hashtable loggedEnteries = _logMgr.GetLoggedEnteries((int)ie.Current); if (loggedEnteries != null && loggedEnteries.Count > 0) { Hashtable removed = loggedEnteries["removed"] as Hashtable; Hashtable updated = loggedEnteries["updated"] as Hashtable; if (removed != null && removed.Count > 0) { IDictionaryEnumerator ide = removed.GetEnumerator(); while (ide.MoveNext()) { Remove(ide.Key, ItemRemoveReason.Removed, false, null, LockAccessType.IGNORE_LOCK,new OperationContext(OperationContextFieldName.OperationType,OperationContextOperationType.CacheOperation)); } } if (updated != null && updated.Count > 0) { IDictionaryEnumerator ide = updated.GetEnumerator(); while (ide.MoveNext()) { CacheEntry entry = ide.Value as CacheEntry; if (entry != null) { Insert(ide.Key, entry, false, false, null, LockAccessType.IGNORE_LOCK,new OperationContext(OperationContextFieldName.OperationType,OperationContextOperationType.CacheOperation)); } } } } //muds: //disable logging for this bucket... _logMgr.RemoveLogger((int)ie.Current); } } } } #region / --- Cache overrides --- / public override void Dispose() { if (_logMgr != null) _logMgr.Dispose(); if (_keyList != null) _keyList.Clear(); base.Dispose(); } internal override CacheAddResult AddInternal(object key, CacheEntry cacheEntry, bool isUserOperation) { int bucketId = GetBucketId(key as string); if (IsBucketTransfered(bucketId)) throw new StateTransferException("I am no more the owner of this bucket"); if (_logMgr.IsLoggingEnbaled(bucketId, LogMode.LogBeforeActualOperation) && isUserOperation) { _logMgr.LogOperation(bucketId, key, cacheEntry, OperationType.Add); return CacheAddResult.Success; } CacheAddResult result = base.AddInternal(key, cacheEntry, isUserOperation); if (result == CacheAddResult.Success || result == CacheAddResult.SuccessNearEviction) { IncrementBucketStats(key as string, bucketId, cacheEntry.DataSize); if (isUserOperation) _logMgr.LogOperation(bucketId, key, cacheEntry, OperationType.Add); } return result; } internal override bool AddInternal(object key, Alachisoft.NCache.Caching.AutoExpiration.ExpirationHint eh, OperationContext operationContext) { int bucketId = GetBucketId(key as string); if (IsBucketTransfered(bucketId)) throw new StateTransferException("I am no more the owner of this bucket"); return base.AddInternal(key, eh, operationContext); } /// <summary> /// Removes all entries from the store. /// </summary> internal override void ClearInternal() { base.ClearInternal(); if (_keyList != null) _keyList.Clear(); if (_logMgr != null) _logMgr.Dispose(); //it clears the operation loggers for each bucket //clear the bucket stats IDictionaryEnumerator ide = LocalBuckets.GetEnumerator(); while (ide.MoveNext()) { BucketStatistics stats = ide.Value as BucketStatistics; if (stats != null) { stats.Clear(); } } } internal override CacheInsResult InsertInternal(object key, CacheEntry cacheEntry, bool isUserOperation, CacheEntry oldEntry, OperationContext operationContext) { int bucketId = GetBucketId(key as string); if (IsBucketTransfered(bucketId)) throw new StateTransferException("I am no more the owner of this bucket"); long oldEntrysize = oldEntry == null ? 0 : oldEntry.DataSize; if (_logMgr.IsLoggingEnbaled(bucketId, LogMode.LogBeforeActualOperation) && isUserOperation) { _logMgr.LogOperation(bucketId, key, cacheEntry, OperationType.Insert); return oldEntry != null ? CacheInsResult.SuccessOverwrite : CacheInsResult.Success; } CacheInsResult result = base.InsertInternal(key, cacheEntry, isUserOperation,oldEntry,operationContext); switch (result) { case CacheInsResult.SuccessNearEvicition: case CacheInsResult.Success: if (isUserOperation) _logMgr.LogOperation(bucketId, key, cacheEntry, OperationType.Insert); IncrementBucketStats(key as string, bucketId, cacheEntry.DataSize); break; case CacheInsResult.SuccessOverwriteNearEviction: case CacheInsResult.SuccessOverwrite: if (isUserOperation) _logMgr.LogOperation(bucketId, key, cacheEntry, OperationType.Insert); DecrementBucketStats(key as string, bucketId, oldEntrysize); IncrementBucketStats(key as string, bucketId, cacheEntry.DataSize); break; } return result; } internal override CacheEntry RemoveInternal(object key, ItemRemoveReason removalReason, bool isUserOperation, OperationContext operationContext) { int bucketId = GetBucketId(key as string); if (isUserOperation) { if (IsBucketTransfered(bucketId)) throw new StateTransferException("I am no more the owner of this bucket"); } if (_logMgr.IsLoggingEnbaled(bucketId, LogMode.LogBeforeActualOperation) && isUserOperation) { CacheEntry e = Get(key,operationContext); _logMgr.LogOperation(bucketId, key, null, OperationType.Delete); return e; } CacheEntry entry = base.RemoveInternal(key, removalReason, isUserOperation,operationContext); if (entry != null) { if (isUserOperation) _logMgr.LogOperation(bucketId, key, null, OperationType.Delete); DecrementBucketStats(key as string, bucketId, entry.DataSize); } return entry; } internal override CacheEntry GetInternal(object key, bool isUserOperation, OperationContext operationContext) { int bucketId = GetBucketId(key as string); if (IsBucketTransfered(bucketId)) throw new StateTransferException("I am no more the owner of this bucket"); return base.GetInternal(key, isUserOperation,operationContext); } internal override bool ContainsInternal(object key) { int bucketId = GetBucketId(key as string); if (IsBucketTransfered(bucketId)) throw new StateTransferException("I am no more the owner of this bucket"); return base.ContainsInternal(key); } #endregion } }
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.LayoutRenderers { using System; using System.Collections.Generic; using NLog.LayoutRenderers; using NLog.Layouts; using NLog.Targets; using NLog.Internal; using Xunit; using NLog.Config; public class ExceptionTests : NLogTestBase { private ILogger logger = LogManager.GetLogger("NLog.UnitTests.LayoutRenderer.ExceptionTests"); private const string ExceptionDataFormat = "{0}: {1}"; [Fact] public void ExceptionWithStackTrace_ObsoleteMethodTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets> <target name='debug1' type='Debug' layout='${exception}' /> <target name='debug2' type='Debug' layout='${exception:format=stacktrace}' /> <target name='debug3' type='Debug' layout='${exception:format=type}' /> <target name='debug4' type='Debug' layout='${exception:format=shorttype}' /> <target name='debug5' type='Debug' layout='${exception:format=tostring}' /> <target name='debug6' type='Debug' layout='${exception:format=message}' /> <target name='debug7' type='Debug' layout='${exception:format=method}' /> <target name='debug8' type='Debug' layout='${exception:format=message,shorttype:separator=*}' /> <target name='debug9' type='Debug' layout='${exception:format=data}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug1,debug2,debug3,debug4,debug5,debug6,debug7,debug8,debug9' /> </rules> </nlog>"); const string exceptionMessage = "Test exception"; const string exceptionDataKey = "testkey"; const string exceptionDataValue = "testvalue"; Exception ex = GetExceptionWithStackTrace(exceptionMessage); ex.Data.Add(exceptionDataKey, exceptionDataValue); #pragma warning disable 0618 // Obsolete method requires testing until completely removed. logger.ErrorException("msg", ex); #pragma warning restore 0618 AssertDebugLastMessage("debug1", exceptionMessage); AssertDebugLastMessage("debug2", ex.StackTrace); AssertDebugLastMessage("debug3", typeof(InvalidOperationException).FullName); AssertDebugLastMessage("debug4", typeof(InvalidOperationException).Name); AssertDebugLastMessage("debug5", ex.ToString()); AssertDebugLastMessage("debug6", exceptionMessage); AssertDebugLastMessage("debug9", string.Format(ExceptionDataFormat, exceptionDataKey, exceptionDataValue)); // each version of the framework produces slightly different information for MethodInfo, so we just // make sure it's not empty var debug7Target = (NLog.Targets.DebugTarget)LogManager.Configuration.FindTargetByName("debug7"); Assert.False(string.IsNullOrEmpty(debug7Target.LastMessage)); AssertDebugLastMessage("debug8", "Test exception*" + typeof(InvalidOperationException).Name); } [Fact] public void ExceptionWithStackTraceTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets> <target name='debug1' type='Debug' layout='${exception}' /> <target name='debug2' type='Debug' layout='${exception:format=stacktrace}' /> <target name='debug3' type='Debug' layout='${exception:format=type}' /> <target name='debug4' type='Debug' layout='${exception:format=shorttype}' /> <target name='debug5' type='Debug' layout='${exception:format=tostring}' /> <target name='debug6' type='Debug' layout='${exception:format=message}' /> <target name='debug7' type='Debug' layout='${exception:format=method}' /> <target name='debug8' type='Debug' layout='${exception:format=message,shorttype:separator=*}' /> <target name='debug9' type='Debug' layout='${exception:format=data}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug1,debug2,debug3,debug4,debug5,debug6,debug7,debug8,debug9' /> </rules> </nlog>"); const string exceptionMessage = "Test exception"; const string exceptionDataKey = "testkey"; const string exceptionDataValue = "testvalue"; Exception ex = GetExceptionWithStackTrace(exceptionMessage); ex.Data.Add(exceptionDataKey, exceptionDataValue); logger.Error(ex, "msg"); AssertDebugLastMessage("debug1", exceptionMessage); AssertDebugLastMessage("debug2", ex.StackTrace); AssertDebugLastMessage("debug3", typeof(InvalidOperationException).FullName); AssertDebugLastMessage("debug4", typeof(InvalidOperationException).Name); AssertDebugLastMessage("debug5", ex.ToString()); AssertDebugLastMessage("debug6", exceptionMessage); AssertDebugLastMessage("debug9", string.Format(ExceptionDataFormat, exceptionDataKey, exceptionDataValue)); // each version of the framework produces slightly different information for MethodInfo, so we just // make sure it's not empty var debug7Target = (NLog.Targets.DebugTarget)LogManager.Configuration.FindTargetByName("debug7"); Assert.False(string.IsNullOrEmpty(debug7Target.LastMessage)); AssertDebugLastMessage("debug8", exceptionMessage + "*" + typeof(InvalidOperationException).Name); } /// <summary> /// Just wrrite exception, no message argument. /// </summary> [Fact] public void ExceptionWithoutMessageParam() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets> <target name='debug1' type='Debug' layout='${exception}' /> <target name='debug2' type='Debug' layout='${exception:format=stacktrace}' /> <target name='debug3' type='Debug' layout='${exception:format=type}' /> <target name='debug4' type='Debug' layout='${exception:format=shorttype}' /> <target name='debug5' type='Debug' layout='${exception:format=tostring}' /> <target name='debug6' type='Debug' layout='${exception:format=message}' /> <target name='debug7' type='Debug' layout='${exception:format=method}' /> <target name='debug8' type='Debug' layout='${exception:format=message,shorttype:separator=*}' /> <target name='debug9' type='Debug' layout='${exception:format=data}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug1,debug2,debug3,debug4,debug5,debug6,debug7,debug8,debug9' /> </rules> </nlog>"); const string exceptionMessage = "I don't like nullref exception!"; const string exceptionDataKey = "testkey"; const string exceptionDataValue = "testvalue"; Exception ex = GetExceptionWithStackTrace(exceptionMessage); ex.Data.Add(exceptionDataKey, exceptionDataValue); logger.Error(ex); AssertDebugLastMessage("debug1", exceptionMessage); AssertDebugLastMessage("debug2", ex.StackTrace); AssertDebugLastMessage("debug3", typeof(InvalidOperationException).FullName); AssertDebugLastMessage("debug4", typeof(InvalidOperationException).Name); AssertDebugLastMessage("debug5", ex.ToString()); AssertDebugLastMessage("debug6", exceptionMessage); AssertDebugLastMessage("debug9", string.Format(ExceptionDataFormat, exceptionDataKey, exceptionDataValue)); // each version of the framework produces slightly different information for MethodInfo, so we just // make sure it's not empty var debug7Target = (NLog.Targets.DebugTarget)LogManager.Configuration.FindTargetByName("debug7"); Assert.False(string.IsNullOrEmpty(debug7Target.LastMessage)); AssertDebugLastMessage("debug8", exceptionMessage + "*" + typeof(InvalidOperationException).Name); } [Fact] public void ExceptionWithoutStackTrace_ObsoleteMethodTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets> <target name='debug1' type='Debug' layout='${exception}' /> <target name='debug2' type='Debug' layout='${exception:format=stacktrace}' /> <target name='debug3' type='Debug' layout='${exception:format=type}' /> <target name='debug4' type='Debug' layout='${exception:format=shorttype}' /> <target name='debug5' type='Debug' layout='${exception:format=tostring}' /> <target name='debug6' type='Debug' layout='${exception:format=message}' /> <target name='debug7' type='Debug' layout='${exception:format=method}' /> <target name='debug8' type='Debug' layout='${exception:format=message,shorttype:separator=*}' /> <target name='debug9' type='Debug' layout='${exception:format=data}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug1,debug2,debug3,debug4,debug5,debug6,debug7,debug8,debug9' /> </rules> </nlog>"); const string exceptionMessage = "Test exception"; const string exceptionDataKey = "testkey"; const string exceptionDataValue = "testvalue"; Exception ex = GetExceptionWithoutStackTrace(exceptionMessage); ex.Data.Add(exceptionDataKey, exceptionDataValue); #pragma warning disable 0618 // Obsolete method requires testing until completely removed. logger.ErrorException("msg", ex); #pragma warning restore 0618 AssertDebugLastMessage("debug1", exceptionMessage); AssertDebugLastMessage("debug2", ""); AssertDebugLastMessage("debug3", typeof(InvalidOperationException).FullName); AssertDebugLastMessage("debug4", typeof(InvalidOperationException).Name); AssertDebugLastMessage("debug5", ex.ToString()); AssertDebugLastMessage("debug6", exceptionMessage); AssertDebugLastMessage("debug7", ""); AssertDebugLastMessage("debug8", "Test exception*" + typeof(InvalidOperationException).Name); AssertDebugLastMessage("debug9", string.Format(ExceptionDataFormat, exceptionDataKey, exceptionDataValue)); } [Fact] public void ExceptionWithoutStackTraceTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets> <target name='debug1' type='Debug' layout='${exception}' /> <target name='debug2' type='Debug' layout='${exception:format=stacktrace}' /> <target name='debug3' type='Debug' layout='${exception:format=type}' /> <target name='debug4' type='Debug' layout='${exception:format=shorttype}' /> <target name='debug5' type='Debug' layout='${exception:format=tostring}' /> <target name='debug6' type='Debug' layout='${exception:format=message}' /> <target name='debug7' type='Debug' layout='${exception:format=method}' /> <target name='debug8' type='Debug' layout='${exception:format=message,shorttype:separator=*}' /> <target name='debug9' type='Debug' layout='${exception:format=data}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug1,debug2,debug3,debug4,debug5,debug6,debug7,debug8,debug9' /> </rules> </nlog>"); const string exceptionMessage = "Test exception"; const string exceptionDataKey = "testkey"; const string exceptionDataValue = "testvalue"; Exception ex = GetExceptionWithoutStackTrace(exceptionMessage); ex.Data.Add(exceptionDataKey, exceptionDataValue); logger.Error(ex, "msg"); AssertDebugLastMessage("debug1", exceptionMessage); AssertDebugLastMessage("debug2", ""); AssertDebugLastMessage("debug3", typeof(InvalidOperationException).FullName); AssertDebugLastMessage("debug4", typeof(InvalidOperationException).Name); AssertDebugLastMessage("debug5", ex.ToString()); AssertDebugLastMessage("debug6", exceptionMessage); AssertDebugLastMessage("debug7", ""); AssertDebugLastMessage("debug8", "Test exception*" + typeof(InvalidOperationException).Name); AssertDebugLastMessage("debug9", string.Format(ExceptionDataFormat, exceptionDataKey, exceptionDataValue)); } [Fact] public void ExceptionNewLineSeparatorTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets> <target name='debug1' type='Debug' layout='${exception:format=message,shorttype:separator=&#13;&#10;}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug1' /> </rules> </nlog>"); string exceptionMessage = "Test exception"; Exception ex = GetExceptionWithStackTrace(exceptionMessage); #pragma warning disable 0618 // Obsolete method requires testing until completely removed. logger.ErrorException("msg", ex); AssertDebugLastMessage("debug1", "Test exception\r\n" + typeof(InvalidOperationException).Name); #pragma warning restore 0618 logger.Error(ex, "msg"); AssertDebugLastMessage("debug1", "Test exception\r\n" + typeof(InvalidOperationException).Name); } [Fact] public void ExceptionUsingLogMethodTest() { SetConfigurationForExceptionUsingRootMethodTests(); string exceptionMessage = "Test exception"; Exception ex = GetExceptionWithStackTrace(exceptionMessage); logger.Log(LogLevel.Error, ex, "msg"); AssertDebugLastMessage("debug1", "ERROR*Test exception*" + typeof(InvalidOperationException).Name); } [Fact] public void ExceptionUsingTraceMethodTest() { SetConfigurationForExceptionUsingRootMethodTests(); string exceptionMessage = "Test exception"; Exception ex = GetExceptionWithStackTrace(exceptionMessage); logger.Trace(ex, "msg"); AssertDebugLastMessage("debug1", "TRACE*Test exception*" + typeof(InvalidOperationException).Name); } [Fact] public void ExceptionUsingDebugMethodTest() { SetConfigurationForExceptionUsingRootMethodTests(); string exceptionMessage = "Test exception"; Exception ex = GetExceptionWithStackTrace(exceptionMessage); logger.Debug(ex, "msg"); AssertDebugLastMessage("debug1", "DEBUG*Test exception*" + typeof(InvalidOperationException).Name); } [Fact] public void ExceptionUsingInfoMethodTest() { SetConfigurationForExceptionUsingRootMethodTests(); string exceptionMessage = "Test exception"; Exception ex = GetExceptionWithStackTrace(exceptionMessage); logger.Info(ex, "msg"); AssertDebugLastMessage("debug1", "INFO*Test exception*" + typeof(InvalidOperationException).Name); } [Fact] public void ExceptionUsingWarnMethodTest() { SetConfigurationForExceptionUsingRootMethodTests(); string exceptionMessage = "Test exception"; Exception ex = GetExceptionWithStackTrace(exceptionMessage); logger.Warn(ex, "msg"); AssertDebugLastMessage("debug1", "WARN*Test exception*" + typeof(InvalidOperationException).Name); } [Fact] public void ExceptionUsingErrorMethodTest() { SetConfigurationForExceptionUsingRootMethodTests(); string exceptionMessage = "Test exception"; Exception ex = GetExceptionWithStackTrace(exceptionMessage); logger.Error(ex, "msg"); AssertDebugLastMessage("debug1", "ERROR*Test exception*" + typeof(InvalidOperationException).Name); } [Fact] public void ExceptionUsingFatalMethodTest() { SetConfigurationForExceptionUsingRootMethodTests(); string exceptionMessage = "Test exception"; Exception ex = GetExceptionWithStackTrace(exceptionMessage); logger.Fatal(ex, "msg"); AssertDebugLastMessage("debug1", "FATAL*Test exception*" + typeof(InvalidOperationException).Name); } [Fact] public void InnerExceptionTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets> <target name='debug1' type='Debug' layout='${exception:format=shorttype,message:maxInnerExceptionLevel=3}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug1' /> </rules> </nlog>"); string exceptionMessage = "Test exception"; Exception ex = GetNestedExceptionWithStackTrace(exceptionMessage); #pragma warning disable 0618 // Obsolete method requires testing until completely removed. logger.ErrorException("msg", ex); AssertDebugLastMessage("debug1", "InvalidOperationException Wrapper2" + EnvironmentHelper.NewLine + "InvalidOperationException Wrapper1" + EnvironmentHelper.NewLine + "InvalidOperationException Test exception"); #pragma warning restore 0618 logger.Error(ex, "msg"); AssertDebugLastMessage("debug1", "InvalidOperationException Wrapper2" + EnvironmentHelper.NewLine + "InvalidOperationException Wrapper1" + EnvironmentHelper.NewLine + "InvalidOperationException Test exception"); } [Fact] public void CustomInnerException_ObsoleteMethodTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets> <target name='debug1' type='Debug' layout='${exception:format=shorttype,message:maxInnerExceptionLevel=1:innerExceptionSeparator=&#13;&#10;----INNER----&#13;&#10;:innerFormat=type,message}' /> <target name='debug2' type='Debug' layout='${exception:format=shorttype,message:maxInnerExceptionLevel=1:innerExceptionSeparator=&#13;&#10;----INNER----&#13;&#10;:innerFormat=type,message,data}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug1' /> <logger minlevel='Info' writeTo='debug2' /> </rules> </nlog>"); var t = (DebugTarget)LogManager.Configuration.AllTargets[0]; var elr = ((SimpleLayout)t.Layout).Renderers[0] as ExceptionLayoutRenderer; Assert.Equal("\r\n----INNER----\r\n", elr.InnerExceptionSeparator); string exceptionMessage = "Test exception"; const string exceptionDataKey = "testkey"; const string exceptionDataValue = "testvalue"; Exception ex = GetNestedExceptionWithStackTrace(exceptionMessage); ex.InnerException.Data.Add(exceptionDataKey, exceptionDataValue); #pragma warning disable 0618 // Obsolete method requires testing until completely removed. logger.ErrorException("msg", ex); #pragma warning restore 0618 AssertDebugLastMessage("debug1", "InvalidOperationException Wrapper2" + "\r\n----INNER----\r\n" + "System.InvalidOperationException Wrapper1"); AssertDebugLastMessage("debug2", string.Format("InvalidOperationException Wrapper2" + "\r\n----INNER----\r\n" + "System.InvalidOperationException Wrapper1 " + ExceptionDataFormat, exceptionDataKey, exceptionDataValue)); } [Fact] public void CustomInnerExceptionTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets> <target name='debug1' type='Debug' layout='${exception:format=shorttype,message:maxInnerExceptionLevel=1:innerExceptionSeparator=&#13;&#10;----INNER----&#13;&#10;:innerFormat=type,message}' /> <target name='debug2' type='Debug' layout='${exception:format=shorttype,message:maxInnerExceptionLevel=1:innerExceptionSeparator=&#13;&#10;----INNER----&#13;&#10;:innerFormat=type,message,data}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug1' /> <logger minlevel='Info' writeTo='debug2' /> </rules> </nlog>"); var t = (DebugTarget)LogManager.Configuration.AllTargets[0]; var elr = ((SimpleLayout)t.Layout).Renderers[0] as ExceptionLayoutRenderer; Assert.Equal("\r\n----INNER----\r\n", elr.InnerExceptionSeparator); string exceptionMessage = "Test exception"; const string exceptionDataKey = "testkey"; const string exceptionDataValue = "testvalue"; Exception ex = GetNestedExceptionWithStackTrace(exceptionMessage); ex.InnerException.Data.Add(exceptionDataKey, exceptionDataValue); logger.Error(ex, "msg"); AssertDebugLastMessage("debug1", "InvalidOperationException Wrapper2" + "\r\n----INNER----\r\n" + "System.InvalidOperationException Wrapper1"); AssertDebugLastMessage("debug2", string.Format("InvalidOperationException Wrapper2" + "\r\n----INNER----\r\n" + "System.InvalidOperationException Wrapper1 " + ExceptionDataFormat, exceptionDataKey, exceptionDataValue)); } [Fact] public void ErrorException_should_not_throw_exception_when_exception_message_property_throw_exception() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets> <target name='debug1' type='Debug' layout='${exception}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug1' /> </rules> </nlog>"); var ex = new ExceptionWithBrokenMessagePropertyException(); #pragma warning disable 0618 // Obsolete method requires testing until completely removed. Assert.ThrowsDelegate action = () => logger.ErrorException("msg", ex); #pragma warning restore 0618 Assert.DoesNotThrow(action); } private class ExceptionWithBrokenMessagePropertyException : NLogConfigurationException { public override string Message { get { throw new Exception("Exception from Message property"); } } } private void SetConfigurationForExceptionUsingRootMethodTests() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets> <target name='debug1' type='Debug' layout='${level:uppercase=true}*${exception:format=message,shorttype:separator=*}' /> </targets> <rules> <logger minlevel='Trace' writeTo='debug1' /> </rules> </nlog>"); } /// <summary> /// Get an excption with stacktrace by genating a exception /// </summary> /// <param name="exceptionMessage"></param> /// <returns></returns> private Exception GetExceptionWithStackTrace(string exceptionMessage) { try { GenericClass<int, string, bool>.Method1("aaa", true, null, 42, DateTime.Now, exceptionMessage); return null; } catch (Exception exception) { return exception; } } private Exception GetNestedExceptionWithStackTrace(string exceptionMessage) { try { try { try { GenericClass<int, string, bool>.Method1("aaa", true, null, 42, DateTime.Now, exceptionMessage); } catch (Exception exception) { throw new InvalidOperationException("Wrapper1", exception); } } catch (Exception exception) { throw new InvalidOperationException("Wrapper2", exception); } return null; } catch (Exception ex) { return ex; } } private Exception GetExceptionWithoutStackTrace(string exceptionMessage) { return new InvalidOperationException(exceptionMessage); } private class GenericClass<TA, TB, TC> { internal static List<GenericClass<TA, TB, TC>> Method1(string aaa, bool b, object o, int i, DateTime now, string exceptionMessage) { Method2(aaa, b, o, i, now, null, null, exceptionMessage); return null; } internal static int Method2<T1, T2, T3>(T1 aaa, T2 b, T3 o, int i, DateTime now, Nullable<int> gfff, List<int>[] something, string exceptionMessage) { throw new InvalidOperationException(exceptionMessage); } } [Fact] public void ExcpetionTestAPI() { var config = new LoggingConfiguration(); var debugTarget = new DebugTarget(); config.AddTarget("debug1", debugTarget); debugTarget.Layout = @"${exception:format=shorttype,message:maxInnerExceptionLevel=3}"; var rule = new LoggingRule("*", LogLevel.Info, debugTarget); config.LoggingRules.Add(rule); LogManager.Configuration = config; string exceptionMessage = "Test exception"; Exception ex = GetNestedExceptionWithStackTrace(exceptionMessage); #pragma warning disable 0618 // Obsolete method requires testing until completely removed. logger.ErrorException("msg", ex); AssertDebugLastMessage("debug1", "InvalidOperationException Wrapper2" + EnvironmentHelper.NewLine + "InvalidOperationException Wrapper1" + EnvironmentHelper.NewLine + "InvalidOperationException Test exception"); #pragma warning restore 0618 logger.Error(ex, "msg"); AssertDebugLastMessage("debug1", "InvalidOperationException Wrapper2" + EnvironmentHelper.NewLine + "InvalidOperationException Wrapper1" + EnvironmentHelper.NewLine + "InvalidOperationException Test exception"); var t = (DebugTarget)LogManager.Configuration.AllTargets[0]; var elr = ((SimpleLayout)t.Layout).Renderers[0] as ExceptionLayoutRenderer; Assert.Equal(ExceptionRenderingFormat.ShortType, elr.Formats[0]); Assert.Equal(ExceptionRenderingFormat.Message, elr.Formats[1]); } [Fact] public void InnerExceptionTestAPI() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets> <target name='debug1' type='Debug' layout='${exception:format=shorttype,message:maxInnerExceptionLevel=3:innerFormat=message}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug1' /> </rules> </nlog>"); string exceptionMessage = "Test exception"; Exception ex = GetNestedExceptionWithStackTrace(exceptionMessage); #pragma warning disable 0618 // Obsolete method requires testing until completely removed. logger.ErrorException("msg", ex); AssertDebugLastMessage("debug1", "InvalidOperationException Wrapper2" + EnvironmentHelper.NewLine + "Wrapper1" + EnvironmentHelper.NewLine + "Test exception"); #pragma warning restore 0618 logger.Error(ex, "msg"); AssertDebugLastMessage("debug1", "InvalidOperationException Wrapper2" + EnvironmentHelper.NewLine + "Wrapper1" + EnvironmentHelper.NewLine + "Test exception"); var t = (DebugTarget)LogManager.Configuration.AllTargets[0]; var elr = ((SimpleLayout)t.Layout).Renderers[0] as ExceptionLayoutRenderer; Assert.Equal(ExceptionRenderingFormat.ShortType, elr.Formats[0]); Assert.Equal(ExceptionRenderingFormat.Message, elr.Formats[1]); Assert.Equal(ExceptionRenderingFormat.Message, elr.InnerFormats[0]); } [Fact] public void CustomExceptionLayoutRendrerInnerExceptionTest() { ConfigurationItemFactory.Default.LayoutRenderers.RegisterDefinition("exception-custom", typeof(CustomExceptionLayoutRendrer)); LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets> <target name='debug1' type='Debug' layout='${exception-custom:format=shorttype,message:maxInnerExceptionLevel=1:innerExceptionSeparator=&#13;&#10;----INNER----&#13;&#10;:innerFormat=type,message}' /> <target name='debug2' type='Debug' layout='${exception-custom:format=shorttype,message:maxInnerExceptionLevel=1:innerExceptionSeparator=&#13;&#10;----INNER----&#13;&#10;:innerFormat=type,message,data}' /> </targets> <rules> <logger minlevel='Info' writeTo='debug1' /> <logger minlevel='Info' writeTo='debug2' /> </rules> </nlog>"); var t = (DebugTarget)LogManager.Configuration.AllTargets[0]; var elr = ((SimpleLayout)t.Layout).Renderers[0] as CustomExceptionLayoutRendrer; Assert.Equal("\r\n----INNER----\r\n", elr.InnerExceptionSeparator); string exceptionMessage = "Test exception"; const string exceptionDataKey = "testkey"; const string exceptionDataValue = "testvalue"; Exception ex = GetNestedExceptionWithStackTrace(exceptionMessage); ex.InnerException.Data.Add(exceptionDataKey, exceptionDataValue); logger.Error(ex, "msg"); AssertDebugLastMessage("debug1", "InvalidOperationException Wrapper2" + "\r\ncustom-exception-renderer" + "\r\n----INNER----\r\n" + "System.InvalidOperationException Wrapper1" + "\r\ncustom-exception-renderer"); AssertDebugLastMessage("debug2", string.Format("InvalidOperationException Wrapper2" + "\r\ncustom-exception-renderer" + "\r\n----INNER----\r\n" + "System.InvalidOperationException Wrapper1" + "\r\ncustom-exception-renderer " + ExceptionDataFormat, exceptionDataKey, exceptionDataValue + "\r\ncustom-exception-renderer-data")); } } [LayoutRenderer("exception-custom")] [ThreadAgnostic] public class CustomExceptionLayoutRendrer : ExceptionLayoutRenderer { protected override void AppendMessage(System.Text.StringBuilder sb, Exception ex) { base.AppendMessage(sb, ex); sb.Append("\r\ncustom-exception-renderer"); } protected override void AppendData(System.Text.StringBuilder sb, Exception ex) { base.AppendData(sb, ex); sb.Append("\r\ncustom-exception-renderer-data"); } } }
//------------------------------------------------------------------------------ // <copyright file="HtmlTableCell.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* * HtmlTableCell.cs * * Copyright (c) 2000 Microsoft Corporation */ namespace System.Web.UI.HtmlControls { using System; using System.Collections; using System.ComponentModel; using System.Globalization; using System.Web; using System.Web.UI; using System.Security.Permissions; /// <devdoc> /// <para> /// The <see langword='HtmlTableCell'/> /// class defines the properties, methods, and events for the HtmlTableCell control. /// This class allows programmatic access on the server to individual HTML /// &lt;td&gt; and &lt;th&gt; elements enclosed within an /// <see langword='HtmlTableRow'/> /// control. /// </para> /// </devdoc> [ConstructorNeedsTag(true)] public class HtmlTableCell : HtmlContainerControl { /// <devdoc> /// </devdoc> public HtmlTableCell() : base("td") { } /// <devdoc> /// </devdoc> public HtmlTableCell(string tagName) : base(tagName) { } /// <devdoc> /// <para> /// Gets or sets the horizontal alignment of content within an /// <see langword='HtmlTableCell'/> control. /// </para> /// </devdoc> [ WebCategory("Layout"), DefaultValue(""), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public string Align { get { string s = Attributes["align"]; return((s != null) ? s : String.Empty); } set { Attributes["align"] = MapStringAttributeToString(value); } } /// <devdoc> /// <para> /// Gets or sets the background color of an <see langword='HtmlTableCell'/> /// control. /// </para> /// </devdoc> [ WebCategory("Appearance"), DefaultValue(""), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public string BgColor { get { string s = Attributes["bgcolor"]; return((s != null) ? s : String.Empty); } set { Attributes["bgcolor"] = MapStringAttributeToString(value); } } /// <devdoc> /// <para> /// Gets or sets the border color of an <see langword='HtmlTableCell'/> /// control. /// </para> /// </devdoc> [ WebCategory("Appearance"), DefaultValue(""), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public string BorderColor { get { string s = Attributes["bordercolor"]; return((s != null) ? s : String.Empty); } set { Attributes["bordercolor"] = MapStringAttributeToString(value); } } /* * Number of columns that this cell spans. */ /// <devdoc> /// <para> /// Gets or sets the number of columns that the HtmlTableCell control spans. /// </para> /// </devdoc> [ WebCategory("Layout"), DefaultValue(""), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public int ColSpan { get { string s = Attributes["colspan"]; return((s != null) ? Int32.Parse(s, CultureInfo.InvariantCulture) : -1); } set { Attributes["colspan"] = MapIntegerAttributeToString(value); } } /// <devdoc> /// <para> /// Gets or sets the height, in pixels, of an <see langword='HtmlTableCell'/> /// control. /// </para> /// </devdoc> [ WebCategory("Layout"), DefaultValue(""), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public string Height { get { string s = Attributes["height"]; return((s != null) ? s : String.Empty); } set { Attributes["height"] = MapStringAttributeToString(value); } } /* * Suppresses wrapping. */ /// <devdoc> /// <para> /// Gets or sets a value indicating whether text within an /// <see langword='HtmlTableCell'/> control /// should be wrapped. /// </para> /// </devdoc> [ WebCategory("Behavior"), DefaultValue(""), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), TypeConverter(typeof(MinimizableAttributeTypeConverter)) ] public bool NoWrap { get { string s = Attributes["nowrap"]; return((s != null) ? (s.Equals("nowrap")) : false); } set { if (value) Attributes["nowrap"] = "nowrap"; else Attributes["nowrap"] = null; } } /* * Number of rows that this cell spans. */ /// <devdoc> /// <para> /// Gets or sets the number of rows an <see langword='HtmlTableCell'/> control /// spans. /// </para> /// </devdoc> [ WebCategory("Layout"), DefaultValue(""), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public int RowSpan { get { string s = Attributes["rowspan"]; return((s != null) ? Int32.Parse(s, CultureInfo.InvariantCulture) : -1); } set { Attributes["rowspan"] = MapIntegerAttributeToString(value); } } /// <devdoc> /// <para> /// Gets or sets the vertical alignment for text within an /// <see langword='HtmlTableCell'/> control. /// </para> /// </devdoc> [ WebCategory("Layout"), DefaultValue(""), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public string VAlign { get { string s = Attributes["valign"]; return((s != null) ? s : String.Empty); } set { Attributes["valign"] = MapStringAttributeToString(value); } } /// <devdoc> /// <para> /// Gets or sets the width, in pixels, of an <see langword='HtmlTableCell'/> /// control. /// </para> /// </devdoc> [ WebCategory("Layout"), DefaultValue(""), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public string Width { get { string s = Attributes["width"]; return((s != null) ? s : String.Empty); } set { Attributes["width"] = MapStringAttributeToString(value); } } /// <internalonly/> /// <devdoc> /// </devdoc> protected override void RenderEndTag(HtmlTextWriter writer) { base.RenderEndTag(writer); writer.WriteLine(); } } }
/* ==================================================================== */ using System; using System.Xml; using System.Text; using System.IO; using System.Drawing.Imaging; using System.Globalization; using System.Threading; using System.Net; namespace Oranikle.Report.Engine { ///<summary> /// Represents the background image information in a Style. ///</summary> [Serializable] public class StyleBackgroundImage : ReportLink { StyleBackgroundImageSourceEnum _Source; // Identifies the source of the image: Expression _Value; // (string) See Source. Expected datatype is string or // binary, depending on Source. If the Value is // null, no background image is displayed. Expression _MIMEType; // (string) The MIMEType for the image. // Valid values are: image/bmp, image/jpeg, // image/gif, image/png, image/x-png // Required if Source = Database. Ignored otherwise. Expression _BackgroundRepeat; // (Enum BackgroundRepeat) Indicates how the background image should // repeat to fill the available space: Default: Repeat bool _ConstantImage; // true if constant image public StyleBackgroundImage(ReportDefn r, ReportLink p, XmlNode xNode) : base(r, p) { _Source=StyleBackgroundImageSourceEnum.Unknown; _Value=null; _MIMEType=null; _BackgroundRepeat=null; _ConstantImage=false; // Loop thru all the child nodes foreach(XmlNode xNodeLoop in xNode.ChildNodes) { if (xNodeLoop.NodeType != XmlNodeType.Element) continue; switch (xNodeLoop.Name) { case "Source": _Source = StyleBackgroundImageSource.GetStyle(xNodeLoop.InnerText); break; case "Value": _Value = new Expression(r, this, xNodeLoop, ExpressionType.String); break; case "MIMEType": _MIMEType = new Expression(r, this, xNodeLoop, ExpressionType.String); break; case "BackgroundRepeat": _BackgroundRepeat = new Expression(r, this, xNodeLoop, ExpressionType.Enum); break; default: // don't know this element - log it OwnerReport.rl.LogError(4, "Unknown BackgroundImage element '" + xNodeLoop.Name + "' ignored."); break; } } if (_Source == StyleBackgroundImageSourceEnum.Unknown) OwnerReport.rl.LogError(8, "BackgroundImage requires the Source element."); if (_Value == null) OwnerReport.rl.LogError(8, "BackgroundImage requires the Value element."); } // Handle parsing of function in final pass override public void FinalPass() { if (_Value != null) _Value.FinalPass(); if (_MIMEType != null) _MIMEType.FinalPass(); if (_BackgroundRepeat != null) _BackgroundRepeat.FinalPass(); _ConstantImage = this.IsConstant(); return; } // Generate a CSS string from the specified styles public string GetCSS(Report rpt, Row row, bool bDefaults) { StringBuilder sb = new StringBuilder(); // TODO: need to handle other types of sources if (_Value != null && _Source==StyleBackgroundImageSourceEnum.External) sb.AppendFormat(NumberFormatInfo.InvariantInfo, "background-image:url(\"{0}\");",_Value.EvaluateString(rpt, row)); else if (bDefaults) return "background-image:none;"; if (_BackgroundRepeat != null) sb.AppendFormat(NumberFormatInfo.InvariantInfo, "background-repeat:{0};",_BackgroundRepeat.EvaluateString(rpt, row)); else if (bDefaults) sb.AppendFormat(NumberFormatInfo.InvariantInfo, "background-repeat:repeat;"); return sb.ToString(); } public bool IsConstant() { if (_Source == StyleBackgroundImageSourceEnum.Database) return false; bool rc = true; if (_Value != null) rc = _Value.IsConstant(); if (!rc) return false; if (_BackgroundRepeat != null) rc = _BackgroundRepeat.IsConstant(); return rc; } public PageImage GetPageImage(Report rpt, Row row) { string mtype=null; Stream strm=null; System.Drawing.Image im=null; PageImage pi=null; WorkClass wc = GetWC(rpt); if (wc.PgImage != null) { // have we already generated this one // reuse most of the work; only position will likely change pi = new PageImage(wc.PgImage.ImgFormat, wc.PgImage.ImageData, wc.PgImage.SamplesW, wc.PgImage.SamplesH); pi.Name = wc.PgImage.Name; // this is name it will be shared under return pi; } try { strm = GetImageStream(rpt, row, out mtype); if (strm == null) { rpt.rl.LogError(4, string.Format("Unable to load image {0}.", this._Value==null?"": this._Value.EvaluateString(rpt, row))); return null; } im = System.Drawing.Image.FromStream(strm); int height = im.Height; int width = im.Width; MemoryStream ostrm = new MemoryStream(); ImageFormat imf; // if (mtype.ToLower() == "image/jpeg") //TODO: how do we get png to work // imf = ImageFormat.Jpeg; // else imf = ImageFormat.Jpeg; System.Drawing.Imaging.ImageCodecInfo[] info; info = ImageCodecInfo.GetImageEncoders(); EncoderParameters encoderParameters; encoderParameters = new EncoderParameters(1); encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, ImageQualityManager.EmbeddedImageQuality); System.Drawing.Imaging.ImageCodecInfo codec = null; for (int i = 0; i < info.Length; i++) { if (info[i].FormatDescription == "JPEG") { codec = info[i]; break; } } im.Save(ostrm, codec, encoderParameters); byte[] ba = ostrm.ToArray(); ostrm.Close(); pi = new PageImage(imf, ba, width, height); pi.SI = new StyleInfo(); // this will just default everything if (_BackgroundRepeat != null) { string r = _BackgroundRepeat.EvaluateString(rpt, row).ToLower(); switch (r) { case "repeat": pi.Repeat = ImageRepeat.Repeat; break; case "repeatx": pi.Repeat = ImageRepeat.RepeatX; break; case "repeaty": pi.Repeat = ImageRepeat.RepeatY; break; case "norepeat": default: pi.Repeat = ImageRepeat.NoRepeat; break; } } else pi.Repeat = ImageRepeat.Repeat; if (_ConstantImage) { wc.PgImage = pi; // create unique name; PDF generation uses this to optimize the saving of the image only once pi.Name = "pi" + Interlocked.Increment(ref Parser.Counter).ToString(); // create unique name } } finally { if (strm != null) strm.Close(); if (im != null) im.Dispose(); } return pi; } Stream GetImageStream(Report rpt, Row row, out string mtype) { mtype=null; Stream strm=null; try { switch (this._Source) { case StyleBackgroundImageSourceEnum.Database: if (_MIMEType == null) return null; mtype = _MIMEType.EvaluateString(rpt, row); object o = _Value.Evaluate(rpt, row); strm = new MemoryStream((byte[]) o); break; case StyleBackgroundImageSourceEnum.Embedded: string name = _Value.EvaluateString(rpt, row); EmbeddedImage ei = (EmbeddedImage) OwnerReport.LUEmbeddedImages[name]; mtype = ei.MIMEType; byte[] ba = Convert.FromBase64String(ei.ImageData); strm = new MemoryStream(ba); break; case StyleBackgroundImageSourceEnum.External: string fname = _Value.EvaluateString(rpt, row); mtype = Image.GetMimeType(fname); if (fname.StartsWith("http:") || fname.StartsWith("file:") || fname.StartsWith("https:")) { WebRequest wreq = WebRequest.Create(fname); WebResponse wres = wreq.GetResponse(); strm = wres.GetResponseStream(); } else strm = new FileStream(fname, System.IO.FileMode.Open, FileAccess.Read); break; default: return null; } } catch { if (strm != null) { strm.Close(); strm = null; } } return strm; } static public string GetCSSDefaults() { return "background-image:none;"; } public StyleBackgroundImageSourceEnum Source { get { return _Source; } set { _Source = value; } } public Expression Value { get { return _Value; } set { _Value = value; } } public Expression MIMEType { get { return _MIMEType; } set { _MIMEType = value; } } public Expression BackgroundRepeat { get { return _BackgroundRepeat; } set { _BackgroundRepeat = value; } } private WorkClass GetWC(Report rpt) { WorkClass wc = rpt.Cache.Get(this, "wc") as WorkClass; if (wc == null) { wc = new WorkClass(); rpt.Cache.Add(this, "wc", wc); } return wc; } private void RemoveWC(Report rpt) { rpt.Cache.Remove(this, "wc"); } class WorkClass { public PageImage PgImage; // When ConstantImage is true this will save the PageImage for reuse public WorkClass() { PgImage=null; } } } public enum BackgroundRepeat { Repeat, // repeat image in both x and y directions NoRepeat, // don't repeat RepeatX, // repeat image in x direction RepeatY // repeat image in y direction } }
// 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.Concurrent; using System.Collections.Generic; using System.Threading; using Xunit; namespace System.Linq.Parallel.Tests { public class AggregateTests { private const int ResultFuncModifier = 17; public static IEnumerable<object[]> AggregateExceptionData(int[] counts) { foreach (object[] results in UnorderedSources.Ranges(counts.Cast<int>())) { Labeled<ParallelQuery<int>> query = (Labeled<ParallelQuery<int>>)results[0]; if (query.ToString().StartsWith("Partitioner")) { yield return new object[] { Labeled.Label(query.ToString(), Partitioner.Create(UnorderedSources.GetRangeArray(0, (int)results[1]), false).AsParallel()), results[1] }; } else if (query.ToString().StartsWith("Enumerable.Range")) { yield return new object[] { Labeled.Label(query.ToString(), new StrictPartitioner<int>(Partitioner.Create(Enumerable.Range(0, (int)results[1]), EnumerablePartitionerOptions.None), (int)results[1]).AsParallel()), results[1] }; } else { yield return results; } } } [Theory] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void Aggregate_Sum(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; if (count == 0) { Assert.Throws<InvalidOperationException>(() => query.Aggregate((x, y) => x + y)); } else { // The operation will overflow for long-running sizes, but that's okay: // The helper is overflowing too! Assert.Equal(Functions.SumRange(0, count), query.Aggregate((x, y) => x + y)); } } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 1024 * 1024, 1024 * 1024 * 4 }), MemberType = typeof(UnorderedSources))] public static void Aggregate_Sum_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { Aggregate_Sum(labeled, count); } [Theory] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void Aggregate_Sum_Seed(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; Assert.Equal(Functions.SumRange(0, count), query.Aggregate(0, (x, y) => x + y)); } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 1024 * 1024, 1024 * 1024 * 4 }), MemberType = typeof(UnorderedSources))] public static void Aggregate_Sum_Seed_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { Aggregate_Sum_Seed(labeled, count); } [Theory] [MemberData(nameof(Sources.Ranges), 1, new int[] { 0, 1, 2, 16 }, MemberType = typeof(UnorderedSources))] public static void Aggregate_Product_Seed(Labeled<ParallelQuery<int>> labeled, int count, int start) { ParallelQuery<int> query = labeled.Item; // The operation will overflow for long-running sizes, but that's okay: // The helper is overflowing too! Assert.Equal(Functions.ProductRange(start, count), query.Aggregate(1L, (x, y) => x * y)); } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), 1, new int[] { 1024 * 1024, 1024 * 1024 * 4 }, MemberType = typeof(UnorderedSources))] public static void Aggregate_Product_Seed_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int start) { Aggregate_Product_Seed(labeled, count, start); } [Theory] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void Aggregate_Collection_Seed(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; Assert.Equal(Enumerable.Range(0, count), query.Aggregate((IList<int>)new List<int>(), (l, x) => l.AddToCopy(x)).OrderBy(x => x)); } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 512, 1024 * 16 }), MemberType = typeof(UnorderedSources))] public static void Aggregate_Collection_Seed_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { Aggregate_Collection_Seed(labeled, count); } [Theory] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void Aggregate_Sum_Result(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; Assert.Equal(Functions.SumRange(0, count) + ResultFuncModifier, query.Aggregate(0, (x, y) => x + y, result => result + ResultFuncModifier)); } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 1024 * 1024, 1024 * 1024 * 4 }), MemberType = typeof(UnorderedSources))] public static void Aggregate_Sum_Result_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { Aggregate_Sum_Result(labeled, count); } [Theory] [MemberData(nameof(Sources.Ranges), 1, new int[] { 0, 1, 2, 16 }, MemberType = typeof(UnorderedSources))] public static void Aggregate_Product_Result(Labeled<ParallelQuery<int>> labeled, int count, int start) { ParallelQuery<int> query = labeled.Item; Assert.Equal(Functions.ProductRange(start, count) + ResultFuncModifier, query.Aggregate(1L, (x, y) => x * y, result => result + ResultFuncModifier)); } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), 1, new int[] { 1024 * 1024, 1024 * 1024 * 4 }, MemberType = typeof(UnorderedSources))] public static void Aggregate_Product_Results_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int start) { Aggregate_Product_Result(labeled, count, start); } [Theory] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void Aggregate_Collection_Results(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; Assert.Equal(Enumerable.Range(0, count), query.Aggregate((IList<int>)new List<int>(), (l, x) => l.AddToCopy(x), l => l.OrderBy(x => x))); } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 512, 1024 * 16 }), MemberType = typeof(UnorderedSources))] public static void Aggregate_Collection_Results_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { Aggregate_Collection_Results(labeled, count); } [Theory] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void Aggregate_Sum_Accumulator(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; int actual = query.Aggregate( 0, (accumulator, x) => accumulator + x, (left, right) => left + right, result => result + ResultFuncModifier); Assert.Equal(Functions.SumRange(0, count) + ResultFuncModifier, actual); } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 1024 * 1024, 1024 * 1024 * 4 }), MemberType = typeof(UnorderedSources))] public static void Aggregate_Sum_Accumulator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { Aggregate_Sum_Accumulator(labeled, count); } [Theory] [MemberData(nameof(Sources.Ranges), 1, new int[] { 0, 1, 2, 16 }, MemberType = typeof(UnorderedSources))] public static void Aggregate_Product_Accumulator(Labeled<ParallelQuery<int>> labeled, int count, int start) { ParallelQuery<int> query = labeled.Item; long actual = query.Aggregate( 1L, (accumulator, x) => accumulator * x, (left, right) => left * right, result => result + ResultFuncModifier); Assert.Equal(Functions.ProductRange(start, count) + ResultFuncModifier, actual); } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), 1, new int[] { 1024 * 1024, 1024 * 1024 * 4 }, MemberType = typeof(UnorderedSources))] public static void Aggregate_Product_Accumulator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int start) { Aggregate_Product_Accumulator(labeled, count, start); } [Theory] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void Aggregate_Collection_Accumulator(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; IList<int> actual = query.Aggregate( (IList<int>)new List<int>(), (accumulator, x) => accumulator.AddToCopy(x), (left, right) => left.ConcatCopy(right), result => result.OrderBy(x => x).ToList()); Assert.Equal(Enumerable.Range(0, count), actual); } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 512, 1024 * 16 }), MemberType = typeof(UnorderedSources))] public static void Aggregate_Collection_Accumulator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { Aggregate_Collection_Accumulator(labeled, count); } [Theory] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void Aggregate_Sum_SeedFunction(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; int actual = query.Aggregate( () => 0, (accumulator, x) => accumulator + x, (left, right) => left + right, result => result + ResultFuncModifier); Assert.Equal(Functions.SumRange(0, count) + ResultFuncModifier, actual); } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 1024 * 1024, 1024 * 1024 * 4 }), MemberType = typeof(UnorderedSources))] public static void Aggregate_Sum_SeedFunction_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { Aggregate_Sum_SeedFunction(labeled, count); } [Theory] [MemberData(nameof(Sources.Ranges), 1, new int[] { 0, 1, 2, 16 }, MemberType = typeof(UnorderedSources))] public static void Aggregate_Product_SeedFunction(Labeled<ParallelQuery<int>> labeled, int count, int start) { ParallelQuery<int> query = labeled.Item; long actual = query.Aggregate( () => 1L, (accumulator, x) => accumulator * x, (left, right) => left * right, result => result + ResultFuncModifier); Assert.Equal(Functions.ProductRange(start, count) + ResultFuncModifier, actual); } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), 1, new int[] { 1024 * 1024, 1024 * 1024 * 4 }, MemberType = typeof(UnorderedSources))] public static void Aggregate_Product_SeedFunction_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int start) { Aggregate_Product_SeedFunction(labeled, count, start); } [Theory] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 0, 1, 2, 16 }), MemberType = typeof(UnorderedSources))] public static void Aggregate_Collection_SeedFunction(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; IList<int> actual = query.Aggregate( () => (IList<int>)new List<int>(), (accumulator, x) => accumulator.AddToCopy(x), (left, right) => left.ConcatCopy(right), result => result.OrderBy(x => x).ToList()); Assert.Equal(Enumerable.Range(0, count), actual); } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 512, 1024 * 16 }), MemberType = typeof(UnorderedSources))] public static void Aggregate_Collection_SeedFunction_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { Aggregate_Collection_SeedFunction(labeled, count); } [Fact] public static void Aggregate_InvalidOperationException() { Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<int>().Aggregate((i, j) => i)); // All other invocations return the seed value. Assert.Equal(-1, ParallelEnumerable.Empty<int>().Aggregate(-1, (i, j) => i + j)); Assert.Equal(-1, ParallelEnumerable.Empty<int>().Aggregate(-1, (i, j) => i + j, i => i)); Assert.Equal(-1, ParallelEnumerable.Empty<int>().Aggregate(-1, (i, j) => i + j, (i, j) => i + j, i => i)); Assert.Equal(-1, ParallelEnumerable.Empty<int>().Aggregate(() => -1, (i, j) => i + j, (i, j) => i + j, i => i)); } [Theory] [MemberData(nameof(Sources.Ranges), (object)(new int[] { 2 }), MemberType = typeof(UnorderedSources))] public static void Aggregate_OperationCanceledException_PreCanceled(Labeled<ParallelQuery<int>> labeled, int count) { CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Aggregate((i, j) => i)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Aggregate(0, (i, j) => i)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Aggregate(0, (i, j) => i, i => i)); Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Aggregate(0, (i, j) => i, (i, j) => i, i => i)); } [Theory] [MemberData(nameof(AggregateExceptionData), (object)(new int[] { 2 }))] public static void Aggregate_AggregateException(Labeled<ParallelQuery<int>> labeled, int count) { Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Aggregate((i, j) => { throw new DeliberateTestException(); })); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Aggregate(0, (i, j) => { throw new DeliberateTestException(); })); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Aggregate(0, (i, j) => { throw new DeliberateTestException(); }, i => i)); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Aggregate<int, int, int>(0, (i, j) => i, i => { throw new DeliberateTestException(); })); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Aggregate(0, (i, j) => { throw new DeliberateTestException(); }, (i, j) => i, i => i)); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Aggregate<int, int, int>(0, (i, j) => i, (i, j) => i, i => { throw new DeliberateTestException(); })); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Aggregate<int, int, int>(() => { throw new DeliberateTestException(); }, (i, j) => i, (i, j) => i, i => i)); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Aggregate(() => 0, (i, j) => { throw new DeliberateTestException(); }, (i, j) => i, i => i)); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Aggregate<int, int, int>(() => 0, (i, j) => i, (i, j) => i, i => { throw new DeliberateTestException(); })); if (Environment.ProcessorCount >= 2) { Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Aggregate(0, (i, j) => i, (i, j) => { throw new DeliberateTestException(); }, i => i)); Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Aggregate(() => 0, (i, j) => i, (i, j) => { throw new DeliberateTestException(); }, i => i)); } } [Fact] public static void Aggregate_ArgumentNullException() { Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Aggregate((i, j) => i)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Aggregate(null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Aggregate(0, (i, j) => i)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Aggregate(0, null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Aggregate(0, (i, j) => i, i => i)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Aggregate(0, null, i => i)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Aggregate<int, int, int>(0, (i, j) => i, null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Aggregate(0, (i, j) => i, (i, j) => i, i => i)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Aggregate(0, null, (i, j) => i, i => i)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Aggregate(0, (i, j) => i, null, i => i)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Aggregate<int, int, int>(0, (i, j) => i, (i, j) => i, null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Aggregate(() => 0, (i, j) => i, (i, j) => i, i => i)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Aggregate<int, int, int>(null, (i, j) => i, (i, j) => i, i => i)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Aggregate(() => 0, null, (i, j) => i, i => i)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Aggregate(() => 0, (i, j) => i, null, i => i)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Aggregate<int, int, int>(() => 0, (i, j) => i, (i, j) => i, null)); } } internal static class ListHelper { // System.Collections.Immutable.ImmutableList wasn't available. public static IList<int> AddToCopy(this IList<int> collection, int element) { collection = new List<int>(collection); collection.Add(element); return collection; } public static IList<int> ConcatCopy(this IList<int> left, IList<int> right) { List<int> results = new List<int>(left); results.AddRange(right); return results; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using MigAz.Azure.Core.Interface; using MigAz.Azure.MigrationTarget; namespace MigAz.Azure.UserControls { public partial class PropertyPanel : UserControl { private TargetTreeView _TargetTreeView; private Core.MigrationTarget _MigrationTarget; public delegate Task AfterPropertyChanged(Core.MigrationTarget migrationTarget); public event AfterPropertyChanged PropertyChanged; public PropertyPanel() { InitializeComponent(); } public IStatusProvider StatusProvider { get; set; } public TargetTreeView TargetTreeView { get { return _TargetTreeView; } set { _TargetTreeView = value; } } public Core.MigrationTarget MigrationTarget { get { return _MigrationTarget; } private set { _MigrationTarget = value; } } public Image ResourceImage { get { return pictureBox1.Image; } private set { pictureBox1.Image = value; } } public string ResourceText { get { return lblAzureObjectName.Text; } private set { lblAzureObjectName.Text = value; } } public Control PropertyDetailControl { get { if (this.pnlProperties.Controls.Count == 0) return null; else return this.pnlProperties.Controls[0]; } private set { this.pnlProperties.Controls.Clear(); if (value != null) { this.pnlProperties.Controls.Add(value); } } } public void Clear() { this._MigrationTarget = null; this.ResourceImage = null; this.ResourceText = String.Empty; this.lblResourceType.Text = String.Empty; this.pnlProperties.Controls.Clear(); this.cmbApiVersions.Items.Clear(); this.lblTargetAPIVersion.Visible = false; this.cmbApiVersions.Items.Clear(); this.cmbApiVersions.Visible = false; } private void PropertyPanel_Resize(object sender, EventArgs e) { groupBox1.Width = this.Width - 5; groupBox1.Height = this.Height - 5; } private void groupBox1_Resize(object sender, EventArgs e) { pnlProperties.Width = groupBox1.Width - 15; pnlProperties.Height = groupBox1.Height - 90; } public bool IsBound { get { return _TargetTreeView != null && _MigrationTarget != null; } } public async Task Bind(Core.MigrationTarget migrationTarget) { if (this.TargetTreeView == null) throw new ArgumentException("MigrationTarget Property must be provided."); this.TargetTreeView.LogProvider.WriteLog("PropertyPanel Bind", "Start"); this.Clear(); if (migrationTarget.ApiVersion == null || migrationTarget.ApiVersion == String.Empty) { migrationTarget.DefaultApiVersion(this.TargetTreeView.TargetSubscription); } this._MigrationTarget = migrationTarget; this.ResourceText = migrationTarget.ToString(); this.ResourceImage = imageList1.Images[migrationTarget.ImageKey]; this.lblResourceType.Text = migrationTarget.FriendlyObjectName; if (migrationTarget.GetType() == typeof(VirtualNetworkGateway)) { VirtualNetworkGatewayProperties properties = new VirtualNetworkGatewayProperties(); properties.PropertyChanged += Properties_PropertyChanged; properties.Bind((VirtualNetworkGateway)migrationTarget, _TargetTreeView); this.PropertyDetailControl = properties; } else if (migrationTarget.GetType() == typeof(LocalNetworkGateway)) { LocalNetworkGatewayProperties properties = new LocalNetworkGatewayProperties(); properties.PropertyChanged += Properties_PropertyChanged; properties.Bind((LocalNetworkGateway)migrationTarget, _TargetTreeView); this.PropertyDetailControl = properties; } else if(migrationTarget.GetType() == typeof(VirtualNetworkGatewayConnection)) { VirtualNetworkConnectionProperties properties = new VirtualNetworkConnectionProperties(); properties.PropertyChanged += Properties_PropertyChanged; properties.Bind((VirtualNetworkGatewayConnection)migrationTarget, _TargetTreeView); this.PropertyDetailControl = properties; } else if(migrationTarget.GetType() == typeof(VirtualMachine)) { VirtualMachineProperties properties = new VirtualMachineProperties(); properties.PropertyChanged += Properties_PropertyChanged; await properties.Bind((VirtualMachine)migrationTarget, _TargetTreeView); this.PropertyDetailControl = properties; } else if (migrationTarget.GetType() == typeof(NetworkSecurityGroup)) { NetworkSecurityGroupProperties properties = new NetworkSecurityGroupProperties(); properties.PropertyChanged += Properties_PropertyChanged; properties.Bind((NetworkSecurityGroup)migrationTarget, _TargetTreeView); this.PropertyDetailControl = properties; } if (migrationTarget.GetType() == typeof(VirtualNetwork)) { VirtualNetworkProperties properties = new VirtualNetworkProperties(); properties.PropertyChanged += Properties_PropertyChanged; properties.Bind((VirtualNetwork)migrationTarget, _TargetTreeView); this.PropertyDetailControl = properties; } else if (migrationTarget.GetType() == typeof(Subnet)) { SubnetProperties properties = new SubnetProperties(); properties.PropertyChanged += Properties_PropertyChanged; properties.Bind((Subnet)migrationTarget, _TargetTreeView); this.PropertyDetailControl = properties; } else if (migrationTarget.GetType() == typeof(StorageAccount)) { StorageAccountProperties properties = new StorageAccountProperties(); properties.PropertyChanged += Properties_PropertyChanged; properties.Bind((StorageAccount)migrationTarget, _TargetTreeView); this.PropertyDetailControl = properties; } else if (migrationTarget.GetType() == typeof(AvailabilitySet)) { AvailabilitySetProperties properties = new AvailabilitySetProperties(); properties.PropertyChanged += Properties_PropertyChanged; properties.Bind((AvailabilitySet)migrationTarget, _TargetTreeView); this.PropertyDetailControl = properties; } else if (migrationTarget.GetType() == typeof(PublicIp)) { PublicIpProperties properties = new PublicIpProperties(); properties.PropertyChanged += Properties_PropertyChanged; properties.Bind((PublicIp)migrationTarget, _TargetTreeView); this.PropertyDetailControl = properties; } else if (migrationTarget.GetType() == typeof(RouteTable)) { RouteTableProperties properties = new RouteTableProperties(); properties.PropertyChanged += Properties_PropertyChanged; properties.Bind((RouteTable)migrationTarget, _TargetTreeView); this.PropertyDetailControl = properties; } else if (migrationTarget.GetType() == typeof(NetworkInterface)) { NetworkInterfaceProperties properties = new NetworkInterfaceProperties(); properties.PropertyChanged += Properties_PropertyChanged; await properties.Bind((NetworkInterface)migrationTarget, _TargetTreeView); this.PropertyDetailControl = properties; } else if (migrationTarget.GetType() == typeof(ResourceGroup)) { ResourceGroupProperties properties = new ResourceGroupProperties(); properties.PropertyChanged += Properties_PropertyChanged; await properties.Bind((ResourceGroup)migrationTarget, _TargetTreeView); this.PropertyDetailControl = properties; } else if (migrationTarget.GetType() == typeof(LoadBalancer)) { LoadBalancerProperties properties = new LoadBalancerProperties(); properties.PropertyChanged += Properties_PropertyChanged; await properties.Bind((LoadBalancer)migrationTarget, _TargetTreeView); this.PropertyDetailControl = properties; } else if (migrationTarget.GetType() == typeof(Disk)) { DiskProperties properties = new DiskProperties(); properties.PropertyChanged += Properties_PropertyChanged; await properties.Bind((Disk)migrationTarget, _TargetTreeView); this.PropertyDetailControl = properties; } //else if (migrationTarget.GetType() == typeof(VirtualMachineImage)) //{ // VirtualMachineImageProperties properties = new VirtualMachineImageProperties(); // properties.PropertyChanged += Properties_PropertyChanged; // properties.Bind(_TargetTreeView, (VirtualMachineImage)migrationTarget, _TargetTreeView); // this.PropertyDetailControl = properties; //} Arm.ProviderResourceType targetProvider = this.TargetTreeView.GetTargetProvider(migrationTarget); if (targetProvider != null) { lblTargetAPIVersion.Visible = true; cmbApiVersions.Visible = true; foreach (string apiVersion in targetProvider.ApiVersions) { cmbApiVersions.Items.Add(apiVersion); } if (migrationTarget.ApiVersion != null && migrationTarget.ApiVersion != String.Empty) { cmbApiVersions.SelectedIndex = cmbApiVersions.FindStringExact(migrationTarget.ApiVersion); } } this.TargetTreeView.LogProvider.WriteLog("PropertyPanel Bind", "End"); } private async Task Properties_PropertyChanged(Core.MigrationTarget migrationTarget) { _MigrationTarget = migrationTarget; // Refresh based on property change await PropertyChanged(migrationTarget); } private async void cmbApiVersions_SelectedIndexChanged(object sender, EventArgs e) { if (_MigrationTarget != null) { if (cmbApiVersions.SelectedItem == null) _MigrationTarget.ApiVersion = String.Empty; else _MigrationTarget.ApiVersion = cmbApiVersions.SelectedItem.ToString(); } foreach (Control control in this.pnlProperties.Controls) { TargetPropertyControl targetPropertyControl = (TargetPropertyControl)control; targetPropertyControl.UpdatePropertyEnablement(); } if (PropertyChanged != null && _MigrationTarget != null) await PropertyChanged(_MigrationTarget); } } }
// // 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 AutoMapper; using Microsoft.Azure.Commands.Compute.Automation.Models; using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; namespace Microsoft.Azure.Commands.Compute.Automation { public partial class InvokeAzureComputeMethodCmdlet : ComputeAutomationBaseCmdlet { protected object CreateVirtualMachineScaleSetDeallocateDynamicParameters() { dynamicParameters = new RuntimeDefinedParameterDictionary(); var pResourceGroupName = new RuntimeDefinedParameter(); pResourceGroupName.Name = "ResourceGroupName"; pResourceGroupName.ParameterType = typeof(string); pResourceGroupName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 1, Mandatory = true }); pResourceGroupName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ResourceGroupName", pResourceGroupName); var pVMScaleSetName = new RuntimeDefinedParameter(); pVMScaleSetName.Name = "VMScaleSetName"; pVMScaleSetName.ParameterType = typeof(string); pVMScaleSetName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 2, Mandatory = true }); pVMScaleSetName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("VMScaleSetName", pVMScaleSetName); var pInstanceIds = new RuntimeDefinedParameter(); pInstanceIds.Name = "InstanceId"; pInstanceIds.ParameterType = typeof(string[]); pInstanceIds.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 3, Mandatory = false }); pInstanceIds.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("InstanceId", pInstanceIds); var pArgumentList = new RuntimeDefinedParameter(); pArgumentList.Name = "ArgumentList"; pArgumentList.ParameterType = typeof(object[]); pArgumentList.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByStaticParameters", Position = 4, Mandatory = true }); pArgumentList.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ArgumentList", pArgumentList); return dynamicParameters; } protected void ExecuteVirtualMachineScaleSetDeallocateMethod(object[] invokeMethodInputParameters) { string resourceGroupName = (string)ParseParameter(invokeMethodInputParameters[0]); string vmScaleSetName = (string)ParseParameter(invokeMethodInputParameters[1]); System.Collections.Generic.IList<string> instanceIds = null; if (invokeMethodInputParameters[2] != null) { var inputArray2 = Array.ConvertAll((object[]) ParseParameter(invokeMethodInputParameters[2]), e => e.ToString()); instanceIds = inputArray2.ToList(); } var result = VirtualMachineScaleSetsClient.Deallocate(resourceGroupName, vmScaleSetName, instanceIds); WriteObject(result); } } public partial class NewAzureComputeArgumentListCmdlet : ComputeAutomationBaseCmdlet { protected PSArgument[] CreateVirtualMachineScaleSetDeallocateParameters() { string resourceGroupName = string.Empty; string vmScaleSetName = string.Empty; var instanceIds = new string[0]; return ConvertFromObjectsToArguments( new string[] { "ResourceGroupName", "VMScaleSetName", "InstanceIds" }, new object[] { resourceGroupName, vmScaleSetName, instanceIds }); } } [Cmdlet(VerbsLifecycle.Stop, "AzureRmVmss", DefaultParameterSetName = "DefaultParameter", SupportsShouldProcess = true)] [OutputType(typeof(PSOperationStatusResponse))] public partial class StopAzureRmVmss : ComputeAutomationBaseCmdlet { protected override void ProcessRecord() { AutoMapper.Mapper.AddProfile<ComputeAutomationAutoMapperProfile>(); ExecuteClientAction(() => { if (ShouldProcess(this.ResourceGroupName, VerbsLifecycle.Stop) && (this.Force.IsPresent || this.ShouldContinue(Properties.Resources.ResourceStoppingConfirmation, "Stop-AzureRmVmss operation"))) { string resourceGroupName = this.ResourceGroupName; string vmScaleSetName = this.VMScaleSetName; System.Collections.Generic.IList<string> instanceIds = this.InstanceId; if (this.ParameterSetName.Equals("FriendMethod")) { var result = VirtualMachineScaleSetsClient.PowerOff(resourceGroupName, vmScaleSetName, instanceIds); var psObject = new PSOperationStatusResponse(); Mapper.Map<Azure.Management.Compute.Models.OperationStatusResponse, PSOperationStatusResponse>(result, psObject); WriteObject(psObject); } else { var result = VirtualMachineScaleSetsClient.Deallocate(resourceGroupName, vmScaleSetName, instanceIds); var psObject = new PSOperationStatusResponse(); Mapper.Map<Azure.Management.Compute.Models.OperationStatusResponse, PSOperationStatusResponse>(result, psObject); WriteObject(psObject); } } }); } [Parameter( ParameterSetName = "DefaultParameter", Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false)] [Parameter( ParameterSetName = "FriendMethod", Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false)] [AllowNull] public string ResourceGroupName { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Position = 2, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false)] [Parameter( ParameterSetName = "FriendMethod", Position = 2, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false)] [Alias("Name")] [AllowNull] public string VMScaleSetName { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Position = 3, Mandatory = false, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false)] [Parameter( ParameterSetName = "FriendMethod", Position = 3, Mandatory = false, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false)] [AllowNull] public string [] InstanceId { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = false)] [Parameter( ParameterSetName = "FriendMethod", Mandatory = false)] [AllowNull] public SwitchParameter Force { get; set; } [Parameter( ParameterSetName = "FriendMethod", Mandatory = true)] [AllowNull] public SwitchParameter StayProvisioned { get; set; } } }
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; namespace Hydra.Framework.Geometric { public class PolylineObject : IMapviewObject,IPersist ,ICloneable { #region Private Members of Polyline Object public event GraphicEvents GraphicSelected; public ArrayList m_points = new ArrayList(); private bool isselected = false; private bool isfilled=false; private bool visible=true; private bool showtooptip=false; private bool iscurrent=true; private bool islocked=false; private bool isdisabled=false; private bool showhandle=false; private int handlesize=6; private Color fillcolor=Color.Cyan; private Color normalcolor= Color.Yellow; private Color selectcolor= Color.Red; private Color disabledcolor= Color.Gray; private int linewidth=2; public PointF[] points; private string xml=""; #endregion #region Properties of Polyline Object public PointF[] Vertices { get{return points;} set{points=value;} } [Category("Colors" ),Description("The disabled graphic object will be drawn using this pen")] public Color DisabledColor { get{return disabledcolor;} set{disabledcolor=value;} } [Category("Colors" ),Description("The selected graphic object willbe drawn using this pen")] public Color SelectColor { get{return selectcolor;} set{selectcolor=value;} } [Category("Colors" ),Description("The graphic object willbe drawn using this pen")] public Color NormalColor { get{return normalcolor;} set{normalcolor=value;} } [DefaultValue(2),Category("AbstractStyle"),Description("The gives the line thickness of the graphic object")] public int LineWidth { get{return linewidth;} set{linewidth=value;} } [Category("Appearance"),Description("The graphic object will be filled with a given color or pattern")] public bool IsFilled{get{return isfilled;}set{isfilled=value;} } [Category("Appearance"), Description("Determines whether the object is visible or hidden")] public bool Visible { get{return visible;} set{visible=value;} } [Category("Appearance"), Description("Determines whether the tooltip information to be shown or not")] public bool ShowToopTip { get{return showtooptip;} set{showtooptip=value;} } [Category("Appearance"), Description("Determines whether the object is in current selected legend or not")] public bool IsCurrent { get{return iscurrent;} set{iscurrent=value;} } [Category("Appearance"), Description("Determines whether the object is locked from the current user or not")] public bool IsLocked { get{return islocked;} set{islocked=value;} } [Category("Appearance"), Description("Determines whether the object is disabled from editing")] public bool IsDisabled { get{return isdisabled;} set{isdisabled=value;} } [Category("Appearance"), Description("Determines whether the object is in edit mode")] public bool IsEdit { get{return showhandle;} set{isselected=true; showhandle=value;} } #endregion #region Constructors of Polyline Object public PolylineObject(ArrayList points) { m_points.Clear(); foreach(PointF item in points) { m_points.Add(item); } } public PolylineObject(PolylineObject po){} #endregion #region Methods of ICloneable public object Clone() { return new PolylineObject( this ); } #endregion #region Method of Polyline Object public bool IsSelected() { return isselected; } public void Select(bool m) { isselected = m; } public bool IsObjectAt(PointF pnt,float dist) { double min_dist = 100000; for(int i=0; i<m_points.Count-1; i++) { PointF p1 = (PointF)m_points[i]; PointF p2 = (PointF)m_points[i+1]; double curr_dist = GeoUtil.DistanceBetweenPointToSegment(p1,p2,pnt); if(min_dist>curr_dist) min_dist = curr_dist; } return Math.Sqrt(min_dist) < dist; } public void Insert(PointF pt,int i) { m_points.Insert(i,pt); } public void Insert(PointF[] pt, int i) { m_points.InsertRange(i,pt); } // public Rectangle BoundingBox(int i) // { // //TODO: To be fine tuned // return new Rectangle(0,0,0,0); // } public Rectangle BoundingBox() { int x1=(int)((PointF)(m_points[0])).X; int y1=(int)((PointF)(m_points[0])).Y; int x2=(int)((PointF)(m_points[0])).X; int y2=(int)((PointF)(m_points[0])).Y; for(int i=0; i<m_points.Count; i++) { if((int)((PointF)m_points[i]).X < x1) x1 = (int)((PointF)m_points[i]).X; else if((int)((PointF)m_points[i]).X > x2) x2 = (int)((PointF)m_points[i]).X; if((int)((PointF)m_points[i]).Y < y1) y1 = (int)((PointF)m_points[i]).Y; else if((int)((PointF)m_points[i]).Y > y2) y2 = (int)((PointF)m_points[i]).Y; } return new Rectangle((int)x1,(int)y1,(int)x2,(int)y2); } public float X() { return ((PointF)m_points[0]).X; } public float Y() { return ((PointF)m_points[0]).Y; } public void Move(PointF p) { float dx = p.X-((PointF)m_points[0]).X; float dy = p.Y-((PointF)m_points[0]).Y; for(int i=0; i<m_points.Count; i++) { PointF cp = new PointF(((PointF)m_points[i]).X + dx, ((PointF)m_points[i]).Y + dy); m_points[i] = cp; } } public void MoveBy(float dx,float dy) { for(int i=0; i<m_points.Count; i++) { PointF cp = new PointF(((PointF)m_points[i]).X + dx, ((PointF)m_points[i]).Y + dy); m_points[i] = cp; } } public void Scale(int scale) { for(int i=0; i<m_points.Count; i++) { PointF cp = new PointF(((PointF)m_points[i]).X * scale, ((PointF)m_points[i]).Y + scale); m_points[i] = cp; } } public void Rotate(float radians) { // } public void RotateAt(PointF pt) { // } public void RoateAt(Point pt) { // } public void Draw(Graphics graph,System.Drawing.Drawing2D.Matrix trans) { if (visible) { // create 0,0 and width,height points PointF [] points = new PointF[m_points.Count]; m_points.CopyTo(0,points,0,m_points.Count); trans.TransformPoints(points); if(isselected) { graph.DrawLines(new Pen(selectcolor,linewidth),points); if (showhandle) { for (int i=0; i<m_points.Count; i++) { graph.FillRectangle(new SolidBrush(fillcolor),points[i].X-handlesize/2,points[i].Y-handlesize/2,handlesize,handlesize); graph.DrawRectangle(new Pen(Color.Black,1),points[i].X-handlesize/2,points[i].Y-handlesize/2,handlesize,handlesize); } } } else if (isdisabled || islocked) { graph.DrawLines(new Pen(disabledcolor,linewidth), points); } else { graph.DrawLines(new Pen(normalcolor,linewidth), points); } } } #endregion #region Method of IPersist public string ToXML { get{return xml;} set{xml=value;} } public string ToGML { get{return xml;} set{xml=value;} } public string ToVML { get{return xml;} set{xml=value;} } public string ToSVG { get { string spoints=""; for (int i=0; i<m_points.Count-1; i++) { spoints=((PointF)m_points[i]).X + "," + ((PointF)m_points[i]).Y + " "; } return "<polyline fill='none' stroke=" + normalcolor + " stroke-width=" + linewidth + " points=" + spoints + " />"; } set{xml=value;} } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Linq; using System.Text; using System.Threading.Tasks; using Validation; namespace System.Collections.Immutable { /// <summary> /// A set of initialization methods for instances of <see cref="ImmutableDictionary{TKey, TValue}" />. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] public static class ImmutableDictionary { /// <summary> /// Returns an empty collection. /// </summary> /// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam> /// <returns>The immutable collection.</returns> [Pure] public static ImmutableDictionary<TKey, TValue> Create<TKey, TValue>() { return ImmutableDictionary<TKey, TValue>.Empty; } /// <summary> /// Returns an empty collection with the specified key comparer. /// </summary> /// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam> /// <param name="keyComparer">The key comparer.</param> /// <returns> /// The immutable collection. /// </returns> [Pure] public static ImmutableDictionary<TKey, TValue> Create<TKey, TValue>(IEqualityComparer<TKey> keyComparer) { return ImmutableDictionary<TKey, TValue>.Empty.WithComparers(keyComparer); } /// <summary> /// Returns an empty collection with the specified comparers. /// </summary> /// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam> /// <param name="keyComparer">The key comparer.</param> /// <param name="valueComparer">The value comparer.</param> /// <returns> /// The immutable collection. /// </returns> [Pure] public static ImmutableDictionary<TKey, TValue> Create<TKey, TValue>(IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer) { return ImmutableDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer); } /// <summary> /// Creates a new immutable collection prefilled with the specified items. /// </summary> /// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam> /// <param name="items">The items to prepopulate.</param> /// <returns>The new immutable collection.</returns> [Pure] [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public static ImmutableDictionary<TKey, TValue> CreateRange<TKey, TValue>(IEnumerable<KeyValuePair<TKey, TValue>> items) { return ImmutableDictionary<TKey, TValue>.Empty.AddRange(items); } /// <summary> /// Creates a new immutable collection prefilled with the specified items. /// </summary> /// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam> /// <param name="keyComparer">The key comparer.</param> /// <param name="items">The items to prepopulate.</param> /// <returns>The new immutable collection.</returns> [Pure] [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public static ImmutableDictionary<TKey, TValue> CreateRange<TKey, TValue>(IEqualityComparer<TKey> keyComparer, IEnumerable<KeyValuePair<TKey, TValue>> items) { return ImmutableDictionary<TKey, TValue>.Empty.WithComparers(keyComparer).AddRange(items); } /// <summary> /// Creates a new immutable collection prefilled with the specified items. /// </summary> /// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam> /// <param name="keyComparer">The key comparer.</param> /// <param name="valueComparer">The value comparer.</param> /// <param name="items">The items to prepopulate.</param> /// <returns>The new immutable collection.</returns> [Pure] [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public static ImmutableDictionary<TKey, TValue> CreateRange<TKey, TValue>(IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer, IEnumerable<KeyValuePair<TKey, TValue>> items) { return ImmutableDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer).AddRange(items); } /// <summary> /// Creates a new immutable dictionary builder. /// </summary> /// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam> /// <returns>The new builder.</returns> [Pure] public static ImmutableDictionary<TKey, TValue>.Builder CreateBuilder<TKey, TValue>() { return Create<TKey, TValue>().ToBuilder(); } /// <summary> /// Creates a new immutable dictionary builder. /// </summary> /// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam> /// <param name="keyComparer">The key comparer.</param> /// <returns>The new builder.</returns> [Pure] public static ImmutableDictionary<TKey, TValue>.Builder CreateBuilder<TKey, TValue>(IEqualityComparer<TKey> keyComparer) { return Create<TKey, TValue>(keyComparer).ToBuilder(); } /// <summary> /// Creates a new immutable dictionary builder. /// </summary> /// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam> /// <param name="keyComparer">The key comparer.</param> /// <param name="valueComparer">The value comparer.</param> /// <returns>The new builder.</returns> [Pure] public static ImmutableDictionary<TKey, TValue>.Builder CreateBuilder<TKey, TValue>(IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer) { return Create<TKey, TValue>(keyComparer, valueComparer).ToBuilder(); } /// <summary> /// Constructs an immutable dictionary based on some transformation of a sequence. /// </summary> /// <typeparam name="TSource">The type of element in the sequence.</typeparam> /// <typeparam name="TKey">The type of key in the resulting map.</typeparam> /// <typeparam name="TValue">The type of value in the resulting map.</typeparam> /// <param name="source">The sequence to enumerate to generate the map.</param> /// <param name="keySelector">The function that will produce the key for the map from each sequence element.</param> /// <param name="elementSelector">The function that will produce the value for the map from each sequence element.</param> /// <param name="keyComparer">The key comparer to use for the map.</param> /// <param name="valueComparer">The value comparer to use for the map.</param> /// <returns>The immutable map.</returns> [Pure] public static ImmutableDictionary<TKey, TValue> ToImmutableDictionary<TSource, TKey, TValue>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TValue> elementSelector, IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer) { Requires.NotNull(source, "source"); Requires.NotNull(keySelector, "keySelector"); Requires.NotNull(elementSelector, "elementSelector"); Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null); return ImmutableDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer) .AddRange(source.Select(element => new KeyValuePair<TKey, TValue>(keySelector(element), elementSelector(element)))); } /// <summary> /// Constructs an immutable dictionary based on some transformation of a sequence. /// </summary> /// <typeparam name="TSource">The type of element in the sequence.</typeparam> /// <typeparam name="TKey">The type of key in the resulting map.</typeparam> /// <typeparam name="TValue">The type of value in the resulting map.</typeparam> /// <param name="source">The sequence to enumerate to generate the map.</param> /// <param name="keySelector">The function that will produce the key for the map from each sequence element.</param> /// <param name="elementSelector">The function that will produce the value for the map from each sequence element.</param> /// <param name="keyComparer">The key comparer to use for the map.</param> /// <returns>The immutable map.</returns> [Pure] public static ImmutableDictionary<TKey, TValue> ToImmutableDictionary<TSource, TKey, TValue>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TValue> elementSelector, IEqualityComparer<TKey> keyComparer) { return ToImmutableDictionary(source, keySelector, elementSelector, keyComparer, null); } /// <summary> /// Constructs an immutable dictionary based on some transformation of a sequence. /// </summary> /// <typeparam name="TSource">The type of element in the sequence.</typeparam> /// <typeparam name="TKey">The type of key in the resulting map.</typeparam> /// <param name="source">The sequence to enumerate to generate the map.</param> /// <param name="keySelector">The function that will produce the key for the map from each sequence element.</param> /// <returns>The immutable map.</returns> [Pure] public static ImmutableDictionary<TKey, TSource> ToImmutableDictionary<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) { return ToImmutableDictionary(source, keySelector, v => v, null, null); } /// <summary> /// Constructs an immutable dictionary based on some transformation of a sequence. /// </summary> /// <typeparam name="TSource">The type of element in the sequence.</typeparam> /// <typeparam name="TKey">The type of key in the resulting map.</typeparam> /// <param name="source">The sequence to enumerate to generate the map.</param> /// <param name="keySelector">The function that will produce the key for the map from each sequence element.</param> /// <param name="keyComparer">The key comparer to use for the map.</param> /// <returns>The immutable map.</returns> [Pure] public static ImmutableDictionary<TKey, TSource> ToImmutableDictionary<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> keyComparer) { return ToImmutableDictionary(source, keySelector, v => v, keyComparer, null); } /// <summary> /// Constructs an immutable dictionary based on some transformation of a sequence. /// </summary> /// <typeparam name="TSource">The type of element in the sequence.</typeparam> /// <typeparam name="TKey">The type of key in the resulting map.</typeparam> /// <typeparam name="TValue">The type of value in the resulting map.</typeparam> /// <param name="source">The sequence to enumerate to generate the map.</param> /// <param name="keySelector">The function that will produce the key for the map from each sequence element.</param> /// <param name="elementSelector">The function that will produce the value for the map from each sequence element.</param> /// <returns>The immutable map.</returns> [Pure] public static ImmutableDictionary<TKey, TValue> ToImmutableDictionary<TSource, TKey, TValue>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TValue> elementSelector) { return ToImmutableDictionary(source, keySelector, elementSelector, null, null); } /// <summary> /// Creates an immutable dictionary given a sequence of key=value pairs. /// </summary> /// <typeparam name="TKey">The type of key in the map.</typeparam> /// <typeparam name="TValue">The type of value in the map.</typeparam> /// <param name="source">The sequence of key=value pairs.</param> /// <param name="keyComparer">The key comparer to use when building the immutable map.</param> /// <param name="valueComparer">The value comparer to use for the immutable map.</param> /// <returns>An immutable map.</returns> [Pure] [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public static ImmutableDictionary<TKey, TValue> ToImmutableDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source, IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer) { Requires.NotNull(source, "source"); Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null); var existingDictionary = source as ImmutableDictionary<TKey, TValue>; if (existingDictionary != null) { return existingDictionary.WithComparers(keyComparer, valueComparer); } return ImmutableDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer).AddRange(source); } /// <summary> /// Creates an immutable dictionary given a sequence of key=value pairs. /// </summary> /// <typeparam name="TKey">The type of key in the map.</typeparam> /// <typeparam name="TValue">The type of value in the map.</typeparam> /// <param name="source">The sequence of key=value pairs.</param> /// <param name="keyComparer">The key comparer to use when building the immutable map.</param> /// <returns>An immutable map.</returns> [Pure] [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public static ImmutableDictionary<TKey, TValue> ToImmutableDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source, IEqualityComparer<TKey> keyComparer) { return ToImmutableDictionary(source, keyComparer, null); } /// <summary> /// Creates an immutable dictionary given a sequence of key=value pairs. /// </summary> /// <typeparam name="TKey">The type of key in the map.</typeparam> /// <typeparam name="TValue">The type of value in the map.</typeparam> /// <param name="source">The sequence of key=value pairs.</param> /// <returns>An immutable map.</returns> [Pure] [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public static ImmutableDictionary<TKey, TValue> ToImmutableDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source) { return ToImmutableDictionary(source, null, null); } /// <summary> /// Determines whether this map contains the specified key-value pair. /// </summary> /// <typeparam name="TKey">The type of key in the map.</typeparam> /// <typeparam name="TValue">The type of value in the map.</typeparam> /// <param name="map">The map to search.</param> /// <param name="key">The key to check for.</param> /// <param name="value">The value to check for on a matching key, if found.</param> /// <returns> /// <c>true</c> if this map contains the key-value pair; otherwise, <c>false</c>. /// </returns> [Pure] public static bool Contains<TKey, TValue>(this IImmutableDictionary<TKey, TValue> map, TKey key, TValue value) { Requires.NotNull(map, "map"); Requires.NotNullAllowStructs(key, "key"); return map.Contains(new KeyValuePair<TKey, TValue>(key, value)); } /// <summary> /// Gets the value for a given key if a matching key exists in the dictionary. /// </summary> /// <param name="dictionary">The dictionary to retrieve the value from.</param> /// <param name="key">The key to search for.</param> /// <returns>The value for the key, or <c>default(TValue)</c> if no matching key was found.</returns> [Pure] public static TValue GetValueOrDefault<TKey, TValue>(this IImmutableDictionary<TKey, TValue> dictionary, TKey key) { return GetValueOrDefault(dictionary, key, default(TValue)); } /// <summary> /// Gets the value for a given key if a matching key exists in the dictionary. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="dictionary">The dictionary to retrieve the value from.</param> /// <param name="key">The key to search for.</param> /// <param name="defaultValue">The default value to return if no matching key is found in the dictionary.</param> /// <returns> /// The value for the key, or <paramref name="defaultValue"/> if no matching key was found. /// </returns> [Pure] public static TValue GetValueOrDefault<TKey, TValue>(this IImmutableDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue) { Requires.NotNull(dictionary, "dictionary"); Requires.NotNullAllowStructs(key, "key"); TValue value; if (dictionary.TryGetValue(key, out value)) { return value; } return defaultValue; } } }
//--------------------------------------------------------------------- // <copyright file="Installer.cs" company="Microsoft Corporation"> // Copyright (c) 1999, Microsoft Corporation. All rights reserved. // </copyright> // <summary> // Part of the Deployment Tools Foundation project. // </summary> //--------------------------------------------------------------------- namespace Microsoft.PackageManagement.Msi.Internal.Deployment.WindowsInstaller { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Resources; using System.Text; /// <summary> /// Receives an exception from /// <see cref="Installer.DetermineApplicablePatches(string,string[],InapplicablePatchHandler,string,UserContexts)"/> /// indicating the reason a particular patch is not applicable to a product. /// </summary> /// <param name="patch">MSP file path, XML file path, or XML blob that was passed to /// <see cref="Installer.DetermineApplicablePatches(string,string[],InapplicablePatchHandler,string,UserContexts)"/></param> /// <param name="exception">exception indicating the reason the patch is not applicable</param> /// <remarks><p> /// If <paramref name="exception"/> is an <see cref="InstallerException"/> or subclass, then /// its <see cref="InstallerException.ErrorCode"/> and <see cref="InstallerException.Message"/> /// properties will indicate a more specific reason the patch was not applicable. /// </p><p> /// The <paramref name="exception"/> could also be a FileNotFoundException if the /// patch string was a file path. /// </p></remarks> public delegate void InapplicablePatchHandler(string patch, Exception exception); /// <summary> /// Provides static methods for installing and configuring products and patches. /// </summary> internal static partial class Installer { private static bool rebootRequired; private static bool rebootInitiated; private static ResourceManager errorResources; /// <summary> /// Indicates whether a system reboot is required after running an installation or configuration operation. /// </summary> public static bool RebootRequired { get { return Installer.rebootRequired; } } /// <summary> /// Indicates whether a system reboot has been initiated after running an installation or configuration operation. /// </summary> public static bool RebootInitiated { get { return Installer.rebootInitiated; } } /// <summary> /// Enables the installer's internal user interface. Then this user interface is used /// for all subsequent calls to user-interface-generating installer functions in this process. /// </summary> /// <param name="uiOptions">Specifies the level of complexity of the user interface</param> /// <param name="windowHandle">Handle to a window, which becomes the owner of any user interface created. /// A pointer to the previous owner of the user interface is returned.</param> /// <returns>The previous user interface level</returns> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msisetinternalui.asp">MsiSetInternalUI</a> /// </p></remarks> [SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] public static InstallUIOptions SetInternalUI(InstallUIOptions uiOptions, ref IntPtr windowHandle) { return (InstallUIOptions) NativeMethods.MsiSetInternalUI((uint) uiOptions, ref windowHandle); } /// <summary> /// Enables the installer's internal user interface. Then this user interface is used /// for all subsequent calls to user-interface-generating installer functions in this process. /// The owner of the user interface does not change. /// </summary> /// <param name="uiOptions">Specifies the level of complexity of the user interface</param> /// <returns>The previous user interface level</returns> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msisetinternalui.asp">MsiSetInternalUI</a> /// </p></remarks> public static InstallUIOptions SetInternalUI(InstallUIOptions uiOptions) { return (InstallUIOptions) NativeMethods.MsiSetInternalUI((uint) uiOptions, IntPtr.Zero); } /// <summary> /// Enables logging of the selected message type for all subsequent install sessions in /// the current process space. /// </summary> /// <param name="logModes">One or more mode flags specifying the type of messages to log</param> /// <param name="logFile">Full path to the log file. A null path disables logging, /// in which case the logModes paraneter is ignored.</param> /// <exception cref="ArgumentException">an invalid log mode was specified</exception> /// <remarks>This method takes effect on any new installation processes. Calling this /// method from within a custom action will not start logging for that installation.</remarks> public static void EnableLog(InstallLogModes logModes, string logFile) { Installer.EnableLog(logModes, logFile, false, true); } /// <summary> /// Enables logging of the selected message type for all subsequent install sessions in /// the current process space. /// </summary> /// <param name="logModes">One or more mode flags specifying the type of messages to log</param> /// <param name="logFile">Full path to the log file. A null path disables logging, /// in which case the logModes paraneter is ignored.</param> /// <param name="append">If true, the log lines will be appended to any existing file content. /// If false, the log file will be truncated if it exists. The default is false.</param> /// <param name="flushEveryLine">If true, the log will be flushed after every line. /// If false, the log will be flushed every 20 lines. The default is true.</param> /// <exception cref="ArgumentException">an invalid log mode was specified</exception> /// <remarks><p> /// This method takes effect on any new installation processes. Calling this /// method from within a custom action will not start logging for that installation. /// </p><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msienablelog.asp">MsiEnableLog</a> /// </p></remarks> public static void EnableLog(InstallLogModes logModes, string logFile, bool append, bool flushEveryLine) { uint ret = NativeMethods.MsiEnableLog((uint) logModes, logFile, (append ? (uint) 1 : 0) + (flushEveryLine ? (uint) 2 : 0)); if (ret != 0 && ret != (uint) NativeMethods.Error.FILE_INVALID) { throw InstallerException.ExceptionFromReturnCode(ret); } } /// <summary> /// increments the usage count for a particular feature and returns the installation state for /// that feature. This method should be used to indicate an application's intent to use a feature. /// </summary> /// <param name="productCode">The product code of the product.</param> /// <param name="feature">The feature to be used.</param> /// <param name="installMode">Must have the value <see cref="InstallMode.NoDetection"/>.</param> /// <returns>The installed state of the feature.</returns> /// <remarks><p> /// The UseFeature method should only be used on features known to be published. The application /// should determine the status of the feature by calling either the FeatureState method or /// Features method. /// </p><p> /// Win32 MSI APIs: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msiusefeature.asp">MsiUseFeature</a>, /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msiusefeatureex.asp">MsiUseFeatureEx</a> /// </p></remarks> public static InstallState UseFeature(string productCode, string feature, InstallMode installMode) { int installState = NativeMethods.MsiUseFeatureEx(productCode, feature, unchecked ((uint) installMode), 0); return (InstallState) installState; } /// <summary> /// Opens an installer package for use with functions that access the product database and install engine, /// returning an Session object. /// </summary> /// <param name="packagePath">Path to the package</param> /// <param name="ignoreMachineState">Specifies whether or not the create a Session object that ignores the /// computer state and that is incapable of changing the current computer state. A value of false yields /// the normal behavior. A value of true creates a "safe" Session object that cannot change of the current /// machine state.</param> /// <returns>A Session object allowing access to the product database and install engine</returns> /// <exception cref="InstallerException">The product could not be opened</exception> /// <exception cref="InstallerException">The installer configuration data is corrupt</exception> /// <remarks><p> /// Note that only one Session object can be opened by a single process. OpenPackage cannot be used in a /// custom action because the active installation is the only session allowed. /// </p><p> /// A "safe" Session object ignores the current computer state when opening the package and prevents /// changes to the current computer state. /// </p><p> /// The Session object should be <see cref="InstallerHandle.Close"/>d after use. /// It is best that the handle be closed manually as soon as it is no longer /// needed, as leaving lots of unused handles open can degrade performance. /// </p><p> /// Win32 MSI APIs: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msiopenpackage.asp">MsiOpenPackage</a>, /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msiopenpackageex.asp">MsiOpenPackageEx</a> /// </p></remarks> public static Session OpenPackage(string packagePath, bool ignoreMachineState) { int sessionHandle; uint ret = NativeMethods.MsiOpenPackageEx(packagePath, ignoreMachineState ? (uint) 1 : 0, out sessionHandle); if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } return new Session((IntPtr) sessionHandle, true); } /// <summary> /// Opens an installer package for use with functions that access the product database and install engine, /// returning an Session object. /// </summary> /// <param name="database">Database used to create the session</param> /// <param name="ignoreMachineState">Specifies whether or not the create a Session object that ignores the /// computer state and that is incapable of changing the current computer state. A value of false yields /// the normal behavior. A value of true creates a "safe" Session object that cannot change of the current /// machine state.</param> /// <returns>A Session object allowing access to the product database and install engine</returns> /// <exception cref="InstallerException">The product could not be opened</exception> /// <exception cref="InstallerException">The installer configuration data is corrupt</exception> /// <remarks><p> /// Note that only one Session object can be opened by a single process. OpenPackage cannot be used in a /// custom action because the active installation is the only session allowed. /// </p><p> /// A "safe" Session object ignores the current computer state when opening the package and prevents /// changes to the current computer state. /// </p><p> /// The Session object should be <see cref="InstallerHandle.Close"/>d after use. /// It is best that the handle be closed manually as soon as it is no longer /// needed, as leaving lots of unused handles open can degrade performance. /// </p><p> /// Win32 MSI APIs: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msiopenpackage.asp">MsiOpenPackage</a>, /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msiopenpackageex.asp">MsiOpenPackageEx</a> /// </p></remarks> [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] public static Session OpenPackage(Database database, bool ignoreMachineState) { if (database == null) { throw new ArgumentNullException("database"); } return Installer.OpenPackage( String.Format(CultureInfo.InvariantCulture, "#{0}", database.Handle), ignoreMachineState); } /// <summary> /// Opens an installer package for an installed product using the product code. /// </summary> /// <param name="productCode">Product code of the installed product</param> /// <returns>A Session object allowing access to the product database and install engine, /// or null if the specified product is not installed.</returns> /// <exception cref="ArgumentException">An unknown product was requested</exception> /// <exception cref="InstallerException">The product could not be opened</exception> /// <exception cref="InstallerException">The installer configuration data is corrupt</exception> /// <remarks><p> /// Note that only one Session object can be opened by a single process. OpenProduct cannot be /// used in a custom action because the active installation is the only session allowed. /// </p><p> /// The Session object should be <see cref="InstallerHandle.Close"/>d after use. /// It is best that the handle be closed manually as soon as it is no longer /// needed, as leaving lots of unused handles open can degrade performance. /// </p><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msiopenproduct.asp">MsiOpenProduct</a> /// </p></remarks> public static Session OpenProduct(string productCode) { int sessionHandle; uint ret = NativeMethods.MsiOpenProduct(productCode, out sessionHandle); if (ret != 0) { if (ret == (uint) NativeMethods.Error.UNKNOWN_PRODUCT) { return null; } else { throw InstallerException.ExceptionFromReturnCode(ret); } } return new Session((IntPtr) sessionHandle, true); } /// <summary> /// Gets the full component path, performing any necessary installation. This method prompts for source if /// necessary and increments the usage count for the feature. /// </summary> /// <param name="product">Product code for the product that contains the feature with the necessary component</param> /// <param name="feature">Feature ID of the feature with the necessary component</param> /// <param name="component">Component code of the necessary component</param> /// <param name="installMode">Installation mode; this can also include bits from <see cref="ReinstallModes"/></param> /// <returns>Path to the component</returns> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msiprovidecomponent.asp">MsiProvideComponent</a> /// </p></remarks> public static string ProvideComponent(string product, string feature, string component, InstallMode installMode) { StringBuilder pathBuf = new StringBuilder(512); uint pathBufSize = (uint) pathBuf.Capacity; uint ret = NativeMethods.MsiProvideComponent(product, feature, component, unchecked((uint)installMode), pathBuf, ref pathBufSize); if (ret == (uint) NativeMethods.Error.MORE_DATA) { pathBuf.Capacity = (int) ++pathBufSize; ret = NativeMethods.MsiProvideComponent(product, feature, component, unchecked((uint)installMode), pathBuf, ref pathBufSize); } if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } return pathBuf.ToString(); } /// <summary> /// Gets the full component path for a qualified component that is published by a product and /// performs any necessary installation. This method prompts for source if necessary and increments /// the usage count for the feature. /// </summary> /// <param name="component">Specifies the component ID for the requested component. This may not be the /// GUID for the component itself but rather a server that provides the correct functionality, as in the /// ComponentId column of the PublishComponent table.</param> /// <param name="qualifier">Specifies a qualifier into a list of advertising components (from PublishComponent Table).</param> /// <param name="installMode">Installation mode; this can also include bits from <see cref="ReinstallModes"/></param> /// <param name="product">Optional; specifies the product to match that has published the qualified component.</param> /// <returns>Path to the component</returns> /// <remarks><p> /// Win32 MSI APIs: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msiprovidequalifiedcomponent.asp">MsiProvideQualifiedComponent</a> /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msiprovidequalifiedcomponentex.asp">MsiProvideQualifiedComponentEx</a> /// </p></remarks> public static string ProvideQualifiedComponent(string component, string qualifier, InstallMode installMode, string product) { StringBuilder pathBuf = new StringBuilder(512); uint pathBufSize = (uint) pathBuf.Capacity; uint ret = NativeMethods.MsiProvideQualifiedComponentEx(component, qualifier, unchecked((uint)installMode), product, 0, 0, pathBuf, ref pathBufSize); if (ret == (uint) NativeMethods.Error.MORE_DATA) { pathBuf.Capacity = (int) ++pathBufSize; ret = NativeMethods.MsiProvideQualifiedComponentEx(component, qualifier, unchecked((uint)installMode), product, 0, 0, pathBuf, ref pathBufSize); } if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } return pathBuf.ToString(); } /// <summary> /// Gets the full path to a Windows Installer component containing an assembly. This method prompts for a source and /// increments the usage count for the feature. /// </summary> /// <param name="assemblyName">Assembly name</param> /// <param name="appContext">Set to null for global assemblies. For private assemblies, set to the full path of the /// application configuration file (.cfg file) or executable file (.exe) of the application to which the assembly /// has been made private.</param> /// <param name="installMode">Installation mode; this can also include bits from <see cref="ReinstallModes"/></param> /// <param name="isWin32Assembly">True if this is a Win32 assembly, false if it is a .NET assembly</param> /// <returns>Path to the assembly</returns> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msiprovideassembly.asp">MsiProvideAssembly</a> /// </p></remarks> public static string ProvideAssembly(string assemblyName, string appContext, InstallMode installMode, bool isWin32Assembly) { StringBuilder pathBuf = new StringBuilder(512); uint pathBufSize = (uint) pathBuf.Capacity; uint ret = NativeMethods.MsiProvideAssembly(assemblyName, appContext, unchecked ((uint) installMode), (isWin32Assembly ? (uint) 1 : 0), pathBuf, ref pathBufSize); if (ret == (uint) NativeMethods.Error.MORE_DATA) { pathBuf.Capacity = (int) ++pathBufSize; ret = NativeMethods.MsiProvideAssembly(assemblyName, appContext, unchecked ((uint) installMode), (isWin32Assembly ? (uint) 1 : 0), pathBuf, ref pathBufSize); } if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } return pathBuf.ToString(); } /// <summary> /// Installs files that are unexpectedly missing. /// </summary> /// <param name="product">Product code for the product that owns the component to be installed</param> /// <param name="component">Component to be installed</param> /// <param name="installState">Specifies the way the component should be installed.</param> /// <exception cref="InstallCanceledException">the user exited the installation</exception> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msiinstallmissingcomponent.asp">MsiInstallMissingComponent</a> /// </p></remarks> public static void InstallMissingComponent(string product, string component, InstallState installState) { uint ret = NativeMethods.MsiInstallMissingComponent(product, component, (int) installState); if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } } /// <summary> /// Installs files that are unexpectedly missing. /// </summary> /// <param name="product">Product code for the product that owns the file to be installed</param> /// <param name="file">File to be installed</param> /// <exception cref="InstallCanceledException">the user exited the installation</exception> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msiinstallmissingfile.asp">MsiInstallMissingFile</a> /// </p></remarks> public static void InstallMissingFile(string product, string file) { uint ret = NativeMethods.MsiInstallMissingFile(product, file); if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } } /// <summary> /// Reinstalls a feature. /// </summary> /// <param name="product">Product code for the product containing the feature to be reinstalled</param> /// <param name="feature">Feature to be reinstalled</param> /// <param name="reinstallModes">Reinstall modes</param> /// <exception cref="InstallCanceledException">the user exited the installation</exception> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msireinstallfeature.asp">MsiReinstallFeature</a> /// </p></remarks> public static void ReinstallFeature(string product, string feature, ReinstallModes reinstallModes) { uint ret = NativeMethods.MsiReinstallFeature(product, feature, (uint) reinstallModes); if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } } /// <summary> /// Reinstalls a product. /// </summary> /// <param name="product">Product code for the product to be reinstalled</param> /// <param name="reinstallModes">Reinstall modes</param> /// <exception cref="InstallCanceledException">the user exited the installation</exception> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msireinstallproduct.asp">MsiReinstallProduct</a> /// </p></remarks> public static void ReinstallProduct(string product, ReinstallModes reinstallModes) { uint ret = NativeMethods.MsiReinstallProduct(product, (uint) reinstallModes); if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } } /// <summary> /// Opens an installer package and initializes an install session. /// </summary> /// <param name="packagePath">path to the patch package</param> /// <param name="commandLine">command line property settings</param> /// <exception cref="InstallerException">There was an error installing the product</exception> /// <remarks><p> /// To completely remove a product, set REMOVE=ALL in <paramRef name="commandLine"/>. /// </p><p> /// This method displays the user interface with the current settings and /// log mode. You can change user interface settings with the <see cref="SetInternalUI(InstallUIOptions)"/> /// and <see cref="SetExternalUI(ExternalUIHandler,InstallLogModes)"/> functions. You can set the log mode with the /// <see cref="EnableLog(InstallLogModes,string)"/> function. /// </p><p> /// The <see cref="RebootRequired"/> and <see cref="RebootInitiated"/> properties should be /// tested after calling this method. /// </p><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msiinstallproduct.asp">MsiInstallProduct</a> /// </p></remarks> public static void InstallProduct(string packagePath, string commandLine) { uint ret = NativeMethods.MsiInstallProduct(packagePath, commandLine); Installer.CheckInstallResult(ret); } /// <summary> /// Installs or uninstalls a product. /// </summary> /// <param name="productCode">Product code of the product to be configured.</param> /// <param name="installLevel">Specifies the default installation configuration of the /// product. The <paramref name="installLevel"/> parameter is ignored and all features /// are installed if the <paramref name="installState"/> parameter is set to any other /// value than <see cref="InstallState.Default"/>. This parameter must be either 0 /// (install using authored feature levels), 65535 (install all features), or a value /// between 0 and 65535 to install a subset of available features. </param> /// <param name="installState">Specifies the installation state for the product.</param> /// <param name="commandLine">Specifies the command line property settings. This should /// be a list of the format Property=Setting Property=Setting.</param> /// <exception cref="InstallerException">There was an error configuring the product</exception> /// <remarks><p> /// This method displays the user interface with the current settings and /// log mode. You can change user interface settings with the <see cref="SetInternalUI(InstallUIOptions)"/> /// and <see cref="SetExternalUI(ExternalUIHandler,InstallLogModes)"/> functions. You can set the log mode with the /// <see cref="EnableLog(InstallLogModes,string)"/> function. /// </p><p> /// The <see cref="RebootRequired"/> and <see cref="RebootInitiated"/> properties should be /// tested after calling this method. /// </p><p> /// Win32 MSI APIs: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msiconfigureproduct.asp">MsiConfigureProduct</a>, /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msiconfigureproductex.asp">MsiConfigureProductEx</a> /// </p></remarks> public static void ConfigureProduct(string productCode, int installLevel, InstallState installState, string commandLine) { uint ret = NativeMethods.MsiConfigureProductEx(productCode, installLevel, (int) installState, commandLine); Installer.CheckInstallResult(ret); } /// <summary> /// Configures the installed state for a product feature. /// </summary> /// <param name="productCode">Product code of the product to be configured.</param> /// <param name="feature">Specifies the feature ID for the feature to be configured.</param> /// <param name="installState">Specifies the installation state for the feature.</param> /// <exception cref="InstallerException">There was an error configuring the feature</exception> /// <remarks><p> /// The <see cref="RebootRequired"/> and <see cref="RebootInitiated"/> properties should be /// tested after calling this method. /// </p><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msiconfigurefeature.asp">MsiConfigureFeature</a> /// </p></remarks> public static void ConfigureFeature(string productCode, string feature, InstallState installState) { uint ret = NativeMethods.MsiConfigureFeature(productCode, feature, (int) installState); Installer.CheckInstallResult(ret); } /// <summary> /// For each product listed by the patch package as eligible to receive the patch, ApplyPatch invokes /// an installation and sets the PATCH property to the path of the patch package. /// </summary> /// <param name="patchPackage">path to the patch package</param> /// <param name="commandLine">optional command line property settings</param> /// <exception cref="InstallerException">There was an error applying the patch</exception> /// <remarks><p> /// The <see cref="RebootRequired"/> and <see cref="RebootInitiated"/> properties should be /// tested after calling this method. /// </p><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msiapplypatch.asp">MsiApplyPatch</a> /// </p></remarks> public static void ApplyPatch(string patchPackage, string commandLine) { Installer.ApplyPatch(patchPackage, null, InstallType.Default, commandLine); } /// <summary> /// For each product listed by the patch package as eligible to receive the patch, ApplyPatch invokes /// an installation and sets the PATCH property to the path of the patch package. /// </summary> /// <param name="patchPackage">path to the patch package</param> /// <param name="installPackage">path to the product to be patched, if installType /// is set to <see cref="InstallType.NetworkImage"/></param> /// <param name="installType">type of installation to patch</param> /// <param name="commandLine">optional command line property settings</param> /// <exception cref="InstallerException">There was an error applying the patch</exception> /// <remarks><p> /// The <see cref="RebootRequired"/> and <see cref="RebootInitiated"/> properties should be /// tested after calling this method. /// </p><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msiapplypatch.asp">MsiApplyPatch</a> /// </p></remarks> public static void ApplyPatch(string patchPackage, string installPackage, InstallType installType, string commandLine) { uint ret = NativeMethods.MsiApplyPatch(patchPackage, installPackage, (int) installType, commandLine); Installer.CheckInstallResult(ret); } /// <summary> /// Removes one or more patches from a single product. To remove a patch from /// multiple products, RemovePatches must be called for each product. /// </summary> /// <param name="patches">List of patches to remove. Each patch can be specified by the GUID /// of the patch or the full path to the patch package.</param> /// <param name="productCode">The ProductCode (GUID) of the product from which the patches /// are removed. This parameter cannot be null.</param> /// <param name="commandLine">optional command line property settings</param> /// <exception cref="InstallerException">There was an error removing the patches</exception> /// <remarks><p> /// The <see cref="RebootRequired"/> and <see cref="RebootInitiated"/> properties should be /// tested after calling this method. /// </p><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msiremovepatches.asp">MsiRemovePatches</a> /// </p></remarks> public static void RemovePatches(IList<string> patches, string productCode, string commandLine) { if (patches == null || patches.Count == 0) { throw new ArgumentNullException("patches"); } if (productCode == null) { throw new ArgumentNullException("productCode"); } StringBuilder patchList = new StringBuilder(); foreach (string patch in patches) { if (patch != null) { if (patchList.Length != 0) { patchList.Append(';'); } patchList.Append(patch); } } if (patchList.Length == 0) { throw new ArgumentNullException("patches"); } uint ret = NativeMethods.MsiRemovePatches(patchList.ToString(), productCode, (int) InstallType.SingleInstance, commandLine); Installer.CheckInstallResult(ret); } /// <summary> /// Determines which patches apply to a specified product MSI and in what sequence. /// </summary> /// <param name="productPackage">Full path to an MSI file that is the target product /// for the set of patches.</param> /// <param name="patches">An array of strings specifying the patches to be checked. Each item /// may be the path to an MSP file, the path an XML file, or just an XML blob.</param> /// <param name="errorHandler">Callback to be invoked for each inapplicable patch, reporting the /// reason the patch is not applicable. This value may be left null if that information is not /// desired.</param> /// <returns>An array of selected patch strings from <paramref name="patches"/>, indicating /// the set of applicable patches. The items are re-ordered to be in the best sequence.</returns> /// <remarks><p> /// If an item in <paramref name="patches"/> is a file path but does not end in .MSP or .XML, /// it is assumed to be an MSP file. /// </p><p> /// As this overload uses InstallContext.None, it does not consider the current state of /// the system. /// </p><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msidetermineapplicablepatches.asp">MsiDetermineApplicablePatches</a> /// </p></remarks> public static IList<string> DetermineApplicablePatches( string productPackage, string[] patches, InapplicablePatchHandler errorHandler) { return DetermineApplicablePatches(productPackage, patches, errorHandler, null, UserContexts.None); } /// <summary> /// Determines which patches apply to a specified product and in what sequence. If /// the product is installed, this method accounts for patches that have already been applied to /// the product and accounts for obsolete and superceded patches. /// </summary> /// <param name="product">The product that is the target for the set of patches. This may be /// either a ProductCode (GUID) of a product that is currently installed, or the path to a an /// MSI file.</param> /// <param name="patches">An array of strings specifying the patches to be checked. Each item /// may be the path to an MSP file, the path an XML file, or just an XML blob.</param> /// <param name="errorHandler">Callback to be invoked for each inapplicable patch, reporting the /// reason the patch is not applicable. This value may be left null if that information is not /// desired.</param> /// <param name="userSid">Specifies a security identifier (SID) of a user. This parameter restricts /// the context of enumeration for this user account. This parameter cannot be the special SID /// strings s-1-1-0 (everyone) or s-1-5-18 (local system). If <paramref name="context"/> is set to /// <see cref="UserContexts.None"/> or <see cref="UserContexts.Machine"/>, then /// <paramref name="userSid"/> must be null. For the current user context, <paramref name="userSid"/> /// can be null and <paramref name="context"/> can be set to <see cref="UserContexts.UserManaged"/> /// or <see cref="UserContexts.UserUnmanaged"/>.</param> /// <param name="context">Restricts the enumeration to per-user-unmanaged, per-user-managed, /// or per-machine context, or (if referring to an MSI) to no system context at all. This /// parameter can be <see cref="UserContexts.Machine"/>, <see cref="UserContexts.UserManaged"/>, /// <see cref="UserContexts.UserUnmanaged"/>, or <see cref="UserContexts.None"/>.</param> /// <returns>An array of selected patch strings from <paramref name="patches"/>, indicating /// the set of applicable patches. The items are re-ordered to be in the best sequence.</returns> /// <remarks><p> /// If an item in <paramref name="patches"/> is a file path but does not end in .MSP or .XML, /// it is assumed to be an MSP file. /// </p><p> /// Passing an InstallContext of None only analyzes the MSI file; it does not consider the /// current state of the system. You cannot use InstallContext.None with a ProductCode GUID. /// </p><p> /// Win32 MSI APIs: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msidetermineapplicablepatches.asp">MsiDetermineApplicablePatches</a> /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msideterminepatchsequence.asp">MsiDeterminePatchSequence</a> /// </p></remarks> public static IList<string> DetermineApplicablePatches( string product, string[] patches, InapplicablePatchHandler errorHandler, string userSid, UserContexts context) { if (string.IsNullOrWhiteSpace(product)) { throw new ArgumentNullException("product"); } if (patches == null) { throw new ArgumentNullException("patches"); } NativeMethods.MsiPatchSequenceData[] sequenceData = new NativeMethods.MsiPatchSequenceData[patches.Length]; for (int i = 0; i < patches.Length; i++) { if (string.IsNullOrWhiteSpace(patches[i])) { throw new ArgumentNullException("patches[" + i + "]"); } sequenceData[i].szPatchData = patches[i]; sequenceData[i].ePatchDataType = GetPatchStringDataType(patches[i]); sequenceData[i].dwOrder = -1; sequenceData[i].dwStatus = 0; } uint ret; if (context == UserContexts.None) { ret = NativeMethods.MsiDetermineApplicablePatches(product, (uint) sequenceData.Length, sequenceData); } else { ret = NativeMethods.MsiDeterminePatchSequence(product, userSid, context, (uint) sequenceData.Length, sequenceData); } if (errorHandler != null) { for (int i = 0; i < sequenceData.Length; i++) { if (sequenceData[i].dwOrder < 0 && sequenceData[i].dwStatus != 0) { errorHandler(sequenceData[i].szPatchData, InstallerException.ExceptionFromReturnCode(sequenceData[i].dwStatus)); } } } if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } IList<string> patchSeq = new List<string>(patches.Length); for (int i = 0; i < sequenceData.Length; i++) { for (int j = 0; j < sequenceData.Length; j++) { if (sequenceData[j].dwOrder == i) { patchSeq.Add(sequenceData[j].szPatchData); } } } return patchSeq; } /// <summary> /// Applies one or more patches to products that are eligible to receive the patch. /// For each product listed by the patch package as eligible to receive the patch, ApplyPatch invokes /// an installation and sets the PATCH property to the path of the patch package. /// </summary> /// <param name="patchPackages">The set of patch packages to be applied. /// Each item is the full path to an MSP file.</param> /// <param name="productCode">Provides the ProductCode of the product being patched. If this parameter /// is null, the patches are applied to all products that are eligible to receive these patches.</param> /// <param name="commandLine">optional command line property settings</param> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msiapplymultiplepatches.asp">MsiApplyMultiplePatches</a> /// </p></remarks> public static void ApplyMultiplePatches( IList<string> patchPackages, string productCode, string commandLine) { if (patchPackages == null || patchPackages.Count == 0) { throw new ArgumentNullException("patchPackages"); } StringBuilder patchList = new StringBuilder(); foreach (string patch in patchPackages) { if (patch != null) { if (patchList.Length != 0) { patchList.Append(';'); } patchList.Append(patch); } } if (patchList.Length == 0) { throw new ArgumentNullException("patchPackages"); } uint ret = NativeMethods.MsiApplyMultiplePatches(patchList.ToString(), productCode, commandLine); Installer.CheckInstallResult(ret); } /// <summary> /// Extracts information from a patch that can be used to determine whether the patch /// applies on a target system. The method returns an XML string that can be provided to /// <see cref="DetermineApplicablePatches(string,string[],InapplicablePatchHandler,string,UserContexts)"/> /// instead of the full patch file. /// </summary> /// <param name="patchPath">Full path to the patch being queried.</param> /// <returns>XML string containing patch data.</returns> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msiextractpatchxmldata.asp">MsiExtractPatchXMLData</a> /// </p></remarks> public static string ExtractPatchXmlData(string patchPath) { StringBuilder buf = new StringBuilder(""); uint bufSize = 0; uint ret = NativeMethods.MsiExtractPatchXMLData(patchPath, 0, buf, ref bufSize); if (ret == (uint) NativeMethods.Error.MORE_DATA) { buf.Capacity = (int) ++bufSize; ret = NativeMethods.MsiExtractPatchXMLData(patchPath, 0, buf, ref bufSize); } if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } return buf.ToString(); } /// <summary> /// [MSI 3.1] Migrates a user's application configuration data to a new SID. /// </summary> /// <param name="oldSid">Previous user SID that data is to be migrated from</param> /// <param name="newSid">New user SID that data is to be migrated to</param> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msinotifysidchange.asp">MsiNotifySidChange</a> /// </p></remarks> public static void NotifySidChange(string oldSid, string newSid) { uint ret = NativeMethods.MsiNotifySidChange(oldSid, newSid); if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } } private static void CheckInstallResult(uint ret) { switch (ret) { case (uint) NativeMethods.Error.SUCCESS: break; case (uint) NativeMethods.Error.SUCCESS_REBOOT_REQUIRED: Installer.rebootRequired = true; break; case (uint) NativeMethods.Error.SUCCESS_REBOOT_INITIATED: Installer.rebootInitiated = true; break; default: throw InstallerException.ExceptionFromReturnCode(ret); } } private static int GetPatchStringDataType(string patchData) { if (patchData.IndexOf("<", StringComparison.Ordinal) >= 0 && patchData.IndexOf(">", StringComparison.Ordinal) >= 0) { return 2; // XML blob } else if (String.Compare(Path.GetExtension(patchData), ".xml", StringComparison.OrdinalIgnoreCase) == 0) { return 1; // XML file path } else { return 0; // MSP file path } } } }
using UnityEngine; using System.Collections.Generic; namespace tk2dRuntime.TileMap { public static class BuilderUtil { /// Syncs layer data and makes sure data is valid public static bool InitDataStore(tk2dTileMap tileMap) { bool dataChanged = false; int numLayers = tileMap.data.NumLayers; if (tileMap.Layers == null) { tileMap.Layers = new Layer[numLayers]; for (int i = 0; i < numLayers; ++i) tileMap.Layers[i] = new Layer(tileMap.data.Layers[i].hash, tileMap.width, tileMap.height, tileMap.partitionSizeX, tileMap.partitionSizeY); dataChanged = true; } else { // link up layer hashes Layer[] newLayers = new Layer[numLayers]; for (int i = 0; i < numLayers; ++i) { var layerInfo = tileMap.data.Layers[i]; bool found = false; // Find an existing layer with this hash for (int j = 0; j < tileMap.Layers.Length; ++j) { if (tileMap.Layers[j].hash == layerInfo.hash) { newLayers[i] = tileMap.Layers[j]; found = true; break; } } if (!found) newLayers[i] = new Layer(layerInfo.hash, tileMap.width, tileMap.height, tileMap.partitionSizeX, tileMap.partitionSizeY); } // Identify if it has changed int numActiveLayers = 0; foreach (var layer in newLayers) if (!layer.IsEmpty) numActiveLayers++; int numPreviousActiveLayers = 0; foreach (var layer in tileMap.Layers) { if (!layer.IsEmpty) numPreviousActiveLayers++; } if (numActiveLayers != numPreviousActiveLayers) dataChanged = true; tileMap.Layers = newLayers; } if (tileMap.ColorChannel == null) { tileMap.ColorChannel = new ColorChannel(tileMap.width, tileMap.height, tileMap.partitionSizeX, tileMap.partitionSizeY); } return dataChanged; } static List<int> TilePrefabsX; static List<int> TilePrefabsY; static List<int> TilePrefabsLayer; static List<GameObject> TilePrefabsInstance; static GameObject GetExistingTilePrefabInstance(tk2dTileMap tileMap, int tileX, int tileY, int tileLayer) { int n = tileMap.GetTilePrefabsListCount(); for (int i = 0; i < n; ++i) { int x, y, layer; GameObject instance; tileMap.GetTilePrefabsListItem(i, out x, out y, out layer, out instance); if (x == tileX && y == tileY && layer == tileLayer) return instance; } return null; } /// Spawns all prefabs for a given chunk /// Expects the chunk to have a valid GameObject public static void SpawnPrefabsForChunk(tk2dTileMap tileMap, SpriteChunk chunk, int baseX, int baseY, int layer, int[] prefabCounts) { var chunkData = chunk.spriteIds; var tilePrefabs = tileMap.data.tilePrefabs; Vector3 tileSize = tileMap.data.tileSize; var parent = chunk.gameObject.transform; float xOffsetMult = 0.0f, yOffsetMult = 0.0f; tileMap.data.GetTileOffset(out xOffsetMult, out yOffsetMult); for (int y = 0; y < tileMap.partitionSizeY; ++y) { float xOffset = ((baseY + y) & 1) * xOffsetMult; for (int x = 0; x < tileMap.partitionSizeX; ++x) { int tile = GetTileFromRawTile(chunkData[y * tileMap.partitionSizeX + x]); if (tile < 0 || tile >= tilePrefabs.Length) continue; Object prefab = tilePrefabs[tile]; if (prefab != null) { prefabCounts[tile]++; GameObject instance = GetExistingTilePrefabInstance(tileMap, baseX + x, baseY + y, layer); bool foundExisting = (instance != null); #if UNITY_EDITOR if (instance != null) { if (UnityEditor.PrefabUtility.GetPrefabParent(instance) != prefab) { instance = null; } } #endif if (instance == null) { #if UNITY_EDITOR instance = UnityEditor.PrefabUtility.InstantiatePrefab(prefab) as GameObject; #else instance = GameObject.Instantiate(prefab, Vector3.zero, Quaternion.identity) as GameObject; #endif #if UNITY_EDITOR && !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2) if (!Application.isPlaying) { UnityEditor.Undo.RegisterCreatedObjectUndo(instance, "Instantiated Prefab"); } #endif } if (instance != null) { GameObject prefabGameObject = prefab as GameObject; Vector3 pos = new Vector3(tileSize.x * (x + xOffset), tileSize.y * y, 0); bool enablePrefabOffset = false; var tileInfo = tileMap.data.GetTileInfoForSprite(tile); if (tileInfo != null) enablePrefabOffset = tileInfo.enablePrefabOffset; if (enablePrefabOffset && prefabGameObject != null) pos += prefabGameObject.transform.position; if (!foundExisting) instance.name = prefab.name + " " + prefabCounts[tile].ToString(); tk2dUtil.SetTransformParent(instance.transform, parent); instance.transform.localPosition = pos; // Add to tilePrefabs list TilePrefabsX.Add(baseX + x); TilePrefabsY.Add(baseY + y); TilePrefabsLayer.Add(layer); TilePrefabsInstance.Add(instance); } } } } } /// Spawns all prefabs for a given tilemap /// Expects populated chunks to have valid GameObjects public static void SpawnPrefabs(tk2dTileMap tileMap, bool forceBuild) { // Restart these lists that will be stored in the tileMap tilePrefabsList TilePrefabsX = new List<int>(); TilePrefabsY = new List<int>(); TilePrefabsLayer = new List<int>(); TilePrefabsInstance = new List<GameObject>(); int[] prefabCounts = new int[tileMap.data.tilePrefabs.Length]; int numLayers = tileMap.Layers.Length; for (int layerId = 0; layerId < numLayers; ++layerId) { var layer = tileMap.Layers[layerId]; var layerData = tileMap.data.Layers[layerId]; // We skip offsetting the first one if (layer.IsEmpty || layerData.skipMeshGeneration) continue; for (int cellY = 0; cellY < layer.numRows; ++cellY) { int baseY = cellY * layer.divY; for (int cellX = 0; cellX < layer.numColumns; ++cellX) { int baseX = cellX * layer.divX; var chunk = layer.GetChunk(cellX, cellY); if (chunk.IsEmpty) continue; if (!forceBuild && !chunk.Dirty) continue; SpawnPrefabsForChunk(tileMap, chunk, baseX, baseY, layerId, prefabCounts); } } } tileMap.SetTilePrefabsList(TilePrefabsX, TilePrefabsY, TilePrefabsLayer, TilePrefabsInstance); } /// <summary> /// Moves the chunk's gameobject's children to the prefab root /// </summary> public static void HideTileMapPrefabs(tk2dTileMap tileMap) { if (tileMap.renderData == null || tileMap.Layers == null) { // No Render Data to parent Prefab Root to return; } if (tileMap.PrefabsRoot == null) { var go = tileMap.PrefabsRoot = tk2dUtil.CreateGameObject("Prefabs"); go.transform.parent = tileMap.renderData.transform; go.transform.localPosition = Vector3.zero; go.transform.localRotation = Quaternion.identity; go.transform.localScale = Vector3.one; } int instListCount = tileMap.GetTilePrefabsListCount(); bool[] instExists = new bool[instListCount]; for (int i = 0; i < tileMap.Layers.Length; ++i) { var layer = tileMap.Layers[i]; for (int j = 0; j < layer.spriteChannel.chunks.Length; ++j) { var chunk = layer.spriteChannel.chunks[j]; if (chunk.gameObject == null) continue; var t = chunk.gameObject.transform; int childCount = t.childCount; for (int k = 0; k < childCount; ++k) { GameObject go = t.GetChild(k).gameObject; for (int q = 0; q < instListCount; ++q) { int x, y, layerIdx; GameObject instance; tileMap.GetTilePrefabsListItem(q, out x, out y, out layerIdx, out instance); if (instance == go) { instExists[q] = true; break; } } } } } Object[] prefabs = tileMap.data.tilePrefabs; List<int> tileX = new List<int>(); List<int> tileY = new List<int>(); List<int> tileLayer = new List<int>(); List<GameObject> tileInst = new List<GameObject>(); for (int i = 0; i < instListCount; ++i) { int x, y, layerIdx; GameObject instance; tileMap.GetTilePrefabsListItem(i, out x, out y, out layerIdx, out instance); // Is it already IN the list for some reason? if (!instExists[i]) { int tileId = (x >= 0 && x < tileMap.width && y >= 0 && y < tileMap.height) ? tileMap.GetTile(x, y, layerIdx) : -1; if (tileId >= 0 && tileId < prefabs.Length && prefabs[tileId] != null) { instExists[i] = true; } } if (instExists[i]) { tileX.Add(x); tileY.Add(y); tileLayer.Add(layerIdx); tileInst.Add(instance); tk2dUtil.SetTransformParent(instance.transform, tileMap.PrefabsRoot.transform); } } tileMap.SetTilePrefabsList(tileX, tileY, tileLayer, tileInst); } static Vector3 GetTilePosition(tk2dTileMap tileMap, int x, int y) { return new Vector3(tileMap.data.tileSize.x * x, tileMap.data.tileSize.y * y, 0.0f); } /// Creates render data for given tilemap public static void CreateRenderData(tk2dTileMap tileMap, bool editMode, Dictionary<Layer, bool> layersActive) { // Create render data if (tileMap.renderData == null) tileMap.renderData = tk2dUtil.CreateGameObject(tileMap.name + " Render Data"); tileMap.renderData.transform.position = tileMap.transform.position; float accumulatedLayerZ = 0.0f; // Create all objects int layerId = 0; foreach (var layer in tileMap.Layers) { // We skip offsetting the first one float layerInfoZ = tileMap.data.Layers[layerId].z; if (layerId != 0) accumulatedLayerZ -= layerInfoZ; if (layer.IsEmpty && layer.gameObject != null) { tk2dUtil.DestroyImmediate(layer.gameObject); layer.gameObject = null; } else if (!layer.IsEmpty && layer.gameObject == null) { var go = layer.gameObject = tk2dUtil.CreateGameObject(""); go.transform.parent = tileMap.renderData.transform; } int unityLayer = tileMap.data.Layers[layerId].unityLayer; if (layer.gameObject != null) { #if UNITY_3_5 if (!editMode && layersActive.ContainsKey(layer) && layer.gameObject.active != layersActive[layer]) layer.gameObject.SetActiveRecursively(layersActive[layer]); #else if (!editMode && layersActive.ContainsKey(layer) && layer.gameObject.activeSelf != layersActive[layer]) layer.gameObject.SetActive(layersActive[layer]); #endif layer.gameObject.name = tileMap.data.Layers[layerId].name; layer.gameObject.transform.localPosition = new Vector3(0, 0, tileMap.data.layersFixedZ ? (-layerInfoZ) : accumulatedLayerZ); layer.gameObject.transform.localRotation = Quaternion.identity; layer.gameObject.transform.localScale = Vector3.one; layer.gameObject.layer = unityLayer; } int x0, x1, dx; int y0, y1, dy; BuilderUtil.GetLoopOrder(tileMap.data.sortMethod, layer.numColumns, layer.numRows, out x0, out x1, out dx, out y0, out y1, out dy); float z = 0.0f; for (int y = y0; y != y1; y += dy) { for (int x = x0; x != x1; x += dx) { var chunk = layer.GetChunk(x, y); bool isEmpty = layer.IsEmpty || chunk.IsEmpty; if (editMode) { isEmpty = false; } if (isEmpty && chunk.HasGameData) { chunk.DestroyGameData(tileMap); } else if (!isEmpty && chunk.gameObject == null) { string chunkName = "Chunk " + y.ToString() + " " + x.ToString(); var go = chunk.gameObject = tk2dUtil.CreateGameObject(chunkName); go.transform.parent = layer.gameObject.transform; // render mesh MeshFilter meshFilter = tk2dUtil.AddComponent<MeshFilter>(go); tk2dUtil.AddComponent<MeshRenderer>(go); chunk.mesh = tk2dUtil.CreateMesh(); meshFilter.mesh = chunk.mesh; } if (chunk.gameObject != null) { Vector3 tilePosition = GetTilePosition(tileMap, x * tileMap.partitionSizeX, y * tileMap.partitionSizeY); tilePosition.z += z; chunk.gameObject.transform.localPosition = tilePosition; chunk.gameObject.transform.localRotation = Quaternion.identity; chunk.gameObject.transform.localScale = Vector3.one; chunk.gameObject.layer = unityLayer; // We won't be generating collider data in edit mode, so clear everything if (editMode) { chunk.DestroyColliderData(tileMap); } } z -= 0.000001f; } } ++layerId; } } public static void GetLoopOrder(tk2dTileMapData.SortMethod sortMethod, int w, int h, out int x0, out int x1, out int dx, out int y0, out int y1, out int dy) { switch (sortMethod) { case tk2dTileMapData.SortMethod.BottomLeft: x0 = 0; x1 = w; dx = 1; y0 = 0; y1 = h; dy = 1; break; case tk2dTileMapData.SortMethod.BottomRight: x0 = w - 1; x1 = -1; dx = -1; y0 = 0; y1 = h; dy = 1; break; case tk2dTileMapData.SortMethod.TopLeft: x0 = 0; x1 = w; dx = 1; y0 = h - 1; y1 = -1; dy = -1; break; case tk2dTileMapData.SortMethod.TopRight: x0 = w - 1; x1 = -1; dx = -1; y0 = h - 1; y1 = -1; dy = -1; break; default: Debug.LogError("Unhandled sort method"); goto case tk2dTileMapData.SortMethod.BottomLeft; } } const int tileMask = 0x00ffffff; public static int GetTileFromRawTile(int rawTile) { if (rawTile == -1) return -1; return rawTile & tileMask; } public static bool IsRawTileFlagSet(int rawTile, tk2dTileFlags flag) { if (rawTile == -1) return false; return (rawTile & (int)flag) != 0; } public static void SetRawTileFlag(ref int rawTile, tk2dTileFlags flag, bool setValue) { if (rawTile == -1) return; rawTile = setValue ? (rawTile | (int)flag) : (rawTile & (int)(~flag)); } public static void InvertRawTileFlag(ref int rawTile, tk2dTileFlags flag) { if (rawTile == -1) return; bool setValue = (rawTile & (int)flag) == 0; rawTile = setValue ? (rawTile | (int)flag) : (rawTile & (int)(~flag)); } public static Vector3 ApplySpriteVertexTileFlags(tk2dTileMap tileMap, tk2dSpriteDefinition spriteDef, Vector3 pos, bool flipH, bool flipV, bool rot90) { float cx = tileMap.data.tileOrigin.x + 0.5f * tileMap.data.tileSize.x; float cy = tileMap.data.tileOrigin.y + 0.5f * tileMap.data.tileSize.y; float dx = pos.x - cx; float dy = pos.y - cy; if (rot90) { float tmp = dx; dx = dy; dy = -tmp; } if (flipH) dx *= -1.0f; if (flipV) dy *= -1.0f; pos.x = cx + dx; pos.y = cy + dy; return pos; } public static Vector2 ApplySpriteVertexTileFlags(tk2dTileMap tileMap, tk2dSpriteDefinition spriteDef, Vector2 pos, bool flipH, bool flipV, bool rot90) { float cx = tileMap.data.tileOrigin.x + 0.5f * tileMap.data.tileSize.x; float cy = tileMap.data.tileOrigin.y + 0.5f * tileMap.data.tileSize.y; float dx = pos.x - cx; float dy = pos.y - cy; if (rot90) { float tmp = dx; dx = dy; dy = -tmp; } if (flipH) dx *= -1.0f; if (flipV) dy *= -1.0f; pos.x = cx + dx; pos.y = cy + dy; return pos; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; #if CORECLR using System.Runtime.Loader; #endif using System.Reflection; using System.IO; class InstanceFieldTest : MyClass { public int Value; } class InstanceFieldTest2 : InstanceFieldTest { public int Value2; } [StructLayout(LayoutKind.Sequential)] class InstanceFieldTestWithLayout : MyClassWithLayout { public int Value; } class GrowingBase { MyGrowingStruct s; } class InheritingFromGrowingBase : GrowingBase { public int x; } static class OpenClosedDelegateExtension { public static string OpenClosedDelegateTarget(this string x, string foo) { return x + ", " + foo; } } class Program { static void TestVirtualMethodCalls() { var o = new MyClass(); Assert.AreEqual(o.VirtualMethod(), "Virtual method result"); var iface = (IMyInterface)o; Assert.AreEqual(iface.InterfaceMethod(" "), "Interface result"); Assert.AreEqual(MyClass.TestInterfaceMethod(iface, "+"), "Interface+result"); } static void TestMovedVirtualMethods() { var o = new MyChildClass(); Assert.AreEqual(o.MovedToBaseClass(), "MovedToBaseClass"); Assert.AreEqual(o.ChangedToVirtual(), "ChangedToVirtual"); if (!LLILCJitEnabled) { o = null; try { o.MovedToBaseClass(); } catch (NullReferenceException) { try { o.ChangedToVirtual(); } catch (NullReferenceException) { return; } } Assert.AreEqual("NullReferenceException", "thrown"); } } static void TestConstrainedMethodCalls() { using (MyStruct s = new MyStruct()) { ((Object)s).ToString(); } } static void TestConstrainedMethodCalls_Unsupported() { MyStruct s = new MyStruct(); s.ToString(); } static void TestInterop() { // Verify both intra-module and inter-module PInvoke interop if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { MyClass.GetTickCount(); } else { MyClass.GetCurrentThreadId(); } MyClass.TestInterop(); } static void TestStaticFields() { MyClass.StaticObjectField = 894; MyClass.StaticLongField = 4392854; MyClass.StaticNullableGuidField = new Guid("0D7E505F-E767-4FEF-AEEC-3243A3005673"); MyClass.ThreadStaticStringField = "Hello"; MyClass.ThreadStaticIntField = 735; MyClass.ThreadStaticDateTimeField = new DateTime(2011, 1, 1); MyClass.TestStaticFields(); #if false // TODO: Enable once LDFTN is supported Task.Run(() => { MyClass.ThreadStaticStringField = "Garbage"; MyClass.ThreadStaticIntField = 0xBAAD; MyClass.ThreadStaticDateTimeField = DateTime.Now; }).Wait(); #endif Assert.AreEqual(MyClass.StaticObjectField, 894 + 12345678 /* + 1234 */); Assert.AreEqual(MyClass.StaticLongField, (long)(4392854 * 456 /* * 45 */)); Assert.AreEqual(MyClass.StaticNullableGuidField, null); Assert.AreEqual(MyClass.ThreadStaticStringField, "HelloWorld"); Assert.AreEqual(MyClass.ThreadStaticIntField, 735/78); Assert.AreEqual(MyClass.ThreadStaticDateTimeField, new DateTime(2011, 1, 1) + new TimeSpan(123)); } static void TestPreInitializedArray() { var a = new int[] { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512 }; int sum = 0; foreach (var e in a) sum += e; Assert.AreEqual(sum, 1023); } static void TestMultiDimmArray() { var a = new int[2,3,4]; a[0,1,2] = a[0,0,0] + a[1,1,1]; a.ToString(); } static void TestGenericVirtualMethod() { var o = new MyGeneric<String, Object>(); Assert.AreEqual(o.GenericVirtualMethod<Program, IEnumerable<String>>(), "System.StringSystem.ObjectProgramSystem.Collections.Generic.IEnumerable`1[System.String]"); } static void TestMovedGenericVirtualMethod() { var o = new MyChildGeneric<Object>(); Assert.AreEqual(o.MovedToBaseClass<WeakReference>(), typeof(List<WeakReference>).ToString()); Assert.AreEqual(o.ChangedToVirtual<WeakReference>(), typeof(List<WeakReference>).ToString()); if (!LLILCJitEnabled) { o = null; try { o.MovedToBaseClass<WeakReference>(); } catch (NullReferenceException) { try { o.ChangedToVirtual<WeakReference>(); } catch (NullReferenceException) { return; } } Assert.AreEqual("NullReferenceException", "thrown"); } } [MethodImplAttribute(MethodImplOptions.NoInlining)] static void TestGenericNonVirtualMethod() { var c = new MyChildGeneric<string>(); Assert.AreEqual(CallGeneric(c), "MyGeneric.NonVirtualMethod"); } [MethodImplAttribute(MethodImplOptions.NoInlining)] static string CallGeneric<T>(MyGeneric<T, T> g) { return g.NonVirtualMethod(); } static void TestGenericOverStruct() { var o1 = new MyGeneric<String, MyGrowingStruct>(); Assert.AreEqual(o1.GenericVirtualMethod < MyChangingStruct, IEnumerable<Program>>(), "System.StringMyGrowingStructMyChangingStructSystem.Collections.Generic.IEnumerable`1[Program]"); var o2 = new MyChildGeneric<MyChangingStruct>(); Assert.AreEqual(o2.MovedToBaseClass<MyGrowingStruct>(), typeof(List<MyGrowingStruct>).ToString()); Assert.AreEqual(o2.ChangedToVirtual<MyGrowingStruct>(), typeof(List<MyGrowingStruct>).ToString()); } static void TestInstanceFields() { var t = new InstanceFieldTest2(); t.Value = 123; t.Value2 = 234; t.InstanceField = 345; Assert.AreEqual(typeof(InstanceFieldTest).GetRuntimeField("Value").GetValue(t), 123); Assert.AreEqual(typeof(InstanceFieldTest2).GetRuntimeField("Value2").GetValue(t), 234); Assert.AreEqual(typeof(MyClass).GetRuntimeField("InstanceField").GetValue(t), 345); } static void TestInstanceFieldsWithLayout() { var t = new InstanceFieldTestWithLayout(); t.Value = 123; Assert.AreEqual(typeof(InstanceFieldTestWithLayout).GetRuntimeField("Value").GetValue(t), 123); } static void TestInheritingFromGrowingBase() { var o = new InheritingFromGrowingBase(); o.x = 6780; Assert.AreEqual(typeof(InheritingFromGrowingBase).GetRuntimeField("x").GetValue(o), 6780); } [MethodImplAttribute(MethodImplOptions.NoInlining)] static void TestGrowingStruct() { MyGrowingStruct s = MyGrowingStruct.Construct(); MyGrowingStruct.Check(ref s); } [MethodImplAttribute(MethodImplOptions.NoInlining)] static void TestChangingStruct() { MyChangingStruct s = MyChangingStruct.Construct(); s.x++; MyChangingStruct.Check(ref s); } [MethodImplAttribute(MethodImplOptions.NoInlining)] static void TestChangingHFAStruct() { MyChangingHFAStruct s = MyChangingHFAStruct.Construct(); MyChangingHFAStruct.Check(s); } [MethodImplAttribute(MethodImplOptions.NoInlining)] static void TestGetType() { new MyClass().GetType().ToString(); } [MethodImplAttribute(MethodImplOptions.NoInlining)] static void TestStaticBaseCSE() { // There should be just one call to CORINFO_HELP_READYTORUN_STATIC_BASE // in the generated code. s++; s++; Assert.AreEqual(s, 2); s = 0; } [MethodImplAttribute(MethodImplOptions.NoInlining)] static void TestIsInstCSE() { // There should be just one call to CORINFO_HELP_READYTORUN_ISINSTANCEOF // in the generated code. object o1 = (s < 1) ? (object)"foo" : (object)1; Assert.AreEqual(o1 is string, true); Assert.AreEqual(o1 is string, true); } [MethodImplAttribute(MethodImplOptions.NoInlining)] static void TestCastClassCSE() { // There should be just one call to CORINFO_HELP_READYTORUN_CHKCAST // in the generated code. object o1 = (s < 1) ? (object)"foo" : (object)1; string str1 = (string)o1; string str2 = (string)o1; Assert.AreEqual(str1, str2); } [MethodImplAttribute(MethodImplOptions.NoInlining)] static void TestRangeCheckElimination() { // Range checks for array accesses should be eliminated by the compiler. int[] array = new int[5]; array[2] = 2; Assert.AreEqual(array[2], 2); } #if CORECLR class MyLoadContext : AssemblyLoadContext { public MyLoadContext() { } public void TestMultipleLoads() { Assembly a = LoadFromAssemblyPath(Path.Combine(Directory.GetCurrentDirectory(), "test.ni.dll")); Assert.AreEqual(AssemblyLoadContext.GetLoadContext(a), this); } protected override Assembly Load(AssemblyName an) { throw new NotImplementedException(); } } static void TestMultipleLoads() { if (!LLILCJitEnabled) { // Runtime should be able to load the same R2R image in another load context, // even though it will be treated as an IL-only image. new MyLoadContext().TestMultipleLoads(); } } #endif static void TestFieldLayoutNGenMixAndMatch() { // This test is verifying consistent field layout when ReadyToRun images are combined with NGen images // "ngen install /nodependencies main.exe" to exercise the interesting case var o = new ByteChildClass(67); Assert.AreEqual(o.ChildByte, (byte)67); } static void TestOpenClosedDelegate() { // This test is verifying the the fixups for open vs. closed delegate created against the same target // method are encoded correctly. Func<string, string, object> idOpen = OpenClosedDelegateExtension.OpenClosedDelegateTarget; Assert.AreEqual(idOpen("World", "foo"), "World, foo"); Func<string, object> idClosed = "World".OpenClosedDelegateTarget; Assert.AreEqual(idClosed("hey"), "World, hey"); } static void GenericLdtokenFieldsTest() { Func<FieldInfo, string> FieldFullName = (fi) => fi.FieldType + " " + fi.DeclaringType.ToString() + "::" + fi.Name; IFieldGetter getter1 = new FieldGetter<string>(); IFieldGetter getter2 = new FieldGetter<object>(); IFieldGetter getter3 = new FieldGetter<int>(); foreach (var instArg in new Type[]{typeof(String), typeof(object), typeof(int)}) { IFieldGetter getter = (IFieldGetter)Activator.CreateInstance(typeof(FieldGetter<>).MakeGenericType(instArg)); string expectedField1 = "System.Int32 Gen`1[???]::m_Field1".Replace("???", instArg.ToString()); string expectedField2 = "System.String Gen`1[???]::m_Field2".Replace("???", instArg.ToString()); string expectedField3 = "??? Gen`1[???]::m_Field3".Replace("???", instArg.ToString()); string expectedField4 = "System.Collections.Generic.List`1[???] Gen`1[???]::m_Field4".Replace("???", instArg.ToString()); string expectedField5 = "System.Collections.Generic.KeyValuePair`2[???,System.Int32] Gen`1[???]::m_Field5".Replace("???", instArg.ToString()); string expectedDllField1 = "System.String MyGeneric`2[???,???]::m_Field1".Replace("???", instArg.ToString()); string expectedDllField2 = "??? MyGeneric`2[???,???]::m_Field2".Replace("???", instArg.ToString()); string expectedDllField3 = "System.Collections.Generic.List`1[???] MyGeneric`2[???,???]::m_Field3".Replace("???", instArg.ToString()); string expectedDllField4 = "System.Collections.Generic.KeyValuePair`2[???,System.Int32] MyGeneric`2[???,???]::m_Field4".Replace("???", instArg.ToString()); string expectedDllField5 = "System.Int32 MyGeneric`2[???,???]::m_Field5".Replace("???", instArg.ToString()); Assert.AreEqual(expectedField1, FieldFullName(getter.GetGenT_Field1())); Assert.AreEqual(expectedField2, FieldFullName(getter.GetGenT_Field2())); Assert.AreEqual(expectedField3, FieldFullName(getter.GetGenT_Field3())); Assert.AreEqual(expectedField4, FieldFullName(getter.GetGenT_Field4())); Assert.AreEqual(expectedField5, FieldFullName(getter.GetGenT_Field5())); Assert.AreEqual(expectedDllField1, FieldFullName(getter.GetGenDllT_Field1())); Assert.AreEqual(expectedDllField2, FieldFullName(getter.GetGenDllT_Field2())); Assert.AreEqual(expectedDllField3, FieldFullName(getter.GetGenDllT_Field3())); Assert.AreEqual(expectedDllField4, FieldFullName(getter.GetGenDllT_Field4())); Assert.AreEqual(expectedDllField5, FieldFullName(getter.GetGenDllT_Field5())); } } static void RunAllTests() { TestVirtualMethodCalls(); TestMovedVirtualMethods(); TestConstrainedMethodCalls(); TestConstrainedMethodCalls_Unsupported(); TestInterop(); TestStaticFields(); TestPreInitializedArray(); TestMultiDimmArray(); TestGenericVirtualMethod(); TestMovedGenericVirtualMethod(); TestGenericNonVirtualMethod(); TestGenericOverStruct(); TestInstanceFields(); TestInstanceFieldsWithLayout(); TestInheritingFromGrowingBase(); TestGrowingStruct(); TestChangingStruct(); TestChangingHFAStruct(); TestGetType(); #if CORECLR TestMultipleLoads(); #endif TestFieldLayoutNGenMixAndMatch(); TestStaticBaseCSE(); TestIsInstCSE(); TestCastClassCSE(); TestRangeCheckElimination(); TestOpenClosedDelegate(); GenericLdtokenFieldsTest(); } static int Main() { // Code compiled by LLILC jit can't catch exceptions yet so the tests // don't throw them if LLILC jit is enabled. This should be removed once // exception catching is supported by LLILC jit. string AltJitName = System.Environment.GetEnvironmentVariable("complus_altjitname"); LLILCJitEnabled = ((AltJitName != null) && AltJitName.ToLower().StartsWith("llilcjit") && ((System.Environment.GetEnvironmentVariable("complus_altjit") != null) || (System.Environment.GetEnvironmentVariable("complus_altjitngen") != null))); // Run all tests 3x times to exercise both slow and fast paths work for (int i = 0; i < 3; i++) RunAllTests(); Console.WriteLine("PASSED"); return Assert.HasAssertFired ? 1 : 100; } static bool LLILCJitEnabled; static int s; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using System; using System.IO; using System.Text; using System.Xml; using System.Diagnostics; using System.Collections; using System.Globalization; using System.Collections.Generic; // OpenIssue : is it better to cache the current namespace decls for each elem // as the current code does, or should it just always walk the namespace stack? namespace System.Xml { internal partial class XmlWellFormedWriter : XmlWriter { public override Task WriteStartDocumentAsync() { return WriteStartDocumentImplAsync(XmlStandalone.Omit); } public override Task WriteStartDocumentAsync(bool standalone) { return WriteStartDocumentImplAsync(standalone ? XmlStandalone.Yes : XmlStandalone.No); } public override async Task WriteEndDocumentAsync() { try { // auto-close all elements while (_elemTop > 0) { await WriteEndElementAsync().ConfigureAwait(false); } State prevState = _currentState; await AdvanceStateAsync(Token.EndDocument).ConfigureAwait(false); if (prevState != State.AfterRootEle) { throw new ArgumentException(SR.Xml_NoRoot); } if (_rawWriter == null) { await _writer.WriteEndDocumentAsync().ConfigureAwait(false); } } catch { _currentState = State.Error; throw; } } public override async Task WriteDocTypeAsync(string name, string pubid, string sysid, string subset) { try { if (name == null || name.Length == 0) { throw new ArgumentException(SR.Xml_EmptyName); } XmlConvert.VerifyQName(name, ExceptionType.XmlException); if (_conformanceLevel == ConformanceLevel.Fragment) { throw new InvalidOperationException(SR.Xml_DtdNotAllowedInFragment); } await AdvanceStateAsync(Token.Dtd).ConfigureAwait(false); if (_dtdWritten) { _currentState = State.Error; throw new InvalidOperationException(SR.Xml_DtdAlreadyWritten); } if (_conformanceLevel == ConformanceLevel.Auto) { _conformanceLevel = ConformanceLevel.Document; _stateTable = s_stateTableDocument; } int i; // check characters if (_checkCharacters) { if (pubid != null) { if ((i = _xmlCharType.IsPublicId(pubid)) >= 0) { throw new ArgumentException(SR.Format(SR.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(pubid, i)), nameof(pubid)); } } if (sysid != null) { if ((i = _xmlCharType.IsOnlyCharData(sysid)) >= 0) { throw new ArgumentException(SR.Format(SR.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(sysid, i)), nameof(sysid)); } } if (subset != null) { if ((i = _xmlCharType.IsOnlyCharData(subset)) >= 0) { throw new ArgumentException(SR.Format(SR.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(subset, i)), nameof(subset)); } } } // write doctype await _writer.WriteDocTypeAsync(name, pubid, sysid, subset).ConfigureAwait(false); _dtdWritten = true; } catch { _currentState = State.Error; throw; } } //check if any exception before return the task private Task TryReturnTask(Task task) { if (task.IsSuccess()) { return Task.CompletedTask; } else { return _TryReturnTask(task); } } private async Task _TryReturnTask(Task task) { try { await task.ConfigureAwait(false); } catch { _currentState = State.Error; throw; } } //call nextTaskFun after task finish. Check exception. private Task SequenceRun<TArg>(Task task, Func<TArg, Task> nextTaskFun, TArg arg) { if (task.IsSuccess()) { return TryReturnTask(nextTaskFun(arg)); } else { return _SequenceRun(task, nextTaskFun, arg); } } private async Task _SequenceRun<TArg>(Task task, Func<TArg, Task> nextTaskFun, TArg arg) { try { await task.ConfigureAwait(false); await nextTaskFun(arg).ConfigureAwait(false); } catch { _currentState = State.Error; throw; } } public override Task WriteStartElementAsync(string prefix, string localName, string ns) { try { // check local name if (localName == null || localName.Length == 0) { throw new ArgumentException(SR.Xml_EmptyLocalName); } CheckNCName(localName); Task task = AdvanceStateAsync(Token.StartElement); if (task.IsSuccess()) { return WriteStartElementAsync_NoAdvanceState(prefix, localName, ns); } else { return WriteStartElementAsync_NoAdvanceState(task, prefix, localName, ns); } } catch { _currentState = State.Error; throw; } } private Task WriteStartElementAsync_NoAdvanceState(string prefix, string localName, string ns) { try { // lookup prefix / namespace if (prefix == null) { if (ns != null) { prefix = LookupPrefix(ns); } if (prefix == null) { prefix = string.Empty; } } else if (prefix.Length > 0) { CheckNCName(prefix); if (ns == null) { ns = LookupNamespace(prefix); } if (ns == null || (ns != null && ns.Length == 0)) { throw new ArgumentException(SR.Xml_PrefixForEmptyNs); } } if (ns == null) { ns = LookupNamespace(prefix); if (ns == null) { Debug.Assert(prefix.Length == 0); ns = string.Empty; } } if (_elemTop == 0 && _rawWriter != null) { // notify the underlying raw writer about the root level element _rawWriter.OnRootElement(_conformanceLevel); } // write start tag Task task = _writer.WriteStartElementAsync(prefix, localName, ns); if (task.IsSuccess()) { WriteStartElementAsync_FinishWrite(prefix, localName, ns); } else { return WriteStartElementAsync_FinishWrite(task, prefix, localName, ns); } return Task.CompletedTask; } catch { _currentState = State.Error; throw; } } private async Task WriteStartElementAsync_NoAdvanceState(Task task, string prefix, string localName, string ns) { try { await task.ConfigureAwait(false); await WriteStartElementAsync_NoAdvanceState(prefix, localName, ns).ConfigureAwait(false); } catch { _currentState = State.Error; throw; } } private void WriteStartElementAsync_FinishWrite(string prefix, string localName, string ns) { try { // push element on stack and add/check namespace int top = ++_elemTop; if (top == _elemScopeStack.Length) { ElementScope[] newStack = new ElementScope[top * 2]; Array.Copy(_elemScopeStack, newStack, top); _elemScopeStack = newStack; } _elemScopeStack[top].Set(prefix, localName, ns, _nsTop); PushNamespaceImplicit(prefix, ns); if (_attrCount >= MaxAttrDuplWalkCount) { _attrHashTable.Clear(); } _attrCount = 0; } catch { _currentState = State.Error; throw; } } private async Task WriteStartElementAsync_FinishWrite(Task t, string prefix, string localName, string ns) { try { await t.ConfigureAwait(false); WriteStartElementAsync_FinishWrite(prefix, localName, ns); } catch { _currentState = State.Error; throw; } } public override Task WriteEndElementAsync() { try { Task task = AdvanceStateAsync(Token.EndElement); return SequenceRun(task, thisRef => thisRef.WriteEndElementAsync_NoAdvanceState(), this); } catch { _currentState = State.Error; throw; } } private Task WriteEndElementAsync_NoAdvanceState() { try { int top = _elemTop; if (top == 0) { throw new XmlException(SR.Xml_NoStartTag, string.Empty); } Task task; // write end tag if (_rawWriter != null) { task = _elemScopeStack[top].WriteEndElementAsync(_rawWriter); } else { task = _writer.WriteEndElementAsync(); } return SequenceRun(task, thisRef => thisRef.WriteEndElementAsync_FinishWrite(), this); } catch { _currentState = State.Error; throw; } } private Task WriteEndElementAsync_FinishWrite() { try { int top = _elemTop; // pop namespaces int prevNsTop = _elemScopeStack[top].prevNSTop; if (_useNsHashtable && prevNsTop < _nsTop) { PopNamespaces(prevNsTop + 1, _nsTop); } _nsTop = prevNsTop; _elemTop = --top; // check "one root element" condition for ConformanceLevel.Document if (top == 0) { if (_conformanceLevel == ConformanceLevel.Document) { _currentState = State.AfterRootEle; } else { _currentState = State.TopLevel; } } } catch { _currentState = State.Error; throw; } return Task.CompletedTask; } public override Task WriteFullEndElementAsync() { try { Task task = AdvanceStateAsync(Token.EndElement); return SequenceRun(task, thisRef => thisRef.WriteFullEndElementAsync_NoAdvanceState(), this); } catch { _currentState = State.Error; throw; } } private Task WriteFullEndElementAsync_NoAdvanceState() { try { int top = _elemTop; if (top == 0) { throw new XmlException(SR.Xml_NoStartTag, string.Empty); } Task task; // write end tag if (_rawWriter != null) { task = _elemScopeStack[top].WriteFullEndElementAsync(_rawWriter); } else { task = _writer.WriteFullEndElementAsync(); } return SequenceRun(task, thisRef => thisRef.WriteEndElementAsync_FinishWrite(), this); } catch { _currentState = State.Error; throw; } } protected internal override Task WriteStartAttributeAsync(string prefix, string localName, string namespaceName) { try { // check local name if (localName == null || localName.Length == 0) { if (prefix == "xmlns") { localName = "xmlns"; prefix = string.Empty; } else { throw new ArgumentException(SR.Xml_EmptyLocalName); } } CheckNCName(localName); Task task = AdvanceStateAsync(Token.StartAttribute); if (task.IsSuccess()) { return WriteStartAttributeAsync_NoAdvanceState(prefix, localName, namespaceName); } else { return WriteStartAttributeAsync_NoAdvanceState(task, prefix, localName, namespaceName); } } catch { _currentState = State.Error; throw; } } private Task WriteStartAttributeAsync_NoAdvanceState(string prefix, string localName, string namespaceName) { try { // lookup prefix / namespace if (prefix == null) { if (namespaceName != null) { // special case prefix=null/localname=xmlns if (!(localName == "xmlns" && namespaceName == XmlReservedNs.NsXmlNs)) prefix = LookupPrefix(namespaceName); } if (prefix == null) { prefix = string.Empty; } } if (namespaceName == null) { if (prefix != null && prefix.Length > 0) { namespaceName = LookupNamespace(prefix); } if (namespaceName == null) { namespaceName = string.Empty; } } if (prefix.Length == 0) { if (localName[0] == 'x' && localName == "xmlns") { if (namespaceName.Length > 0 && namespaceName != XmlReservedNs.NsXmlNs) { throw new ArgumentException(SR.Xml_XmlnsPrefix); } _curDeclPrefix = String.Empty; SetSpecialAttribute(SpecialAttribute.DefaultXmlns); goto SkipPushAndWrite; } else if (namespaceName.Length > 0) { prefix = LookupPrefix(namespaceName); if (prefix == null || prefix.Length == 0) { prefix = GeneratePrefix(); } } } else { if (prefix[0] == 'x') { if (prefix == "xmlns") { if (namespaceName.Length > 0 && namespaceName != XmlReservedNs.NsXmlNs) { throw new ArgumentException(SR.Xml_XmlnsPrefix); } _curDeclPrefix = localName; SetSpecialAttribute(SpecialAttribute.PrefixedXmlns); goto SkipPushAndWrite; } else if (prefix == "xml") { if (namespaceName.Length > 0 && namespaceName != XmlReservedNs.NsXml) { throw new ArgumentException(SR.Xml_XmlPrefix); } switch (localName) { case "space": SetSpecialAttribute(SpecialAttribute.XmlSpace); goto SkipPushAndWrite; case "lang": SetSpecialAttribute(SpecialAttribute.XmlLang); goto SkipPushAndWrite; } } } CheckNCName(prefix); if (namespaceName.Length == 0) { // attributes cannot have default namespace prefix = string.Empty; } else { string definedNs = LookupLocalNamespace(prefix); if (definedNs != null && definedNs != namespaceName) { prefix = GeneratePrefix(); } } } if (prefix.Length != 0) { PushNamespaceImplicit(prefix, namespaceName); } SkipPushAndWrite: // add attribute to the list and check for duplicates AddAttribute(prefix, localName, namespaceName); if (_specAttr == SpecialAttribute.No) { // write attribute name return TryReturnTask(_writer.WriteStartAttributeAsync(prefix, localName, namespaceName)); } return Task.CompletedTask; } catch { _currentState = State.Error; throw; } } private async Task WriteStartAttributeAsync_NoAdvanceState(Task task, string prefix, string localName, string namespaceName) { try { await task.ConfigureAwait(false); await WriteStartAttributeAsync_NoAdvanceState(prefix, localName, namespaceName).ConfigureAwait(false); } catch { _currentState = State.Error; throw; } } protected internal override Task WriteEndAttributeAsync() { try { Task task = AdvanceStateAsync(Token.EndAttribute); return SequenceRun(task, thisRef => thisRef.WriteEndAttributeAsync_NoAdvance(), this); } catch { _currentState = State.Error; throw; } } private Task WriteEndAttributeAsync_NoAdvance() { try { if (_specAttr != SpecialAttribute.No) { return WriteEndAttributeAsync_SepcialAtt(); } else { return TryReturnTask(_writer.WriteEndAttributeAsync()); } } catch { _currentState = State.Error; throw; } } private async Task WriteEndAttributeAsync_SepcialAtt() { try { string value; switch (_specAttr) { case SpecialAttribute.DefaultXmlns: value = _attrValueCache.StringValue; if (PushNamespaceExplicit(string.Empty, value)) { // returns true if the namespace declaration should be written out if (_rawWriter != null) { if (_rawWriter.SupportsNamespaceDeclarationInChunks) { await _rawWriter.WriteStartNamespaceDeclarationAsync(string.Empty).ConfigureAwait(false); await _attrValueCache.ReplayAsync(_rawWriter).ConfigureAwait(false); await _rawWriter.WriteEndNamespaceDeclarationAsync().ConfigureAwait(false); } else { await _rawWriter.WriteNamespaceDeclarationAsync(string.Empty, value).ConfigureAwait(false); } } else { await _writer.WriteStartAttributeAsync(string.Empty, "xmlns", XmlReservedNs.NsXmlNs).ConfigureAwait(false); await _attrValueCache.ReplayAsync(_writer).ConfigureAwait(false); await _writer.WriteEndAttributeAsync().ConfigureAwait(false); } } _curDeclPrefix = null; break; case SpecialAttribute.PrefixedXmlns: value = _attrValueCache.StringValue; if (value.Length == 0) { throw new ArgumentException(SR.Xml_PrefixForEmptyNs); } if (value == XmlReservedNs.NsXmlNs || (value == XmlReservedNs.NsXml && _curDeclPrefix != "xml")) { throw new ArgumentException(SR.Xml_CanNotBindToReservedNamespace); } if (PushNamespaceExplicit(_curDeclPrefix, value)) { // returns true if the namespace declaration should be written out if (_rawWriter != null) { if (_rawWriter.SupportsNamespaceDeclarationInChunks) { await _rawWriter.WriteStartNamespaceDeclarationAsync(_curDeclPrefix).ConfigureAwait(false); await _attrValueCache.ReplayAsync(_rawWriter).ConfigureAwait(false); await _rawWriter.WriteEndNamespaceDeclarationAsync().ConfigureAwait(false); } else { await _rawWriter.WriteNamespaceDeclarationAsync(_curDeclPrefix, value).ConfigureAwait(false); } } else { await _writer.WriteStartAttributeAsync("xmlns", _curDeclPrefix, XmlReservedNs.NsXmlNs).ConfigureAwait(false); await _attrValueCache.ReplayAsync(_writer).ConfigureAwait(false); await _writer.WriteEndAttributeAsync().ConfigureAwait(false); } } _curDeclPrefix = null; break; case SpecialAttribute.XmlSpace: _attrValueCache.Trim(); value = _attrValueCache.StringValue; if (value == "default") { _elemScopeStack[_elemTop].xmlSpace = XmlSpace.Default; } else if (value == "preserve") { _elemScopeStack[_elemTop].xmlSpace = XmlSpace.Preserve; } else { throw new ArgumentException(SR.Format(SR.Xml_InvalidXmlSpace, value)); } await _writer.WriteStartAttributeAsync("xml", "space", XmlReservedNs.NsXml).ConfigureAwait(false); await _attrValueCache.ReplayAsync(_writer).ConfigureAwait(false); await _writer.WriteEndAttributeAsync().ConfigureAwait(false); break; case SpecialAttribute.XmlLang: value = _attrValueCache.StringValue; _elemScopeStack[_elemTop].xmlLang = value; await _writer.WriteStartAttributeAsync("xml", "lang", XmlReservedNs.NsXml).ConfigureAwait(false); await _attrValueCache.ReplayAsync(_writer).ConfigureAwait(false); await _writer.WriteEndAttributeAsync().ConfigureAwait(false); break; } _specAttr = SpecialAttribute.No; _attrValueCache.Clear(); } catch { _currentState = State.Error; throw; } } public override async Task WriteCDataAsync(string text) { try { if (text == null) { text = string.Empty; } await AdvanceStateAsync(Token.CData).ConfigureAwait(false); await _writer.WriteCDataAsync(text).ConfigureAwait(false); } catch { _currentState = State.Error; throw; } } public override async Task WriteCommentAsync(string text) { try { if (text == null) { text = string.Empty; } await AdvanceStateAsync(Token.Comment).ConfigureAwait(false); await _writer.WriteCommentAsync(text).ConfigureAwait(false); } catch { _currentState = State.Error; throw; } } public override async Task WriteProcessingInstructionAsync(string name, string text) { try { // check name if (name == null || name.Length == 0) { throw new ArgumentException(SR.Xml_EmptyName); } CheckNCName(name); // check text if (text == null) { text = string.Empty; } // xml declaration is a special case (not a processing instruction, but we allow WriteProcessingInstruction as a convenience) if (name.Length == 3 && string.Equals(name, "xml", StringComparison.OrdinalIgnoreCase)) { if (_currentState != State.Start) { throw new ArgumentException(_conformanceLevel == ConformanceLevel.Document ? SR.Xml_DupXmlDecl : SR.Xml_CannotWriteXmlDecl); } _xmlDeclFollows = true; await AdvanceStateAsync(Token.PI).ConfigureAwait(false); if (_rawWriter != null) { // Translate PI into an xml declaration await _rawWriter.WriteXmlDeclarationAsync(text).ConfigureAwait(false); } else { await _writer.WriteProcessingInstructionAsync(name, text).ConfigureAwait(false); } } else { await AdvanceStateAsync(Token.PI).ConfigureAwait(false); await _writer.WriteProcessingInstructionAsync(name, text).ConfigureAwait(false); } } catch { _currentState = State.Error; throw; } } public override async Task WriteEntityRefAsync(string name) { try { // check name if (name == null || name.Length == 0) { throw new ArgumentException(SR.Xml_EmptyName); } CheckNCName(name); await AdvanceStateAsync(Token.Text).ConfigureAwait(false); if (SaveAttrValue) { _attrValueCache.WriteEntityRef(name); } else { await _writer.WriteEntityRefAsync(name).ConfigureAwait(false); } } catch { _currentState = State.Error; throw; } } public override async Task WriteCharEntityAsync(char ch) { try { if (Char.IsSurrogate(ch)) { throw new ArgumentException(SR.Xml_InvalidSurrogateMissingLowChar); } await AdvanceStateAsync(Token.Text).ConfigureAwait(false); if (SaveAttrValue) { _attrValueCache.WriteCharEntity(ch); } else { await _writer.WriteCharEntityAsync(ch).ConfigureAwait(false); } } catch { _currentState = State.Error; throw; } } public override async Task WriteSurrogateCharEntityAsync(char lowChar, char highChar) { try { if (!Char.IsSurrogatePair(highChar, lowChar)) { throw XmlConvert.CreateInvalidSurrogatePairException(lowChar, highChar); } await AdvanceStateAsync(Token.Text).ConfigureAwait(false); if (SaveAttrValue) { _attrValueCache.WriteSurrogateCharEntity(lowChar, highChar); } else { await _writer.WriteSurrogateCharEntityAsync(lowChar, highChar).ConfigureAwait(false); } } catch { _currentState = State.Error; throw; } } public override async Task WriteWhitespaceAsync(string ws) { try { if (ws == null) { ws = string.Empty; } if (!XmlCharType.Instance.IsOnlyWhitespace(ws)) { throw new ArgumentException(SR.Xml_NonWhitespace); } await AdvanceStateAsync(Token.Whitespace).ConfigureAwait(false); if (SaveAttrValue) { _attrValueCache.WriteWhitespace(ws); } else { await _writer.WriteWhitespaceAsync(ws).ConfigureAwait(false); } } catch { _currentState = State.Error; throw; } } public override Task WriteStringAsync(string text) { try { if (text == null) { return Task.CompletedTask; } Task task = AdvanceStateAsync(Token.Text); if (task.IsSuccess()) { return WriteStringAsync_NoAdvanceState(text); } else { return WriteStringAsync_NoAdvanceState(task, text); } } catch { _currentState = State.Error; throw; } } private Task WriteStringAsync_NoAdvanceState(string text) { try { if (SaveAttrValue) { _attrValueCache.WriteString(text); return Task.CompletedTask; } else { return TryReturnTask(_writer.WriteStringAsync(text)); } } catch { _currentState = State.Error; throw; } } private async Task WriteStringAsync_NoAdvanceState(Task task, string text) { try { await task.ConfigureAwait(false); await WriteStringAsync_NoAdvanceState(text).ConfigureAwait(false); } catch { _currentState = State.Error; throw; } } public override async Task WriteCharsAsync(char[] buffer, int index, int count) { try { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (count > buffer.Length - index) { throw new ArgumentOutOfRangeException(nameof(count)); } await AdvanceStateAsync(Token.Text).ConfigureAwait(false); if (SaveAttrValue) { _attrValueCache.WriteChars(buffer, index, count); } else { await _writer.WriteCharsAsync(buffer, index, count).ConfigureAwait(false); } } catch { _currentState = State.Error; throw; } } public override async Task WriteRawAsync(char[] buffer, int index, int count) { try { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (count > buffer.Length - index) { throw new ArgumentOutOfRangeException(nameof(count)); } await AdvanceStateAsync(Token.RawData).ConfigureAwait(false); if (SaveAttrValue) { _attrValueCache.WriteRaw(buffer, index, count); } else { await _writer.WriteRawAsync(buffer, index, count).ConfigureAwait(false); } } catch { _currentState = State.Error; throw; } } public override async Task WriteRawAsync(string data) { try { if (data == null) { return; } await AdvanceStateAsync(Token.RawData).ConfigureAwait(false); if (SaveAttrValue) { _attrValueCache.WriteRaw(data); } else { await _writer.WriteRawAsync(data).ConfigureAwait(false); } } catch { _currentState = State.Error; throw; } } public override Task WriteBase64Async(byte[] buffer, int index, int count) { try { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (count > buffer.Length - index) { throw new ArgumentOutOfRangeException(nameof(count)); } Task task = AdvanceStateAsync(Token.Base64); if (task.IsSuccess()) { return TryReturnTask(_writer.WriteBase64Async(buffer, index, count)); } else { return WriteBase64Async_NoAdvanceState(task, buffer, index, count); } } catch { _currentState = State.Error; throw; } } private async Task WriteBase64Async_NoAdvanceState(Task task, byte[] buffer, int index, int count) { try { await task.ConfigureAwait(false); await _writer.WriteBase64Async(buffer, index, count).ConfigureAwait(false); } catch { _currentState = State.Error; throw; } } public override async Task FlushAsync() { try { await _writer.FlushAsync().ConfigureAwait(false); } catch { _currentState = State.Error; throw; } } public override async Task WriteQualifiedNameAsync(string localName, string ns) { try { if (localName == null || localName.Length == 0) { throw new ArgumentException(SR.Xml_EmptyLocalName); } CheckNCName(localName); await AdvanceStateAsync(Token.Text).ConfigureAwait(false); string prefix = String.Empty; if (ns != null && ns.Length != 0) { prefix = LookupPrefix(ns); if (prefix == null) { if (_currentState != State.Attribute) { throw new ArgumentException(SR.Format(SR.Xml_UndefNamespace, ns)); } prefix = GeneratePrefix(); PushNamespaceImplicit(prefix, ns); } } // if this is a special attribute, then just convert this to text // otherwise delegate to raw-writer if (SaveAttrValue || _rawWriter == null) { if (prefix.Length != 0) { await WriteStringAsync(prefix).ConfigureAwait(false); await WriteStringAsync(":").ConfigureAwait(false); } await WriteStringAsync(localName).ConfigureAwait(false); } else { await _rawWriter.WriteQualifiedNameAsync(prefix, localName, ns).ConfigureAwait(false); } } catch { _currentState = State.Error; throw; } } public override async Task WriteBinHexAsync(byte[] buffer, int index, int count) { if (IsClosedOrErrorState) { throw new InvalidOperationException(SR.Xml_ClosedOrError); } try { await AdvanceStateAsync(Token.Text).ConfigureAwait(false); await base.WriteBinHexAsync(buffer, index, count).ConfigureAwait(false); } catch { _currentState = State.Error; throw; } } private async Task WriteStartDocumentImplAsync(XmlStandalone standalone) { try { await AdvanceStateAsync(Token.StartDocument).ConfigureAwait(false); if (_conformanceLevel == ConformanceLevel.Auto) { _conformanceLevel = ConformanceLevel.Document; _stateTable = s_stateTableDocument; } else if (_conformanceLevel == ConformanceLevel.Fragment) { throw new InvalidOperationException(SR.Xml_CannotStartDocumentOnFragment); } if (_rawWriter != null) { if (!_xmlDeclFollows) { await _rawWriter.WriteXmlDeclarationAsync(standalone).ConfigureAwait(false); } } else { // We do not pass the standalone value here await _writer.WriteStartDocumentAsync().ConfigureAwait(false); } } catch { _currentState = State.Error; throw; } } //call taskFun and change state in sequence private Task AdvanceStateAsync_ReturnWhenFinish(Task task, State newState) { if (task.IsSuccess()) { _currentState = newState; return Task.CompletedTask; } else { return _AdvanceStateAsync_ReturnWhenFinish(task, newState); } } private async Task _AdvanceStateAsync_ReturnWhenFinish(Task task, State newState) { await task.ConfigureAwait(false); _currentState = newState; } private Task AdvanceStateAsync_ContinueWhenFinish(Task task, State newState, Token token) { if (task.IsSuccess()) { _currentState = newState; return AdvanceStateAsync(token); } else { return _AdvanceStateAsync_ContinueWhenFinish(task, newState, token); } } private async Task _AdvanceStateAsync_ContinueWhenFinish(Task task, State newState, Token token) { await task.ConfigureAwait(false); _currentState = newState; await AdvanceStateAsync(token).ConfigureAwait(false); } // Advance the state machine private Task AdvanceStateAsync(Token token) { if ((int)_currentState >= (int)State.Closed) { if (_currentState == State.Closed || _currentState == State.Error) { throw new InvalidOperationException(SR.Xml_ClosedOrError); } else { throw new InvalidOperationException(SR.Format(SR.Xml_WrongToken, tokenName[(int)token], GetStateName(_currentState))); } } Advance: State newState = _stateTable[((int)token << 4) + (int)_currentState]; // [ (int)token * 16 + (int)currentState ]; Task task; if ((int)newState >= (int)State.Error) { switch (newState) { case State.Error: ThrowInvalidStateTransition(token, _currentState); break; case State.StartContent: return AdvanceStateAsync_ReturnWhenFinish(StartElementContentAsync(), State.Content); case State.StartContentEle: return AdvanceStateAsync_ReturnWhenFinish(StartElementContentAsync(), State.Element); case State.StartContentB64: return AdvanceStateAsync_ReturnWhenFinish(StartElementContentAsync(), State.B64Content); case State.StartDoc: return AdvanceStateAsync_ReturnWhenFinish(WriteStartDocumentAsync(), State.Document); case State.StartDocEle: return AdvanceStateAsync_ReturnWhenFinish(WriteStartDocumentAsync(), State.Element); case State.EndAttrSEle: task = SequenceRun(WriteEndAttributeAsync(), thisRef => thisRef.StartElementContentAsync(), this); return AdvanceStateAsync_ReturnWhenFinish(task, State.Element); case State.EndAttrEEle: task = SequenceRun(WriteEndAttributeAsync(), thisRef => thisRef.StartElementContentAsync(), this); return AdvanceStateAsync_ReturnWhenFinish(task, State.Content); case State.EndAttrSCont: task = SequenceRun(WriteEndAttributeAsync(), thisRef => thisRef.StartElementContentAsync(), this); return AdvanceStateAsync_ReturnWhenFinish(task, State.Content); case State.EndAttrSAttr: return AdvanceStateAsync_ReturnWhenFinish(WriteEndAttributeAsync(), State.Attribute); case State.PostB64Cont: if (_rawWriter != null) { return AdvanceStateAsync_ContinueWhenFinish(_rawWriter.WriteEndBase64Async(), State.Content, token); } _currentState = State.Content; goto Advance; case State.PostB64Attr: if (_rawWriter != null) { return AdvanceStateAsync_ContinueWhenFinish(_rawWriter.WriteEndBase64Async(), State.Attribute, token); } _currentState = State.Attribute; goto Advance; case State.PostB64RootAttr: if (_rawWriter != null) { return AdvanceStateAsync_ContinueWhenFinish(_rawWriter.WriteEndBase64Async(), State.RootLevelAttr, token); } _currentState = State.RootLevelAttr; goto Advance; case State.StartFragEle: StartFragment(); newState = State.Element; break; case State.StartFragCont: StartFragment(); newState = State.Content; break; case State.StartFragB64: StartFragment(); newState = State.B64Content; break; case State.StartRootLevelAttr: return AdvanceStateAsync_ReturnWhenFinish(WriteEndAttributeAsync(), State.RootLevelAttr); default: Debug.Assert(false, "We should not get to this point."); break; } } _currentState = newState; return Task.CompletedTask; } // write namespace declarations private async Task StartElementContentAsync_WithNS() { int start = _elemScopeStack[_elemTop].prevNSTop; for (int i = _nsTop; i > start; i--) { if (_nsStack[i].kind == NamespaceKind.NeedToWrite) { await _nsStack[i].WriteDeclAsync(_writer, _rawWriter).ConfigureAwait(false); } } if (_rawWriter != null) { _rawWriter.StartElementContent(); } } private Task StartElementContentAsync() { if (_nsTop > _elemScopeStack[_elemTop].prevNSTop) { return StartElementContentAsync_WithNS(); } if (_rawWriter != null) { _rawWriter.StartElementContent(); } return Task.CompletedTask; } } }
// 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.Network { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Network Client /// </summary> public partial interface INetworkManagementClient : System.IDisposable { /// <summary> /// The base URI of the service. /// </summary> System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> JsonSerializerSettings SerializationSettings { get; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> JsonSerializerSettings DeserializationSettings { get; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> ServiceClientCredentials Credentials { get; } /// <summary> /// The subscription credentials which uniquely identify the Microsoft /// Azure subscription. The subscription ID forms part of the URI for /// every service call. /// </summary> string SubscriptionId { get; set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running /// Operations. Default value is 30. /// </summary> int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated /// and included in each request. Default is true. /// </summary> bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IApplicationGatewaysOperations. /// </summary> IApplicationGatewaysOperations ApplicationGateways { get; } /// <summary> /// Gets the IAvailableEndpointServicesOperations. /// </summary> IAvailableEndpointServicesOperations AvailableEndpointServices { get; } /// <summary> /// Gets the IExpressRouteCircuitAuthorizationsOperations. /// </summary> IExpressRouteCircuitAuthorizationsOperations ExpressRouteCircuitAuthorizations { get; } /// <summary> /// Gets the IExpressRouteCircuitPeeringsOperations. /// </summary> IExpressRouteCircuitPeeringsOperations ExpressRouteCircuitPeerings { get; } /// <summary> /// Gets the IExpressRouteCircuitsOperations. /// </summary> IExpressRouteCircuitsOperations ExpressRouteCircuits { get; } /// <summary> /// Gets the IExpressRouteServiceProvidersOperations. /// </summary> IExpressRouteServiceProvidersOperations ExpressRouteServiceProviders { get; } /// <summary> /// Gets the ILoadBalancersOperations. /// </summary> ILoadBalancersOperations LoadBalancers { get; } /// <summary> /// Gets the ILoadBalancerBackendAddressPoolsOperations. /// </summary> ILoadBalancerBackendAddressPoolsOperations LoadBalancerBackendAddressPools { get; } /// <summary> /// Gets the ILoadBalancerFrontendIPConfigurationsOperations. /// </summary> ILoadBalancerFrontendIPConfigurationsOperations LoadBalancerFrontendIPConfigurations { get; } /// <summary> /// Gets the IInboundNatRulesOperations. /// </summary> IInboundNatRulesOperations InboundNatRules { get; } /// <summary> /// Gets the ILoadBalancerLoadBalancingRulesOperations. /// </summary> ILoadBalancerLoadBalancingRulesOperations LoadBalancerLoadBalancingRules { get; } /// <summary> /// Gets the ILoadBalancerNetworkInterfacesOperations. /// </summary> ILoadBalancerNetworkInterfacesOperations LoadBalancerNetworkInterfaces { get; } /// <summary> /// Gets the ILoadBalancerProbesOperations. /// </summary> ILoadBalancerProbesOperations LoadBalancerProbes { get; } /// <summary> /// Gets the INetworkInterfacesOperations. /// </summary> INetworkInterfacesOperations NetworkInterfaces { get; } /// <summary> /// Gets the INetworkInterfaceIPConfigurationsOperations. /// </summary> INetworkInterfaceIPConfigurationsOperations NetworkInterfaceIPConfigurations { get; } /// <summary> /// Gets the INetworkInterfaceLoadBalancersOperations. /// </summary> INetworkInterfaceLoadBalancersOperations NetworkInterfaceLoadBalancers { get; } /// <summary> /// Gets the INetworkSecurityGroupsOperations. /// </summary> INetworkSecurityGroupsOperations NetworkSecurityGroups { get; } /// <summary> /// Gets the ISecurityRulesOperations. /// </summary> ISecurityRulesOperations SecurityRules { get; } /// <summary> /// Gets the IDefaultSecurityRulesOperations. /// </summary> IDefaultSecurityRulesOperations DefaultSecurityRules { get; } /// <summary> /// Gets the INetworkWatchersOperations. /// </summary> INetworkWatchersOperations NetworkWatchers { get; } /// <summary> /// Gets the IPacketCapturesOperations. /// </summary> IPacketCapturesOperations PacketCaptures { get; } /// <summary> /// Gets the IPublicIPAddressesOperations. /// </summary> IPublicIPAddressesOperations PublicIPAddresses { get; } /// <summary> /// Gets the IRouteFiltersOperations. /// </summary> IRouteFiltersOperations RouteFilters { get; } /// <summary> /// Gets the IRouteFilterRulesOperations. /// </summary> IRouteFilterRulesOperations RouteFilterRules { get; } /// <summary> /// Gets the IRouteTablesOperations. /// </summary> IRouteTablesOperations RouteTables { get; } /// <summary> /// Gets the IRoutesOperations. /// </summary> IRoutesOperations Routes { get; } /// <summary> /// Gets the IBgpServiceCommunitiesOperations. /// </summary> IBgpServiceCommunitiesOperations BgpServiceCommunities { get; } /// <summary> /// Gets the IUsagesOperations. /// </summary> IUsagesOperations Usages { get; } /// <summary> /// Gets the IVirtualNetworksOperations. /// </summary> IVirtualNetworksOperations VirtualNetworks { get; } /// <summary> /// Gets the ISubnetsOperations. /// </summary> ISubnetsOperations Subnets { get; } /// <summary> /// Gets the IVirtualNetworkPeeringsOperations. /// </summary> IVirtualNetworkPeeringsOperations VirtualNetworkPeerings { get; } /// <summary> /// Gets the IVirtualNetworkGatewaysOperations. /// </summary> IVirtualNetworkGatewaysOperations VirtualNetworkGateways { get; } /// <summary> /// Gets the IVirtualNetworkGatewayConnectionsOperations. /// </summary> IVirtualNetworkGatewayConnectionsOperations VirtualNetworkGatewayConnections { get; } /// <summary> /// Gets the ILocalNetworkGatewaysOperations. /// </summary> ILocalNetworkGatewaysOperations LocalNetworkGateways { get; } /// <summary> /// Checks whether a domain name in the cloudapp.net zone is available /// for use. /// </summary> /// <param name='location'> /// The location of the domain name. /// </param> /// <param name='domainNameLabel'> /// The domain name to be verified. It must conform to the following /// regular expression: ^[a-z][a-z0-9-]{1,61}[a-z0-9]$. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<DnsNameAvailabilityResult>> CheckDnsNameAvailabilityWithHttpMessagesAsync(string location, string domainNameLabel = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
/* * 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 System; using System.Diagnostics; using FarseerPhysics.Common; using Microsoft.Xna.Framework; namespace FarseerPhysics.Dynamics.Joints { // 1-D rained system // m (v2 - v1) = lambda // v2 + (beta/h) * x1 + gamma * lambda = 0, gamma has units of inverse mass. // x2 = x1 + h * v2 // 1-D mass-damper-spring system // m (v2 - v1) + h * d * v2 + h * k * // C = norm(p2 - p1) - L // u = (p2 - p1) / norm(p2 - p1) // Cdot = dot(u, v2 + cross(w2, r2) - v1 - cross(w1, r1)) // J = [-u -cross(r1, u) u cross(r2, u)] // K = J * invM * JT // = invMass1 + invI1 * cross(r1, u)^2 + invMass2 + invI2 * cross(r2, u)^2 /// <summary> /// A distance joint rains two points on two bodies /// to remain at a fixed distance from each other. You can view /// this as a massless, rigid rod. /// </summary> public class DistanceJoint : Joint { private float _bias; private float _gamma; private float _impulse; private float _mass; private float _tmpFloat1; private Vector2 _tmpVector1; private Vector2 _u; /// <summary> /// This requires defining an /// anchor point on both bodies and the non-zero length of the /// distance joint. If you don't supply a length, the local anchor points /// is used so that the initial configuration can violate the constraint /// slightly. This helps when saving and loading a game. /// @warning Do not use a zero or short length. /// </summary> /// <param name="bodyA">The first body</param> /// <param name="bodyB">The second body</param> /// <param name="anchorA">The first body anchor</param> /// <param name="anchorB">The second body anchor</param> public DistanceJoint(Body bodyA, Body bodyB, Vector2 anchorA, Vector2 anchorB) : base(bodyA, bodyB) { JointType = JointType.Distance; LocalAnchorA = anchorA; LocalAnchorB = anchorB; Vector2 d = WorldAnchorB - WorldAnchorA; Length = d.Length(); } /// <summary> /// The natural length between the anchor points. /// Manipulating the length can lead to non-physical behavior when the frequency is zero. /// </summary> public float Length { get; set; } /// <summary> /// The mass-spring-damper frequency in Hertz. /// </summary> public float Frequency { get; set; } /// <summary> /// The damping ratio. 0 = no damping, 1 = critical damping. /// </summary> public float DampingRatio { get; set; } public override sealed Vector2 WorldAnchorA { get { return BodyA.GetWorldPoint(LocalAnchorA); } } public override sealed Vector2 WorldAnchorB { get { return BodyB.GetWorldPoint(LocalAnchorB); } } /// <summary> /// The local anchor point relative to bodyA's origin. /// </summary> public Vector2 LocalAnchorA { get; set; } /// <summary> /// The local anchor point relative to bodyB's origin. /// </summary> public Vector2 LocalAnchorB { get; set; } public override Vector2 GetReactionForce(float inv_dt) { Vector2 F = (inv_dt * _impulse) * _u; return F; } public override float GetReactionTorque(float inv_dt) { return 0.0f; } internal override void InitVelocityConstraints(ref TimeStep step) { Body b1 = BodyA; Body b2 = BodyB; // Compute the effective mass matrix. Vector2 r1 = MathUtils.Multiply(ref b1.Xf.R, LocalAnchorA - b1.LocalCenter); Vector2 r2 = MathUtils.Multiply(ref b2.Xf.R, LocalAnchorB - b2.LocalCenter); _u = b2.Sweep.C + r2 - b1.Sweep.C - r1; // Handle singularity. float length = _u.Length(); if (length > Settings.LinearSlop) { _u *= 1.0f / length; } else { _u = Vector2.Zero; } float cr1u, cr2u; MathUtils.Cross(ref r1, ref _u, out cr1u); MathUtils.Cross(ref r2, ref _u, out cr2u); float invMass = b1.InvMass + b1.InvI * cr1u * cr1u + b2.InvMass + b2.InvI * cr2u * cr2u; Debug.Assert(invMass > Settings.Epsilon); _mass = invMass != 0.0f ? 1.0f / invMass : 0.0f; if (Frequency > 0.0f) { float C = length - Length; // Frequency float omega = 2.0f * Settings.Pi * Frequency; // Damping coefficient float d = 2.0f * _mass * DampingRatio * omega; // Spring stiffness float k = _mass * omega * omega; // magic formulas _gamma = step.dt * (d + step.dt * k); _gamma = _gamma != 0.0f ? 1.0f / _gamma : 0.0f; _bias = C * step.dt * k * _gamma; _mass = invMass + _gamma; _mass = _mass != 0.0f ? 1.0f / _mass : 0.0f; } if (Settings.EnableWarmstarting) { // Scale the impulse to support a variable time step. _impulse *= step.dtRatio; Vector2 P = _impulse * _u; b1.LinearVelocityInternal -= b1.InvMass * P; MathUtils.Cross(ref r1, ref P, out _tmpFloat1); b1.AngularVelocityInternal -= b1.InvI * /* r1 x P */ _tmpFloat1; b2.LinearVelocityInternal += b2.InvMass * P; MathUtils.Cross(ref r2, ref P, out _tmpFloat1); b2.AngularVelocityInternal += b2.InvI * /* r2 x P */ _tmpFloat1; } else { _impulse = 0.0f; } } internal override void SolveVelocityConstraints(ref TimeStep step) { Body b1 = BodyA; Body b2 = BodyB; Transform xf1, xf2; b1.GetTransform(out xf1); b2.GetTransform(out xf2); Vector2 r1 = MathUtils.Multiply(ref xf1.R, LocalAnchorA - b1.LocalCenter); Vector2 r2 = MathUtils.Multiply(ref xf2.R, LocalAnchorB - b2.LocalCenter); // Cdot = dot(u, v + cross(w, r)) MathUtils.Cross(b1.AngularVelocityInternal, ref r1, out _tmpVector1); Vector2 v1 = b1.LinearVelocityInternal + _tmpVector1; MathUtils.Cross(b2.AngularVelocityInternal, ref r2, out _tmpVector1); Vector2 v2 = b2.LinearVelocityInternal + _tmpVector1; float Cdot = Vector2.Dot(_u, v2 - v1); float impulse = -_mass * (Cdot + _bias + _gamma * _impulse); _impulse += impulse; Vector2 P = impulse * _u; b1.LinearVelocityInternal -= b1.InvMass * P; MathUtils.Cross(ref r1, ref P, out _tmpFloat1); b1.AngularVelocityInternal -= b1.InvI * _tmpFloat1; b2.LinearVelocityInternal += b2.InvMass * P; MathUtils.Cross(ref r2, ref P, out _tmpFloat1); b2.AngularVelocityInternal += b2.InvI * _tmpFloat1; } internal override bool SolvePositionConstraints() { if (Frequency > 0.0f) { // There is no position correction for soft distance constraints. return true; } Body b1 = BodyA; Body b2 = BodyB; Transform xf1, xf2; b1.GetTransform(out xf1); b2.GetTransform(out xf2); Vector2 r1 = MathUtils.Multiply(ref xf1.R, LocalAnchorA - b1.LocalCenter); Vector2 r2 = MathUtils.Multiply(ref xf2.R, LocalAnchorB - b2.LocalCenter); Vector2 d = b2.Sweep.C + r2 - b1.Sweep.C - r1; float length = d.Length(); if (length == 0.0f) return true; d /= length; float C = length - Length; C = MathUtils.Clamp(C, -Settings.MaxLinearCorrection, Settings.MaxLinearCorrection); float impulse = -_mass * C; _u = d; Vector2 P = impulse * _u; b1.Sweep.C -= b1.InvMass * P; MathUtils.Cross(ref r1, ref P, out _tmpFloat1); b1.Sweep.A -= b1.InvI * _tmpFloat1; b2.Sweep.C += b2.InvMass * P; MathUtils.Cross(ref r2, ref P, out _tmpFloat1); b2.Sweep.A += b2.InvI * _tmpFloat1; b1.SynchronizeTransform(); b2.SynchronizeTransform(); return Math.Abs(C) < Settings.LinearSlop; } } }
/* * Copyright 2009 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using ZXing.Common; namespace ZXing.PDF417.Internal { /// <summary> /// <p>Encapsulates logic that can detect a PDF417 Code in an image, even if the /// PDF417 Code is rotated or skewed, or partially obscured.</p> /// /// <author>SITA Lab (kevin.osullivan@sita.aero)</author> /// <author>dswitkin@google.com (Daniel Switkin)</author> /// <author> Guenther Grau</author> /// </summary> public sealed class Detector { private static readonly int[] INDEXES_START_PATTERN = { 0, 4, 1, 5 }; private static readonly int[] INDEXES_STOP_PATTERN = { 6, 2, 7, 3 }; private const int INTEGER_MATH_SHIFT = 8; private const int PATTERN_MATCH_RESULT_SCALE_FACTOR = 1 << INTEGER_MATH_SHIFT; private const int MAX_AVG_VARIANCE = (int)(PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.42f); private const int MAX_INDIVIDUAL_VARIANCE = (int)(PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.8f); /// <summary> /// B S B S B S B S Bar/Space pattern /// 11111111 0 1 0 1 0 1 000. /// </summary> private static readonly int[] START_PATTERN = { 8, 1, 1, 1, 1, 1, 1, 3 }; /// <summary> /// 1111111 0 1 000 1 0 1 00 1 /// </summary> private static readonly int[] STOP_PATTERN = { 7, 1, 1, 3, 1, 1, 1, 2, 1 }; private const int MAX_PIXEL_DRIFT = 3; private const int MAX_PATTERN_DRIFT = 5; /// <summary> /// if we set the value too low, then we don't detect the correct height of the bar if the start patterns are damaged. /// if we set the value too high, then we might detect the start pattern from a neighbor barcode. /// </summary> private const int SKIPPED_ROW_COUNT_MAX = 25; /// <summary> /// A PDF471 barcode should have at least 3 rows, with each row being >= 3 times the module width. Therefore it should be at least /// 9 pixels tall. To be conservative, we use about half the size to ensure we don't miss it. /// </summary> private const int ROW_STEP = 5; private const int BARCODE_MIN_HEIGHT = 10; /// <summary> /// <p>Detects a PDF417 Code in an image. Checks 0, 90, 180, and 270 degree rotations.</p> /// </summary> /// <param name="image">barcode image to decode</param> /// <param name="hints">optional hints to detector</param> /// <param name="multiple">if true, then the image is searched for multiple codes. If false, then at most one code will be found and returned</param> /// <returns> /// <see cref="PDF417DetectorResult"/> encapsulating results of detecting a PDF417 code /// </returns> public static PDF417DetectorResult detect(BinaryBitmap image, IDictionary<DecodeHintType, object> hints, bool multiple) { // TODO detection improvement, tryHarder could try several different luminance thresholds/blackpoints or even // different binarizers (SF: or different Skipped Row Counts/Steps?) //boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER); BitMatrix bitMatrix = image.BlackMatrix; if (bitMatrix == null) return null; List<ResultPoint[]> barcodeCoordinates = detect(multiple, bitMatrix); // Try 180, 270, 90 degree rotations, in that order if (barcodeCoordinates.Count == 0) { bitMatrix = (BitMatrix)bitMatrix.Clone(); for (int rotate = 0; barcodeCoordinates.Count == 0 && rotate < 3; rotate++) { if (rotate != 1) { bitMatrix.rotate180(); } else { bitMatrix.rotate90(); } barcodeCoordinates = detect(multiple, bitMatrix); } } return new PDF417DetectorResult(bitMatrix, barcodeCoordinates); } /// <summary> /// Detects PDF417 codes in an image. Only checks 0 degree rotation (so rotate the matrix and check again outside of this method) /// </summary> /// <param name="multiple">multiple if true, then the image is searched for multiple codes. If false, then at most one code will be found and returned.</param> /// <param name="bitMatrix">bit matrix to detect barcodes in.</param> /// <returns>List of ResultPoint arrays containing the coordinates of found barcodes</returns> private static List<ResultPoint[]> detect(bool multiple, BitMatrix bitMatrix) { List<ResultPoint[]> barcodeCoordinates = new List<ResultPoint[]>(); int row = 0; int column = 0; bool foundBarcodeInRow = false; while (row < bitMatrix.Height) { ResultPoint[] vertices = findVertices(bitMatrix, row, column); if (vertices[0] == null && vertices[3] == null) { if (!foundBarcodeInRow) { // we didn't find any barcode so that's the end of searching break; } // we didn't find a barcode starting at the given column and row. Try again from the first column and slightly // below the lowest barcode we found so far. foundBarcodeInRow = false; column = 0; foreach (ResultPoint[] barcodeCoordinate in barcodeCoordinates) { if (barcodeCoordinate[1] != null) { row = (int)Math.Max(row, barcodeCoordinate[1].Y); } if (barcodeCoordinate[3] != null) { row = Math.Max(row, (int)barcodeCoordinate[3].Y); } } row += ROW_STEP; continue; } foundBarcodeInRow = true; barcodeCoordinates.Add(vertices); if (!multiple) { break; } // if we didn't find a right row indicator column, then continue the search for the next barcode after the // start pattern of the barcode just found. if (vertices[2] != null) { column = (int)vertices[2].X; row = (int)vertices[2].Y; } else { column = (int)vertices[4].X; row = (int)vertices[4].Y; } } return barcodeCoordinates; } /// <summary> /// Locate the vertices and the codewords area of a black blob using the Start and Stop patterns as locators. /// </summary> /// <param name="matrix">Matrix.</param> /// <param name="startRow">Start row.</param> /// <param name="startColumn">Start column.</param> /// <returns> an array containing the vertices: /// vertices[0] x, y top left barcode /// vertices[1] x, y bottom left barcode /// vertices[2] x, y top right barcode /// vertices[3] x, y bottom right barcode /// vertices[4] x, y top left codeword area /// vertices[5] x, y bottom left codeword area /// vertices[6] x, y top right codeword area /// vertices[7] x, y bottom right codeword area /// </returns> private static ResultPoint[] findVertices(BitMatrix matrix, int startRow, int startColumn) { int height = matrix.Height; int width = matrix.Width; ResultPoint[] result = new ResultPoint[8]; copyToResult(result, findRowsWithPattern(matrix, height, width, startRow, startColumn, START_PATTERN), INDEXES_START_PATTERN); if (result[4] != null) { startColumn = (int)result[4].X; startRow = (int)result[4].Y; } copyToResult(result, findRowsWithPattern(matrix, height, width, startRow, startColumn, STOP_PATTERN), INDEXES_STOP_PATTERN); return result; } /// <summary> /// Copies the temp data to the final result /// </summary> /// <param name="result">Result.</param> /// <param name="tmpResult">Temp result.</param> /// <param name="destinationIndexes">Destination indexes.</param> private static void copyToResult(ResultPoint[] result, ResultPoint[] tmpResult, int[] destinationIndexes) { for (int i = 0; i < destinationIndexes.Length; i++) { result[destinationIndexes[i]] = tmpResult[i]; } } /// <summary> /// Finds the rows with the given pattern. /// </summary> /// <returns>The rows with pattern.</returns> /// <param name="matrix">Matrix.</param> /// <param name="height">Height.</param> /// <param name="width">Width.</param> /// <param name="startRow">Start row.</param> /// <param name="startColumn">Start column.</param> /// <param name="pattern">Pattern.</param> private static ResultPoint[] findRowsWithPattern( BitMatrix matrix, int height, int width, int startRow, int startColumn, int[] pattern) { ResultPoint[] result = new ResultPoint[4]; bool found = false; int[] counters = new int[pattern.Length]; for (; startRow < height; startRow += ROW_STEP) { int[] loc = findGuardPattern(matrix, startColumn, startRow, width, pattern, counters); if (loc != null) { while (startRow > 0) { int[] previousRowLoc = findGuardPattern(matrix, startColumn, --startRow, width, pattern, counters); if (previousRowLoc != null) { loc = previousRowLoc; } else { startRow++; break; } } result[0] = new ResultPoint(loc[0], startRow); result[1] = new ResultPoint(loc[1], startRow); found = true; break; } } int stopRow = startRow + 1; // Last row of the current symbol that contains pattern if (found) { int skippedRowCount = 0; int[] previousRowLoc = { (int)result[0].X, (int)result[1].X }; for (; stopRow < height; stopRow++) { int[] loc = findGuardPattern(matrix, previousRowLoc[0], stopRow, width, pattern, counters); // a found pattern is only considered to belong to the same barcode if the start and end positions // don't differ too much. Pattern drift should be not bigger than two for consecutive rows. With // a higher number of skipped rows drift could be larger. To keep it simple for now, we allow a slightly // larger drift and don't check for skipped rows. if (loc != null && Math.Abs(previousRowLoc[0] - loc[0]) < MAX_PATTERN_DRIFT && Math.Abs(previousRowLoc[1] - loc[1]) < MAX_PATTERN_DRIFT) { previousRowLoc = loc; skippedRowCount = 0; } else { if (skippedRowCount > SKIPPED_ROW_COUNT_MAX) { break; } else { skippedRowCount++; } } } stopRow -= skippedRowCount + 1; result[2] = new ResultPoint(previousRowLoc[0], stopRow); result[3] = new ResultPoint(previousRowLoc[1], stopRow); } if (stopRow - startRow < BARCODE_MIN_HEIGHT) { for (int i = 0; i < result.Length; i++) { result[i] = null; } } return result; } /// <summary> /// Finds the guard pattern. Uses System.Linq.Enumerable.Repeat to fill in counters. This might be a performance issue? /// </summary> /// <returns>start/end horizontal offset of guard pattern, as an array of two ints.</returns> /// <param name="matrix">matrix row of black/white values to search</param> /// <param name="column">column x position to start search.</param> /// <param name="row">row y position to start search.</param> /// <param name="width">width the number of pixels to search on this row.</param> /// <param name="pattern">pattern of counts of number of black and white pixels that are being searched for as a pattern.</param> /// <param name="counters">counters array of counters, as long as pattern, to re-use .</param> private static int[] findGuardPattern( BitMatrix matrix, int column, int row, int width, int[] pattern, int[] counters) { SupportClass.Fill(counters, 0); var patternStart = column; var pixelDrift = 0; // if there are black pixels left of the current pixel shift to the left, but only for MAX_PIXEL_DRIFT pixels while (matrix[patternStart, row] && patternStart > 0 && pixelDrift++ < MAX_PIXEL_DRIFT) { patternStart--; } var x = patternStart; var counterPosition = 0; var patternLength = pattern.Length; for (var isWhite = false; x < width; x++) { var pixel = matrix[x, row]; if (pixel != isWhite) { counters[counterPosition]++; } else { if (counterPosition == patternLength - 1) { if (patternMatchVariance(counters, pattern) < MAX_AVG_VARIANCE) { return new int[] { patternStart, x }; } patternStart += counters[0] + counters[1]; Array.Copy(counters, 2, counters, 0, counterPosition - 1); counters[counterPosition - 1] = 0; counters[counterPosition] = 0; counterPosition--; } else { counterPosition++; } counters[counterPosition] = 1; isWhite = !isWhite; } } if (counterPosition == patternLength - 1 && patternMatchVariance(counters, pattern) < MAX_AVG_VARIANCE) { return new int[] { patternStart, x - 1 }; } return null; } /// <summary> /// Determines how closely a set of observed counts of runs of black/white. /// values matches a given target pattern. This is reported as the ratio of /// the total variance from the expected pattern proportions across all /// pattern elements, to the length of the pattern. /// </summary> /// <returns> /// ratio of total variance between counters and pattern compared to /// total pattern size, where the ratio has been multiplied by 256. /// So, 0 means no variance (perfect match); 256 means the total /// variance between counters and patterns equals the pattern length, /// higher values mean even more variance /// </returns> /// <param name="counters">observed counters.</param> /// <param name="pattern">expected pattern.</param> private static int patternMatchVariance(int[] counters, int[] pattern) { int numCounters = counters.Length; int total = 0; int patternLength = 0; for (int i = 0; i < numCounters; i++) { total += counters[i]; patternLength += pattern[i]; } if (total < patternLength) { // If we don't even have one pixel per unit of bar width, assume this // is too small to reliably match, so fail: return int.MaxValue; } // We're going to fake floating-point math in integers. We just need to use more bits. // Scale up patternLength so that intermediate values below like scaledCounter will have // more "significant digits". int unitBarWidth = (total << INTEGER_MATH_SHIFT) / patternLength; int maxIndividualVariance = (MAX_INDIVIDUAL_VARIANCE * unitBarWidth) >> INTEGER_MATH_SHIFT; int totalVariance = 0; for (int x = 0; x < numCounters; x++) { int counter = counters[x] << INTEGER_MATH_SHIFT; int scaledPattern = pattern[x] * unitBarWidth; int variance = counter > scaledPattern ? counter - scaledPattern : scaledPattern - counter; if (variance > maxIndividualVariance) { return int.MaxValue; } totalVariance += variance; } return totalVariance / total; } } }
// 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.CommandLine; using System.CommandLine.Builder; using System.CommandLine.Invocation; using System.IO; namespace ReadyToRun.SuperIlc { internal static class CommandLineOptions { public static CommandLineBuilder Build() { var parser = new CommandLineBuilder() .AddCommand(CompileFolder()) .AddCommand(CompileSubtree()) .AddCommand(CompileFramework()) .AddCommand(CompileNugetPackages()) .AddCommand(CompileCrossgenRsp()); return parser; Command CompileFolder() => new Command("compile-directory", "Compile all assemblies in directory", new Option[] { InputDirectory(), OutputDirectory(), CoreRootDirectory(), Crossgen(), CrossgenPath(), NoJit(), NoCrossgen2(), Exe(), NoExe(), NoEtw(), NoCleanup(), DegreeOfParallelism(), Sequential(), Framework(), UseFramework(), Release(), LargeBubble(), ReferencePath(), IssuesPath(), CompilationTimeoutMinutes(), ExecutionTimeoutMinutes(), R2RDumpPath(), MeasurePerf(), InputFileSearchString(), }, handler: CommandHandler.Create<BuildOptions>(CompileDirectoryCommand.CompileDirectory)); Command CompileSubtree() => new Command("compile-subtree", "Build each directory in a given subtree containing any managed assemblies as a separate app", new Option[] { InputDirectory(), OutputDirectory(), CoreRootDirectory(), Crossgen(), CrossgenPath(), NoJit(), NoCrossgen2(), Exe(), NoExe(), NoEtw(), NoCleanup(), DegreeOfParallelism(), Sequential(), Framework(), UseFramework(), Release(), LargeBubble(), ReferencePath(), IssuesPath(), CompilationTimeoutMinutes(), ExecutionTimeoutMinutes(), R2RDumpPath(), }, handler: CommandHandler.Create<BuildOptions>(CompileSubtreeCommand.CompileSubtree)); Command CompileFramework() => new Command("compile-framework", "Compile managed framework assemblies in Core_Root", new Option[] { CoreRootDirectory(), Crossgen(), CrossgenPath(), NoCrossgen2(), NoCleanup(), DegreeOfParallelism(), Sequential(), Release(), LargeBubble(), ReferencePath(), IssuesPath(), CompilationTimeoutMinutes(), R2RDumpPath(), MeasurePerf(), InputFileSearchString(), }, handler: CommandHandler.Create<BuildOptions>(CompileFrameworkCommand.CompileFramework)); Command CompileNugetPackages() => new Command("compile-nuget", "Restore a list of Nuget packages into an empty console app, publish, and optimize with Crossgen / CPAOT", new Option[] { R2RDumpPath(), InputDirectory(), OutputDirectory(), PackageList(), CoreRootDirectory(), Crossgen(), NoCleanup(), DegreeOfParallelism(), CompilationTimeoutMinutes(), ExecutionTimeoutMinutes(), }, handler: CommandHandler.Create<BuildOptions>(CompileNugetCommand.CompileNuget)); Command CompileCrossgenRsp() => new Command("compile-crossgen-rsp", "Use existing Crossgen .rsp file(s) to build assemblies, optionally rewriting base paths", new Option[] { InputDirectory(), CrossgenResponseFile(), OutputDirectory(), CoreRootDirectory(), Crossgen(), NoCleanup(), DegreeOfParallelism(), CompilationTimeoutMinutes(), RewriteOldPath(), RewriteNewPath(), }, handler: CommandHandler.Create<BuildOptions>(CompileFromCrossgenRspCommand.CompileFromCrossgenRsp)); // Todo: Input / Output directories should be required arguments to the command when they're made available to handlers // https://github.com/dotnet/command-line-api/issues/297 Option InputDirectory() => new Option(new[] { "--input-directory", "-in" }, "Folder containing assemblies to optimize", new Argument<DirectoryInfo>().ExistingOnly()); Option OutputDirectory() => new Option(new[] { "--output-directory", "-out" }, "Folder to emit compiled assemblies", new Argument<DirectoryInfo>().LegalFilePathsOnly()); Option CoreRootDirectory() => new Option(new[] { "--core-root-directory", "-cr" }, "Location of the CoreCLR CORE_ROOT folder", new Argument<DirectoryInfo>().ExistingOnly()); Option ReferencePath() => new Option(new[] { "--reference-path", "-r" }, "Folder containing assemblies to reference during compilation", new Argument<DirectoryInfo[]>() { Arity = ArgumentArity.ZeroOrMore }.ExistingOnly()); Option Crossgen() => new Option(new[] { "--crossgen" }, "Compile the apps using Crossgen in the CORE_ROOT folder", new Argument<bool>()); Option CrossgenPath() => new Option(new[] { "--crossgen-path", "-cp" }, "Explicit Crossgen path (useful for cross-targeting)", new Argument<FileInfo>().ExistingOnly()); Option NoJit() => new Option(new[] { "--nojit" }, "Don't run tests in JITted mode", new Argument<bool>()); Option NoCrossgen2() => new Option(new[] { "--nocrossgen2" }, "Don't run tests in Crossgen2 mode", new Argument<bool>()); Option Exe() => new Option(new[] { "--exe" }, "Don't compile tests, just execute them", new Argument<bool>()); Option NoExe() => new Option(new[] { "--noexe" }, "Compilation-only mode (don't execute the built apps)", new Argument<bool>()); Option NoEtw() => new Option(new[] { "--noetw" }, "Don't capture jitted methods using ETW", new Argument<bool>()); Option NoCleanup() => new Option(new[] { "--nocleanup" }, "Don't clean up compilation artifacts after test runs", new Argument<bool>()); Option DegreeOfParallelism() => new Option(new[] { "--degree-of-parallelism", "-dop" }, "Override default compilation / execution DOP (default = logical processor count)", new Argument<int>()); Option Sequential() => new Option(new[] { "--sequential" }, "Run tests sequentially", new Argument<bool>()); Option Framework() => new Option(new[] { "--framework" }, "Precompile and use native framework", new Argument<bool>()); Option UseFramework() => new Option(new[] { "--use-framework" }, "Use native framework (don't precompile, assume previously compiled)", new Argument<bool>()); Option Release() => new Option(new[] { "--release" }, "Build the tests in release mode", new Argument<bool>()); Option LargeBubble() => new Option(new[] { "--large-bubble" }, "Assume all input files as part of one version bubble", new Argument<bool>()); Option IssuesPath() => new Option(new[] { "--issues-path", "-ip" }, "Path to issues.targets", new Argument<FileInfo[]>() { Arity = ArgumentArity.ZeroOrMore }); Option CompilationTimeoutMinutes() => new Option(new[] { "--compilation-timeout-minutes", "-ct" }, "Compilation timeout (minutes)", new Argument<int>()); Option ExecutionTimeoutMinutes() => new Option(new[] { "--execution-timeout-minutes", "-et" }, "Execution timeout (minutes)", new Argument<int>()); Option R2RDumpPath() => new Option(new[] { "--r2r-dump-path", "-r2r" }, "Path to R2RDump.exe/dll", new Argument<FileInfo>().ExistingOnly()); Option CrossgenResponseFile() => new Option(new [] { "--crossgen-response-file", "-rsp" }, "Response file to transpose", new Argument<FileInfo>().ExistingOnly()); Option RewriteOldPath() => new Option(new [] { "--rewrite-old-path" }, "Path substring to replace", new Argument<DirectoryInfo[]>(){ Arity = ArgumentArity.ZeroOrMore }); Option RewriteNewPath() => new Option(new [] { "--rewrite-new-path" }, "Path substring to use instead", new Argument<DirectoryInfo[]>(){ Arity = ArgumentArity.ZeroOrMore }); Option MeasurePerf() => new Option(new[] { "--measure-perf" }, "Print out compilation time", new Argument<bool>()); Option InputFileSearchString() => new Option(new[] { "--input-file-search-string", "-input-file" }, "Search string for input files in the input directory", new Argument<string>()); // // compile-nuget specific options // Option PackageList() => new Option(new[] { "--package-list", "-pl" }, "Text file containing a package name on each line", new Argument<FileInfo>().ExistingOnly()); } } }
using Microsoft.Data.Entity.Migrations; namespace AllReady.Migrations { public partial class UserTimeZone : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey(name: "FK_Activity_Campaign_CampaignId", table: "Activity"); migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Activity_ActivityId", table: "ActivitySkill"); migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Skill_SkillId", table: "ActivitySkill"); migrationBuilder.DropForeignKey(name: "FK_Campaign_Tenant_ManagingTenantId", table: "Campaign"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_TenantContact_Contact_ContactId", table: "TenantContact"); migrationBuilder.DropForeignKey(name: "FK_TenantContact_Tenant_TenantId", table: "TenantContact"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_Skill_SkillId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles"); migrationBuilder.AddColumn<string>( name: "TimeZoneId", table: "AspNetUsers", nullable: false, defaultValue: "Central Standard Time"); migrationBuilder.AddForeignKey( name: "FK_Activity_Campaign_CampaignId", table: "Activity", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_ActivitySkill_Activity_ActivityId", table: "ActivitySkill", column: "ActivityId", principalTable: "Activity", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_ActivitySkill_Skill_SkillId", table: "ActivitySkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Campaign_Tenant_ManagingTenantId", table: "Campaign", column: "ManagingTenantId", principalTable: "Tenant", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact", column: "ContactId", principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill", column: "TaskId", principalTable: "AllReadyTask", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_TenantContact_Contact_ContactId", table: "TenantContact", column: "ContactId", principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_TenantContact_Tenant_TenantId", table: "TenantContact", column: "TenantId", principalTable: "Tenant", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_UserSkill_Skill_SkillId", table: "UserSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey(name: "FK_Activity_Campaign_CampaignId", table: "Activity"); migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Activity_ActivityId", table: "ActivitySkill"); migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Skill_SkillId", table: "ActivitySkill"); migrationBuilder.DropForeignKey(name: "FK_Campaign_Tenant_ManagingTenantId", table: "Campaign"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_TenantContact_Contact_ContactId", table: "TenantContact"); migrationBuilder.DropForeignKey(name: "FK_TenantContact_Tenant_TenantId", table: "TenantContact"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_Skill_SkillId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles"); migrationBuilder.DropColumn(name: "TimeZoneId", table: "AspNetUsers"); migrationBuilder.AddForeignKey( name: "FK_Activity_Campaign_CampaignId", table: "Activity", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_ActivitySkill_Activity_ActivityId", table: "ActivitySkill", column: "ActivityId", principalTable: "Activity", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_ActivitySkill_Skill_SkillId", table: "ActivitySkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Campaign_Tenant_ManagingTenantId", table: "Campaign", column: "ManagingTenantId", principalTable: "Tenant", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact", column: "ContactId", principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill", column: "TaskId", principalTable: "AllReadyTask", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_TenantContact_Contact_ContactId", table: "TenantContact", column: "ContactId", principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_TenantContact_Tenant_TenantId", table: "TenantContact", column: "TenantId", principalTable: "Tenant", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_UserSkill_Skill_SkillId", table: "UserSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using System; using System.Runtime; using System.Threading; using System.Threading.Tasks; using System.Diagnostics; using System.Runtime.InteropServices; internal class MidObj { public int i; public Object parent; public MidObj(int _i, Object obj) { i = _i; parent = obj; } } internal class MiddlePin { public byte[] smallNonePinned; // this is very small, 3 or 4 ptr size public byte[] pinnedObj; // this is very small as well, 3 or 4 ptr size public byte[] nonePinned; // this is variable size } internal class MyRequest { public GCHandle pin; public MidObj[] mObj; public byte[] obj; private bool _is_pinned; private static int s_count; // We distinguish between permanent and mid so we can free Mid and // influence the demotion effect. If Mid is a lot, we will hit // demotion; otherwise they will make into gen2. public MyRequest(int sizePermanent, int sizeMid, bool pinned) { if ((s_count % 32) == 0) { sizePermanent = 1; sizeMid = 1; } mObj = new MidObj[sizeMid]; mObj[0] = new MidObj(s_count, this); obj = new byte[sizePermanent]; FillInPin(obj); _is_pinned = pinned; if (pinned) { pin = GCHandle.Alloc(obj, GCHandleType.Pinned); } s_count++; } private void FillInPin(byte[] pinnedObj) { int len = pinnedObj.Length; int lenToFill = 10; if (lenToFill > len) { lenToFill = len - 1; } for (int i = 0; i < lenToFill; i++) { obj[len - i - 1] = (byte)(0x11 * i); } } public void Free() { if (_is_pinned) { lock (this) { if (_is_pinned) { pin.Free(); _is_pinned = false; } } } } } internal class MemoryAlloc { private MyRequest[] _old = null; private MyRequest[] _med = null; private int _num_old_data = 2000; private int _num_med_data = 200; private int _mean_old_alloc_size = 1000; private int _mean_med_alloc_size = 300; private int _mean_young_alloc_size = 60; private int _old_time = 3; private int _med_time = 2; private int _young_time = 1; private int _index = 0; private int _iter_count = 0; private Rand _rand; // pinning 10%. private double _pinRatio = 0.1; private double _fragRatio = 0.2; public MemoryAlloc(int iter, Rand _rand, int i) { _iter_count = iter; if (_iter_count == 0) _iter_count = 1000; this._rand = _rand; _index = i; } public void RunTest() { AllocTest(); SteadyState(); } public void CreateFragmentation() { int iFreeInterval = (int)((double)1 / _fragRatio); //Console.WriteLine("{0}: Freeing approx every {1} object", index, iFreeInterval); int iNextFree = _rand.getRand(iFreeInterval) + 1; int iFreedObjects = 0; int iGen2Objects = 0; for (int j = 0; j < _old.Length; j++) { //int iGen = GC.GetGeneration(old[j].mObj); int iGen = _rand.getRand(3); //Console.WriteLine("old[{0}] is in gen{1}", j, iGen); if (iGen == 2) { iGen2Objects++; if (iGen2Objects == iNextFree) { iFreedObjects++; if (_old[j].mObj == null) { //Console.WriteLine("old[{0}].mObj is null", j); } else { int iLen = _old[j].mObj.Length; _old[j].mObj = new MidObj[iLen]; } int inc = _rand.getRand(iFreeInterval) + 1; iNextFree += inc; } } } // Console.WriteLine("there are {0} gen2 objects (total {1}), freed {2}", // iGen2Objects, old.Length, iFreedObjects); } // This pins every few objects (defined by pinRatio) in the old array. // med is just created with non pinned. public void AllocTest() { // Console.WriteLine(index + ": Allocating memory - old: " + num_old_data + "[~" + mean_old_alloc_size + "]; med: " // + num_med_data + "[~" + mean_med_alloc_size + "]"); Stopwatch stopwatch = new Stopwatch(); stopwatch.Reset(); stopwatch.Start(); _old = new MyRequest[_num_old_data]; _med = new MyRequest[_num_med_data]; bool fIsPinned = false; int iPinInterval = (int)((double)1 / _pinRatio); //Console.WriteLine("Pinning approx every {0} object", iPinInterval); int iPinnedObject = 0; int iPinnedMidSize = 0; //int iNextPin = iPinInterval / 5 + rand.getRand(iPinInterval); int iNextPin = _rand.getRand(iPinInterval * 4) + 1; //Console.WriteLine("Pin object {0}", iNextPin); for (int j = 0; j < _old.Length; j++) { //old [j] = new byte [GetSizeRandom (mean_old_alloc_size)]; if (j == iNextPin) { fIsPinned = true; //iNextPin = j + iPinInterval / 5 + rand.getRand(iPinInterval); iNextPin = j + _rand.getRand(iPinInterval * 4) + 1; //Console.WriteLine("Pin object {0}", iNextPin); } else { fIsPinned = false; } iPinnedMidSize = _mean_old_alloc_size * 2; if (fIsPinned) { iPinnedObject++; if ((iPinnedObject % 10) == 0) { iPinnedMidSize = _mean_old_alloc_size * 10; //Console.WriteLine("{0}th pinned object, non pin size is {1}", iPinnedObject, iPinnedMidSize); } else { //Console.WriteLine("{0}th pinned object, non pin size is {1}", iPinnedObject, iPinnedMidSize); } } //Console.WriteLine("item {0}: {1}, pin size: {2}, non pin size: {3}", j, (fIsPinned ? "pinned" : "not pinned"), mean_old_alloc_size, iPinnedMidSize); byte[] temp = new byte[_mean_med_alloc_size * 3]; _old[j] = new MyRequest(_mean_old_alloc_size, iPinnedMidSize, fIsPinned); //if ((j % (old.Length / 10)) == 0) //{ // Console.WriteLine("{0}: allocated {1} on old array, {2}ms elapsed, Heap size {3}, gen0: {4}, gen1: {5}, gen2: {6})", // index, // j, // (int)stopwatch.Elapsed.TotalMilliseconds, // GC.GetTotalMemory(false), // GC.CollectionCount(0), // GC.CollectionCount(1), // GC.CollectionCount(2)); //} } //Console.WriteLine("pinned {0} objects out of {1}", iPinnedObject, old.Length); { // Console.WriteLine("{0}: allocated {1} on old array, {2}ms elapsed, Heap size {3}, gen0: {4}, gen1: {5}, gen2: {6})", // index, // old.Length, // (int)stopwatch.Elapsed.TotalMilliseconds, // GC.GetTotalMemory(false), // GC.CollectionCount(0), // GC.CollectionCount(1), // GC.CollectionCount(2)); } for (int j = 0; j < _med.Length; j++) { //med [j] = new byte [GetSizeRandom (mean_med_alloc_size)]; _med[j] = new MyRequest(_mean_med_alloc_size, (_mean_med_alloc_size * 2), false); } stopwatch.Stop(); // Console.WriteLine ("{0}: startup: {1:d} seconds({2:d} ms. Heap size {3})", // index, (int)stopwatch.Elapsed.TotalSeconds, (int)stopwatch.Elapsed.TotalMilliseconds, // GC.GetTotalMemory(false)); } public void SteadyState() { Console.WriteLine(_index + ": replacing old every " + _old_time + "; med every " + _med_time + ";creating young " + _young_time + "times (" + "(size " + _mean_young_alloc_size + ")"); Console.WriteLine("iterating {0} times", _iter_count); int iter_interval = _iter_count / 10; Stopwatch stopwatch = new Stopwatch(); stopwatch.Reset(); stopwatch.Start(); //int lastGen2Count = 0; int lastGen1Count = 0; int checkInterval = _old.Length / 10; int lastChecked = 0; int iCheckedEnd = 0; int timeoutInterval = 5; double pinRatio = 0.1; bool fIsPinned = false; int iPinInterval = (int)((double)1 / pinRatio); Console.WriteLine("Pinning every {0} object", iPinInterval); int iNextPin = _rand.getRand(iPinInterval * 4) + 1; int iPinnedObject = 0; int iPinnedMidSize = _mean_old_alloc_size * 2; int countObjects = 0; int countObjectsGen1 = 0; int[] countWithGen = new int[3]; MiddlePin[] steadyPinningArray = new MiddlePin[100]; GCHandle[] steadyPinningHandles = new GCHandle[100]; int steadyPinningIndex = 0; for (steadyPinningIndex = 0; steadyPinningIndex < steadyPinningArray.Length; steadyPinningIndex++) { steadyPinningArray[steadyPinningIndex] = new MiddlePin(); steadyPinningHandles[steadyPinningIndex] = new GCHandle(); } for (int j = 0; j < _iter_count; j++) { if (steadyPinningIndex >= steadyPinningArray.Length) { steadyPinningIndex = 0; // Console.WriteLine("steady array wrapped, press enter to continue"); // Console.ReadLine(); } byte[] tempObj = new byte[1]; steadyPinningArray[steadyPinningIndex].smallNonePinned = new byte[8]; steadyPinningArray[steadyPinningIndex].pinnedObj = new byte[8]; steadyPinningArray[steadyPinningIndex].nonePinned = new byte[24]; steadyPinningHandles[steadyPinningIndex] = GCHandle.Alloc(steadyPinningArray[steadyPinningIndex].pinnedObj, GCHandleType.Pinned); steadyPinningArray[steadyPinningIndex].smallNonePinned[3] = 0x31; steadyPinningArray[steadyPinningIndex].smallNonePinned[5] = 0x51; steadyPinningArray[steadyPinningIndex].smallNonePinned[7] = 0x71; steadyPinningArray[steadyPinningIndex].pinnedObj[3] = 0x21; steadyPinningArray[steadyPinningIndex].pinnedObj[5] = 0x41; steadyPinningArray[steadyPinningIndex].pinnedObj[7] = 0x61; tempObj = new byte[256]; steadyPinningIndex++; countObjects = 0; countObjectsGen1 = 0; iCheckedEnd = lastChecked + checkInterval; if (iCheckedEnd > _old.Length) { iCheckedEnd = _old.Length; } //Console.WriteLine("timing out item {0} to {1}", lastChecked, iCheckedEnd); // time out requests in this range. // for the range we are looking at time out requests (ie, end them and replace them with new ones). // we go from the beginning of the range to the end, time out every Nth one; then time out everyone // after that, and so on. for (int iIter = 0; iIter < timeoutInterval; iIter++) { for (int iCheckIndex = 0; iCheckIndex < ((iCheckedEnd - lastChecked) / timeoutInterval); iCheckIndex++) { int iItemIndex = (lastChecked + iCheckIndex * timeoutInterval + iIter) % _old.Length; // Console.WriteLine("replacing item {0}", iItemIndex); _old[iItemIndex].Free(); countObjects++; if ((countObjects % 10) == 0) { byte[] temp = new byte[_mean_med_alloc_size * 3]; temp[0] = (byte)27; // 0x1b } else if ((countObjects % 4) == 0) { byte[] temp = new byte[1]; temp[0] = (byte)27; // 0x1b } if (countObjects == iNextPin) { fIsPinned = true; iNextPin += _rand.getRand(iPinInterval * 4) + 1; } else { fIsPinned = false; } iPinnedMidSize = _mean_old_alloc_size * 2; if (fIsPinned) { iPinnedObject++; if ((iPinnedObject % 10) == 0) { iPinnedMidSize = _mean_old_alloc_size * 10; } } //Console.WriteLine("perm {0}, mid {1}, {2}", mean_old_alloc_size, iPinnedMidSize, (fIsPinned ? "pinned" : "not pinned")); _old[iItemIndex] = new MyRequest(_mean_old_alloc_size, iPinnedMidSize, fIsPinned); } } for (int i = 0; i < 3; i++) { countWithGen[i] = 0; } // Console.WriteLine("Checking {0} to {1}", lastChecked, iCheckedEnd); for (int iItemIndex = lastChecked; iItemIndex < iCheckedEnd; iItemIndex++) { //int iGen = GC.GetGeneration(old[iItemIndex].mObj); int iGen = _rand.getRand(3); countWithGen[iGen]++; if (iGen == 1) { //Console.WriteLine("item {0} is in gen1, getting rid of it", iItemIndex); if ((countObjectsGen1 % 5) == 0) _old[iItemIndex].mObj = null; countObjectsGen1++; } } // Console.WriteLine("{0} in gen0, {1} in gen1, {2} in gen2", // countWithGen[0], // countWithGen[1], // countWithGen[2]); // // Console.WriteLine("{0} objects out of {1} are in gen1", countObjectsGen1, (iCheckedEnd - lastChecked)); if (iCheckedEnd == _old.Length) { lastChecked = 0; } else { lastChecked += checkInterval; } int currentGen1Count = GC.CollectionCount(1); if ((currentGen1Count - lastGen1Count) > 30) { GC.Collect(2, GCCollectionMode.Forced, false); Console.WriteLine("{0}: iter {1}, heap size: {2}", _index, j, GC.GetTotalMemory(false)); lastGen1Count = currentGen1Count; } } for (steadyPinningIndex = 0; steadyPinningIndex < steadyPinningArray.Length; steadyPinningIndex++) { if (steadyPinningHandles[steadyPinningIndex].IsAllocated) steadyPinningHandles[steadyPinningIndex].Free(); } stopwatch.Stop(); Console.WriteLine("{0}: steady: {1:d} seconds({2:d} ms. Heap size {3})", _index, (int)stopwatch.Elapsed.TotalSeconds, (int)stopwatch.Elapsed.TotalMilliseconds, GC.GetTotalMemory(false)); } } internal class FreeListTest { private static int s_iLastGen0Count; private static int s_iLastGen1Count; private static void InducedGen2() { int iCurrentGen0Count = GC.CollectionCount(0); if ((iCurrentGen0Count - s_iLastGen0Count) > 50) { //Console.WriteLine("we've done {0} gen0 GCs, inducing a gen2", (iCurrentGen0Count - iLastGen0Count)); s_iLastGen0Count = iCurrentGen0Count; GC.Collect(2, GCCollectionMode.Forced, false); //GC.Collect(2); } int iCurrentGen1Count = GC.CollectionCount(1); if ((iCurrentGen1Count - s_iLastGen1Count) > 10) { //Console.WriteLine("we've done {0} gen1 GCs, inducing a gen2", (iCurrentGen1Count - iLastGen1Count)); s_iLastGen1Count = iCurrentGen1Count; GC.Collect(2, GCCollectionMode.Forced, false); } } public static int Main(String[] args) { if (GCSettings.IsServerGC == true) { Console.WriteLine("we are using server GC"); } int iter_num = 500000; if (args.Length >= 1) { iter_num = int.Parse(args[0]); Console.WriteLine("iterating {0} times", iter_num); } // ProjectN doesn't support thread! for now just do everything on the main thread. //int threadCount = 8; // int threadCount = 1; // if (args.Length >= 2) // { // threadCount = int.Parse(args[1]); // Console.WriteLine ("creating {0} threads", threadCount); // } long tStart, tEnd; tStart = Environment.TickCount; // MyThread t; // ThreadStart ts; // Thread[] threads = new Thread[threadCount]; // // for (int i = 0; i < threadCount; i++) // { // t = new MyThread(i, iter_num, old, med); // ts = new ThreadStart(t.TimeTest); // threads[i] = new Thread( ts ); // threads[i].Start(); // } // // for (int i = 0; i < threadCount; i++) // { // threads[i].Join(); // } // Console.WriteLine("start with {0} gen1 GCs", s_iLastGen1Count); s_iLastGen0Count = GC.CollectionCount(0); s_iLastGen1Count = GC.CollectionCount(1); for (int iter = 0; iter < 1; iter++) { MemoryAlloc[] maArr = new MemoryAlloc[16]; Rand rand = new Rand(); for (int i = 0; i < maArr.Length; i++) { maArr[i] = new MemoryAlloc(rand.getRand(500), rand, i); maArr[i].AllocTest(); //Console.WriteLine("{0} allocated", i); InducedGen2(); for (int iAllocated = 0; iAllocated < i; iAllocated++) { //Console.WriteLine("creating fragmentation in obj {0}", iAllocated); maArr[iAllocated].CreateFragmentation(); InducedGen2(); } } for (int i = 0; i < maArr.Length; i++) { InducedGen2(); Console.WriteLine("steady state for " + i); maArr[i].SteadyState(); Console.WriteLine("DONE: steady state for " + i); } } tEnd = Environment.TickCount; Console.WriteLine("Test completed; " + (tEnd - tStart) + "ms"); // Console.WriteLine("Press any key to exit."); // Console.ReadLine(); return 100; } }; internal sealed class Rand { /* Generate Random numbers */ private int _x = 0; public int getRand() { _x = (314159269 * _x + 278281) & 0x7FFFFFFF; return _x; } // obtain random number in the range 0 .. r-1 public int getRand(int r) { // require r >= 0 int x = (int)(((long)getRand() * r) >> 31); return x; } public double getFloat() { return (double)getRand() / (double)0x7FFFFFFF; } };
// 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.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Compute { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// AvailabilitySetsOperations operations. /// </summary> internal partial class AvailabilitySetsOperations : Microsoft.Rest.IServiceOperations<ComputeManagementClient>, IAvailabilitySetsOperations { /// <summary> /// Initializes a new instance of the AvailabilitySetsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal AvailabilitySetsOperations(ComputeManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the ComputeManagementClient /// </summary> public ComputeManagementClient Client { get; private set; } /// <summary> /// The operation to create or update the availability set. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='name'> /// Parameters supplied to the Create Availability Set operation. /// </param> /// <param name='parameters'> /// Parameters supplied to the Create Availability Set operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// 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> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<AvailabilitySet>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string name, AvailabilitySet parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (name == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "name"); } if (parameters == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-03-30"; // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("name", name); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{name}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.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(parameters != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.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) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<AvailabilitySet>(); _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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<AvailabilitySet>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// The operation to delete the availability set. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='availabilitySetName'> /// The name of the availability set. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string availabilitySetName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (availabilitySetName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "availabilitySetName"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-03-30"; // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("availabilitySetName", availabilitySetName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{availabilitySetName}", System.Uri.EscapeDataString(availabilitySetName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.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) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 204) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.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) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// The operation to get the availability set. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='availabilitySetName'> /// The name of the availability set. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// 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> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<AvailabilitySet>> GetWithHttpMessagesAsync(string resourceGroupName, string availabilitySetName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (availabilitySetName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "availabilitySetName"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-03-30"; // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("availabilitySetName", availabilitySetName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{availabilitySetName}", System.Uri.EscapeDataString(availabilitySetName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.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) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<AvailabilitySet>(); _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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<AvailabilitySet>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// The operation to list the availability sets. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// 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> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.Collections.Generic.IEnumerable<AvailabilitySet>>> ListWithHttpMessagesAsync(string resourceGroupName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-03-30"; // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.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) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<System.Collections.Generic.IEnumerable<AvailabilitySet>>(); _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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<AvailabilitySet>>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists all available virtual machine sizes that can be used to create a new /// virtual machine in an existing availability set. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='availabilitySetName'> /// The name of the availability set. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// 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> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.Collections.Generic.IEnumerable<VirtualMachineSize>>> ListAvailableSizesWithHttpMessagesAsync(string resourceGroupName, string availabilitySetName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (availabilitySetName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "availabilitySetName"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-03-30"; // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("availabilitySetName", availabilitySetName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListAvailableSizes", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/availabilitySets/{availabilitySetName}/vmSizes").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{availabilitySetName}", System.Uri.EscapeDataString(availabilitySetName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.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) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<System.Collections.Generic.IEnumerable<VirtualMachineSize>>(); _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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<VirtualMachineSize>>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using System.Text; /// <summary> /// GetByteCount(System.Char[],System.Int32,System.Int32) [v-jianq] /// </summary> public class UTF8EncodingGetByteCount1 { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; // // TODO: Add your negative test cases here // // TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; retVal = NegTest4() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method GetByteCount(Char[],Int32,Int32) with non-null char[]"); try { Char[] chars = new Char[] { '\u0023', '\u0025', '\u03a0', '\u03a3' }; UTF8Encoding utf8 = new UTF8Encoding(); int byteCount = utf8.GetByteCount(chars, 1, 2); } catch (Exception e) { TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest2: Verify method GetByteCount(Char[],Int32,Int32) with null char[]"); try { Char[] chars = new Char[] { }; UTF8Encoding utf8 = new UTF8Encoding(); int byteCount = utf8.GetByteCount(chars, 0, 0); if (byteCount != 0) { TestLibrary.TestFramework.LogError("001.1", "Method GetByteCount Err."); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentNullException is not thrown when chars is a null reference"); try { Char[] chars = null; UTF8Encoding utf8 = new UTF8Encoding(); int byteCount = utf8.GetByteCount(chars, 0, 0); TestLibrary.TestFramework.LogError("101.1", "ArgumentNullException is not thrown when chars is a null reference."); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: ArgumentOutOfRangeException is not thrown when index is less than zero."); try { Char[] chars = new Char[] { '\u0023', '\u0025', '\u03a0', '\u03a3' }; UTF8Encoding utf8 = new UTF8Encoding(); int byteCount = utf8.GetByteCount(chars, -1, 2); TestLibrary.TestFramework.LogError("102.1", "ArgumentOutOfRangeException is not thrown when index is less than zero."); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest3: ArgumentOutOfRangeException is not thrown when count is less than zero."); try { Char[] chars = new Char[] { '\u0023', '\u0025', '\u03a0', '\u03a3' }; UTF8Encoding utf8 = new UTF8Encoding(); int byteCount = utf8.GetByteCount(chars, 1, -2); TestLibrary.TestFramework.LogError("103.1", "ArgumentOutOfRangeException is not thrown when count is less than zero."); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("103.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest4: ArgumentOutOfRangeException is not thrown when index and count do not denote a valid range in chars."); try { Char[] chars = new Char[] { '\u0023', '\u0025', '\u03a0', '\u03a3' }; UTF8Encoding utf8 = new UTF8Encoding(); int byteCount = utf8.GetByteCount(chars, 1, chars.Length); TestLibrary.TestFramework.LogError("104.1", "ArgumentOutOfRangeException is not thrown when index and count do not denote a valid range in chars."); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("104.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { UTF8EncodingGetByteCount1 test = new UTF8EncodingGetByteCount1(); TestLibrary.TestFramework.BeginTestCase("UTF8EncodingGetByteCount1"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } }
// dnlib: See LICENSE.txt for more info using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Threading; using dnlib.IO; using dnlib.PE; namespace dnlib.DotNet.MD { /// <summary> /// Common base class for #~ and #- metadata classes /// </summary> abstract class MetadataBase : Metadata { /// <summary> /// The PE image /// </summary> protected IPEImage peImage; /// <summary> /// The .NET header /// </summary> protected ImageCor20Header cor20Header; /// <summary> /// The MD header /// </summary> protected MetadataHeader mdHeader; /// <summary> /// The #Strings stream /// </summary> protected StringsStream stringsStream; /// <summary> /// The #US stream /// </summary> protected USStream usStream; /// <summary> /// The #Blob stream /// </summary> protected BlobStream blobStream; /// <summary> /// The #GUID stream /// </summary> protected GuidStream guidStream; /// <summary> /// The #~ or #- stream /// </summary> protected TablesStream tablesStream; /// <summary> /// The #Pdb stream /// </summary> protected PdbStream pdbStream; /// <summary> /// All the streams that are present in the PE image /// </summary> protected IList<DotNetStream> allStreams; public override bool IsStandalonePortablePdb => isStandalonePortablePdb; /// <summary><c>true</c> if this is standalone Portable PDB metadata</summary> protected readonly bool isStandalonePortablePdb; uint[] fieldRidToTypeDefRid; uint[] methodRidToTypeDefRid; uint[] eventRidToTypeDefRid; uint[] propertyRidToTypeDefRid; uint[] gpRidToOwnerRid; uint[] gpcRidToOwnerRid; uint[] paramRidToOwnerRid; Dictionary<uint, List<uint>> typeDefRidToNestedClasses; StrongBox<RidList> nonNestedTypes; DataReaderFactory mdReaderFactoryToDisposeLater; /// <summary> /// Sorts a table by key column /// </summary> protected sealed class SortedTable { RowInfo[] rows; /// <summary> /// Remembers <c>rid</c> and key /// </summary> [DebuggerDisplay("{rid} {key}")] readonly struct RowInfo : IComparable<RowInfo> { public readonly uint rid; public readonly uint key; /// <summary> /// Constructor /// </summary> /// <param name="rid">Row ID</param> /// <param name="key">Key</param> public RowInfo(uint rid, uint key) { this.rid = rid; this.key = key; } public int CompareTo(RowInfo other) { if (key < other.key) return -1; if (key > other.key) return 1; return rid.CompareTo(other.rid); } } /// <summary> /// Constructor /// </summary> /// <param name="mdTable">The MD table</param> /// <param name="keyColIndex">Index of key column</param> public SortedTable(MDTable mdTable, int keyColIndex) { InitializeKeys(mdTable, keyColIndex); Array.Sort(rows); } void InitializeKeys(MDTable mdTable, int keyColIndex) { var keyColumn = mdTable.TableInfo.Columns[keyColIndex]; Debug.Assert(keyColumn.Size == 2 || keyColumn.Size == 4); rows = new RowInfo[mdTable.Rows + 1]; if (mdTable.Rows == 0) return; var reader = mdTable.DataReader; reader.Position = (uint)keyColumn.Offset; uint increment = (uint)(mdTable.TableInfo.RowSize - keyColumn.Size); for (uint i = 1; i <= mdTable.Rows; i++) { rows[i] = new RowInfo(i, keyColumn.Unsafe_Read24(ref reader)); if (i < mdTable.Rows) reader.Position += increment; } } /// <summary> /// Binary searches for a row with a certain key /// </summary> /// <param name="key">The key</param> /// <returns>The row or 0 if not found</returns> int BinarySearch(uint key) { int lo = 1, hi = rows.Length - 1; while (lo <= hi && hi != -1) { int curr = (lo + hi) / 2; uint key2 = rows[curr].key; if (key == key2) return curr; if (key2 > key) hi = curr - 1; else lo = curr + 1; } return 0; } /// <summary> /// Find all rids that contain <paramref name="key"/> /// </summary> /// <param name="key">The key</param> /// <returns>A new <see cref="RidList"/> instance</returns> public RidList FindAllRows(uint key) { int startIndex = BinarySearch(key); if (startIndex == 0) return RidList.Empty; int endIndex = startIndex + 1; for (; startIndex > 1; startIndex--) { if (key != rows[startIndex - 1].key) break; } for (; endIndex < rows.Length; endIndex++) { if (key != rows[endIndex].key) break; } var list = new List<uint>(endIndex - startIndex); for (int i = startIndex; i < endIndex; i++) list.Add(rows[i].rid); return RidList.Create(list); } } SortedTable eventMapSortedTable; SortedTable propertyMapSortedTable; public override ImageCor20Header ImageCor20Header => cor20Header; public override uint Version => ((uint)mdHeader.MajorVersion << 16) | mdHeader.MinorVersion; public override string VersionString => mdHeader.VersionString; public override IPEImage PEImage => peImage; public override MetadataHeader MetadataHeader => mdHeader; public override StringsStream StringsStream => stringsStream; public override USStream USStream => usStream; public override BlobStream BlobStream => blobStream; public override GuidStream GuidStream => guidStream; public override TablesStream TablesStream => tablesStream; public override PdbStream PdbStream => pdbStream; public override IList<DotNetStream> AllStreams => allStreams; /// <summary> /// Constructor /// </summary> /// <param name="peImage">The PE image</param> /// <param name="cor20Header">The .NET header</param> /// <param name="mdHeader">The MD header</param> protected MetadataBase(IPEImage peImage, ImageCor20Header cor20Header, MetadataHeader mdHeader) { try { allStreams = new List<DotNetStream>(); this.peImage = peImage; this.cor20Header = cor20Header; this.mdHeader = mdHeader; isStandalonePortablePdb = false; } catch { if (peImage is not null) peImage.Dispose(); throw; } } internal MetadataBase(MetadataHeader mdHeader, bool isStandalonePortablePdb) { allStreams = new List<DotNetStream>(); peImage = null; cor20Header = null; this.mdHeader = mdHeader; this.isStandalonePortablePdb = isStandalonePortablePdb; } /// <summary> /// Initializes the metadata, tables, streams /// </summary> public void Initialize(DataReaderFactory mdReaderFactory) { mdReaderFactoryToDisposeLater = mdReaderFactory; uint metadataBaseOffset; if (peImage is not null) { Debug.Assert(mdReaderFactory is null); Debug.Assert(cor20Header is not null); metadataBaseOffset = (uint)peImage.ToFileOffset(cor20Header.Metadata.VirtualAddress); mdReaderFactory = peImage.DataReaderFactory; } else { Debug.Assert(mdReaderFactory is not null); metadataBaseOffset = 0; } InitializeInternal(mdReaderFactory, metadataBaseOffset); if (tablesStream is null) throw new BadImageFormatException("Missing MD stream"); if (isStandalonePortablePdb && pdbStream is null) throw new BadImageFormatException("Missing #Pdb stream"); InitializeNonExistentHeaps(); } /// <summary> /// Creates empty heap objects if they're not present in the metadata /// </summary> protected void InitializeNonExistentHeaps() { if (stringsStream is null) stringsStream = new StringsStream(); if (usStream is null) usStream = new USStream(); if (blobStream is null) blobStream = new BlobStream(); if (guidStream is null) guidStream = new GuidStream(); } /// <summary> /// Called by <see cref="Initialize(DataReaderFactory)"/> /// </summary> protected abstract void InitializeInternal(DataReaderFactory mdReaderFactory, uint metadataBaseOffset); public override RidList GetTypeDefRidList() => RidList.Create(1, tablesStream.TypeDefTable.Rows); public override RidList GetExportedTypeRidList() => RidList.Create(1, tablesStream.ExportedTypeTable.Rows); /// <summary> /// Binary searches the table for a <c>rid</c> whose key column at index /// <paramref name="keyColIndex"/> is equal to <paramref name="key"/>. /// </summary> /// <param name="tableSource">Table to search</param> /// <param name="keyColIndex">Key column index</param> /// <param name="key">Key</param> /// <returns>The <c>rid</c> of the found row, or 0 if none found</returns> protected abstract uint BinarySearch(MDTable tableSource, int keyColIndex, uint key); /// <summary> /// Finds all rows owned by <paramref name="key"/> in table <paramref name="tableSource"/> /// whose index is <paramref name="keyColIndex"/> /// </summary> /// <param name="tableSource">Table to search</param> /// <param name="keyColIndex">Key column index</param> /// <param name="key">Key</param> /// <returns>A <see cref="RidList"/> instance</returns> protected RidList FindAllRows(MDTable tableSource, int keyColIndex, uint key) { uint startRid = BinarySearch(tableSource, keyColIndex, key); if (tableSource.IsInvalidRID(startRid)) return RidList.Empty; uint endRid = startRid + 1; var column = tableSource.TableInfo.Columns[keyColIndex]; for (; startRid > 1; startRid--) { if (!tablesStream.TryReadColumn24(tableSource, startRid - 1, column, out uint key2)) break; // Should never happen since startRid is valid if (key != key2) break; } for (; endRid <= tableSource.Rows; endRid++) { if (!tablesStream.TryReadColumn24(tableSource, endRid, column, out uint key2)) break; // Should never happen since endRid is valid if (key != key2) break; } return RidList.Create(startRid, endRid - startRid); } /// <summary> /// Finds all rows owned by <paramref name="key"/> in table <paramref name="tableSource"/> /// whose index is <paramref name="keyColIndex"/>. Should be called if <paramref name="tableSource"/> /// could be unsorted. /// </summary> /// <param name="tableSource">Table to search</param> /// <param name="keyColIndex">Key column index</param> /// <param name="key">Key</param> /// <returns>A <see cref="RidList"/> instance</returns> protected virtual RidList FindAllRowsUnsorted(MDTable tableSource, int keyColIndex, uint key) => FindAllRows(tableSource, keyColIndex, key); public override RidList GetInterfaceImplRidList(uint typeDefRid) => FindAllRowsUnsorted(tablesStream.InterfaceImplTable, 0, typeDefRid); public override RidList GetGenericParamRidList(Table table, uint rid) { if (!CodedToken.TypeOrMethodDef.Encode(new MDToken(table, rid), out uint codedToken)) return RidList.Empty; return FindAllRowsUnsorted(tablesStream.GenericParamTable, 2, codedToken); } public override RidList GetGenericParamConstraintRidList(uint genericParamRid) => FindAllRowsUnsorted(tablesStream.GenericParamConstraintTable, 0, genericParamRid); public override RidList GetCustomAttributeRidList(Table table, uint rid) { if (!CodedToken.HasCustomAttribute.Encode(new MDToken(table, rid), out uint codedToken)) return RidList.Empty; return FindAllRowsUnsorted(tablesStream.CustomAttributeTable, 0, codedToken); } public override RidList GetDeclSecurityRidList(Table table, uint rid) { if (!CodedToken.HasDeclSecurity.Encode(new MDToken(table, rid), out uint codedToken)) return RidList.Empty; return FindAllRowsUnsorted(tablesStream.DeclSecurityTable, 1, codedToken); } public override RidList GetMethodSemanticsRidList(Table table, uint rid) { if (!CodedToken.HasSemantic.Encode(new MDToken(table, rid), out uint codedToken)) return RidList.Empty; return FindAllRowsUnsorted(tablesStream.MethodSemanticsTable, 2, codedToken); } public override RidList GetMethodImplRidList(uint typeDefRid) => FindAllRowsUnsorted(tablesStream.MethodImplTable, 0, typeDefRid); public override uint GetClassLayoutRid(uint typeDefRid) { var list = FindAllRowsUnsorted(tablesStream.ClassLayoutTable, 2, typeDefRid); return list.Count == 0 ? 0 : list[0]; } public override uint GetFieldLayoutRid(uint fieldRid) { var list = FindAllRowsUnsorted(tablesStream.FieldLayoutTable, 1, fieldRid); return list.Count == 0 ? 0 : list[0]; } public override uint GetFieldMarshalRid(Table table, uint rid) { if (!CodedToken.HasFieldMarshal.Encode(new MDToken(table, rid), out uint codedToken)) return 0; var list = FindAllRowsUnsorted(tablesStream.FieldMarshalTable, 0, codedToken); return list.Count == 0 ? 0 : list[0]; } public override uint GetFieldRVARid(uint fieldRid) { var list = FindAllRowsUnsorted(tablesStream.FieldRVATable, 1, fieldRid); return list.Count == 0 ? 0 : list[0]; } public override uint GetImplMapRid(Table table, uint rid) { if (!CodedToken.MemberForwarded.Encode(new MDToken(table, rid), out uint codedToken)) return 0; var list = FindAllRowsUnsorted(tablesStream.ImplMapTable, 1, codedToken); return list.Count == 0 ? 0 : list[0]; } public override uint GetNestedClassRid(uint typeDefRid) { var list = FindAllRowsUnsorted(tablesStream.NestedClassTable, 0, typeDefRid); return list.Count == 0 ? 0 : list[0]; } public override uint GetEventMapRid(uint typeDefRid) { // The EventMap and PropertyMap tables can only be trusted to be sorted if it's // an NGen image and it's the normal #- stream. The IsSorted bit must not be used // to check whether the tables are sorted. See coreclr: md/inc/metamodel.h / IsVerified() if (eventMapSortedTable is null) Interlocked.CompareExchange(ref eventMapSortedTable, new SortedTable(tablesStream.EventMapTable, 0), null); var list = eventMapSortedTable.FindAllRows(typeDefRid); return list.Count == 0 ? 0 : list[0]; } public override uint GetPropertyMapRid(uint typeDefRid) { // Always unsorted, see comment in GetEventMapRid() above if (propertyMapSortedTable is null) Interlocked.CompareExchange(ref propertyMapSortedTable, new SortedTable(tablesStream.PropertyMapTable, 0), null); var list = propertyMapSortedTable.FindAllRows(typeDefRid); return list.Count == 0 ? 0 : list[0]; } public override uint GetConstantRid(Table table, uint rid) { if (!CodedToken.HasConstant.Encode(new MDToken(table, rid), out uint codedToken)) return 0; var list = FindAllRowsUnsorted(tablesStream.ConstantTable, 2, codedToken); return list.Count == 0 ? 0 : list[0]; } public override uint GetOwnerTypeOfField(uint fieldRid) { if (fieldRidToTypeDefRid is null) InitializeInverseFieldOwnerRidList(); uint index = fieldRid - 1; if (index >= fieldRidToTypeDefRid.LongLength) return 0; return fieldRidToTypeDefRid[index]; } void InitializeInverseFieldOwnerRidList() { if (fieldRidToTypeDefRid is not null) return; var newFieldRidToTypeDefRid = new uint[tablesStream.FieldTable.Rows]; var ownerList = GetTypeDefRidList(); for (int i = 0; i < ownerList.Count; i++) { var ownerRid = ownerList[i]; var fieldList = GetFieldRidList(ownerRid); for (int j = 0; j < fieldList.Count; j++) { uint ridIndex = fieldList[j] - 1; if (newFieldRidToTypeDefRid[ridIndex] != 0) continue; newFieldRidToTypeDefRid[ridIndex] = ownerRid; } } Interlocked.CompareExchange(ref fieldRidToTypeDefRid, newFieldRidToTypeDefRid, null); } public override uint GetOwnerTypeOfMethod(uint methodRid) { if (methodRidToTypeDefRid is null) InitializeInverseMethodOwnerRidList(); uint index = methodRid - 1; if (index >= methodRidToTypeDefRid.LongLength) return 0; return methodRidToTypeDefRid[index]; } void InitializeInverseMethodOwnerRidList() { if (methodRidToTypeDefRid is not null) return; var newMethodRidToTypeDefRid = new uint[tablesStream.MethodTable.Rows]; var ownerList = GetTypeDefRidList(); for (int i = 0; i < ownerList.Count; i++) { var ownerRid = ownerList[i]; var methodList = GetMethodRidList(ownerRid); for (int j = 0; j < methodList.Count; j++) { uint ridIndex = methodList[j] - 1; if (newMethodRidToTypeDefRid[ridIndex] != 0) continue; newMethodRidToTypeDefRid[ridIndex] = ownerRid; } } Interlocked.CompareExchange(ref methodRidToTypeDefRid, newMethodRidToTypeDefRid, null); } public override uint GetOwnerTypeOfEvent(uint eventRid) { if (eventRidToTypeDefRid is null) InitializeInverseEventOwnerRidList(); uint index = eventRid - 1; if (index >= eventRidToTypeDefRid.LongLength) return 0; return eventRidToTypeDefRid[index]; } void InitializeInverseEventOwnerRidList() { if (eventRidToTypeDefRid is not null) return; var newEventRidToTypeDefRid = new uint[tablesStream.EventTable.Rows]; var ownerList = GetTypeDefRidList(); for (int i = 0; i < ownerList.Count; i++) { var ownerRid = ownerList[i]; var eventList = GetEventRidList(GetEventMapRid(ownerRid)); for (int j = 0; j < eventList.Count; j++) { uint ridIndex = eventList[j] - 1; if (newEventRidToTypeDefRid[ridIndex] != 0) continue; newEventRidToTypeDefRid[ridIndex] = ownerRid; } } Interlocked.CompareExchange(ref eventRidToTypeDefRid, newEventRidToTypeDefRid, null); } public override uint GetOwnerTypeOfProperty(uint propertyRid) { if (propertyRidToTypeDefRid is null) InitializeInversePropertyOwnerRidList(); uint index = propertyRid - 1; if (index >= propertyRidToTypeDefRid.LongLength) return 0; return propertyRidToTypeDefRid[index]; } void InitializeInversePropertyOwnerRidList() { if (propertyRidToTypeDefRid is not null) return; var newPropertyRidToTypeDefRid = new uint[tablesStream.PropertyTable.Rows]; var ownerList = GetTypeDefRidList(); for (int i = 0; i < ownerList.Count; i++) { var ownerRid = ownerList[i]; var propertyList = GetPropertyRidList(GetPropertyMapRid(ownerRid)); for (int j = 0; j < propertyList.Count; j++) { uint ridIndex = propertyList[j] - 1; if (newPropertyRidToTypeDefRid[ridIndex] != 0) continue; newPropertyRidToTypeDefRid[ridIndex] = ownerRid; } } Interlocked.CompareExchange(ref propertyRidToTypeDefRid, newPropertyRidToTypeDefRid, null); } public override uint GetOwnerOfGenericParam(uint gpRid) { // Don't use GenericParam.Owner column. If the GP table is sorted, it's // possible to have two blocks of GPs with the same owner. Only one of the // blocks is the "real" generic params for the owner. Of course, rarely // if ever will this occur, but could happen if some obfuscator has // added it. if (gpRidToOwnerRid is null) InitializeInverseGenericParamOwnerRidList(); uint index = gpRid - 1; if (index >= gpRidToOwnerRid.LongLength) return 0; return gpRidToOwnerRid[index]; } void InitializeInverseGenericParamOwnerRidList() { if (gpRidToOwnerRid is not null) return; var gpTable = tablesStream.GenericParamTable; var newGpRidToOwnerRid = new uint[gpTable.Rows]; // Find all owners by reading the GenericParam.Owner column var ownerCol = gpTable.TableInfo.Columns[2]; var ownersDict = new Dictionary<uint, bool>(); for (uint rid = 1; rid <= gpTable.Rows; rid++) { if (!tablesStream.TryReadColumn24(gpTable, rid, ownerCol, out uint owner)) continue; ownersDict[owner] = true; } // Now that we have the owners, find all the generic params they own. An obfuscated // module could have 2+ owners pointing to the same generic param row. var owners = new List<uint>(ownersDict.Keys); owners.Sort(); for (int i = 0; i < owners.Count; i++) { if (!CodedToken.TypeOrMethodDef.Decode(owners[i], out uint ownerToken)) continue; var ridList = GetGenericParamRidList(MDToken.ToTable(ownerToken), MDToken.ToRID(ownerToken)); for (int j = 0; j < ridList.Count; j++) { uint ridIndex = ridList[j] - 1; if (newGpRidToOwnerRid[ridIndex] != 0) continue; newGpRidToOwnerRid[ridIndex] = owners[i]; } } Interlocked.CompareExchange(ref gpRidToOwnerRid, newGpRidToOwnerRid, null); } public override uint GetOwnerOfGenericParamConstraint(uint gpcRid) { // Don't use GenericParamConstraint.Owner column for the same reason // as described in GetOwnerOfGenericParam(). if (gpcRidToOwnerRid is null) InitializeInverseGenericParamConstraintOwnerRidList(); uint index = gpcRid - 1; if (index >= gpcRidToOwnerRid.LongLength) return 0; return gpcRidToOwnerRid[index]; } void InitializeInverseGenericParamConstraintOwnerRidList() { if (gpcRidToOwnerRid is not null) return; var gpcTable = tablesStream.GenericParamConstraintTable; var newGpcRidToOwnerRid = new uint[gpcTable.Rows]; var ownerCol = gpcTable.TableInfo.Columns[0]; var ownersDict = new Dictionary<uint, bool>(); for (uint rid = 1; rid <= gpcTable.Rows; rid++) { if (!tablesStream.TryReadColumn24(gpcTable, rid, ownerCol, out uint owner)) continue; ownersDict[owner] = true; } var owners = new List<uint>(ownersDict.Keys); owners.Sort(); for (int i = 0; i < owners.Count; i++) { uint ownerToken = owners[i]; var ridList = GetGenericParamConstraintRidList(ownerToken); for (int j = 0; j < ridList.Count; j++) { uint ridIndex = ridList[j] - 1; if (newGpcRidToOwnerRid[ridIndex] != 0) continue; newGpcRidToOwnerRid[ridIndex] = ownerToken; } } Interlocked.CompareExchange(ref gpcRidToOwnerRid, newGpcRidToOwnerRid, null); } public override uint GetOwnerOfParam(uint paramRid) { if (paramRidToOwnerRid is null) InitializeInverseParamOwnerRidList(); uint index = paramRid - 1; if (index >= paramRidToOwnerRid.LongLength) return 0; return paramRidToOwnerRid[index]; } void InitializeInverseParamOwnerRidList() { if (paramRidToOwnerRid is not null) return; var newParamRidToOwnerRid = new uint[tablesStream.ParamTable.Rows]; var table = tablesStream.MethodTable; for (uint rid = 1; rid <= table.Rows; rid++) { var ridList = GetParamRidList(rid); for (int j = 0; j < ridList.Count; j++) { uint ridIndex = ridList[j] - 1; if (newParamRidToOwnerRid[ridIndex] != 0) continue; newParamRidToOwnerRid[ridIndex] = rid; } } Interlocked.CompareExchange(ref paramRidToOwnerRid, newParamRidToOwnerRid, null); } public override RidList GetNestedClassRidList(uint typeDefRid) { if (typeDefRidToNestedClasses is null) InitializeNestedClassesDictionary(); if (typeDefRidToNestedClasses.TryGetValue(typeDefRid, out var ridList)) return RidList.Create(ridList); return RidList.Empty; } void InitializeNestedClassesDictionary() { var table = tablesStream.NestedClassTable; var destTable = tablesStream.TypeDefTable; Dictionary<uint, bool> validTypeDefRids = null; var typeDefRidList = GetTypeDefRidList(); if ((uint)typeDefRidList.Count != destTable.Rows) { validTypeDefRids = new Dictionary<uint, bool>(typeDefRidList.Count); for (int i = 0; i < typeDefRidList.Count; i++) validTypeDefRids[typeDefRidList[i]] = true; } var nestedRidsDict = new Dictionary<uint, bool>((int)table.Rows); var nestedRids = new List<uint>((int)table.Rows); // Need it so we add the rids in correct order for (uint rid = 1; rid <= table.Rows; rid++) { if (validTypeDefRids is not null && !validTypeDefRids.ContainsKey(rid)) continue; if (!tablesStream.TryReadNestedClassRow(rid, out var row)) continue; // Should never happen since rid is valid if (!destTable.IsValidRID(row.NestedClass) || !destTable.IsValidRID(row.EnclosingClass)) continue; if (nestedRidsDict.ContainsKey(row.NestedClass)) continue; nestedRidsDict[row.NestedClass] = true; nestedRids.Add(row.NestedClass); } var newTypeDefRidToNestedClasses = new Dictionary<uint, List<uint>>(); int count = nestedRids.Count; for (int i = 0; i < count; i++) { var nestedRid = nestedRids[i]; if (!tablesStream.TryReadNestedClassRow(GetNestedClassRid(nestedRid), out var row)) continue; if (!newTypeDefRidToNestedClasses.TryGetValue(row.EnclosingClass, out var ridList)) newTypeDefRidToNestedClasses[row.EnclosingClass] = ridList = new List<uint>(); ridList.Add(nestedRid); } var newNonNestedTypes = new List<uint>((int)(destTable.Rows - nestedRidsDict.Count)); for (uint rid = 1; rid <= destTable.Rows; rid++) { if (validTypeDefRids is not null && !validTypeDefRids.ContainsKey(rid)) continue; if (nestedRidsDict.ContainsKey(rid)) continue; newNonNestedTypes.Add(rid); } Interlocked.CompareExchange(ref nonNestedTypes, new StrongBox<RidList>(RidList.Create(newNonNestedTypes)), null); // Initialize this one last since it's tested by the callers of this method Interlocked.CompareExchange(ref typeDefRidToNestedClasses, newTypeDefRidToNestedClasses, null); } public override RidList GetNonNestedClassRidList() { // Check typeDefRidToNestedClasses and not nonNestedTypes since // InitializeNestedClassesDictionary() writes to typeDefRidToNestedClasses last. if (typeDefRidToNestedClasses is null) InitializeNestedClassesDictionary(); return nonNestedTypes.Value; } public override RidList GetLocalScopeRidList(uint methodRid) => FindAllRows(tablesStream.LocalScopeTable, 0, methodRid); public override uint GetStateMachineMethodRid(uint methodRid) { var list = FindAllRows(tablesStream.StateMachineMethodTable, 0, methodRid); return list.Count == 0 ? 0 : list[0]; } public override RidList GetCustomDebugInformationRidList(Table table, uint rid) { if (!CodedToken.HasCustomDebugInformation.Encode(new MDToken(table, rid), out uint codedToken)) return RidList.Empty; return FindAllRows(tablesStream.CustomDebugInformationTable, 0, codedToken); } public override void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Dispose method /// </summary> /// <param name="disposing"><c>true</c> if called by <see cref="Dispose()"/></param> protected virtual void Dispose(bool disposing) { if (!disposing) return; peImage?.Dispose(); stringsStream?.Dispose(); usStream?.Dispose(); blobStream?.Dispose(); guidStream?.Dispose(); tablesStream?.Dispose(); var as2 = allStreams; if (as2 is not null) { foreach (var stream in as2) stream?.Dispose(); } mdReaderFactoryToDisposeLater?.Dispose(); peImage = null; cor20Header = null; mdHeader = null; stringsStream = null; usStream = null; blobStream = null; guidStream = null; tablesStream = null; allStreams = null; fieldRidToTypeDefRid = null; methodRidToTypeDefRid = null; typeDefRidToNestedClasses = null; mdReaderFactoryToDisposeLater = null; } } }
#region File Description //----------------------------------------------------------------------------- // GameScreen.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion using System; using System.IO; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input.Touch; namespace GameStateManagement { /// <summary> /// Enum describes the screen transition state. /// </summary> public enum ScreenState { TransitionOn, Active, TransitionOff, Hidden, } /// <summary> /// A screen is a single layer that has update and draw logic, and which /// can be combined with other layers to build up a complex menu system. /// For instance the main menu, the options menu, the "are you sure you /// want to quit" message box, and the main game itself are all implemented /// as screens. /// </summary> public abstract class GameScreen { /// <summary> /// Normally when one screen is brought up over the top of another, /// the first screen will transition off to make room for the new /// one. This property indicates whether the screen is only a small /// popup, in which case screens underneath it do not need to bother /// transitioning off. /// </summary> public bool IsPopup { get { return isPopup; } protected set { isPopup = value; } } bool isPopup = false; /// <summary> /// Indicates how long the screen takes to /// transition on when it is activated. /// </summary> public TimeSpan TransitionOnTime { get { return transitionOnTime; } protected set { transitionOnTime = value; } } TimeSpan transitionOnTime = TimeSpan.Zero; /// <summary> /// Indicates how long the screen takes to /// transition off when it is deactivated. /// </summary> public TimeSpan TransitionOffTime { get { return transitionOffTime; } protected set { transitionOffTime = value; } } TimeSpan transitionOffTime = TimeSpan.Zero; /// <summary> /// Gets the current position of the screen transition, ranging /// from zero (fully active, no transition) to one (transitioned /// fully off to nothing). /// </summary> public float TransitionPosition { get { return transitionPosition; } protected set { transitionPosition = value; } } float transitionPosition = 1; /// <summary> /// Gets the current alpha of the screen transition, ranging /// from 1 (fully active, no transition) to 0 (transitioned /// fully off to nothing). /// </summary> public float TransitionAlpha { get { return 1f - TransitionPosition; } } /// <summary> /// Gets the current screen transition state. /// </summary> public ScreenState ScreenState { get { return screenState; } protected set { screenState = value; } } ScreenState screenState = ScreenState.TransitionOn; /// <summary> /// There are two possible reasons why a screen might be transitioning /// off. It could be temporarily going away to make room for another /// screen that is on top of it, or it could be going away for good. /// This property indicates whether the screen is exiting for real: /// if set, the screen will automatically remove itself as soon as the /// transition finishes. /// </summary> public bool IsExiting { get { return isExiting; } protected internal set { isExiting = value; } } bool isExiting = false; /// <summary> /// Checks whether this screen is active and can respond to user input. /// </summary> public bool IsActive { get { return !otherScreenHasFocus && (screenState == ScreenState.TransitionOn || screenState == ScreenState.Active); } } bool otherScreenHasFocus; /// <summary> /// Gets the manager that this screen belongs to. /// </summary> public ScreenManager ScreenManager { get { return screenManager; } internal set { screenManager = value; } } ScreenManager screenManager; /// <summary> /// Gets the index of the player who is currently controlling this screen, /// or null if it is accepting input from any player. This is used to lock /// the game to a specific player profile. The main menu responds to input /// from any connected gamepad, but whichever player makes a selection from /// this menu is given control over all subsequent screens, so other gamepads /// are inactive until the controlling player returns to the main menu. /// </summary> public PlayerIndex? ControllingPlayer { get { return controllingPlayer; } internal set { controllingPlayer = value; } } PlayerIndex? controllingPlayer; /// <summary> /// Gets the gestures the screen is interested in. Screens should be as specific /// as possible with gestures to increase the accuracy of the gesture engine. /// For example, most menus only need Tap or perhaps Tap and VerticalDrag to operate. /// These gestures are handled by the ScreenManager when screens change and /// all gestures are placed in the InputState passed to the HandleInput method. /// </summary> public GestureType EnabledGestures { get { return enabledGestures; } protected set { enabledGestures = value; // the screen manager handles this during screen changes, but // if this screen is active and the gesture types are changing, // we have to update the TouchPanel ourself. if (ScreenState == ScreenState.Active) { TouchPanel.EnabledGestures = value; } } } GestureType enabledGestures = GestureType.None; /// <summary> /// Gets whether or not this screen is serializable. If this is true, /// the screen will be recorded into the screen manager's state and /// its Serialize and Deserialize methods will be called as appropriate. /// If this is false, the screen will be ignored during serialization. /// By default, all screens are assumed to be serializable. /// </summary> public bool IsSerializable { get { return isSerializable; } protected set { isSerializable = value; } } bool isSerializable = true; /// <summary> /// Activates the screen. Called when the screen is added to the screen manager or if the game resumes /// from being paused or tombstoned. /// </summary> /// <param name="instancePreserved"> /// True if the game was preserved during deactivation, false if the screen is just being added or if the game was tombstoned. /// On Xbox and Windows this will always be false. /// </param> public virtual void Activate(bool instancePreserved) { } /// <summary> /// Deactivates the screen. Called when the game is being deactivated due to pausing or tombstoning. /// </summary> public virtual void Deactivate() { } /// <summary> /// Unload content for the screen. Called when the screen is removed from the screen manager. /// </summary> public virtual void Unload() { } /// <summary> /// Allows the screen to run logic, such as updating the transition position. /// Unlike HandleInput, this method is called regardless of whether the screen /// is active, hidden, or in the middle of a transition. /// </summary> public virtual void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen) { this.otherScreenHasFocus = otherScreenHasFocus; if (isExiting) { // If the screen is going away to die, it should transition off. screenState = ScreenState.TransitionOff; if (!UpdateTransition(gameTime, transitionOffTime, 1)) { // When the transition finishes, remove the screen. ScreenManager.RemoveScreen(this); } } else if (coveredByOtherScreen) { // If the screen is covered by another, it should transition off. if (UpdateTransition(gameTime, transitionOffTime, 1)) { // Still busy transitioning. screenState = ScreenState.TransitionOff; } else { // Transition finished! screenState = ScreenState.Hidden; } } else { // Otherwise the screen should transition on and become active. if (UpdateTransition(gameTime, transitionOnTime, -1)) { // Still busy transitioning. screenState = ScreenState.TransitionOn; } else { // Transition finished! screenState = ScreenState.Active; } } } /// <summary> /// Helper for updating the screen transition position. /// </summary> bool UpdateTransition(GameTime gameTime, TimeSpan time, int direction) { // How much should we move by? float transitionDelta; if (time == TimeSpan.Zero) transitionDelta = 1; else transitionDelta = (float)(gameTime.ElapsedGameTime.TotalMilliseconds / time.TotalMilliseconds); // Update the transition position. transitionPosition += transitionDelta * direction; // Did we reach the end of the transition? if (((direction < 0) && (transitionPosition <= 0)) || ((direction > 0) && (transitionPosition >= 1))) { transitionPosition = MathHelper.Clamp(transitionPosition, 0, 1); return false; } // Otherwise we are still busy transitioning. return true; } /// <summary> /// Allows the screen to handle user input. Unlike Update, this method /// is only called when the screen is active, and not when some other /// screen has taken the focus. /// </summary> public virtual void HandleInput(GameTime gameTime, InputState input) { } /// <summary> /// This is called when the screen should draw itself. /// </summary> public virtual void Draw(GameTime gameTime) { } /// <summary> /// Tells the screen to go away. Unlike ScreenManager.RemoveScreen, which /// instantly kills the screen, this method respects the transition timings /// and will give the screen a chance to gradually transition off. /// </summary> public void ExitScreen() { if (TransitionOffTime == TimeSpan.Zero) { // If the screen has a zero transition time, remove it immediately. ScreenManager.RemoveScreen(this); } else { // Otherwise flag that it should transition off and then exit. isExiting = true; } } } }
// 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.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ResourceManager { 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; using Models; /// <summary> /// SubscriptionsOperations operations. /// </summary> internal partial class SubscriptionsOperations : IServiceOperations<SubscriptionClient>, ISubscriptionsOperations { /// <summary> /// Initializes a new instance of the SubscriptionsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal SubscriptionsOperations(SubscriptionClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the SubscriptionClient /// </summary> public SubscriptionClient Client { get; private set; } /// <summary> /// Gets a list of the subscription locations. /// </summary> /// <param name='subscriptionId'> /// Id of the subscription /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<IEnumerable<Location>>> ListLocationsWithHttpMessagesAsync(string subscriptionId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (subscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionId"); } 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("subscriptionId", subscriptionId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListLocations", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/locations").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(subscriptionId)); 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<IEnumerable<Location>>(); _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<Location>>(_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> /// Gets details about particular subscription. /// </summary> /// <param name='subscriptionId'> /// Id of the subscription. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<Subscription>> GetWithHttpMessagesAsync(string subscriptionId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (subscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionId"); } 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("subscriptionId", subscriptionId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(subscriptionId)); 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<Subscription>(); _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<Subscription>(_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> /// Gets a list of the subscriptionIds. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<IPage<Subscription>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { 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("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").ToString(); 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<IPage<Subscription>>(); _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<Subscription>>(_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> /// Gets a list of the subscriptionIds. /// </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> public async Task<AzureOperationResponse<IPage<Subscription>>> 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<Subscription>>(); _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<Subscription>>(_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; } } }
using System; using System.IO; using System.Net; using System.Text; using System.Web; using ServiceStack.Common.Web; using ServiceStack.Logging; using ServiceStack.MiniProfiler; using ServiceStack.Service; using ServiceStack.ServiceHost; using ServiceStack.Text; namespace ServiceStack.WebHost.Endpoints.Extensions { public static class HttpResponseExtensions { private static readonly ILog Log = LogManager.GetLogger(typeof(HttpResponseExtensions)); public static bool WriteToOutputStream(IHttpResponse response, object result, byte[] bodyPrefix, byte[] bodySuffix) { var streamWriter = result as IStreamWriter; if (streamWriter != null) { if (bodyPrefix != null) response.OutputStream.Write(bodyPrefix, 0, bodyPrefix.Length); streamWriter.WriteTo(response.OutputStream); if (bodySuffix != null) response.OutputStream.Write(bodySuffix, 0, bodySuffix.Length); return true; } var stream = result as Stream; if (stream != null) { if (bodyPrefix != null) response.OutputStream.Write(bodyPrefix, 0, bodyPrefix.Length); stream.WriteTo(response.OutputStream); if (bodySuffix != null) response.OutputStream.Write(bodySuffix, 0, bodySuffix.Length); return true; } var bytes = result as byte[]; if (bytes != null) { response.ContentType = ContentType.Binary; if (bodyPrefix != null) response.OutputStream.Write(bodyPrefix, 0, bodyPrefix.Length); response.OutputStream.Write(bytes, 0, bytes.Length); if (bodySuffix != null) response.OutputStream.Write(bodySuffix, 0, bodySuffix.Length); return true; } return false; } public static bool WriteToResponse(this IHttpResponse httpRes, object result, string contentType) { var serializer = EndpointHost.AppHost.ContentTypeFilters.GetResponseSerializer(contentType); return httpRes.WriteToResponse(result, serializer, new SerializationContext(contentType)); } public static bool WriteToResponse(this IHttpResponse httpRes, IHttpRequest httpReq, object result) { return WriteToResponse(httpRes, httpReq, result, null, null); } public static bool WriteToResponse(this IHttpResponse httpRes, IHttpRequest httpReq, object result, byte[] bodyPrefix, byte[] bodySuffix) { if (result == null) return true; var serializationContext = new HttpRequestContext(httpReq, httpRes, result); var httpResult = result as IHttpResult; if (httpResult != null) { if (httpResult.ResponseFilter == null) { httpResult.ResponseFilter = EndpointHost.AppHost.ContentTypeFilters; } httpResult.RequestContext = serializationContext; serializationContext.ResponseContentType = httpResult.ContentType ?? httpReq.ResponseContentType; var httpResSerializer = httpResult.ResponseFilter.GetResponseSerializer(serializationContext.ResponseContentType); return httpRes.WriteToResponse(httpResult, httpResSerializer, serializationContext, bodyPrefix, bodySuffix); } var serializer = EndpointHost.AppHost.ContentTypeFilters.GetResponseSerializer(httpReq.ResponseContentType); return httpRes.WriteToResponse(result, serializer, serializationContext, bodyPrefix, bodySuffix); } public static bool WriteToResponse(this IHttpResponse httpRes, object result, ResponseSerializerDelegate serializer, IRequestContext serializationContext) { return httpRes.WriteToResponse(result, serializer, serializationContext, null, null); } /// <summary> /// Writes to response. /// Response headers are customizable by implementing IHasOptions an returning Dictionary of Http headers. /// </summary> /// <param name="response">The response.</param> /// <param name="result">Whether or not it was implicity handled by ServiceStack's built-in handlers.</param> /// <param name="defaultAction">The default action.</param> /// <param name="serializerCtx">The serialization context.</param> /// <param name="bodyPrefix">Add prefix to response body if any</param> /// <param name="bodySuffix">Add suffix to response body if any</param> /// <returns></returns> public static bool WriteToResponse(this IHttpResponse response, object result, ResponseSerializerDelegate defaultAction, IRequestContext serializerCtx, byte[] bodyPrefix, byte[] bodySuffix) { using (Profiler.Current.Step("Writing to Response")) { var defaultContentType = serializerCtx.ResponseContentType; try { if (result == null) return true; ApplyGlobalResponseHeaders(response); var httpResult = result as IHttpResult; var disposableResult = result as IDisposable; if (httpResult != null) { response.StatusCode = httpResult.Status; response.StatusDescription = httpResult.StatusDescription ?? httpResult.StatusCode.ToString(); if (String.IsNullOrEmpty(httpResult.ContentType)) { httpResult.ContentType = defaultContentType; } response.ContentType = httpResult.ContentType; } /* Mono Error: Exception: Method not found: 'System.Web.HttpResponse.get_Headers' */ var responseOptions = result as IHasOptions; if (responseOptions != null) { //Reserving options with keys in the format 'xx.xxx' (No Http headers contain a '.' so its a safe restriction) const string reservedOptions = "."; foreach (var responseHeaders in responseOptions.Options) { if (responseHeaders.Key.Contains(reservedOptions)) continue; Log.DebugFormat("Setting Custom HTTP Header: {0}: {1}", responseHeaders.Key, responseHeaders.Value); response.AddHeader(responseHeaders.Key, responseHeaders.Value); } } if (WriteToOutputStream(response, result, bodyPrefix, bodySuffix)) { response.Flush(); //required for Compression if (disposableResult != null) disposableResult.Dispose(); return true; } if (httpResult != null) { result = httpResult.Response; } //ContentType='text/html' is the default for a HttpResponse //Do not override if another has been set if (response.ContentType == null || response.ContentType == ContentType.Html) { response.ContentType = defaultContentType; } if (bodyPrefix != null && response.ContentType.IndexOf(ContentType.Json) >= 0) { response.ContentType = ContentType.JavaScript; } if (EndpointHost.Config.AppendUtf8CharsetOnContentTypes.Contains(response.ContentType)) { response.ContentType += ContentType.Utf8Suffix; } var responseText = result as string; if (responseText != null) { if (bodyPrefix != null) response.OutputStream.Write(bodyPrefix, 0, bodyPrefix.Length); WriteTextToResponse(response, responseText, defaultContentType); if (bodySuffix != null) response.OutputStream.Write(bodySuffix, 0, bodySuffix.Length); return true; } if (defaultAction == null) { throw new ArgumentNullException("defaultAction", String.Format( "As result '{0}' is not a supported responseType, a defaultAction must be supplied", (result != null ? result.GetType().Name : ""))); } if (bodyPrefix != null) response.OutputStream.Write(bodyPrefix, 0, bodyPrefix.Length); if (result != null) defaultAction(serializerCtx, result, response); if (bodySuffix != null) response.OutputStream.Write(bodySuffix, 0, bodySuffix.Length); if (disposableResult != null) disposableResult.Dispose(); return false; } catch (Exception originalEx) { //TM: It would be good to handle 'remote end dropped connection' problems here. Arguably they should at least be suppressible via configuration //DB: Using standard ServiceStack configuration method if (!EndpointHost.Config.WriteErrorsToResponse) throw; var errorMessage = String.Format( "Error occured while Processing Request: [{0}] {1}", originalEx.GetType().Name, originalEx.Message); Log.Error(errorMessage, originalEx); var operationName = result != null ? result.GetType().Name.Replace("Response", "") : "OperationName"; try { if (!response.IsClosed) { response.WriteErrorToResponse(defaultContentType, operationName, errorMessage, originalEx); } } catch (Exception writeErrorEx) { //Exception in writing to response should not hide the original exception Log.Info("Failed to write error to response: {0}", writeErrorEx); throw originalEx; } return true; } finally { response.EndServiceStackRequest(skipHeaders:true); } } } public static void WriteTextToResponse(this IHttpResponse response, string text, string defaultContentType) { try { //ContentType='text/html' is the default for a HttpResponse //Do not override if another has been set if (response.ContentType == null || response.ContentType == ContentType.Html) { response.ContentType = defaultContentType; } response.Write(text); } catch (Exception ex) { Log.Error("Could not WriteTextToResponse: " + ex.Message, ex); throw; } } public static void WriteError(this IHttpResponse response, IHttpRequest httpReq, object dto, string errorMessage) { WriteErrorToResponse(response, httpReq.ResponseContentType, dto.GetType().Name, errorMessage, null, (int)HttpStatusCode.InternalServerError); } public static void WriteErrorToResponse(this IHttpResponse response, string contentType, string operationName, string errorMessage, Exception ex) { WriteErrorToResponse(response, contentType, operationName, errorMessage, ex, (int)HttpStatusCode.InternalServerError); } public static void WriteErrorToResponse(this IHttpResponse response, string contentType, string operationName, string errorMessage, Exception ex, int statusCode) { switch (contentType) { case ContentType.Xml: WriteXmlErrorToResponse(response, operationName, errorMessage, ex, statusCode); break; case ContentType.Json: WriteJsonErrorToResponse(response, operationName, errorMessage, ex, statusCode); break; case ContentType.Jsv: WriteJsvErrorToResponse(response, operationName, errorMessage, ex, statusCode); break; default: WriteXmlErrorToResponse(response, operationName, errorMessage, ex, statusCode); break; } } public static void WriteErrorToResponse(this IHttpResponse response, EndpointAttributes contentType, string operationName, string errorMessage, Exception ex, int statusCode) { switch (contentType) { case EndpointAttributes.Xml: WriteXmlErrorToResponse(response, operationName, errorMessage, ex, statusCode); break; case EndpointAttributes.Json: WriteJsonErrorToResponse(response, operationName, errorMessage, ex, statusCode); break; case EndpointAttributes.Jsv: WriteJsvErrorToResponse(response, operationName, errorMessage, ex, statusCode); break; default: WriteXmlErrorToResponse(response, operationName, errorMessage, ex, statusCode); break; } } private static void WriteErrorTextToResponse(this IHttpResponse response, StringBuilder sb, string contentType, int statusCode) { response.StatusCode = statusCode; WriteTextToResponse(response, sb.ToString(), contentType); response.Close(); } private static void WriteXmlErrorToResponse(this IHttpResponse response, string operationName, string errorMessage, Exception ex, int statusCode) { var sb = new StringBuilder(); sb.AppendFormat("<{0}Response xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"{1}\">\n", operationName, EndpointHost.Config.DefaultOperationNamespace); sb.AppendLine("<ResponseStatus>"); sb.AppendFormat("<ErrorCode>{0}</ErrorCode>\n", ex.ToErrorCode().EncodeXml()); sb.AppendFormat("<Message>{0}</Message>\n", ex.Message.EncodeXml()); if (EndpointHost.Config.DebugMode) sb.AppendFormat("<StackTrace>{0}</StackTrace>\n", ex.StackTrace.EncodeXml()); sb.AppendLine("</ResponseStatus>"); sb.AppendFormat("</{0}Response>", operationName); response.WriteErrorTextToResponse(sb, ContentType.Xml, statusCode); } private static void WriteJsonErrorToResponse(this IHttpResponse response, string operationName, string errorMessage, Exception ex, int statusCode) { var sb = new StringBuilder(); sb.AppendLine("{"); sb.AppendLine("\"ResponseStatus\":{"); sb.AppendFormat(" \"ErrorCode\":{0},\n", ex.ToErrorCode().EncodeJson()); sb.AppendFormat(" \"Message\":{0}", ex.Message.EncodeJson()); if (EndpointHost.Config.DebugMode) sb.AppendFormat(",\n \"StackTrace\":{0}\n", ex.StackTrace.EncodeJson()); else sb.Append("\n"); sb.AppendLine("}"); sb.AppendLine("}"); response.WriteErrorTextToResponse(sb, ContentType.Json, statusCode); } private static void WriteJsvErrorToResponse(this IHttpResponse response, string operationName, string errorMessage, Exception ex, int statusCode) { var sb = new StringBuilder(); sb.Append("{"); sb.Append("ResponseStatus:{"); sb.AppendFormat("ErrorCode:{0},", ex.ToErrorCode().EncodeJsv()); sb.AppendFormat("Message:{0},", ex.Message.EncodeJsv()); if (EndpointHost.Config.DebugMode) sb.AppendFormat("StackTrace:{0}", ex.StackTrace.EncodeJsv()); sb.Append("}"); sb.Append("}"); response.WriteErrorTextToResponse(sb, ContentType.Jsv, statusCode); } public static void ApplyGlobalResponseHeaders(this HttpListenerResponse httpRes) { if (EndpointHost.Config == null) return; foreach (var globalResponseHeader in EndpointHost.Config.GlobalResponseHeaders) { httpRes.AddHeader(globalResponseHeader.Key, globalResponseHeader.Value); } } public static void ApplyGlobalResponseHeaders(this HttpResponse httpRes) { if (EndpointHost.Config == null) return; foreach (var globalResponseHeader in EndpointHost.Config.GlobalResponseHeaders) { httpRes.AddHeader(globalResponseHeader.Key, globalResponseHeader.Value); } } public static void ApplyGlobalResponseHeaders(this IHttpResponse httpRes) { if (EndpointHost.Config == null) return; foreach (var globalResponseHeader in EndpointHost.Config.GlobalResponseHeaders) { httpRes.AddHeader(globalResponseHeader.Key, globalResponseHeader.Value); } } public static void EndServiceStackRequest(this HttpResponse httpRes, bool skipHeaders=false) { if (!skipHeaders) httpRes.ApplyGlobalResponseHeaders(); httpRes.Close(); EndpointHost.CompleteRequest(); } public static void EndServiceStackRequest(this IHttpResponse httpRes, bool skipHeaders = false) { httpRes.EndHttpRequest(skipHeaders: skipHeaders); EndpointHost.CompleteRequest(); } public static void EndHttpRequest(this HttpResponse httpRes, bool skipHeaders = false, bool skipClose = false, bool closeOutputStream = false, Action<HttpResponse> afterBody = null) { if (!skipHeaders) httpRes.ApplyGlobalResponseHeaders(); if (afterBody != null) afterBody(httpRes); if (closeOutputStream) httpRes.CloseOutputStream(); else if (!skipClose) httpRes.Close(); //skipHeaders used when Apache+mod_mono doesn't like: //response.OutputStream.Flush(); //response.Close(); } public static void EndHttpRequest(this IHttpResponse httpRes, bool skipHeaders = false, bool skipClose=false, Action<IHttpResponse> afterBody=null) { if (!skipHeaders) httpRes.ApplyGlobalResponseHeaders(); if (afterBody != null) afterBody(httpRes); if (!skipClose) httpRes.Close(); //skipHeaders used when Apache+mod_mono doesn't like: //response.OutputStream.Flush(); //response.Close(); } } }
// 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.Globalization; using AutoRest.Core; using AutoRest.Core.Model; using AutoRest.Core.Utilities; using AutoRest.Swagger.Model; using AutoRest.Swagger.Properties; using static AutoRest.Core.Utilities.DependencyInjection; using System.Linq; namespace AutoRest.Swagger { /// <summary> /// The builder for building swagger schema into client model parameters, /// service types or Json serialization types. /// </summary> public class SchemaBuilder : ObjectBuilder { private const string DiscriminatorValueExtension = "x-ms-discriminator-value"; private Schema _schema; public SchemaBuilder(Schema schema, SwaggerModeler modeler) : base(schema, modeler) { _schema = schema; } public override IModelType BuildServiceType(string serviceTypeName) { _schema = Modeler.Resolver.Unwrap(_schema); // If it's a primitive type, let the parent build service handle it if (_schema.IsPrimitiveType()) { return _schema.GetBuilder(Modeler).ParentBuildServiceType(serviceTypeName); } // If it's known primary type, return that type var primaryType = _schema.GetSimplePrimaryType(); if (primaryType != KnownPrimaryType.None) { var result = New<PrimaryType>(primaryType); // xml properties result.XmlProperties = _schema.Xml; return result; } // Otherwise create new object type var objectType = New<CompositeType>(serviceTypeName,new { SerializedName = serviceTypeName, Documentation = _schema.Description, ExternalDocsUrl = _schema.ExternalDocs?.Url, Summary = _schema.Title }); // associate this type with its schema (by reference) in order to allow recursive models to terminate // (e.g. if `objectType` type has property of type `objectType[]`) if (Modeler.GeneratingTypes.ContainsKey(_schema)) { return Modeler.GeneratingTypes[_schema]; } Modeler.GeneratingTypes[_schema] = objectType; if (_schema.Type == DataType.Object && _schema.AdditionalProperties != null) { // this schema is defining 'additionalProperties' which expects to create an extra // property that will catch all the unbound properties during deserialization. var name = "additionalProperties"; var propertyType = New<DictionaryType>(new { ValueType = _schema.AdditionalProperties.GetBuilder(Modeler).BuildServiceType( _schema.AdditionalProperties.Reference != null ? _schema.AdditionalProperties.Reference.StripDefinitionPath() : serviceTypeName + "Value"), Extensions = _schema.AdditionalProperties.Extensions, SupportsAdditionalProperties = true }); // now add the extra property to the type. objectType.Add(New<Property>(new { Name = name, ModelType = propertyType, Documentation = "Unmatched properties from the message are deserialized this collection", XmlProperties = _schema.AdditionalProperties.Xml, RealPath = new string[0] })); } if (_schema.Properties != null) { // Visit each property and recursively build service types foreach (var property in _schema.Properties) { string name = property.Key; if (name != _schema.Discriminator) { string propertyServiceTypeName; Schema refSchema = null; if (property.Value.ReadOnly && property.Value.IsRequired) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, Resources.ReadOnlyNotRequired, name, serviceTypeName)); } if (property.Value.Reference != null) { propertyServiceTypeName = property.Value.Reference.StripDefinitionPath(); var unwrappedSchema = Modeler.Resolver.Unwrap(property.Value); // For Enums use the referenced schema in order to set the correct property Type and Enum values if (unwrappedSchema.Enum != null) { refSchema = new Schema().LoadFrom(unwrappedSchema); if (property.Value.IsRequired) { refSchema.IsRequired = property.Value.IsRequired; } //Todo: Remove the following when referenced descriptions are correctly ignored (Issue https://github.com/Azure/autorest/issues/1283) refSchema.Description = property.Value.Description; } } else { propertyServiceTypeName = serviceTypeName + "_" + property.Key; } var propertyType = refSchema != null ? refSchema.GetBuilder(Modeler).BuildServiceType(propertyServiceTypeName) : property.Value.GetBuilder(Modeler).BuildServiceType(propertyServiceTypeName); var propertyObj = New<Property>(new { Name = name, SerializedName = name, RealPath = new string[] { name }, ModelType = propertyType, IsReadOnly = property.Value.ReadOnly, Summary = property.Value.Title, XmlProperties = property.Value.Xml }); PopulateParameter(propertyObj, refSchema != null ? refSchema : property.Value); var propertyCompositeType = propertyType as CompositeType; if (propertyObj.IsConstant || (propertyCompositeType != null && propertyCompositeType.ContainsConstantProperties)) { objectType.ContainsConstantProperties = true; } objectType.Add(propertyObj); } else { objectType.PolymorphicDiscriminator = name; } } } // Copy over extensions _schema.Extensions.ForEach(e => objectType.Extensions[e.Key] = e.Value); // Optionally override the discriminator value for polymorphic types. We expect this concept to be // added to Swagger at some point, but until it is, we use an extension. object discriminatorValueExtension; if (objectType.Extensions.TryGetValue(DiscriminatorValueExtension, out discriminatorValueExtension)) { string discriminatorValue = discriminatorValueExtension as string; if (discriminatorValue != null) { objectType.SerializedName = discriminatorValue; } } if (_schema.Extends != null) { // Put this in the extended type serializationProperty for building method return type in the end Modeler.ExtendedTypes[serviceTypeName] = _schema.Extends.StripDefinitionPath(); } // Put this in already generated types serializationProperty string localName = serviceTypeName; while (Modeler.GeneratedTypes.ContainsKey(localName)) { var existing = Modeler.GeneratedTypes[localName]; if (objectType.StructurallyEquals(existing)) { objectType = existing; break; } localName = localName + "_"; } Modeler.GeneratedTypes[localName] = objectType; // xml properties objectType.XmlProperties = _schema.Xml; return objectType; } public override IModelType ParentBuildServiceType(string serviceTypeName) { return base.BuildServiceType(serviceTypeName); } } }
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using System.Collections.Immutable; using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Nullaby; using RefactoringEssentials.Util.Analysis; namespace RefactoringEssentials.CSharp.Diagnostics { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class FunctionNeverReturnsAnalyzer : DiagnosticAnalyzer { static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( CSharpDiagnosticIDs.FunctionNeverReturnsAnalyzerID, GettextCatalog.GetString("Function does not reach its end or a 'return' statement by any of possible execution paths"), GettextCatalog.GetString("{0} never reaches end or a 'return' statement"), DiagnosticAnalyzerCategories.CodeQualityIssues, DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.FunctionNeverReturnsAnalyzerID) ); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCompilationStartAction(compilationContext => { var compilation = compilationContext.Compilation; compilationContext.RegisterSyntaxTreeAction(async delegate (SyntaxTreeAnalysisContext ctx) { try { if (!compilation.SyntaxTrees.Contains(ctx.Tree)) return; var semanticModel = compilation.GetSemanticModel(ctx.Tree); var root = await ctx.Tree.GetRootAsync(ctx.CancellationToken).ConfigureAwait(false); var model = compilationContext.Compilation.GetSemanticModel(ctx.Tree); if (model.IsFromGeneratedCode(compilationContext.CancellationToken)) return; new GatherVisitor(ctx, semanticModel).Visit(root); } catch (OperationCanceledException) { } }); }); } class GatherVisitor : CSharpSyntaxWalker { readonly SyntaxTreeAnalysisContext context; readonly SemanticModel semanticModel; public GatherVisitor(SyntaxTreeAnalysisContext context, SemanticModel semanticModel) { this.context = context; this.semanticModel = semanticModel; } public override void VisitBlock(Microsoft.CodeAnalysis.CSharp.Syntax.BlockSyntax node) { context.CancellationToken.ThrowIfCancellationRequested(); base.VisitBlock(node); } public override void VisitInterfaceDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.InterfaceDeclarationSyntax node) { // nothing to analyze here } public override void VisitMethodDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.MethodDeclarationSyntax node) { base.VisitMethodDeclaration(node); var body = node.Body; // partial/abstract method if (body == null) return; VisitBody("Method", node.Identifier, body, semanticModel.GetDeclaredSymbol(node)); } public override void VisitAnonymousMethodExpression(Microsoft.CodeAnalysis.CSharp.Syntax.AnonymousMethodExpressionSyntax node) { base.VisitAnonymousMethodExpression(node); VisitBody("Delegate", node.DelegateKeyword, node.Body as StatementSyntax, null); } public override void VisitSimpleLambdaExpression(Microsoft.CodeAnalysis.CSharp.Syntax.SimpleLambdaExpressionSyntax node) { base.VisitSimpleLambdaExpression(node); VisitBody("Lambda expression", node.ArrowToken, node.Body as StatementSyntax, null); } public override void VisitParenthesizedLambdaExpression(Microsoft.CodeAnalysis.CSharp.Syntax.ParenthesizedLambdaExpressionSyntax node) { base.VisitParenthesizedLambdaExpression(node); VisitBody("Lambda expression", node.ArrowToken, node.Body as StatementSyntax, null); } public override void VisitAccessorDeclaration(Microsoft.CodeAnalysis.CSharp.Syntax.AccessorDeclarationSyntax node) { base.VisitAccessorDeclaration(node); if (node.Body == null) return; VisitBody("Accessor", node.Keyword, node.Body, semanticModel.GetDeclaredSymbol(node.Parent.Parent), node.Kind()); } void VisitBody(string entityType, SyntaxToken markerToken, StatementSyntax body, ISymbol symbol, SyntaxKind accessorKind = SyntaxKind.UnknownAccessorDeclaration) { if (body == null) return; var recursiveDetector = new RecursiveDetector(semanticModel, symbol, accessorKind); var reachability = ReachabilityAnalysis.Create((StatementSyntax)body, this.semanticModel, recursiveDetector, context.CancellationToken); bool hasReachableReturn = false; foreach (var statement in reachability.ReachableStatements) { if (statement.IsKind(SyntaxKind.ReturnStatement) || statement.IsKind(SyntaxKind.ThrowStatement) || statement.IsKind(SyntaxKind.YieldBreakStatement)) { if (!recursiveDetector.Visit(statement)) { hasReachableReturn = true; break; } } } if (!hasReachableReturn && !reachability.IsEndpointReachable(body)) { context.ReportDiagnostic(Diagnostic.Create( descriptor, markerToken.GetLocation(), entityType )); } } class RecursiveDetector : ReachabilityAnalysis.RecursiveDetectorVisitor { SemanticModel ctx; ISymbol member; SyntaxKind accessorRole; internal RecursiveDetector(SemanticModel ctx, ISymbol member, SyntaxKind accessorRole) { this.ctx = ctx; this.member = member; this.accessorRole = accessorRole; } public override bool DefaultVisit(SyntaxNode node) { foreach (var child in node.ChildNodes()) { if (Visit(child)) return true; } return false; } public override bool VisitBinaryExpression(BinaryExpressionSyntax node) { switch (node.Kind()) { case SyntaxKind.LogicalAndExpression: case SyntaxKind.LogicalOrExpression: return Visit(node.Left); } return base.VisitBinaryExpression(node); } public override bool VisitAssignmentExpression(AssignmentExpressionSyntax node) { if (accessorRole != SyntaxKind.UnknownAccessorDeclaration) { if (accessorRole == SyntaxKind.SetAccessorDeclaration) { return Visit(node.Left); } return Visit(node.Right); } return base.VisitAssignmentExpression(node); } public override bool VisitAnonymousMethodExpression(AnonymousMethodExpressionSyntax node) { return false; } public override bool VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax node) { return false; } public override bool VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) { return false; } public override bool VisitIdentifierName(IdentifierNameSyntax node) { return CheckRecursion(node); } public override bool VisitMemberAccessExpression(MemberAccessExpressionSyntax node) { if (base.VisitMemberAccessExpression(node)) return true; return CheckRecursion(node); } public override bool VisitInvocationExpression(InvocationExpressionSyntax node) { if (base.VisitInvocationExpression(node)) return true; return CheckRecursion(node); } bool CheckRecursion(SyntaxNode node) { if (member == null) { return false; } var resolveResult = ctx.GetSymbolInfo(node); //We'll ignore Method groups here //If the invocation expressions will be dealt with later anyway //and properties are never in "method groups". var memberResolveResult = resolveResult.Symbol; if (memberResolveResult == null || memberResolveResult != this.member) { return false; } //Now check for virtuals if (memberResolveResult.IsVirtual && !memberResolveResult.ContainingType.IsSealed) { return false; } var parentAssignment = node.Parent as AssignmentExpressionSyntax; if (parentAssignment != null) { if (accessorRole == SyntaxKind.AddAccessorDeclaration) { return parentAssignment.IsKind(SyntaxKind.AddAssignmentExpression); } if (accessorRole == SyntaxKind.RemoveAccessorDeclaration) { return parentAssignment.IsKind(SyntaxKind.SubtractAssignmentExpression); } if (accessorRole == SyntaxKind.GetAccessorDeclaration) { return !parentAssignment.IsKind(SyntaxKind.SimpleAssignmentExpression); } return true; } if (node.Parent.IsKind(SyntaxKind.PreIncrementExpression) || node.Parent.IsKind(SyntaxKind.PreDecrementExpression) || node.Parent.IsKind(SyntaxKind.PostIncrementExpression) || node.Parent.IsKind(SyntaxKind.PostDecrementExpression)) { return true; } return accessorRole == SyntaxKind.UnknownAccessorDeclaration || accessorRole == SyntaxKind.GetAccessorDeclaration; } } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace OKTAIntegration.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Metadata; using Avalonia.Threading; using System; namespace WalletWasabi.Gui.Controls { public class EditableTextBlock : TemplatedControl { private string _text; private string _editText; private TextBox _textBox; private IInputRoot _root; public static readonly DirectProperty<EditableTextBlock, string> TextProperty = TextBlock.TextProperty.AddOwner<EditableTextBlock>(o => o.Text, (o, v) => o.Text = v, defaultBindingMode: BindingMode.TwoWay, enableDataValidation: true); public static readonly DirectProperty<EditableTextBlock, string> EditTextProperty = AvaloniaProperty.RegisterDirect<EditableTextBlock, string>(nameof(EditText), o => o.EditText, (o, v) => o.EditText = v); public static readonly StyledProperty<bool> InEditModeProperty = AvaloniaProperty.Register<EditableTextBlock, bool>(nameof(InEditMode), defaultBindingMode: BindingMode.TwoWay); public static readonly StyledProperty<bool> ReadModeProperty = AvaloniaProperty.Register<EditableTextBlock, bool>(nameof(ReadMode), defaultValue: true, defaultBindingMode: BindingMode.TwoWay); public static readonly StyledProperty<bool> ReadOnlyModeProperty = AvaloniaProperty.Register<EditableTextBlock, bool>(nameof(ReadOnlyMode), defaultValue: true, defaultBindingMode: BindingMode.TwoWay); static EditableTextBlock() { PseudoClass<EditableTextBlock>(InEditModeProperty, ":editing"); } public EditableTextBlock() { EditClickTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(500) }; EditClickTimer.Tick += (sender, e) => { EditClickTimer.Stop(); if (IsFocused && !InEditMode) { EnterEditMode(); } }; this.GetObservable(TextProperty).Subscribe(t => EditText = t); this.GetObservable(InEditModeProperty).Subscribe(mode => { if (mode && _textBox is { }) { EnterEditMode(); } }); AddHandler( PointerPressedEvent, (sender, e) => { EditClickTimer.Stop(); if (!InEditMode) { #pragma warning disable CS0618 // Type or member is obsolete if (e.ClickCount == 1 && e.GetCurrentPoint(this).Properties.IsLeftButtonPressed && IsFocused) #pragma warning restore CS0618 // Type or member is obsolete { EditClickTimer.Start(); } } else { var hit = this.InputHitTest(e.GetPosition(this)); if (hit is null) { ExitEditMode(); } else { e.GetCurrentPoint(this).Pointer.Capture(_textBox); } } }, RoutingStrategies.Tunnel); AddHandler( PointerReleasedEvent, (sender, e) => { if (InEditMode) { var hit = this.InputHitTest(e.GetPosition(this)); if (hit is null) { ExitEditMode(); } else { e.GetCurrentPoint(this).Pointer.Capture(_textBox); } } }, RoutingStrategies.Tunnel); } private DispatcherTimer EditClickTimer { get; } [Content] public string Text { get => _text; set => SetAndRaise(TextProperty, ref _text, value); } public string EditText { get => _editText; set => SetAndRaise(EditTextProperty, ref _editText, value); } public bool InEditMode { get => GetValue(InEditModeProperty); set => SetValue(InEditModeProperty, value); } public bool ReadMode { get => GetValue(ReadModeProperty); set => SetValue(ReadModeProperty, value); } public bool ReadOnlyMode { get => GetValue(ReadOnlyModeProperty); set => SetValue(ReadOnlyModeProperty, value); } protected override void OnTemplateApplied(TemplateAppliedEventArgs e) { base.OnTemplateApplied(e); _textBox = e.NameScope.Find<TextBox>("PART_TextBox"); if (InEditMode) { EnterEditMode(); } } protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e) { base.OnAttachedToVisualTree(e); _root = e.Root as IInputRoot; } protected override void OnKeyUp(KeyEventArgs e) { switch (e.Key) { case Key.Enter: ExitEditMode(); e.Handled = true; break; case Key.Escape: ExitEditMode(true); e.Handled = true; break; } base.OnKeyUp(e); } private void EnterEditMode() { if (!ReadOnlyMode) { EditText = Text; ReadMode = false; InEditMode = true; #pragma warning disable CS0618 // Type or member is obsolete _root.MouseDevice.Capture(_textBox); #pragma warning restore CS0618 // Type or member is obsolete _textBox.SelectionStart = 0; _textBox.SelectionEnd = Text.Length; _textBox.CaretIndex = Text.Length; Dispatcher.UIThread.InvokeAsync(() => _textBox.Focus()); } else { InEditMode = false; } } private void ExitEditMode(bool restore = false) { if (!restore) { Text = EditText; } InEditMode = false; ReadMode = true; #pragma warning disable CS0618 // Type or member is obsolete _root.MouseDevice.Capture(null); #pragma warning restore CS0618 // Type or member is obsolete } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ #if FEATURE_CORE_DLR using System.Linq.Expressions; using System.Numerics; #else using Microsoft.Scripting.Ast; using Microsoft.Scripting.Math; using Complex = Microsoft.Scripting.Math.Complex64; #endif using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Dynamic; using System.Linq; using System.Reflection; using System.Threading; using Microsoft.Scripting; using Microsoft.Scripting.Actions; using Microsoft.Scripting.Actions.Calls; using Microsoft.Scripting.Generation; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronPython.Runtime.Exceptions; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; namespace IronPython.Runtime.Binding { using Ast = Expression; using AstUtils = Microsoft.Scripting.Ast.Utils; partial class PythonBinder : DefaultBinder { private PythonContext/*!*/ _context; private SlotCache/*!*/ _typeMembers = new SlotCache(); private SlotCache/*!*/ _resolvedMembers = new SlotCache(); private Dictionary<Type/*!*/, IList<Type/*!*/>/*!*/>/*!*/ _dlrExtensionTypes; private bool _registeredInterfaceExtensions; // true if someone has registered extensions for interfaces [MultiRuntimeAware] private static readonly Dictionary<Type/*!*/, ExtensionTypeInfo/*!*/>/*!*/ _sysTypes = MakeSystemTypes(); public PythonBinder(PythonContext/*!*/ pythonContext, CodeContext context) { ContractUtils.RequiresNotNull(pythonContext, "pythonContext"); _dlrExtensionTypes = MakeExtensionTypes(); _context = pythonContext; if (context != null) { context.LanguageContext.DomainManager.AssemblyLoaded += new EventHandler<AssemblyLoadedEventArgs>(DomainManager_AssemblyLoaded); foreach (Assembly asm in pythonContext.DomainManager.GetLoadedAssemblyList()) { DomainManager_AssemblyLoaded(this, new AssemblyLoadedEventArgs(asm)); } } } public PythonBinder(PythonBinder binder) { _context = binder._context; _typeMembers = binder._typeMembers; _resolvedMembers = binder._resolvedMembers; _dlrExtensionTypes = binder._dlrExtensionTypes; _registeredInterfaceExtensions = binder._registeredInterfaceExtensions; } public override Expression/*!*/ ConvertExpression(Expression/*!*/ expr, Type/*!*/ toType, ConversionResultKind kind, OverloadResolverFactory factory) { ContractUtils.RequiresNotNull(expr, "expr"); ContractUtils.RequiresNotNull(toType, "toType"); Type exprType = expr.Type; if (toType == typeof(object)) { if (exprType.IsValueType()) { return AstUtils.Convert(expr, toType); } else { return expr; } } if (toType.IsAssignableFrom(exprType)) { return expr; } Type visType = Context.Binder.PrivateBinding ? toType : CompilerHelpers.GetVisibleType(toType); if (exprType == typeof(PythonType) && visType == typeof(Type)) { return AstUtils.Convert(expr, visType); // use the implicit conversion } return Binders.Convert( ((PythonOverloadResolverFactory)factory)._codeContext, _context, visType, visType == typeof(char) ? ConversionResultKind.ImplicitCast : kind, expr ); } internal static MethodInfo GetGenericConvertMethod(Type toType) { if (toType.IsValueType()) { if (toType.IsGenericType() && toType.GetGenericTypeDefinition() == typeof(Nullable<>)) { return typeof(Converter).GetMethod("ConvertToNullableType"); } else { return typeof(Converter).GetMethod("ConvertToValueType"); } } else { return typeof(Converter).GetMethod("ConvertToReferenceType"); } } internal static MethodInfo GetFastConvertMethod(Type toType) { if (toType == typeof(char)) { return typeof(Converter).GetMethod("ConvertToChar"); } else if (toType == typeof(int)) { return typeof(Converter).GetMethod("ConvertToInt32"); } else if (toType == typeof(string)) { return typeof(Converter).GetMethod("ConvertToString"); } else if (toType == typeof(long)) { return typeof(Converter).GetMethod("ConvertToInt64"); } else if (toType == typeof(double)) { return typeof(Converter).GetMethod("ConvertToDouble"); } else if (toType == typeof(bool)) { return typeof(Converter).GetMethod("ConvertToBoolean"); } else if (toType == typeof(BigInteger)) { return typeof(Converter).GetMethod("ConvertToBigInteger"); } else if (toType == typeof(Complex)) { return typeof(Converter).GetMethod("ConvertToComplex"); } else if (toType == typeof(IEnumerable)) { return typeof(Converter).GetMethod("ConvertToIEnumerable"); } else if (toType == typeof(float)) { return typeof(Converter).GetMethod("ConvertToSingle"); } else if (toType == typeof(byte)) { return typeof(Converter).GetMethod("ConvertToByte"); } else if (toType == typeof(sbyte)) { return typeof(Converter).GetMethod("ConvertToSByte"); } else if (toType == typeof(short)) { return typeof(Converter).GetMethod("ConvertToInt16"); } else if (toType == typeof(uint)) { return typeof(Converter).GetMethod("ConvertToUInt32"); } else if (toType == typeof(ulong)) { return typeof(Converter).GetMethod("ConvertToUInt64"); } else if (toType == typeof(ushort)) { return typeof(Converter).GetMethod("ConvertToUInt16"); } else if (toType == typeof(Type)) { return typeof(Converter).GetMethod("ConvertToType"); } else { return null; } } public override object Convert(object obj, Type toType) { return Converter.Convert(obj, toType); } public override bool CanConvertFrom(Type fromType, Type toType, bool toNotNullable, NarrowingLevel level) { return Converter.CanConvertFrom(fromType, toType, level); } public override Candidate PreferConvert(Type t1, Type t2) { return Converter.PreferConvert(t1, t2); } public override bool PrivateBinding { get { return _context.DomainManager.Configuration.PrivateBinding; } } public override ErrorInfo MakeSetValueTypeFieldError(FieldTracker field, DynamicMetaObject instance, DynamicMetaObject value) { // allow the set but emit a warning return ErrorInfo.FromValueNoError( Expression.Block( Expression.Call( typeof(PythonOps).GetMethod("Warn"), Expression.Constant(_context.SharedContext), Expression.Constant(PythonExceptions.RuntimeWarning), Expression.Constant(ReflectedField.UpdateValueTypeFieldWarning), Expression.Constant( new object[] { field.Name, field.DeclaringType.Name } ) ), Expression.Assign( Expression.Field( AstUtils.Convert( instance.Expression, field.DeclaringType ), field.Field ), ConvertExpression( value.Expression, field.FieldType, ConversionResultKind.ExplicitCast, new PythonOverloadResolverFactory( this, Expression.Constant(_context.SharedContext) ) ) ) ) ); } public override ErrorInfo MakeConversionError(Type toType, Expression value) { return ErrorInfo.FromException( Ast.Call( typeof(PythonOps).GetMethod("TypeErrorForTypeMismatch"), AstUtils.Constant(DynamicHelpers.GetPythonTypeFromType(toType).Name), AstUtils.Convert(value, typeof(object)) ) ); } public override ErrorInfo/*!*/ MakeNonPublicMemberGetError(OverloadResolverFactory resolverFactory, MemberTracker member, Type type, DynamicMetaObject instance) { if (PrivateBinding) { return base.MakeNonPublicMemberGetError(resolverFactory, member, type, instance); } return ErrorInfo.FromValue( BindingHelpers.TypeErrorForProtectedMember(type, member.Name) ); } public override ErrorInfo/*!*/ MakeStaticAssignFromDerivedTypeError(Type accessingType, DynamicMetaObject instance, MemberTracker info, DynamicMetaObject assignedValue, OverloadResolverFactory factory) { return MakeMissingMemberError(accessingType, instance, info.Name); } public override ErrorInfo/*!*/ MakeStaticPropertyInstanceAccessError(PropertyTracker/*!*/ tracker, bool isAssignment, IList<DynamicMetaObject>/*!*/ parameters) { ContractUtils.RequiresNotNull(tracker, "tracker"); ContractUtils.RequiresNotNull(parameters, "parameters"); if (isAssignment) { return ErrorInfo.FromException( Ast.Call( typeof(PythonOps).GetMethod("StaticAssignmentFromInstanceError"), AstUtils.Constant(tracker), AstUtils.Constant(isAssignment) ) ); } return ErrorInfo.FromValue( Ast.Property( null, tracker.GetGetMethod(DomainManager.Configuration.PrivateBinding) ) ); } #region .NET member binding public override string GetTypeName(Type t) { return DynamicHelpers.GetPythonTypeFromType(t).Name; } public override MemberGroup/*!*/ GetMember(MemberRequestKind actionKind, Type type, string name) { MemberGroup mg; if (!_resolvedMembers.TryGetCachedMember(type, name, actionKind == MemberRequestKind.Get, out mg)) { mg = PythonTypeInfo.GetMemberAll( this, actionKind, type, name); _resolvedMembers.CacheSlot(type, actionKind == MemberRequestKind.Get, name, PythonTypeOps.GetSlot(mg, name, PrivateBinding), mg); } return mg ?? MemberGroup.EmptyGroup; } public override ErrorInfo/*!*/ MakeEventValidation(MemberGroup/*!*/ members, DynamicMetaObject eventObject, DynamicMetaObject/*!*/ value, OverloadResolverFactory/*!*/ factory) { EventTracker ev = (EventTracker)members[0]; return ErrorInfo.FromValueNoError( Ast.Block( Ast.Call( typeof(PythonOps).GetMethod("SlotTrySetValue"), ((PythonOverloadResolverFactory)factory)._codeContext, AstUtils.Constant(PythonTypeOps.GetReflectedEvent(ev)), eventObject != null ? AstUtils.Convert(eventObject.Expression, typeof(object)) : AstUtils.Constant(null), AstUtils.Constant(null, typeof(PythonType)), AstUtils.Convert(value.Expression, typeof(object)) ), Ast.Constant(null) ) ); } public override ErrorInfo MakeMissingMemberError(Type type, DynamicMetaObject self, string name) { string typeName; if (typeof(TypeTracker).IsAssignableFrom(type)) { typeName = "type"; } else { typeName = NameConverter.GetTypeName(type); } return ErrorInfo.FromException( Ast.New( typeof(MissingMemberException).GetConstructor(new Type[] { typeof(string) }), AstUtils.Constant(String.Format("'{0}' object has no attribute '{1}'", typeName, name)) ) ); } public override ErrorInfo MakeMissingMemberErrorForAssign(Type type, DynamicMetaObject self, string name) { if (self != null) { return MakeMissingMemberError(type, self, name); } return ErrorInfo.FromException( Ast.New( typeof(TypeErrorException).GetConstructor(new Type[] { typeof(string) }), AstUtils.Constant(String.Format("can't set attributes of built-in/extension type '{0}'", NameConverter.GetTypeName(type))) ) ); } public override ErrorInfo MakeMissingMemberErrorForAssignReadOnlyProperty(Type type, DynamicMetaObject self, string name) { return ErrorInfo.FromException( Ast.New( typeof(MissingMemberException).GetConstructor(new Type[] { typeof(string) }), AstUtils.Constant(String.Format("can't assign to read-only property {0} of type '{1}'", name, NameConverter.GetTypeName(type))) ) ); } public override ErrorInfo MakeMissingMemberErrorForDelete(Type type, DynamicMetaObject self, string name) { return MakeMissingMemberErrorForAssign(type, self, name); } /// <summary> /// Provides a way for the binder to provide a custom error message when lookup fails. Just /// doing this for the time being until we get a more robust error return mechanism. /// </summary> public override ErrorInfo MakeReadOnlyMemberError(Type type, string name) { return ErrorInfo.FromException( Ast.New( typeof(MissingMemberException).GetConstructor(new Type[] { typeof(string) }), AstUtils.Constant( String.Format("attribute '{0}' of '{1}' object is read-only", name, NameConverter.GetTypeName(type) ) ) ) ); } /// <summary> /// Provides a way for the binder to provide a custom error message when lookup fails. Just /// doing this for the time being until we get a more robust error return mechanism. /// </summary> public override ErrorInfo MakeUndeletableMemberError(Type type, string name) { return ErrorInfo.FromException( Ast.New( typeof(MissingMemberException).GetConstructor(new Type[] { typeof(string) }), AstUtils.Constant( String.Format("cannot delete attribute '{0}' of builtin type '{1}'", name, NameConverter.GetTypeName(type) ) ) ) ); } #endregion internal IList<Type> GetExtensionTypesInternal(Type t) { List<Type> res = new List<Type>(base.GetExtensionTypes(t)); AddExtensionTypes(t, res); return res.ToArray(); } public override bool IncludeExtensionMember(MemberInfo member) { return !member.DeclaringType.GetTypeInfo().IsDefined(typeof(PythonHiddenBaseClassAttribute), false); } public override IList<Type> GetExtensionTypes(Type t) { List<Type> list = new List<Type>(); // Python includes the types themselves so we can use extension properties w/ CodeContext list.Add(t); list.AddRange(base.GetExtensionTypes(t)); AddExtensionTypes(t, list); return list; } private void AddExtensionTypes(Type t, List<Type> list) { ExtensionTypeInfo extType; if (_sysTypes.TryGetValue(t, out extType)) { list.Add(extType.ExtensionType); } IList<Type> userExtensions; lock (_dlrExtensionTypes) { if (_dlrExtensionTypes.TryGetValue(t, out userExtensions)) { list.AddRange(userExtensions); } if (_registeredInterfaceExtensions) { foreach (Type ifaceType in t.GetInterfaces()) { IList<Type> extTypes; if (_dlrExtensionTypes.TryGetValue(ifaceType, out extTypes)) { list.AddRange(extTypes); } } } if (t.IsGenericType()) { // search for generic extensions, e.g. ListOfTOps<T> for List<T>, // we then make a new generic type out of the extension type. Type typeDef = t.GetGenericTypeDefinition(); Type[] args = t.GetGenericArguments(); if (_dlrExtensionTypes.TryGetValue(typeDef, out userExtensions)) { foreach (Type genExtType in userExtensions) { list.Add(genExtType.MakeGenericType(args)); } } } } } public bool HasExtensionTypes(Type t) { return _dlrExtensionTypes.ContainsKey(t); } public override DynamicMetaObject ReturnMemberTracker(Type type, MemberTracker memberTracker) { var res = ReturnMemberTracker(type, memberTracker, PrivateBinding); return res ?? base.ReturnMemberTracker(type, memberTracker); } private static DynamicMetaObject ReturnMemberTracker(Type type, MemberTracker memberTracker, bool privateBinding) { switch (memberTracker.MemberType) { case TrackerTypes.TypeGroup: return new DynamicMetaObject(AstUtils.Constant(memberTracker), BindingRestrictions.Empty, memberTracker); case TrackerTypes.Type: return ReturnTypeTracker((TypeTracker)memberTracker); case TrackerTypes.Bound: return new DynamicMetaObject(ReturnBoundTracker((BoundMemberTracker)memberTracker, privateBinding), BindingRestrictions.Empty); case TrackerTypes.Property: return new DynamicMetaObject(ReturnPropertyTracker((PropertyTracker)memberTracker, privateBinding), BindingRestrictions.Empty);; case TrackerTypes.Event: return new DynamicMetaObject(Ast.Call( typeof(PythonOps).GetMethod("MakeBoundEvent"), AstUtils.Constant(PythonTypeOps.GetReflectedEvent((EventTracker)memberTracker)), AstUtils.Constant(null), AstUtils.Constant(type) ), BindingRestrictions.Empty);; case TrackerTypes.Field: return new DynamicMetaObject(ReturnFieldTracker((FieldTracker)memberTracker), BindingRestrictions.Empty);; case TrackerTypes.MethodGroup: return new DynamicMetaObject(ReturnMethodGroup((MethodGroup)memberTracker), BindingRestrictions.Empty); ; case TrackerTypes.Constructor: MethodBase[] ctors = CompilerHelpers.GetConstructors(type, privateBinding, true); object val; if (PythonTypeOps.IsDefaultNew(ctors)) { if (IsPythonType(type)) { val = InstanceOps.New; } else { val = InstanceOps.NewCls; } } else { val = PythonTypeOps.GetConstructor(type, InstanceOps.NonDefaultNewInst, ctors); } return new DynamicMetaObject(AstUtils.Constant(val), BindingRestrictions.Empty, val); case TrackerTypes.Custom: return new DynamicMetaObject( AstUtils.Constant(((PythonCustomTracker)memberTracker).GetSlot(), typeof(PythonTypeSlot)), BindingRestrictions.Empty, ((PythonCustomTracker)memberTracker).GetSlot() ); } return null; } /// <summary> /// Gets the PythonBinder associated with tihs CodeContext /// </summary> public static PythonBinder/*!*/ GetBinder(CodeContext/*!*/ context) { return (PythonBinder)PythonContext.GetContext(context).Binder; } /// <summary> /// Performs .NET member resolution. This looks within the given type and also /// includes any extension members. Base classes and their extension members are /// not searched. /// </summary> public bool TryLookupSlot(CodeContext/*!*/ context, PythonType/*!*/ type, string name, out PythonTypeSlot slot) { Debug.Assert(type.IsSystemType); return TryLookupProtectedSlot(context, type, name, out slot); } /// <summary> /// Performs .NET member resolution. This looks within the given type and also /// includes any extension members. Base classes and their extension members are /// not searched. /// /// This version allows PythonType's for protected member resolution. It shouldn't /// be called externally for other purposes. /// </summary> internal bool TryLookupProtectedSlot(CodeContext/*!*/ context, PythonType/*!*/ type, string name, out PythonTypeSlot slot) { Type curType = type.UnderlyingSystemType; if (!_typeMembers.TryGetCachedSlot(curType, true, name, out slot)) { MemberGroup mg = PythonTypeInfo.GetMember( this, MemberRequestKind.Get, curType, name); slot = PythonTypeOps.GetSlot(mg, name, PrivateBinding); _typeMembers.CacheSlot(curType, true, name, slot, mg); } if (slot != null && (slot.IsAlwaysVisible || PythonOps.IsClsVisible(context))) { return true; } slot = null; return false; } /// <summary> /// Performs .NET member resolution. This looks the type and any base types /// for members. It also searches for extension members in the type and any base types. /// </summary> public bool TryResolveSlot(CodeContext/*!*/ context, PythonType/*!*/ type, PythonType/*!*/ owner, string name, out PythonTypeSlot slot) { Type curType = type.UnderlyingSystemType; if (!_resolvedMembers.TryGetCachedSlot(curType, true, name, out slot)) { MemberGroup mg = PythonTypeInfo.GetMemberAll( this, MemberRequestKind.Get, curType, name); slot = PythonTypeOps.GetSlot(mg, name, PrivateBinding); _resolvedMembers.CacheSlot(curType, true, name, slot, mg); } if (slot != null && (slot.IsAlwaysVisible || PythonOps.IsClsVisible(context))) { return true; } slot = null; return false; } /// <summary> /// Gets the member names which are defined in this type and any extension members. /// /// This search does not include members in any subtypes or their extension members. /// </summary> public void LookupMembers(CodeContext/*!*/ context, PythonType/*!*/ type, PythonDictionary/*!*/ memberNames) { if (!_typeMembers.IsFullyCached(type.UnderlyingSystemType, true)) { Dictionary<string, KeyValuePair<PythonTypeSlot, MemberGroup>> members = new Dictionary<string, KeyValuePair<PythonTypeSlot, MemberGroup>>(); foreach (ResolvedMember rm in PythonTypeInfo.GetMembers( this, MemberRequestKind.Get, type.UnderlyingSystemType)) { if (!members.ContainsKey(rm.Name)) { members[rm.Name] = new KeyValuePair<PythonTypeSlot, MemberGroup>( PythonTypeOps.GetSlot(rm.Member, rm.Name, PrivateBinding), rm.Member ); } } _typeMembers.CacheAll(type.UnderlyingSystemType, true, members); } foreach (KeyValuePair<string, PythonTypeSlot> kvp in _typeMembers.GetAllMembers(type.UnderlyingSystemType, true)) { PythonTypeSlot slot = kvp.Value; string name = kvp.Key; if (slot.IsAlwaysVisible || PythonOps.IsClsVisible(context)) { memberNames[name] = slot; } } } /// <summary> /// Gets the member names which are defined in the type and any subtypes. /// /// This search includes members in the type and any subtypes as well as extension /// types of the type and its subtypes. /// </summary> public void ResolveMemberNames(CodeContext/*!*/ context, PythonType/*!*/ type, PythonType/*!*/ owner, Dictionary<string, string>/*!*/ memberNames) { if (!_resolvedMembers.IsFullyCached(type.UnderlyingSystemType, true)) { Dictionary<string, KeyValuePair<PythonTypeSlot, MemberGroup>> members = new Dictionary<string, KeyValuePair<PythonTypeSlot, MemberGroup>>(); foreach (ResolvedMember rm in PythonTypeInfo.GetMembersAll( this, MemberRequestKind.Get, type.UnderlyingSystemType)) { if (!members.ContainsKey(rm.Name)) { members[rm.Name] = new KeyValuePair<PythonTypeSlot, MemberGroup>( PythonTypeOps.GetSlot(rm.Member, rm.Name, PrivateBinding), rm.Member ); } } _resolvedMembers.CacheAll(type.UnderlyingSystemType, true, members); } foreach (KeyValuePair<string, PythonTypeSlot> kvp in _resolvedMembers.GetAllMembers(type.UnderlyingSystemType, true)) { PythonTypeSlot slot = kvp.Value; string name = kvp.Key; if (slot.IsAlwaysVisible || PythonOps.IsClsVisible(context)) { memberNames[name] = name; } } } private static Expression ReturnFieldTracker(FieldTracker fieldTracker) { return AstUtils.Constant(PythonTypeOps.GetReflectedField(fieldTracker.Field)); } private static Expression ReturnMethodGroup(MethodGroup methodGroup) { return AstUtils.Constant(PythonTypeOps.GetFinalSlotForFunction(GetBuiltinFunction(methodGroup))); } private static Expression ReturnBoundTracker(BoundMemberTracker boundMemberTracker, bool privateBinding) { MemberTracker boundTo = boundMemberTracker.BoundTo; switch (boundTo.MemberType) { case TrackerTypes.Property: PropertyTracker pt = (PropertyTracker)boundTo; Debug.Assert(pt.GetIndexParameters().Length > 0); return Ast.New( typeof(ReflectedIndexer).GetConstructor(new Type[] { typeof(ReflectedIndexer), typeof(object) }), AstUtils.Constant(new ReflectedIndexer(((ReflectedPropertyTracker)pt).Property, NameType.Property, privateBinding)), boundMemberTracker.Instance.Expression ); case TrackerTypes.Event: return Ast.Call( typeof(PythonOps).GetMethod("MakeBoundEvent"), AstUtils.Constant(PythonTypeOps.GetReflectedEvent((EventTracker)boundMemberTracker.BoundTo)), boundMemberTracker.Instance.Expression, AstUtils.Constant(boundMemberTracker.DeclaringType) ); case TrackerTypes.MethodGroup: return Ast.Call( typeof(PythonOps).GetMethod("MakeBoundBuiltinFunction"), AstUtils.Constant(GetBuiltinFunction((MethodGroup)boundTo)), AstUtils.Convert( boundMemberTracker.Instance.Expression, typeof(object) ) ); } throw new NotImplementedException(); } private static BuiltinFunction GetBuiltinFunction(MethodGroup mg) { MethodBase[] methods = new MethodBase[mg.Methods.Count]; for (int i = 0; i < mg.Methods.Count; i++) { methods[i] = mg.Methods[i].Method; } return PythonTypeOps.GetBuiltinFunction( mg.DeclaringType, mg.Methods[0].Name, (PythonTypeOps.GetMethodFunctionType(mg.DeclaringType, methods) & (~FunctionType.FunctionMethodMask)) | (mg.ContainsInstance ? FunctionType.Method : FunctionType.None) | (mg.ContainsStatic ? FunctionType.Function : FunctionType.None), mg.GetMethodBases() ); } private static Expression ReturnPropertyTracker(PropertyTracker propertyTracker, bool privateBinding) { return AstUtils.Constant(PythonTypeOps.GetReflectedProperty(propertyTracker, new MemberGroup(propertyTracker), privateBinding)); } private static DynamicMetaObject ReturnTypeTracker(TypeTracker memberTracker) { // all non-group types get exposed as PythonType's object value = DynamicHelpers.GetPythonTypeFromType(memberTracker.Type); return new DynamicMetaObject(Ast.Constant(value), BindingRestrictions.Empty, value); } internal ScriptDomainManager/*!*/ DomainManager { get { return _context.DomainManager; } } private class ExtensionTypeInfo { public Type ExtensionType; public string PythonName; public ExtensionTypeInfo(Type extensionType, string pythonName) { ExtensionType = extensionType; PythonName = pythonName; } } internal static void AssertNotExtensionType(Type t) { foreach (ExtensionTypeInfo typeinfo in _sysTypes.Values) { Debug.Assert(typeinfo.ExtensionType != t); } Debug.Assert(t != typeof(InstanceOps)); } /// <summary> /// Creates the initial table of extension types. These are standard extension that we apply /// to well known .NET types to make working with them better. Being added to this table does /// not make a type a Python type though so that it's members are generally accessible w/o an /// import clr and their type is not re-named. /// </summary> private static Dictionary<Type/*!*/, IList<Type/*!*/>/*!*/>/*!*/ MakeExtensionTypes() { Dictionary<Type, IList<Type>> res = new Dictionary<Type, IList<Type>>(); #if FEATURE_DBNULL res[typeof(DBNull)] = new Type[] { typeof(DBNullOps) }; #endif res[typeof(List<>)] = new Type[] { typeof(ListOfTOps<>) }; res[typeof(Dictionary<,>)] = new Type[] { typeof(DictionaryOfTOps<,>) }; res[typeof(Array)] = new Type[] { typeof(ArrayOps) }; res[typeof(Assembly)] = new Type[] { typeof(PythonAssemblyOps) }; res[typeof(Enum)] = new Type[] { typeof(EnumOps) }; res[typeof(Delegate)] = new Type[] { typeof(DelegateOps) }; res[typeof(Byte)] = new Type[] { typeof(ByteOps) }; res[typeof(SByte)] = new Type[] { typeof(SByteOps) }; res[typeof(Int16)] = new Type[] { typeof(Int16Ops) }; res[typeof(UInt16)] = new Type[] { typeof(UInt16Ops) }; res[typeof(UInt32)] = new Type[] { typeof(UInt32Ops) }; res[typeof(Int64)] = new Type[] { typeof(Int64Ops) }; res[typeof(UInt64)] = new Type[] { typeof(UInt64Ops) }; res[typeof(char)] = new Type[] { typeof(CharOps) }; res[typeof(decimal)] = new Type[] { typeof(DecimalOps) }; res[typeof(float)] = new Type[] { typeof(SingleOps) }; return res; } /// <summary> /// Creates a table of standard .NET types which are also standard Python types. These types have a standard /// set of extension types which are shared between all runtimes. /// </summary> private static Dictionary<Type/*!*/, ExtensionTypeInfo/*!*/>/*!*/ MakeSystemTypes() { Dictionary<Type/*!*/, ExtensionTypeInfo/*!*/> res = new Dictionary<Type, ExtensionTypeInfo>(); // Native CLR types res[typeof(object)] = new ExtensionTypeInfo(typeof(ObjectOps), "object"); res[typeof(string)] = new ExtensionTypeInfo(typeof(StringOps), "str"); res[typeof(int)] = new ExtensionTypeInfo(typeof(Int32Ops), "int"); res[typeof(bool)] = new ExtensionTypeInfo(typeof(BoolOps), "bool"); res[typeof(double)] = new ExtensionTypeInfo(typeof(DoubleOps), "float"); res[typeof(ValueType)] = new ExtensionTypeInfo(typeof(ValueType), "ValueType"); // just hiding it's methods in the inheritance hierarchy // MS.Math types res[typeof(BigInteger)] = new ExtensionTypeInfo(typeof(BigIntegerOps), "long"); res[typeof(Complex)] = new ExtensionTypeInfo(typeof(ComplexOps), "complex"); // DLR types res[typeof(DynamicNull)] = new ExtensionTypeInfo(typeof(NoneTypeOps), "NoneType"); res[typeof(IDictionary<object, object>)] = new ExtensionTypeInfo(typeof(DictionaryOps), "dict"); res[typeof(NamespaceTracker)] = new ExtensionTypeInfo(typeof(NamespaceTrackerOps), "namespace#"); res[typeof(TypeGroup)] = new ExtensionTypeInfo(typeof(TypeGroupOps), "type-collision"); res[typeof(TypeTracker)] = new ExtensionTypeInfo(typeof(TypeTrackerOps), "type-collision"); return res; } internal static string GetTypeNameInternal(Type t) { ExtensionTypeInfo extInfo; if (_sysTypes.TryGetValue(t, out extInfo)) { return extInfo.PythonName; } var attr = t.GetTypeInfo().GetCustomAttributes<PythonTypeAttribute>(false).FirstOrDefault(); if (attr != null && attr.Name != null) { return attr.Name; } return t.Name; } public static bool IsExtendedType(Type/*!*/ t) { Debug.Assert(t != null); return _sysTypes.ContainsKey(t); } public static bool IsPythonType(Type/*!*/ t) { Debug.Assert(t != null); return _sysTypes.ContainsKey(t) || t.GetTypeInfo().IsDefined(typeof(PythonTypeAttribute), false); } /// <summary> /// Event handler for when our domain manager has an assembly loaded by the user hosting the script /// runtime. Here we can gather any information regarding extension methods. /// /// Currently DLR-style extension methods become immediately available w/o an explicit import step. /// </summary> private void DomainManager_AssemblyLoaded(object sender, AssemblyLoadedEventArgs e) { Assembly asm = e.Assembly; var attrs = asm.GetCustomAttributes<ExtensionTypeAttribute>(); if (attrs.Any()) { lock (_dlrExtensionTypes) { foreach (ExtensionTypeAttribute attr in attrs) { if (attr.Extends.IsInterface()) { _registeredInterfaceExtensions = true; } IList<Type> typeList; if (!_dlrExtensionTypes.TryGetValue(attr.Extends, out typeList)) { _dlrExtensionTypes[attr.Extends] = typeList = new List<Type>(); } else if (typeList.IsReadOnly) { _dlrExtensionTypes[attr.Extends] = typeList = new List<Type>(typeList); } // don't add extension types twice even if we receive multiple assembly loads if (!typeList.Contains(attr.ExtensionType)) { typeList.Add(attr.ExtensionType); } } } } TopNamespaceTracker.PublishComTypes(asm); // Add it to the references tuple if we // loaded a new assembly. ClrModule.ReferencesList rl = _context.ReferencedAssemblies; lock (rl) { rl.Add(asm); } #if FEATURE_REFEMIT // load any compiled code that has been cached... LoadScriptCode(_context, asm); #endif // load any Python modules _context.LoadBuiltins(_context.BuiltinModules, asm, true); // load any cached new types NewTypeMaker.LoadNewTypes(asm); } #if FEATURE_REFEMIT private static void LoadScriptCode(PythonContext/*!*/ pc, Assembly/*!*/ asm) { ScriptCode[] codes = SavableScriptCode.LoadFromAssembly(pc.DomainManager, asm); foreach (ScriptCode sc in codes) { pc.GetCompiledLoader().AddScriptCode(sc); } } #endif internal PythonContext/*!*/ Context { get { return _context; } } /// <summary> /// Provides a cache from Type/name -> PythonTypeSlot and also allows access to /// all members (and remembering whether all members are cached). /// </summary> private class SlotCache { private Dictionary<CachedInfoKey/*!*/, SlotCacheInfo/*!*/> _cachedInfos; /// <summary> /// Writes to a cache the result of a type lookup. Null values are allowed for the slots and they indicate that /// the value does not exist. /// </summary> public void CacheSlot(Type/*!*/ type, bool isGetMember, string/*!*/ name, PythonTypeSlot slot, MemberGroup/*!*/ memberGroup) { Debug.Assert(type != null); Debug.Assert(name != null); EnsureInfo(); lock (_cachedInfos) { SlotCacheInfo slots = GetSlotForType(type, isGetMember); if (slots.ResolvedAll && slot == null && memberGroup.Count == 0) { // nothing to cache, and we know we don't need to cache non-hits. return; } slots.Members[name] = new KeyValuePair<PythonTypeSlot, MemberGroup>(slot, memberGroup); } } /// <summary> /// Looks up a cached type slot for the specified member and type. This may return true and return a null slot - that indicates /// that a cached result for a member which doesn't exist has been stored. Otherwise it returns true if a slot is found or /// false if it is not. /// </summary> public bool TryGetCachedSlot(Type/*!*/ type, bool isGetMember, string/*!*/ name, out PythonTypeSlot slot) { Debug.Assert(type != null); Debug.Assert(name != null); if (_cachedInfos != null) { lock (_cachedInfos) { SlotCacheInfo slots; if (_cachedInfos.TryGetValue(new CachedInfoKey(type, isGetMember), out slots) && (slots.TryGetSlot(name, out slot) || slots.ResolvedAll)) { return true; } } } slot = null; return false; } /// <summary> /// Looks up a cached member group for the specified member and type. This may return true and return a null group - that indicates /// that a cached result for a member which doesn't exist has been stored. Otherwise it returns true if a group is found or /// false if it is not. /// </summary> public bool TryGetCachedMember(Type/*!*/ type, string/*!*/ name, bool getMemberAction, out MemberGroup/*!*/ group) { Debug.Assert(type != null); Debug.Assert(name != null); if (_cachedInfos != null) { lock (_cachedInfos) { SlotCacheInfo slots; if (_cachedInfos.TryGetValue(new CachedInfoKey(type, getMemberAction), out slots) && (slots.TryGetMember(name, out group) || (getMemberAction && slots.ResolvedAll))) { return true; } } } group = MemberGroup.EmptyGroup; return false; } /// <summary> /// Checks to see if all members have been populated for the provided type. /// </summary> public bool IsFullyCached(Type/*!*/ type, bool isGetMember) { if (_cachedInfos != null) { lock (_cachedInfos) { SlotCacheInfo info; if (_cachedInfos.TryGetValue(new CachedInfoKey(type, isGetMember), out info)) { return info.ResolvedAll; } } } return false; } /// <summary> /// Populates the type with all the provided members and marks the type /// as being fully cached. /// /// The dictionary is used for the internal storage and should not be modified after /// providing it to the cache. /// </summary> public void CacheAll(Type/*!*/ type, bool isGetMember, Dictionary<string/*!*/, KeyValuePair<PythonTypeSlot/*!*/, MemberGroup/*!*/>> members) { Debug.Assert(type != null); EnsureInfo(); lock (_cachedInfos) { SlotCacheInfo slots = GetSlotForType(type, isGetMember); slots.Members = members; slots.ResolvedAll = true; } } /// <summary> /// Returns an enumerable object which provides access to all the members of the provided type. /// /// The caller must check that the type is fully cached and populate the cache if it isn't before /// calling this method. /// </summary> public IEnumerable<KeyValuePair<string/*!*/, PythonTypeSlot/*!*/>>/*!*/ GetAllMembers(Type/*!*/ type, bool isGetMember) { Debug.Assert(type != null); SlotCacheInfo info = GetSlotForType(type, isGetMember); Debug.Assert(info.ResolvedAll); foreach (KeyValuePair<string, PythonTypeSlot> slot in info.GetAllSlots()) { if (slot.Value != null) { yield return slot; } } } private SlotCacheInfo/*!*/ GetSlotForType(Type/*!*/ type, bool isGetMember) { SlotCacheInfo slots; var key = new CachedInfoKey(type, isGetMember); if (!_cachedInfos.TryGetValue(key, out slots)) { _cachedInfos[key] = slots = new SlotCacheInfo(); } return slots; } class CachedInfoKey : IEquatable<CachedInfoKey> { public readonly Type Type; public readonly bool IsGetMember; public CachedInfoKey(Type type, bool isGetMember) { Type = type; IsGetMember = isGetMember; } #region IEquatable<CachedInfoKey> Members public bool Equals(CachedInfoKey other) { return other.Type == Type && other.IsGetMember == IsGetMember; } #endregion public override bool Equals(object obj) { CachedInfoKey other = obj as CachedInfoKey; if (other != null) { return Equals(other); } return false; } public override int GetHashCode() { return Type.GetHashCode() ^ (IsGetMember ? -1 : 0); } } private void EnsureInfo() { if (_cachedInfos == null) { Interlocked.CompareExchange(ref _cachedInfos, new Dictionary<CachedInfoKey/*!*/, SlotCacheInfo>(), null); } } private class SlotCacheInfo { public SlotCacheInfo() { Members = new Dictionary<string/*!*/, KeyValuePair<PythonTypeSlot, MemberGroup/*!*/>>(StringComparer.Ordinal); } public bool TryGetSlot(string/*!*/ name, out PythonTypeSlot slot) { Debug.Assert(name != null); KeyValuePair<PythonTypeSlot, MemberGroup> kvp; if (Members.TryGetValue(name, out kvp)) { slot = kvp.Key; return true; } slot = null; return false; } public bool TryGetMember(string/*!*/ name, out MemberGroup/*!*/ group) { Debug.Assert(name != null); KeyValuePair<PythonTypeSlot, MemberGroup> kvp; if (Members.TryGetValue(name, out kvp)) { group = kvp.Value; return true; } group = MemberGroup.EmptyGroup; return false; } public IEnumerable<KeyValuePair<string/*!*/, PythonTypeSlot>>/*!*/ GetAllSlots() { foreach (KeyValuePair<string, KeyValuePair<PythonTypeSlot, MemberGroup>> kvp in Members) { yield return new KeyValuePair<string, PythonTypeSlot>(kvp.Key, kvp.Value.Key); } } public Dictionary<string/*!*/, KeyValuePair<PythonTypeSlot, MemberGroup/*!*/>>/*!*/ Members; public bool ResolvedAll; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace ODataValidator.Rule { using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Xml; using System.Xml.XPath; using ODataValidator.Rule.Helper; using ODataValidator.RuleEngine; using ODataValidator.RuleEngine.Common; /// <summary> /// Class of extension rule /// </summary> [Export(typeof(ExtensionRule))] public class MetadataCore4031 : ExtensionRule { /// <summary> /// Gets Category property /// </summary> public override string Category { get { return "core"; } } /// <summary> /// Gets rule name /// </summary> public override string Name { get { return "Metadata.Core.4031"; } } /// <summary> /// Gets rule description /// </summary> public override string Description { get { return "Edm.PrimitiveType cannot be used as the type of a key property of an entity type."; } } /// <summary> /// Gets rule specification in OData document /// </summary> public override string SpecificationSection { get { return "4.5"; } } /// <summary> /// Gets location of help information of the rule /// </summary> public override string HelpLink { get { return null; } } /// <summary> /// Gets the error message for validation failure /// </summary> public override string ErrorMessage { get { return this.Description; } } /// <summary> /// Gets the requirement level. /// </summary> public override RequirementLevel RequirementLevel { get { return RequirementLevel.Must; } } /// <summary> /// Gets the version. /// </summary> public override ODataVersion? Version { get { return ODataVersion.V4; } } /// <summary> /// Gets the payload type to which the rule applies. /// </summary> public override PayloadType? PayloadType { get { return RuleEngine.PayloadType.Metadata; } } /// <summary> /// Gets the flag whether the rule requires metadata document /// </summary> public override bool? RequireMetadata { get { return true; } } /// <summary> /// Gets the offline context to which the rule applies /// </summary> public override bool? IsOfflineContext { get { return false; } } /// <summary> /// Gets the payload format to which the rule applies. /// </summary> public override PayloadFormat? PayloadFormat { get { return RuleEngine.PayloadFormat.Xml; } } /// <summary> /// Verify Metadata.Core.4031 /// </summary> /// <param name="context">Service context</param> /// <param name="info">out parameter to return violation information when rule fail</param> /// <returns>true if rule passes; false otherwise</returns> public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info) { if (context == null) { throw new ArgumentNullException("context"); } bool? passed = null; info = null; // Load MetadataDocument into XMLDOM XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(context.MetadataDocument); // Edm.EntityType cannot use the abstract type Edm.PrimitiveType as its key property type. string xpath = "//*[local-name()='EntityType']"; XmlNodeList propertyNodeList = xmlDoc.SelectNodes(xpath); foreach( XmlNode entityType in propertyNodeList) { XmlNodeList keyPropRefs = entityType.SelectNodes("./*[local-name()='Key']/*[local-name()='PropertyRef']"); if(keyPropRefs != null && keyPropRefs.Count > 0) { foreach(XmlNode keyPropRef in keyPropRefs) { XmlNode resultKeyProp = entityType; if (keyPropRef.Attributes["Name"] == null) continue; if (MetadataHelper.Path(keyPropRef.Attributes["Name"].Value, xmlDoc, context, ref resultKeyProp)) { if (resultKeyProp.Attributes["Type"] != null) { if(!resultKeyProp.Attributes["Type"].Equals("Edm.Primitive")) { passed = true; } else { passed = false; info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload); break; } } } else { continue; } } } } return passed; } } }
// Copyright (C) 2014 dot42 // // Original filename: WebHeaderCollection.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections.Generic; using System.Collections.Specialized; using System.Text; //using Java.Util; using Org.Apache.Http; // See RFC 2068 par 4.2 Message Headers namespace System.Net { public class WebHeaderCollection : NameValueCollection { [Flags] internal enum HeaderInfo { Request = 1, Response = 1 << 1, MultiValue = 1 << 10 } static readonly bool[] allowed_chars = { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, true, true, true, true, false, false, false, true, true, false, true, true, false, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, true, false }; static readonly Dictionary<string, HeaderInfo> headers; HeaderInfo? headerRestriction; HeaderInfo? headerConsistency; static WebHeaderCollection() { headers = new Collections.Generic.Dictionary<string, HeaderInfo>() { { "allow", HeaderInfo.MultiValue }, { "accept", HeaderInfo.Request | HeaderInfo.MultiValue }, { "accept-charset", HeaderInfo.MultiValue }, { "accept-encoding", HeaderInfo.MultiValue }, { "accept-language", HeaderInfo.MultiValue }, { "accept-ranges", HeaderInfo.MultiValue }, { "authorization", HeaderInfo.MultiValue }, { "cache-control", HeaderInfo.MultiValue }, { "cookie", HeaderInfo.MultiValue }, { "connection", HeaderInfo.Request | HeaderInfo.MultiValue }, { "content-encoding", HeaderInfo.MultiValue }, { "content-length", HeaderInfo.Request | HeaderInfo.Response }, { "content-type", HeaderInfo.Request }, { "content-language", HeaderInfo.MultiValue }, { "date", HeaderInfo.Request }, { "expect", HeaderInfo.Request | HeaderInfo.MultiValue}, { "host", HeaderInfo.Request }, { "if-match", HeaderInfo.MultiValue }, { "if-modified-since", HeaderInfo.Request }, { "if-none-match", HeaderInfo.MultiValue }, { "keep-alive", HeaderInfo.Response }, { "pragma", HeaderInfo.MultiValue }, { "proxy-authenticate", HeaderInfo.MultiValue }, { "proxy-authorization", HeaderInfo.MultiValue }, { "proxy-connection", HeaderInfo.Request | HeaderInfo.MultiValue }, { "range", HeaderInfo.Request | HeaderInfo.MultiValue }, { "referer", HeaderInfo.Request }, { "set-cookie", HeaderInfo.MultiValue }, { "set-cookie2", HeaderInfo.MultiValue }, { "te", HeaderInfo.MultiValue }, { "trailer", HeaderInfo.MultiValue }, { "transfer-encoding", HeaderInfo.Request | HeaderInfo.Response | HeaderInfo.MultiValue }, { "upgrade", HeaderInfo.MultiValue }, { "user-agent", HeaderInfo.Request }, { "vary", HeaderInfo.MultiValue }, { "via", HeaderInfo.MultiValue }, { "warning", HeaderInfo.MultiValue }, { "www-authenticate", HeaderInfo.Response | HeaderInfo. MultiValue } }; } public WebHeaderCollection() { } internal WebHeaderCollection(HeaderInfo headerRestriction) { this.headerRestriction = headerRestriction; } internal WebHeaderCollection(IHeader[] headers) { foreach (var header in headers) { Add(header.Name, header.Value); } } public void Add(string header) { if (header == null) throw new ArgumentNullException("header"); int pos = header.IndexOf(':'); if (pos == -1) throw new ArgumentException("no colon found", "header"); this.Add(header.Substring(0, pos), header.Substring(pos + 1)); } public override void Add(string name, string value) { if (name == null) throw new ArgumentNullException("name"); name = name.ToLower(); CheckRestrictedHeader(name); this.AddWithoutValidate(name, value); } protected void AddWithoutValidate(string headerName, string headerValue) { headerName = headerName.ToLower(); if (!IsHeaderName(headerName)) throw new ArgumentException("invalid header name: " + headerName, "headerName"); if (headerValue == null) headerValue = String.Empty; else headerValue = headerValue.Trim(); if (!IsHeaderValue(headerValue)) throw new ArgumentException("invalid header value: " + headerValue, "headerValue"); AddValue(headerName, headerValue); } internal void AddValue(string headerName, string headerValue) { base.Add(headerName, headerValue); } internal string[] GetValues_internal(string header, bool split) { if (header == null) throw new ArgumentNullException("header"); header = header.ToLower(); string[] values = base.GetValues(header); if (values == null || values.Length == 0) return null; if (split && IsMultiValue(header)) { List<string> separated = null; foreach (var value in values) { if (value.IndexOf(',') < 0) continue; if (separated == null) { separated = new List<string>(values.Length + 1); foreach (var v in values) { if (v == value) break; separated.Add(v); } } var slices = value.Split(','); var slices_length = slices.Length; if (value[value.Length - 1] == ',') --slices_length; for (int i = 0; i < slices_length; ++i) { separated.Add(slices[i].Trim()); } } if (separated != null) return separated.ToArray(); } return values; } public override string[] GetValues(string header) { return GetValues_internal(header, true); } public override string[] GetValues(int index) { string[] values = base.GetValues(index); if (values == null || values.Length == 0) { return null; } return values; } public static bool IsRestricted(string headerName) { return IsRestricted(headerName, false); } public static bool IsRestricted(string headerName, bool response) { if (headerName == null) throw new ArgumentNullException("headerName"); if (headerName.Length == 0) throw new ArgumentException("empty string", "headerName"); if (!IsHeaderName(headerName)) throw new ArgumentException("Invalid character in header"); HeaderInfo info; if (!headers.TryGetValue(headerName, out info)) return false; var flag = response ? HeaderInfo.Response : HeaderInfo.Request; return (info & flag) != 0; } public override void Remove(string name) { if (name == null) throw new ArgumentNullException("name"); name = name.ToLower(); CheckRestrictedHeader(name); base.Remove(name); } public override void Set(string name, string value) { if (name == null) throw new ArgumentNullException("name"); name = name.ToLower(); if (!IsHeaderName(name)) throw new ArgumentException("invalid header name"); if (value == null) value = String.Empty; else value = value.Trim(); if (!IsHeaderValue(value)) throw new ArgumentException("invalid header value"); CheckRestrictedHeader(name); base.Set(name, value); } public byte[] ToByteArray() { return Encoding.UTF8.GetBytes(ToString()); } internal string ToStringMultiValue() { StringBuilder sb = new StringBuilder(); int count = base.Count; for (int i = 0; i < count; i++) { string key = GetKey(i); if (IsMultiValue(key)) { foreach (string v in GetValues(i)) { sb.Append(key) .Append(": ") .Append(v) .Append("\r\n"); } } else { sb.Append(key) .Append(": ") .Append(Get(i)) .Append("\r\n"); } } return sb.Append("\r\n").ToString(); } public override string ToString() { var sb = new StringBuilder(); int count = base.Count; for (int i = 0; i < count; i++) sb.Append(GetKey(i)) .Append(": ") .Append(Get(i)) .Append("\r\n"); return sb.Append("\r\n").ToString(); } public void Add(HttpRequestHeader header, string value) { Add(RequestHeaderToString(header), value); } public void Remove(HttpRequestHeader header) { Remove(RequestHeaderToString(header)); } public void Set(HttpRequestHeader header, string value) { Set(RequestHeaderToString(header), value); } public void Add(HttpResponseHeader header, string value) { Add(ResponseHeaderToString(header), value); } public void Remove(HttpResponseHeader header) { Remove(ResponseHeaderToString(header)); } public void Set(HttpResponseHeader header, string value) { Set(ResponseHeaderToString(header), value); } public string this[HttpRequestHeader header] { get { return Get(RequestHeaderToString(header)); } set { Set(header, value); } } public string this[HttpResponseHeader header] { get { return Get(ResponseHeaderToString(header)); } set { Set(header, value); } } public override string Get(string name) { return base.Get(name.ToLower()); } public override void Clear() { base.Clear(); } internal void SetInternal(string header) { int pos = header.IndexOf(':'); if (pos == -1) throw new ArgumentException("no colon found", "header"); SetInternal(header.Substring(0, pos), header.Substring(pos + 1)); } internal void SetInternal(string name, string value) { if (value == null) value = String.Empty; else value = value.Trim(); if (!IsHeaderValue(value)) throw new ArgumentException("invalid header value"); if (IsMultiValue(name)) { base.Add(name, value); } else { base.Remove(name); base.Set(name, value); } } internal void RemoveAndAdd(string name, string value) { if (value == null) value = String.Empty; else value = value.Trim(); base.Remove(name); base.Set(name, value); } internal void RemoveInternal(string name) { if (name == null) throw new ArgumentNullException("name"); base.Remove(name); } private string RequestHeaderToString(HttpRequestHeader value) { CheckHeaderConsistency(HeaderInfo.Request); return HeaderToString(value); } internal static string HeaderToString(HttpRequestHeader value) { switch (value) { case HttpRequestHeader.CacheControl: return "cache-control"; case HttpRequestHeader.Connection: return "connection"; case HttpRequestHeader.Date: return "date"; case HttpRequestHeader.KeepAlive: return "keep-alive"; case HttpRequestHeader.Pragma: return "pragma"; case HttpRequestHeader.Trailer: return "trailer"; case HttpRequestHeader.TransferEncoding: return "transfer-encoding"; case HttpRequestHeader.Upgrade: return "upgrade"; case HttpRequestHeader.Via: return "via"; case HttpRequestHeader.Warning: return "warning"; case HttpRequestHeader.Allow: return "allow"; case HttpRequestHeader.ContentLength: return "content-length"; case HttpRequestHeader.ContentType: return "content-type"; case HttpRequestHeader.ContentEncoding: return "content-encoding"; case HttpRequestHeader.ContentLanguage: return "content-language"; case HttpRequestHeader.ContentLocation: return "content-location"; case HttpRequestHeader.ContentMd5: return "content-md5"; case HttpRequestHeader.ContentRange: return "content-range"; case HttpRequestHeader.Expires: return "expires"; case HttpRequestHeader.LastModified: return "last-modified"; case HttpRequestHeader.Accept: return "accept"; case HttpRequestHeader.AcceptCharset: return "accept-charset"; case HttpRequestHeader.AcceptEncoding: return "accept-encoding"; case HttpRequestHeader.AcceptLanguage: return "accept-language"; case HttpRequestHeader.Authorization: return "authorization"; case HttpRequestHeader.Cookie: return "cookie"; case HttpRequestHeader.Expect: return "expect"; case HttpRequestHeader.From: return "from"; case HttpRequestHeader.Host: return "host"; case HttpRequestHeader.IfMatch: return "if-match"; case HttpRequestHeader.IfModifiedSince: return "if-modified-since"; case HttpRequestHeader.IfNoneMatch: return "if-none-match"; case HttpRequestHeader.IfRange: return "if-range"; case HttpRequestHeader.IfUnmodifiedSince: return "if-unmodified-since"; case HttpRequestHeader.MaxForwards: return "max-forwards"; case HttpRequestHeader.ProxyAuthorization: return "proxy-authorization"; case HttpRequestHeader.Referer: return "referer"; case HttpRequestHeader.Range: return "range"; case HttpRequestHeader.Te: return "te"; case HttpRequestHeader.Translate: return "translate"; case HttpRequestHeader.UserAgent: return "user-agent"; default: throw new InvalidOperationException(); } } private string ResponseHeaderToString(HttpResponseHeader value) { CheckHeaderConsistency(HeaderInfo.Response); return HeaderToString(value); } internal static string HeaderToString(HttpResponseHeader value) { switch (value) { case HttpResponseHeader.CacheControl: return "cache-control"; case HttpResponseHeader.Connection: return "connection"; case HttpResponseHeader.Date: return "date"; case HttpResponseHeader.KeepAlive: return "keep-alive"; case HttpResponseHeader.Pragma: return "pragma"; case HttpResponseHeader.Trailer: return "trailer"; case HttpResponseHeader.TransferEncoding: return "transfer-encoding"; case HttpResponseHeader.Upgrade: return "upgrade"; case HttpResponseHeader.Via: return "via"; case HttpResponseHeader.Warning: return "warning"; case HttpResponseHeader.Allow: return "allow"; case HttpResponseHeader.ContentLength: return "content-length"; case HttpResponseHeader.ContentType: return "content-type"; case HttpResponseHeader.ContentEncoding: return "content-Eencoding"; case HttpResponseHeader.ContentLanguage: return "content-language"; case HttpResponseHeader.ContentLocation: return "content-location"; case HttpResponseHeader.ContentMd5: return "content-md5"; case HttpResponseHeader.ContentRange: return "content-range"; case HttpResponseHeader.Expires: return "expires"; case HttpResponseHeader.LastModified: return "last-modified"; case HttpResponseHeader.AcceptRanges: return "accept-ranges"; case HttpResponseHeader.Age: return "age"; case HttpResponseHeader.ETag: return "etag"; case HttpResponseHeader.Location: return "location"; case HttpResponseHeader.ProxyAuthenticate: return "proxy-authenticate"; case HttpResponseHeader.RetryAfter: return "retry-after"; case HttpResponseHeader.Server: return "server"; case HttpResponseHeader.SetCookie: return "set-cookie"; case HttpResponseHeader.Vary: return "vary"; case HttpResponseHeader.WwwAuthenticate: return "www-authenticate"; default: throw new InvalidOperationException(); } } void CheckRestrictedHeader(string headerName) { if (!headerRestriction.HasValue) return; HeaderInfo info; if (!headers.TryGetValue(headerName, out info)) return; if ((info & headerRestriction.Value) != 0) throw new ArgumentException("This header must be modified with the appropiate property."); } void CheckHeaderConsistency(HeaderInfo value) { if (!headerConsistency.HasValue) { headerConsistency = value; return; } if ((headerConsistency & value) == 0) throw new InvalidOperationException(); } internal static bool IsMultiValue(string headerName) { if (headerName == null) return false; HeaderInfo info; return headers.TryGetValue(headerName, out info) && (info & HeaderInfo.MultiValue) != 0; } internal static bool IsHeaderValue(string value) { // TEXT any 8 bit value except CTL's (0-31 and 127) // but including \r\n space and \t // after a newline at least one space or \t must follow // certain header fields allow comments () int len = value.Length; for (int i = 0; i < len; i++) { char c = value[i]; if (c == 127) return false; if (c < 0x20 && (c != '\r' && c != '\n' && c != '\t')) return false; if (c == '\n' && ++i < len) { c = value[i]; if (c != ' ' && c != '\t') return false; } } return true; } internal static bool IsHeaderName(string name) { if (name == null || name.Length == 0) return false; int len = name.Length; for (int i = 0; i < len; i++) { char c = name[i]; if (c > 126 || !allowed_chars[c]) return false; } return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Text; using System.Xml; namespace System.Xml.Xsl.Qil { /// <summary> /// If an annotation implements this interface, then QilXmlWriter will call ToString() on the annotation /// and serialize the result (if non-empty). /// </summary> internal interface IQilAnnotation { string Name { get; } }; /// <summary> /// An example of QilVisitor. Prints the QilExpression tree as XML. /// </summary> /// <remarks> /// <para>The QilXmlWriter Visits every node in the tree, printing out an XML representation of /// each node. Several formatting options are available, including whether or not to include annotations /// and type information. When full information is printed out, the graph can be reloaded from /// its serialized form using QilXmlReader.</para> /// <para>The XML format essentially uses one XML element for each node in the QIL graph. /// Node properties such as type information are serialized as XML attributes. /// Annotations are serialized as processing-instructions in front of a node.</para> /// <para>Feel free to subclass this visitor to customize its behavior.</para> /// </remarks> internal class QilXmlWriter : QilScopedVisitor { protected XmlWriter writer; protected Options options; private readonly NameGenerator _ngen; [Flags] public enum Options { None = 0, // No options selected Annotations = 1, // Print annotations TypeInfo = 2, // Print type information using "G" option RoundTripTypeInfo = 4, // Print type information using "S" option LineInfo = 8, // Print source line information NodeIdentity = 16, // Print node identity (only works if QIL_TRACE_NODE_CREATION is defined) NodeLocation = 32, // Print node creation location (only works if QIL_TRACE_NODE_CREATION is defined) }; /// <summary> /// Construct a QilXmlWriter. /// </summary> public QilXmlWriter(XmlWriter writer) : this(writer, Options.Annotations | Options.TypeInfo | Options.LineInfo | Options.NodeIdentity | Options.NodeLocation) { } /// <summary> /// Construct a QilXmlWriter. /// </summary> public QilXmlWriter(XmlWriter writer, Options options) { this.writer = writer; _ngen = new NameGenerator(); this.options = options; } /// <summary> /// Serialize a QilExpression graph as XML. /// </summary> /// <param name="node">the QilExpression graph</param> public void ToXml(QilNode node) { VisitAssumeReference(node); } //----------------------------------------------- // QilXmlWrite methods //----------------------------------------------- /// <summary> /// Write all annotations as comments: /// 1. string -- <!-- (string) ann --> /// 2. IQilAnnotation -- <!-- ann.Name = ann.ToString() --> /// 3. IList{object} -- recursively call WriteAnnotations for each object in list /// 4. otherwise, do not write the annotation /// </summary> protected virtual void WriteAnnotations(object ann) { string s = null, name = null; if (ann == null) { return; } else if (ann is string) { s = ann as string; } else if (ann is IQilAnnotation) { // Get annotation's name and string value IQilAnnotation qilann = ann as IQilAnnotation; name = qilann.Name; s = ann.ToString(); } else if (ann is IList<object>) { IList<object> list = (IList<object>)ann; foreach (object annItem in list) WriteAnnotations(annItem); return; } if (s != null && s.Length != 0) this.writer.WriteComment(name != null && name.Length != 0 ? name + ": " + s : s); } /// <summary> /// Called in order to write out source line information. /// </summary> protected virtual void WriteLineInfo(QilNode node) { this.writer.WriteAttributeString("lineInfo", string.Format(CultureInfo.InvariantCulture, "[{0},{1} -- {2},{3}]", node.SourceLine.Start.Line, node.SourceLine.Start.Pos, node.SourceLine.End.Line, node.SourceLine.End.Pos )); } /// <summary> /// Called in order to write out the xml type of a node. /// </summary> protected virtual void WriteXmlType(QilNode node) { this.writer.WriteAttributeString("xmlType", node.XmlType.ToString((this.options & Options.RoundTripTypeInfo) != 0 ? "S" : "G")); } //----------------------------------------------- // QilVisitor overrides //----------------------------------------------- /// <summary> /// Override certain node types in order to add additional attributes, suppress children, etc. /// </summary> protected override QilNode VisitChildren(QilNode node) { if (node is QilLiteral) { // If literal is not handled elsewhere, print its string value this.writer.WriteValue(Convert.ToString(((QilLiteral)node).Value, CultureInfo.InvariantCulture)); return node; } else if (node is QilReference) { QilReference reference = (QilReference)node; // Write the generated identifier for this iterator this.writer.WriteAttributeString("id", _ngen.NameOf(node)); // Write the debug name of this reference (if it's defined) as a "name" attribute if (reference.DebugName != null) this.writer.WriteAttributeString("name", reference.DebugName.ToString()); if (node.NodeType == QilNodeType.Parameter) { // Don't visit parameter's name, or its default value if it is null QilParameter param = (QilParameter)node; if (param.DefaultValue != null) VisitAssumeReference(param.DefaultValue); return node; } } return base.VisitChildren(node); } /// <summary> /// Write references to functions or iterators like this: <RefTo id="$a"/>. /// </summary> protected override QilNode VisitReference(QilNode node) { QilReference reference = (QilReference)node; string name = _ngen.NameOf(node); if (name == null) name = "OUT-OF-SCOPE REFERENCE"; this.writer.WriteStartElement("RefTo"); this.writer.WriteAttributeString("id", name); if (reference.DebugName != null) this.writer.WriteAttributeString("name", reference.DebugName.ToString()); this.writer.WriteEndElement(); return node; } /// <summary> /// Scan through the external parameters, global variables, and function list for forward references. /// </summary> protected override QilNode VisitQilExpression(QilExpression qil) { IList<QilNode> fdecls = new ForwardRefFinder().Find(qil); if (fdecls != null && fdecls.Count > 0) { this.writer.WriteStartElement("ForwardDecls"); foreach (QilNode n in fdecls) { // i.e. <Function id="$a"/> this.writer.WriteStartElement(Enum.GetName(typeof(QilNodeType), n.NodeType)); this.writer.WriteAttributeString("id", _ngen.NameOf(n)); WriteXmlType(n); if (n.NodeType == QilNodeType.Function) { // Visit Arguments and SideEffects operands Visit(n[0]); Visit(n[2]); } this.writer.WriteEndElement(); } this.writer.WriteEndElement(); } return VisitChildren(qil); } /// <summary> /// Serialize literal types using either "S" or "G" formatting, depending on the option which has been set. /// </summary> protected override QilNode VisitLiteralType(QilLiteral value) { this.writer.WriteString(((XmlQueryType)value).ToString((this.options & Options.TypeInfo) != 0 ? "G" : "S")); return value; } /// <summary> /// Serialize literal QName as three separate attributes. /// </summary> protected override QilNode VisitLiteralQName(QilName value) { this.writer.WriteAttributeString("name", value.ToString()); return value; } //----------------------------------------------- // QilScopedVisitor overrides //----------------------------------------------- /// <summary> /// Annotate this iterator or function with a generated name. /// </summary> protected override void BeginScope(QilNode node) { _ngen.NameOf(node); } /// <summary> /// Clear the name annotation on this iterator or function. /// </summary> protected override void EndScope(QilNode node) { _ngen.ClearName(node); } /// <summary> /// By default, call WriteStartElement for every node type. /// </summary> protected override void BeforeVisit(QilNode node) { base.BeforeVisit(node); // Write the annotations in front of the element, to avoid issues with attributes // and make it easier to round-trip if ((this.options & Options.Annotations) != 0) WriteAnnotations(node.Annotation); // Call WriteStartElement this.writer.WriteStartElement("", Enum.GetName(typeof(QilNodeType), node.NodeType), ""); // Write common attributes #if QIL_TRACE_NODE_CREATION if ((this.options & Options.NodeIdentity) != 0) this.writer.WriteAttributeString("nodeId", node.NodeId.ToString(CultureInfo.InvariantCulture)); if ((this.options & Options.NodeLocation) != 0) this.writer.WriteAttributeString("nodeLoc", node.NodeLocation); #endif if ((this.options & (Options.TypeInfo | Options.RoundTripTypeInfo)) != 0) WriteXmlType(node); if ((this.options & Options.LineInfo) != 0 && node.SourceLine != null) WriteLineInfo(node); } /// <summary> /// By default, call WriteEndElement for every node type. /// </summary> protected override void AfterVisit(QilNode node) { this.writer.WriteEndElement(); base.AfterVisit(node); } //----------------------------------------------- // Helper methods //----------------------------------------------- /// <summary> /// Find list of all iterators and functions which are referenced before they have been declared. /// </summary> internal class ForwardRefFinder : QilVisitor { private readonly List<QilNode> _fwdrefs = new List<QilNode>(); private readonly List<QilNode> _backrefs = new List<QilNode>(); public IList<QilNode> Find(QilExpression qil) { Visit(qil); return _fwdrefs; } /// <summary> /// Add iterators and functions to backrefs list as they are visited. /// </summary> protected override QilNode Visit(QilNode node) { if (node is QilIterator || node is QilFunction) _backrefs.Add(node); return base.Visit(node); } /// <summary> /// If reference is not in scope, then it must be a forward reference. /// </summary> protected override QilNode VisitReference(QilNode node) { if (!_backrefs.Contains(node) && !_fwdrefs.Contains(node)) _fwdrefs.Add(node); return node; } } //=================================== Helper class: NameGenerator ========================================= private sealed class NameGenerator { private readonly StringBuilder _name; private int _len; private readonly int _zero; private readonly char _start; private readonly char _end; /// <summary> /// Construct a new name generator with prefix "$" and alphabetical mode. /// </summary> public NameGenerator() { string prefix = "$"; _len = _zero = prefix.Length; _start = 'a'; _end = 'z'; _name = new StringBuilder(prefix, _len + 2); _name.Append(_start); } /// <summary> /// Skolem function for names. /// </summary> /// <returns>a unique name beginning with the prefix</returns> public string NextName() { string result = _name.ToString(); char c = _name[_len]; if (c == _end) { _name[_len] = _start; int i = _len; for (; i-- > _zero && _name[i] == _end;) _name[i] = _start; if (i < _zero) { _len++; _name.Append(_start); } else _name[i]++; } else _name[_len] = ++c; return result; } /// <summary> /// Lookup or generate a name for a node. Uses annotations to store the name on the node. /// </summary> /// <param name="n">the node</param> /// <returns>the node name (unique across nodes)</returns> public string NameOf(QilNode n) { string name = null; object old = n.Annotation; NameAnnotation a = old as NameAnnotation; if (a == null) { name = NextName(); n.Annotation = new NameAnnotation(name, old); } else { name = a.Name; } return name; } /// <summary> /// Clear name annotation from a node. /// </summary> /// <param name="n">the node</param> public void ClearName(QilNode n) { if (n.Annotation is NameAnnotation) n.Annotation = ((NameAnnotation)n.Annotation).PriorAnnotation; } /// <summary> /// Class used to hold our annotations on the graph /// </summary> private class NameAnnotation : ListBase<object> { public string Name; public object PriorAnnotation; public NameAnnotation(string s, object a) { Name = s; PriorAnnotation = a; } public override int Count { get { return 1; } } public override object this[int index] { get { if (index == 0) return PriorAnnotation; throw new IndexOutOfRangeException(); } set { throw new NotSupportedException(); } } } } } }
using System; using NUnit.Framework; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Math; using Org.BouncyCastle.Math.EC; using Org.BouncyCastle.Pkcs; using Org.BouncyCastle.Security; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Encoders; using Org.BouncyCastle.Utilities.Test; using Org.BouncyCastle.X509; namespace Org.BouncyCastle.Tests { [TestFixture] public class DHTest : SimpleTest { private static readonly BigInteger g512 = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16); private static readonly BigInteger p512 = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16); private static readonly BigInteger g768 = new BigInteger("7c240073c1316c621df461b71ebb0cdcc90a6e5527e5e126633d131f87461c4dc4afc60c2cb0f053b6758871489a69613e2a8b4c8acde23954c08c81cbd36132cfd64d69e4ed9f8e51ed6e516297206672d5c0a69135df0a5dcf010d289a9ca1", 16); private static readonly BigInteger p768 = new BigInteger("8c9dd223debed1b80103b8b309715be009d48860ed5ae9b9d5d8159508efd802e3ad4501a7f7e1cfec78844489148cd72da24b21eddd01aa624291c48393e277cfc529e37075eccef957f3616f962d15b44aeab4039d01b817fde9eaa12fd73f", 16); private static readonly BigInteger g1024 = new BigInteger("1db17639cdf96bc4eabba19454f0b7e5bd4e14862889a725c96eb61048dcd676ceb303d586e30f060dbafd8a571a39c4d823982117da5cc4e0f89c77388b7a08896362429b94a18a327604eb7ff227bffbc83459ade299e57b5f77b50fb045250934938efa145511166e3197373e1b5b1e52de713eb49792bedde722c6717abf", 16); private static readonly BigInteger p1024 = new BigInteger("a00e283b3c624e5b2b4d9fbc2653b5185d99499b00fd1bf244c6f0bb817b4d1c451b2958d62a0f8a38caef059fb5ecd25d75ed9af403f5b5bdab97a642902f824e3c13789fed95fa106ddfe0ff4a707c85e2eb77d49e68f2808bcea18ce128b178cd287c6bc00efa9a1ad2a673fe0dceace53166f75b81d6709d5f8af7c66bb7", 16); // public key with mismatched oid/parameters private byte[] oldPubEnc = Base64.Decode( "MIIBnzCCARQGByqGSM4+AgEwggEHAoGBAPxSrN417g43VAM9sZRf1dt6AocAf7D6" + "WVCtqEDcBJrMzt63+g+BNJzhXVtbZ9kp9vw8L/0PHgzv0Ot/kOLX7Khn+JalOECW" + "YlkyBhmOVbjR79TY5u2GAlvG6pqpizieQNBCEMlUuYuK1Iwseil6VoRuA13Zm7uw" + "WO1eZmaJtY7LAoGAQaPRCFKM5rEdkMrV9FNzeSsYRs8m3DqPnnJHpuySpyO9wUcX" + "OOJcJY5qvHbDO5SxHXu/+bMgXmVT6dXI5o0UeYqJR7fj6pR4E6T0FwG55RFr5Ok4" + "3C4cpXmaOu176SyWuoDqGs1RDGmYQjwbZUi23DjaaTFUly9LCYXMliKrQfEDgYQA" + "AoGAQUGCBN4TaBw1BpdBXdTvTfCU69XDB3eyU2FOBE3UWhpx9D8XJlx4f5DpA4Y6" + "6sQMuCbhfmjEph8W7/sbMurM/awR+PSR8tTY7jeQV0OkmAYdGK2nzh0ZSifMO1oE" + "NNhN2O62TLs67msxT28S4/S89+LMtc98mevQ2SX+JF3wEVU="); // bogus key with full PKCS parameter set private byte[] oldFullParams = Base64.Decode( "MIIBIzCCARgGByqGSM4+AgEwggELAoGBAP1/U4EddRIpUt9KnC7s5Of2EbdSPO9E" + "AMMeP4C2USZpRV1AIlH7WT2NWPq/xfW6MPbLm1Vs14E7gB00b/JmYLdrmVClpJ+f" + "6AR7ECLCT7up1/63xhv4O1fnxqimFQ8E+4P208UewwI1VBNaFpEy9nXzrith1yrv" + "8iIDGZ3RSAHHAoGBAPfhoIXWmz3ey7yrXDa4V7l5lK+7+jrqgvlXTAs9B4JnUVlX" + "jrrUWU/mcQcQgYC0SRZxI+hMKBYTt88JMozIpuE8FnqLVHyNKOCjrh4rs6Z1kW6j" + "fwv6ITVi8ftiegEkO8yk8b6oUZCJqIPf4VrlnwaSi2ZegHtVJWQBTDv+z0kqAgFk" + "AwUAAgIH0A=="); private byte[] samplePubEnc = Base64.Decode( "MIIBpjCCARsGCSqGSIb3DQEDATCCAQwCgYEA/X9TgR11EilS30qcLuzk5/YRt1I8" + "70QAwx4/gLZRJmlFXUAiUftZPY1Y+r/F9bow9subVWzXgTuAHTRv8mZgt2uZUKWk" + "n5/oBHsQIsJPu6nX/rfGG/g7V+fGqKYVDwT7g/bTxR7DAjVUE1oWkTL2dfOuK2HX" + "Ku/yIgMZndFIAccCgYEA9+GghdabPd7LvKtcNrhXuXmUr7v6OuqC+VdMCz0HgmdR" + "WVeOutRZT+ZxBxCBgLRJFnEj6EwoFhO3zwkyjMim4TwWeotUfI0o4KOuHiuzpnWR" + "bqN/C/ohNWLx+2J6ASQ7zKTxvqhRkImog9/hWuWfBpKLZl6Ae1UlZAFMO/7PSSoC" + "AgIAA4GEAAKBgEIiqxoUW6E6GChoOgcfNbVFclW91ITf5MFSUGQwt2R0RHoOhxvO" + "lZhNs++d0VPATLAyXovjfgENT9SGCbuZttYcqqLdKTbMXBWPek+rfnAl9E4iEMED" + "IDd83FJTKs9hQcPAm7zmp0Xm1bGF9CbUFjP5G02265z7eBmHDaT0SNlB"); private byte[] samplePrivEnc = Base64.Decode( "MIIBZgIBADCCARsGCSqGSIb3DQEDATCCAQwCgYEA/X9TgR11EilS30qcLuzk5/YR" + "t1I870QAwx4/gLZRJmlFXUAiUftZPY1Y+r/F9bow9subVWzXgTuAHTRv8mZgt2uZ" + "UKWkn5/oBHsQIsJPu6nX/rfGG/g7V+fGqKYVDwT7g/bTxR7DAjVUE1oWkTL2dfOu" + "K2HXKu/yIgMZndFIAccCgYEA9+GghdabPd7LvKtcNrhXuXmUr7v6OuqC+VdMCz0H" + "gmdRWVeOutRZT+ZxBxCBgLRJFnEj6EwoFhO3zwkyjMim4TwWeotUfI0o4KOuHiuz" + "pnWRbqN/C/ohNWLx+2J6ASQ7zKTxvqhRkImog9/hWuWfBpKLZl6Ae1UlZAFMO/7P" + "SSoCAgIABEICQAZYXnBHazxXUUdFP4NIf2Ipu7du0suJPZQKKff81wymi2zfCfHh" + "uhe9gQ9xdm4GpzeNtrQ8/MzpTy+ZVrtd29Q="); public override string Name { get { return "DH"; } } private void doTestGP( string algName, int size, int privateValueSize, BigInteger g, BigInteger p) { IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator(algName); DHParameters dhParams = new DHParameters(p, g, null, privateValueSize); KeyGenerationParameters kgp = new DHKeyGenerationParameters(new SecureRandom(), dhParams); keyGen.Init(kgp); // // a side // AsymmetricCipherKeyPair aKeyPair = keyGen.GenerateKeyPair(); IBasicAgreement aKeyAgreeBasic = AgreementUtilities.GetBasicAgreement(algName); checkKeySize(privateValueSize, aKeyPair); aKeyAgreeBasic.Init(aKeyPair.Private); // // b side // AsymmetricCipherKeyPair bKeyPair = keyGen.GenerateKeyPair(); IBasicAgreement bKeyAgreeBasic = AgreementUtilities.GetBasicAgreement(algName); checkKeySize(privateValueSize, bKeyPair); bKeyAgreeBasic.Init(bKeyPair.Private); // // agreement // // aKeyAgreeBasic.doPhase(bKeyPair.Public, true); // bKeyAgreeBasic.doPhase(aKeyPair.Public, true); // // BigInteger k1 = new BigInteger(aKeyAgreeBasic.generateSecret()); // BigInteger k2 = new BigInteger(bKeyAgreeBasic.generateSecret()); BigInteger k1 = aKeyAgreeBasic.CalculateAgreement(bKeyPair.Public); BigInteger k2 = bKeyAgreeBasic.CalculateAgreement(aKeyPair.Public); if (!k1.Equals(k2)) { Fail(size + " bit 2-way test failed"); } // // public key encoding test // // byte[] pubEnc = aKeyPair.Public.GetEncoded(); byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(aKeyPair.Public).GetDerEncoded(); // KeyFactory keyFac = KeyFactory.getInstance(algName); // X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(pubEnc); // DHPublicKey pubKey = (DHPublicKey)keyFac.generatePublic(pubX509); DHPublicKeyParameters pubKey = (DHPublicKeyParameters) PublicKeyFactory.CreateKey(pubEnc); // DHParameterSpec spec = pubKey.Parameters; DHParameters spec = pubKey.Parameters; if (!spec.G.Equals(dhParams.G) || !spec.P.Equals(dhParams.P)) { Fail(size + " bit public key encoding/decoding test failed on parameters"); } if (!((DHPublicKeyParameters)aKeyPair.Public).Y.Equals(pubKey.Y)) { Fail(size + " bit public key encoding/decoding test failed on y value"); } // // public key serialisation test // // TODO Put back in // MemoryStream bOut = new MemoryStream(); // ObjectOutputStream oOut = new ObjectOutputStream(bOut); // // oOut.WriteObject(aKeyPair.Public); // // MemoryStream bIn = new MemoryStream(bOut.ToArray(), false); // ObjectInputStream oIn = new ObjectInputStream(bIn); // // pubKey = (DHPublicKeyParameters)oIn.ReadObject(); spec = pubKey.Parameters; if (!spec.G.Equals(dhParams.G) || !spec.P.Equals(dhParams.P)) { Fail(size + " bit public key serialisation test failed on parameters"); } if (!((DHPublicKeyParameters)aKeyPair.Public).Y.Equals(pubKey.Y)) { Fail(size + " bit public key serialisation test failed on y value"); } // // private key encoding test // // byte[] privEnc = aKeyPair.Private.GetEncoded(); byte[] privEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(aKeyPair.Private).GetDerEncoded(); // PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc); // DHPrivateKeyParameters privKey = (DHPrivateKey)keyFac.generatePrivate(privPKCS8); DHPrivateKeyParameters privKey = (DHPrivateKeyParameters) PrivateKeyFactory.CreateKey(privEnc); spec = privKey.Parameters; if (!spec.G.Equals(dhParams.G) || !spec.P.Equals(dhParams.P)) { Fail(size + " bit private key encoding/decoding test failed on parameters"); } if (!((DHPrivateKeyParameters)aKeyPair.Private).X.Equals(privKey.X)) { Fail(size + " bit private key encoding/decoding test failed on y value"); } // // private key serialisation test // // TODO Put back in // bOut = new MemoryStream(); // oOut = new ObjectOutputStream(bOut); // // oOut.WriteObject(aKeyPair.Private); // // bIn = new MemoryStream(bOut.ToArray(), false); // oIn = new ObjectInputStream(bIn); // // privKey = (DHPrivateKeyParameters)oIn.ReadObject(); spec = privKey.Parameters; if (!spec.G.Equals(dhParams.G) || !spec.P.Equals(dhParams.P)) { Fail(size + " bit private key serialisation test failed on parameters"); } if (!((DHPrivateKeyParameters)aKeyPair.Private).X.Equals(privKey.X)) { Fail(size + " bit private key serialisation test failed on y value"); } // // three party test // IAsymmetricCipherKeyPairGenerator aPairGen = GeneratorUtilities.GetKeyPairGenerator(algName); aPairGen.Init(new DHKeyGenerationParameters(new SecureRandom(), spec)); AsymmetricCipherKeyPair aPair = aPairGen.GenerateKeyPair(); IAsymmetricCipherKeyPairGenerator bPairGen = GeneratorUtilities.GetKeyPairGenerator(algName); bPairGen.Init(new DHKeyGenerationParameters(new SecureRandom(), spec)); AsymmetricCipherKeyPair bPair = bPairGen.GenerateKeyPair(); IAsymmetricCipherKeyPairGenerator cPairGen = GeneratorUtilities.GetKeyPairGenerator(algName); cPairGen.Init(new DHKeyGenerationParameters(new SecureRandom(), spec)); AsymmetricCipherKeyPair cPair = cPairGen.GenerateKeyPair(); IBasicAgreement aKeyAgree = AgreementUtilities.GetBasicAgreement(algName); aKeyAgree.Init(aPair.Private); IBasicAgreement bKeyAgree = AgreementUtilities.GetBasicAgreement(algName); bKeyAgree.Init(bPair.Private); IBasicAgreement cKeyAgree = AgreementUtilities.GetBasicAgreement(algName); cKeyAgree.Init(cPair.Private); // Key ac = aKeyAgree.doPhase(cPair.Public, false); // Key ba = bKeyAgree.doPhase(aPair.Public, false); // Key cb = cKeyAgree.doPhase(bPair.Public, false); // // aKeyAgree.doPhase(cb, true); // bKeyAgree.doPhase(ac, true); // cKeyAgree.doPhase(ba, true); // // BigInteger aShared = new BigInteger(aKeyAgree.generateSecret()); // BigInteger bShared = new BigInteger(bKeyAgree.generateSecret()); // BigInteger cShared = new BigInteger(cKeyAgree.generateSecret()); DHPublicKeyParameters ac = new DHPublicKeyParameters(aKeyAgree.CalculateAgreement(cPair.Public), spec); DHPublicKeyParameters ba = new DHPublicKeyParameters(bKeyAgree.CalculateAgreement(aPair.Public), spec); DHPublicKeyParameters cb = new DHPublicKeyParameters(cKeyAgree.CalculateAgreement(bPair.Public), spec); BigInteger aShared = aKeyAgree.CalculateAgreement(cb); BigInteger bShared = bKeyAgree.CalculateAgreement(ac); BigInteger cShared = cKeyAgree.CalculateAgreement(ba); if (!aShared.Equals(bShared)) { Fail(size + " bit 3-way test failed (a and b differ)"); } if (!cShared.Equals(bShared)) { Fail(size + " bit 3-way test failed (c and b differ)"); } } private void doTestExplicitWrapping( int size, int privateValueSize, BigInteger g, BigInteger p) { DHParameters dhParams = new DHParameters(p, g, null, privateValueSize); IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("DH"); keyGen.Init(new DHKeyGenerationParameters(new SecureRandom(), dhParams)); // // a side // AsymmetricCipherKeyPair aKeyPair = keyGen.GenerateKeyPair(); IBasicAgreement aKeyAgree = AgreementUtilities.GetBasicAgreement("DH"); checkKeySize(privateValueSize, aKeyPair); aKeyAgree.Init(aKeyPair.Private); // // b side // AsymmetricCipherKeyPair bKeyPair = keyGen.GenerateKeyPair(); IBasicAgreement bKeyAgree = AgreementUtilities.GetBasicAgreement("DH"); checkKeySize(privateValueSize, bKeyPair); bKeyAgree.Init(bKeyPair.Private); // // agreement // // aKeyAgree.doPhase(bKeyPair.Public, true); // bKeyAgree.doPhase(aKeyPair.Public, true); // // SecretKey k1 = aKeyAgree.generateSecret(PkcsObjectIdentifiers.IdAlgCms3DesWrap.Id); // SecretKey k2 = bKeyAgree.generateSecret(PkcsObjectIdentifiers.IdAlgCms3DesWrap.Id); // TODO Does this really test the same thing as the above code? BigInteger b1 = aKeyAgree.CalculateAgreement(bKeyPair.Public); BigInteger b2 = bKeyAgree.CalculateAgreement(aKeyPair.Public); if (!b1.Equals(b2)) { Fail("Explicit wrapping test failed"); } } private void checkKeySize( int privateValueSize, AsymmetricCipherKeyPair aKeyPair) { if (privateValueSize != 0) { DHPrivateKeyParameters key = (DHPrivateKeyParameters)aKeyPair.Private; if (key.X.BitLength != privateValueSize) { Fail("limited key check failed for key size " + privateValueSize); } } } // TODO Put back in // private void doTestRandom( // int size) // { // AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("DH"); // a.init(size, new SecureRandom()); // AlgorithmParameters parameters = a.generateParameters(); // // byte[] encodeParams = parameters.GetEncoded(); // // AlgorithmParameters a2 = AlgorithmParameters.getInstance("DH"); // a2.init(encodeParams); // // // a and a2 should be equivalent! // byte[] encodeParams_2 = a2.GetEncoded(); // // if (!areEqual(encodeParams, encodeParams_2)) // { // Fail("encode/Decode parameters failed"); // } // // DHParameterSpec dhP = (DHParameterSpec)parameters.getParameterSpec(DHParameterSpec.class); // // doTestGP("DH", size, 0, dhP.G, dhP.P); // } [Test] public void TestECDH() { doTestECDH("ECDH"); } [Test] public void TestECDHC() { doTestECDH("ECDHC"); } private void doTestECDH( string algorithm) { IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator(algorithm); // EllipticCurve curve = new EllipticCurve( // new ECFieldFp(new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839")), // q // new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a // new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECCurve curve = new FpCurve( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECDomainParameters ecSpec = new ECDomainParameters( curve, // ECPointUtil.DecodePoint(curve, Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307"), // n BigInteger.One); //1); // h // g.initialize(ecSpec, new SecureRandom()); g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom())); // // a side // AsymmetricCipherKeyPair aKeyPair = g.GenerateKeyPair(); IBasicAgreement aKeyAgreeBasic = AgreementUtilities.GetBasicAgreement(algorithm); aKeyAgreeBasic.Init(aKeyPair.Private); // // b side // AsymmetricCipherKeyPair bKeyPair = g.GenerateKeyPair(); IBasicAgreement bKeyAgreeBasic = AgreementUtilities.GetBasicAgreement(algorithm); bKeyAgreeBasic.Init(bKeyPair.Private); // // agreement // // aKeyAgreeBasic.doPhase(bKeyPair.Public, true); // bKeyAgreeBasic.doPhase(aKeyPair.Public, true); // // BigInteger k1 = new BigInteger(aKeyAgreeBasic.generateSecret()); // BigInteger k2 = new BigInteger(bKeyAgreeBasic.generateSecret()); BigInteger k1 = aKeyAgreeBasic.CalculateAgreement(bKeyPair.Public); BigInteger k2 = bKeyAgreeBasic.CalculateAgreement(aKeyPair.Public); if (!k1.Equals(k2)) { Fail(algorithm + " 2-way test failed"); } // // public key encoding test // // byte[] pubEnc = aKeyPair.Public.GetEncoded(); byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(aKeyPair.Public).GetDerEncoded(); // KeyFactory keyFac = KeyFactory.getInstance(algorithm); // X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(pubEnc); // ECPublicKey pubKey = (ECPublicKey)keyFac.generatePublic(pubX509); ECPublicKeyParameters pubKey = (ECPublicKeyParameters) PublicKeyFactory.CreateKey(pubEnc); ECDomainParameters ecDP = pubKey.Parameters; // if (!pubKey.getW().Equals(((ECPublicKeyParameters)aKeyPair.Public).getW())) if (!pubKey.Q.Equals(((ECPublicKeyParameters)aKeyPair.Public).Q)) { // Console.WriteLine(" expected " + pubKey.getW().getAffineX() + " got " + ((ECPublicKey)aKeyPair.Public).getW().getAffineX()); // Console.WriteLine(" expected " + pubKey.getW().getAffineY() + " got " + ((ECPublicKey)aKeyPair.Public).getW().getAffineY()); // Fail(algorithm + " public key encoding (W test) failed"); Console.WriteLine(" expected " + pubKey.Q.X.ToBigInteger() + " got " + ((ECPublicKeyParameters)aKeyPair.Public).Q.X.ToBigInteger()); Console.WriteLine(" expected " + pubKey.Q.Y.ToBigInteger() + " got " + ((ECPublicKeyParameters)aKeyPair.Public).Q.Y.ToBigInteger()); Fail(algorithm + " public key encoding (Q test) failed"); } // if (!pubKey.Parameters.getGenerator().Equals(((ECPublicKeyParameters)aKeyPair.Public).Parameters.getGenerator())) if (!pubKey.Parameters.G.Equals(((ECPublicKeyParameters)aKeyPair.Public).Parameters.G)) { Fail(algorithm + " public key encoding (G test) failed"); } // // private key encoding test // // byte[] privEnc = aKeyPair.Private.GetEncoded(); byte[] privEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(aKeyPair.Private).GetDerEncoded(); // PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc); // ECPrivateKey privKey = (ECPrivateKey)keyFac.generatePrivate(privPKCS8); ECPrivateKeyParameters privKey = (ECPrivateKeyParameters) PrivateKeyFactory.CreateKey(privEnc); // if (!privKey.getS().Equals(((ECPrivateKey)aKeyPair.Private).getS())) if (!privKey.D.Equals(((ECPrivateKeyParameters)aKeyPair.Private).D)) { // Fail(algorithm + " private key encoding (S test) failed"); Fail(algorithm + " private key encoding (D test) failed"); } // if (!privKey.Parameters.getGenerator().Equals(((ECPrivateKey)aKeyPair.Private).Parameters.getGenerator())) if (!privKey.Parameters.G.Equals(((ECPrivateKeyParameters)aKeyPair.Private).Parameters.G)) { Fail(algorithm + " private key encoding (G test) failed"); } } [Test] public void TestExceptions() { DHParameters dhParams = new DHParameters(p512, g512); try { IBasicAgreement aKeyAgreeBasic = AgreementUtilities.GetBasicAgreement("DH"); // aKeyAgreeBasic.generateSecret("DES"); aKeyAgreeBasic.CalculateAgreement(null); } catch (InvalidOperationException) { // okay } catch (Exception e) { Fail("Unexpected exception: " + e, e); } } private void doTestDesAndDesEde( BigInteger g, BigInteger p) { DHParameters dhParams = new DHParameters(p, g, null, 256); IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("DH"); keyGen.Init(new DHKeyGenerationParameters(new SecureRandom(), dhParams)); AsymmetricCipherKeyPair kp = keyGen.GenerateKeyPair(); IBasicAgreement keyAgreement = AgreementUtilities.GetBasicAgreement("DH"); keyAgreement.Init(kp.Private); BigInteger agreed = keyAgreement.CalculateAgreement(kp.Public); byte[] agreedBytes = agreed.ToByteArrayUnsigned(); // TODO Figure out where the magic happens of choosing the right // bytes from 'agreedBytes' for each key type - need C# equivalent? // (see JCEDHKeyAgreement.engineGenerateSecret) // SecretKey key = keyAgreement.generateSecret("DES"); // // if (key.getEncoded().length != 8) // { // Fail("DES length wrong"); // } // // if (!DESKeySpec.isParityAdjusted(key.getEncoded(), 0)) // { // Fail("DES parity wrong"); // } // // key = keyAgreement.generateSecret("DESEDE"); // // if (key.getEncoded().length != 24) // { // Fail("DESEDE length wrong"); // } // // if (!DESedeKeySpec.isParityAdjusted(key.getEncoded(), 0)) // { // Fail("DESEDE parity wrong"); // } // // key = keyAgreement.generateSecret("Blowfish"); // // if (key.getEncoded().length != 16) // { // Fail("Blowfish length wrong"); // } } [Test] public void TestFunction() { doTestGP("DH", 512, 0, g512, p512); doTestGP("DiffieHellman", 768, 0, g768, p768); doTestGP("DIFFIEHELLMAN", 1024, 0, g1024, p1024); doTestGP("DH", 512, 64, g512, p512); doTestGP("DiffieHellman", 768, 128, g768, p768); doTestGP("DIFFIEHELLMAN", 1024, 256, g1024, p1024); doTestExplicitWrapping(512, 0, g512, p512); doTestDesAndDesEde(g768, p768); // TODO Put back in //doTestRandom(256); } [Test] public void TestEnc() { // KeyFactory kFact = KeyFactory.getInstance("DH", "BC"); // // Key k = kFact.generatePrivate(new PKCS8EncodedKeySpec(samplePrivEnc)); AsymmetricKeyParameter k = PrivateKeyFactory.CreateKey(samplePrivEnc); byte[] encoded = PrivateKeyInfoFactory.CreatePrivateKeyInfo(k).GetEncoded(); if (!Arrays.AreEqual(samplePrivEnc, encoded)) { Fail("private key re-encode failed"); } // k = kFact.generatePublic(new X509EncodedKeySpec(samplePubEnc)); k = PublicKeyFactory.CreateKey(samplePubEnc); encoded = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(k).GetEncoded(); if (!Arrays.AreEqual(samplePubEnc, encoded)) { Fail("public key re-encode failed"); } // k = kFact.generatePublic(new X509EncodedKeySpec(oldPubEnc)); k = PublicKeyFactory.CreateKey(oldPubEnc); encoded = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(k).GetEncoded(); if (!Arrays.AreEqual(oldPubEnc, encoded)) { Fail("old public key re-encode failed"); } // k = kFact.generatePublic(new X509EncodedKeySpec(oldFullParams)); k = PublicKeyFactory.CreateKey(oldFullParams); encoded = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(k).GetEncoded(); if (!Arrays.AreEqual(oldFullParams, encoded)) { Fail("old full public key re-encode failed"); } } public override void PerformTest() { TestEnc(); TestFunction(); TestECDH(); TestECDHC(); TestExceptions(); } public static void Main( string[] args) { RunTest(new DHTest()); } } }
--- /dev/null 2016-03-07 11:46:58.000000000 -0500 +++ src/System.Text.RegularExpressions/src/SR.cs 2016-03-07 11:47:19.086501000 -0500 @@ -0,0 +1,446 @@ +using System; +using System.Resources; + +namespace FxResources.System.Text.RegularExpressions +{ + internal static class SR + { + + } +} + +namespace System +{ + internal static class SR + { + private static ResourceManager s_resourceManager; + + private const String s_resourcesName = "FxResources.System.Text.RegularExpressions.SR"; + + internal static String AlternationCantCapture + { + get + { + return SR.GetResourceString("AlternationCantCapture", null); + } + } + + internal static String AlternationCantHaveComment + { + get + { + return SR.GetResourceString("AlternationCantHaveComment", null); + } + } + + internal static String BadClassInCharRange + { + get + { + return SR.GetResourceString("BadClassInCharRange", null); + } + } + + internal static String BeginIndexNotNegative + { + get + { + return SR.GetResourceString("BeginIndexNotNegative", null); + } + } + + internal static String CapnumNotZero + { + get + { + return SR.GetResourceString("CapnumNotZero", null); + } + } + + internal static String CaptureGroupOutOfRange + { + get + { + return SR.GetResourceString("CaptureGroupOutOfRange", null); + } + } + + internal static String CountTooSmall + { + get + { + return SR.GetResourceString("CountTooSmall", null); + } + } + + internal static String EnumNotStarted + { + get + { + return SR.GetResourceString("EnumNotStarted", null); + } + } + + internal static String IllegalCondition + { + get + { + return SR.GetResourceString("IllegalCondition", null); + } + } + + internal static String IllegalEndEscape + { + get + { + return SR.GetResourceString("IllegalEndEscape", null); + } + } + + internal static String IllegalRange + { + get + { + return SR.GetResourceString("IllegalRange", null); + } + } + + internal static String IncompleteSlashP + { + get + { + return SR.GetResourceString("IncompleteSlashP", null); + } + } + + internal static String InternalError + { + get + { + return SR.GetResourceString("InternalError", null); + } + } + + internal static String InvalidGroupName + { + get + { + return SR.GetResourceString("InvalidGroupName", null); + } + } + + internal static String LengthNotNegative + { + get + { + return SR.GetResourceString("LengthNotNegative", null); + } + } + + internal static String MakeException + { + get + { + return SR.GetResourceString("MakeException", null); + } + } + + internal static String MalformedNameRef + { + get + { + return SR.GetResourceString("MalformedNameRef", null); + } + } + + internal static String MalformedReference + { + get + { + return SR.GetResourceString("MalformedReference", null); + } + } + + internal static String MalformedSlashP + { + get + { + return SR.GetResourceString("MalformedSlashP", null); + } + } + + internal static String MissingControl + { + get + { + return SR.GetResourceString("MissingControl", null); + } + } + + internal static String NestedQuantify + { + get + { + return SR.GetResourceString("NestedQuantify", null); + } + } + + internal static String NoResultOnFailed + { + get + { + return SR.GetResourceString("NoResultOnFailed", null); + } + } + + internal static String NotEnoughParens + { + get + { + return SR.GetResourceString("NotEnoughParens", null); + } + } + + internal static String OnlyAllowedOnce + { + get + { + return SR.GetResourceString("OnlyAllowedOnce", null); + } + } + + internal static String QuantifyAfterNothing + { + get + { + return SR.GetResourceString("QuantifyAfterNothing", null); + } + } + + internal static String RegexMatchTimeoutException_Occurred + { + get + { + return SR.GetResourceString("RegexMatchTimeoutException_Occurred", null); + } + } + + internal static String ReplacementError + { + get + { + return SR.GetResourceString("ReplacementError", null); + } + } + + private static ResourceManager ResourceManager + { + get + { + if (SR.s_resourceManager == null) + { + SR.s_resourceManager = new ResourceManager(SR.ResourceType); + } + return SR.s_resourceManager; + } + } + + internal static Type ResourceType + { + get + { + return typeof(FxResources.System.Text.RegularExpressions.SR); + } + } + + internal static String ReversedCharRange + { + get + { + return SR.GetResourceString("ReversedCharRange", null); + } + } + + internal static String SubtractionMustBeLast + { + get + { + return SR.GetResourceString("SubtractionMustBeLast", null); + } + } + + internal static String TooFewHex + { + get + { + return SR.GetResourceString("TooFewHex", null); + } + } + + internal static String TooManyAlternates + { + get + { + return SR.GetResourceString("TooManyAlternates", null); + } + } + + internal static String TooManyParens + { + get + { + return SR.GetResourceString("TooManyParens", null); + } + } + + internal static String UndefinedBackref + { + get + { + return SR.GetResourceString("UndefinedBackref", null); + } + } + + internal static String UndefinedNameRef + { + get + { + return SR.GetResourceString("UndefinedNameRef", null); + } + } + + internal static String UndefinedReference + { + get + { + return SR.GetResourceString("UndefinedReference", null); + } + } + + internal static String UnexpectedOpcode + { + get + { + return SR.GetResourceString("UnexpectedOpcode", null); + } + } + + internal static String UnimplementedState + { + get + { + return SR.GetResourceString("UnimplementedState", null); + } + } + + internal static String UnknownProperty + { + get + { + return SR.GetResourceString("UnknownProperty", null); + } + } + + internal static String UnrecognizedControl + { + get + { + return SR.GetResourceString("UnrecognizedControl", null); + } + } + + internal static String UnrecognizedEscape + { + get + { + return SR.GetResourceString("UnrecognizedEscape", null); + } + } + + internal static String UnrecognizedGrouping + { + get + { + return SR.GetResourceString("UnrecognizedGrouping", null); + } + } + + internal static String UnterminatedBracket + { + get + { + return SR.GetResourceString("UnterminatedBracket", null); + } + } + + internal static String UnterminatedComment + { + get + { + return SR.GetResourceString("UnterminatedComment", null); + } + } + + internal static String Format(String resourceFormat, params Object[] args) + { + if (args == null) + { + return resourceFormat; + } + if (!SR.UsingResourceKeys()) + { + return String.Format(resourceFormat, args); + } + return String.Concat(resourceFormat, String.Join(", ", args)); + } + + internal static String Format(String resourceFormat, Object p1) + { + if (!SR.UsingResourceKeys()) + { + return String.Format(resourceFormat, p1); + } + return String.Join(", ", new Object[] { resourceFormat, p1 }); + } + + internal static String Format(String resourceFormat, Object p1, Object p2) + { + if (!SR.UsingResourceKeys()) + { + return String.Format(resourceFormat, p1, p2); + } + return String.Join(", ", new Object[] { resourceFormat, p1, p2 }); + } + + internal static String Format(String resourceFormat, Object p1, Object p2, Object p3) + { + if (!SR.UsingResourceKeys()) + { + return String.Format(resourceFormat, p1, p2, p3); + } + return String.Join(", ", new Object[] { resourceFormat, p1, p2, p3 }); + } + + internal static String GetResourceString(String resourceKey, String defaultString) + { + String str = null; + try + { + str = SR.ResourceManager.GetString(resourceKey); + } + catch (MissingManifestResourceException missingManifestResourceException) + { + } + if (defaultString != null && resourceKey.Equals(str)) + { + return defaultString; + } + return str; + } + + private static Boolean UsingResourceKeys() + { + return false; + } + } +}
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; namespace Microsoft.Cci { /// <summary> /// MultiMap{Key, TValue} with 'minimum' space requirement /// </summary> /// <remarks> /// This class is intended to store name to definition mapping within a scope (class/struct). Normally a name is mapped to a single definition, /// but 1 to N mapping is possible in the case of overloading. /// /// Traditional approach would be using Dictionary{TKey, List{TValue}}, but List{TValue} would waste lots of memory for 1:1 mapping. /// /// It's implemented here as Dictionary{TKey, object} where object is either TValue or TValue[] with the exact size. /// For 1:1 mapping, there is no extra per key allocation. /// </remarks> public class NameScope<TKey, TValue> where TValue : class { Dictionary<TKey, object> m_map; /// <summary /> public NameScope(int initSize = 0) { m_map = new Dictionary<TKey, object>(initSize); } /// <summary> /// Key count /// </summary> public int Count { get { return m_map.Count; } } /// <summary> /// Add key -> value mapping /// </summary> /// <returns>true if added, false if duplicate found</returns> public bool Add(TKey key, TValue value) { object values; if (m_map.TryGetValue(key, out values)) { TValue[] valueArray = values as TValue[]; if (valueArray != null) { if (Array.IndexOf<TValue>(valueArray, value) >= 0) // duplicate { return false; } TValue[] newArray = new TValue[valueArray.Length + 1]; // N + 1 valueArray.CopyTo(newArray, 0); valueArray = newArray; } else { TValue first = values as TValue; Debug.Assert(first != null); if (first == value) // duplicate { return false; } valueArray= new TValue[2]; // Convert single value to two element array valueArray[0] = first; } m_map[key] = valueArray; valueArray[valueArray.Length - 1] = value; } else { m_map[key] = value; // single value } return true; } /// <summary> /// Translate object to IEnumerable{TValue} /// </summary> static IEnumerable<TValue> Translate(object values, out int count) { TValue[] valueArray = values as TValue[]; if (valueArray != null) { count = valueArray.Length; return valueArray; } else { Debug.Assert(values is TValue); count = 1; return new SingletonList<TValue>(values as TValue); } } /// <summary> /// Return value or value array, null if key not found. Perf optimization to avoid allocating enumerator /// </summary> public TValue GetValueArray(TKey key, out TValue[] valueArray) { object values; valueArray = null; if (m_map.TryGetValue(key, out values)) { valueArray = values as TValue[]; if (valueArray != null) { return null; } else { return values as TValue; } } return null; } /// <summary> /// Return values associated with key and count, Enumerable{TValue}.Empty if key not found /// </summary> public IEnumerable<TValue> GetValuesAndCount(TKey key, out int count) { object values; if (m_map.TryGetValue(key, out values)) { return Translate(values, out count); } count = 0; return Enumerable<TValue>.Empty; } /// <summary> /// Return values associated with key, Enumerable{TValue}.Empty if key not found /// </summary> public IEnumerable<TValue> GetValues(TKey key) { int count; IEnumerable<TValue> result = GetValuesAndCount(key, out count); return result; } /// <summary> /// Enumeration of value collection as IEnumerator{IEnumerable{TValue}} /// </summary> /// <returns></returns> public IEnumerator<IEnumerable<TValue>> GetEnumerator() { return new ValueEnumerator(m_map.Values.GetEnumerator()); } /// <summary> /// Value collection enumerator /// </summary> struct ValueEnumerator : IEnumerator, IEnumerator<IEnumerable<TValue>> { IEnumerator<object> m_enum; public ValueEnumerator(IEnumerator<object> _enum) { m_enum = _enum; } public IEnumerable<TValue> Current { get { int count; return Translate(m_enum.Current, out count); } } object IEnumerator.Current { get { int count; return Translate(m_enum.Current, out count); } } public bool MoveNext() { return m_enum.MoveNext(); } public void Reset() { m_enum.Reset(); } public void Dispose() { m_enum.Dispose(); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PopulateSwitch; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.PopulateSwitch { public partial class PopulateSwitchTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, CodeFixProvider>( new PopulateSwitchDiagnosticAnalyzer(), new PopulateSwitchCodeFixProvider()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task AllMembersAndDefaultExist() { await TestMissingAsync( @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch ([|e|]) { case MyEnum.Fizz: case MyEnum.Buzz: case MyEnum.FizzBuzz: default: break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task AllMembersExist_NotDefault() { await TestAsync( @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch ([|e|]) { case MyEnum.Fizz: case MyEnum.Buzz: case MyEnum.FizzBuzz: break; } } } }", @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: case MyEnum.FizzBuzz: break; default: break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NotAllMembersExist_NotDefault() { await TestAsync( @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch ([|e|]) { case MyEnum.Fizz: case MyEnum.Buzz: break; } } } }", @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: break; case MyEnum.FizzBuzz: break; default: break; } } } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NotAllMembersExist_WithDefault() { await TestAsync( @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch ([|e|]) { case MyEnum.Fizz: case MyEnum.Buzz: break; default: break; } } } }", @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: break; case MyEnum.FizzBuzz: break; default: break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NotAllMembersExist_NotDefault_EnumHasExplicitType() { await TestAsync( @"namespace ConsoleApplication1 { enum MyEnum : long { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch ([|e|]) { case MyEnum.Fizz: case MyEnum.Buzz: break; } } } }", @"namespace ConsoleApplication1 { enum MyEnum : long { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: break; case MyEnum.FizzBuzz: break; default: break; } } } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NotAllMembersExist_WithMembersAndDefaultInSection_NewValuesAboveDefaultSection() { await TestAsync( @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch ([|e|]) { case MyEnum.Fizz: case MyEnum.Buzz: default: break; } } } }", @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { case MyEnum.FizzBuzz: break; case MyEnum.Fizz: case MyEnum.Buzz: default: break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NotAllMembersExist_WithMembersAndDefaultInSection_AssumesDefaultIsInLastSection() { await TestAsync( @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch ([|e|]) { default: break; case MyEnum.Fizz: case MyEnum.Buzz: break; } } } }", @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { default: break; case MyEnum.Fizz: case MyEnum.Buzz: break; case MyEnum.FizzBuzz: break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NoMembersExist0() { await TestAsync( @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch ([|e|]) { } } } }", @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { case MyEnum.Fizz: break; case MyEnum.Buzz: break; case MyEnum.FizzBuzz: break; } } } }", index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NoMembersExist1() { await TestAsync( @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch ([|e|]) { } } } }", @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { default: break; } } } }", index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NoMembersExist2() { await TestAsync( @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch ([|e|]) { } } } }", @"namespace ConsoleApplication1 { enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { case MyEnum.Fizz: break; case MyEnum.Buzz: break; case MyEnum.FizzBuzz: break; default: break; } } } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task UsingStaticEnum_AllMembersExist() { await TestMissingAsync( @"using static System.IO.FileMode; namespace ConsoleApplication1 { class MyClass { void Method() { var e = Append; switch ([|e|]) { case CreateNew: break; case Create: break; case Open: break; case OpenOrCreate: break; case Truncate: break; case Append: break; default: break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task UsingStaticEnum_AllMembersExist_OutOfDefaultOrder() { await TestMissingAsync( @"using static System.IO.FileMode; namespace ConsoleApplication1 { class MyClass { void Method() { var e = Append; switch ([|e|]) { case CreateNew: break; case OpenOrCreate: break; case Truncate: break; case Open: break; case Append: break; case Create: break; default: break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task UsingStaticEnum_MembersExist() { await TestAsync( @"using static System.IO.FileMode; namespace ConsoleApplication1 { class MyClass { void Method() { var e = Append; switch ([|e|]) { case CreateNew: break; case Create: break; case Open: break; case OpenOrCreate: break; default: break; } } } }", @"using static System.IO.FileMode; namespace ConsoleApplication1 { class MyClass { void Method() { var e = Append; switch (e) { case CreateNew: break; case Create: break; case Open: break; case OpenOrCreate: break; case Truncate: break; case Append: break; default: break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task UsingStaticEnum_NoMembersExist() { await TestAsync( @"using static System.IO.FileMode; namespace ConsoleApplication1 { class MyClass { void Method() { var e = Append; switch ([|e|]) { } } } }", @"using static System.IO.FileMode; namespace ConsoleApplication1 { class MyClass { void Method() { var e = Append; switch (e) { case CreateNew: break; case Create: break; case Open: break; case OpenOrCreate: break; case Truncate: break; case Append: break; default: break; } } } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NotAllMembersExist_NotDefault_EnumHasNonFlagsAttribute() { await TestAsync( @"namespace ConsoleApplication1 { [System.Obsolete] enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch ([|e|]) { case MyEnum.Fizz: case MyEnum.Buzz: break; } } } }", @"namespace ConsoleApplication1 { [System.Obsolete] enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: break; case MyEnum.FizzBuzz: break; default: break; } } } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NotAllMembersExist_NotDefault_EnumIsNested() { await TestAsync( @"namespace ConsoleApplication1 { class MyClass { enum MyEnum { Fizz, Buzz, FizzBuzz } void Method() { var e = MyEnum.Fizz; switch ([|e|]) { case MyEnum.Fizz: case MyEnum.Buzz: break; } } } }", @"namespace ConsoleApplication1 { class MyClass { enum MyEnum { Fizz, Buzz, FizzBuzz } void Method() { var e = MyEnum.Fizz; switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: break; case MyEnum.FizzBuzz: break; default: break; } } } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NotAllMembersExist_SwitchIsNotEnum() { await TestMissingAsync( @"using System; namespace ConsoleApplication1 { class MyClass { void Method() { var e = ""test""; switch ([|e|]) { case ""test1"": case ""test1"": default: break; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] public async Task NotAllMembersExist_NotDefault_UsingConstants() { await TestAsync( @"enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch ([|e|]) { case (MyEnum)0: case (MyEnum)1: break; } } }", @"enum MyEnum { Fizz, Buzz, FizzBuzz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { case (MyEnum)0: case (MyEnum)1: break; case MyEnum.FizzBuzz: break; default: break; } } }", index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPopulateSwitch)] [WorkItem(13455, "https://github.com/dotnet/roslyn/issues/13455")] public async Task AllMissingTokens() { await TestAsync( @" enum MyEnum { Fizz } class MyClass { void Method() { var e = MyEnum.Fizz; switch ([|e|]) } } ", @" enum MyEnum { Fizz } class MyClass { void Method() { var e = MyEnum.Fizz; switch (e) { case MyEnum.Fizz: break; } } }", compareTokens: false); } } }
// Copyright (c) 2015 fjz13. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. using System.Collections.Generic; using System.IO; using System.Linq; using GameKit.Log; using GameKit.Packing; using GameKit.Publish; using GameKit.Resource; namespace GameKit.Analyzer { enum ImageUsage { UI, RoleAnimation, EffectAnimation, Mission, Monster, Other, Storm } public class ImageAnalyzer : IAnalyzer { private List<string> mPVREnabledDirectoryNames = new List<string>(); public static Dictionary<uint, bool> AuraIcons = new Dictionary<uint, bool>(); public static Dictionary<uint, bool> EquipIcons = new Dictionary<uint, bool>(); public static Dictionary<uint, bool> HeroIcons = new Dictionary<uint, bool>(); public static Dictionary<uint, bool> ItemIcons = new Dictionary<uint, bool>(); public static Dictionary<uint, bool> MonsterIcons = new Dictionary<uint, bool>(); public static Dictionary<uint, bool> PetIcons = new Dictionary<uint, bool>(); public static Dictionary<uint, bool> RuneIcons = new Dictionary<uint, bool>(); public static Dictionary<uint, bool> SkillIcons = new Dictionary<uint, bool>(); public static Dictionary<string, FileInfo> UIImages = new Dictionary<string, FileInfo>(); public ImageAnalyzer() { mPVREnabledDirectoryNames.Add(@"Art\Images\Mission"); mPVREnabledDirectoryNames.Add(@"Art\Images\MonsterAnimation"); mPVREnabledDirectoryNames.Add(@"Art\Images\RoleAnimation"); mPVREnabledDirectoryNames.Add(@"Art\Images\EffectAnimation"); mPVREnabledDirectoryNames.Add(@"Art\Images\UI\Map\Map1"); } public void PrevProcess() { AuraIcons.Clear(); EquipIcons.Clear(); HeroIcons.Clear(); ItemIcons.Clear(); MonsterIcons.Clear(); PetIcons.Clear(); RuneIcons.Clear(); SkillIcons.Clear(); UIImages.Clear(); Logger.LogAllLine("Analyze images================>"); GetImagesRecursively(PathManager.InputImagesPath, "\t"); } public void Analyze() { } public void PostCheck() { CheckUsage(); ImagePacker.Pack(PublishTarget.Current); } private void GetImagesRecursively(DirectoryInfo dirPath, string prefix) { var files = SystemTool.GetDirectoryFiles(dirPath); foreach (var file in files) { if (!file.Name.EndsWith(".png")) { Logger.LogInfoLine("{0}Only accept png image:{1}", prefix, file); continue; } var imageFile = new ImageFile(file,true,true); //Logger.LogInfoLine("{0}File:\t{1}", prefix, file.FullName.Replace(PathManager.InputImagesPath.FullName, string.Empty)); bool isPacked = !file.Directory.FullName.Contains(PathManager.InputImageOtherPath.FullName); bool isPVREnabled = false; if (PublishTarget.Current.IsPVR) { isPVREnabled = mPVREnabledDirectoryNames.Any(pvrEnabledDirectoryName => file.Directory.FullName.Contains(pvrEnabledDirectoryName)); } //bool isEffectAnimation = file.Directory.FullName.Contains("EffectAnimation"); //isPacked &= !isEffectAnimation; //bool isOptimzed = !isEffectAnimation; if (!PublishTarget.Current.IsPack) { isPacked = false; } bool isOptimzed = PublishTarget.Current.IsOptimzed; bool isPOT = PublishTarget.Current.IsPOT; bool isSquare = PublishTarget.Current.IsSquare; if (isPVREnabled) { isPOT = true; isSquare = true; } ImagePacker.AddImage(imageFile, PublishTarget.Current, isPacked, isOptimzed, isPVREnabled, isPOT, isSquare); FilterImage(file); } } public void FilterImage(FileInfo info) { string dirName = info.Directory.Name; uint id = FileListFile.GetResourceOrder(info.Name); var resourceName = FileListFile.GetResourceName(info.Name); resourceName = resourceName.Replace(".png", string.Empty); if (info.FullName.Contains("Icon") && info.Directory.FullName.Contains("Art\\Images\\Other")) { if (dirName == resourceName) { var icons = GetIconDict(dirName); if (icons != null) { if (!icons.ContainsKey(id)) { icons.Add(id, false); } } } } else if (info.Directory.FullName.Contains("Art\\Images\\UI")) { if (!UIImages.ContainsKey(info.Name)) { UIImages.Add(info.Name, info); } } } private static Dictionary<uint, bool> GetIconDict(string iconName) { switch (iconName) { case "AuraIcon": return AuraIcons; case "EquipIcon": return EquipIcons; case "HeroIcon": return HeroIcons; case "ItemIcon": return ItemIcons; case "MonsterIcon": return MonsterIcons; case "PetIcon": return PetIcons; case "RuneIcon": return RuneIcons; case "SkillIcon": return SkillIcons; } return null; } public static bool UseUIImage(string name) { if (UIImages.ContainsKey(name)) { UIImages[name] = null; return true; } return false; } public static void UseIcon(string iconName, uint id) { var icons = GetIconDict(iconName); if (icons != null) { if (!icons.ContainsKey(id)) { Logger.LogErrorLine("Cannot find {0}:{1}", iconName, id); } else { icons[id] = true; } } } public static void CheckUsage(string iconName) { var icons = GetIconDict(iconName); if (icons != null) { foreach (var auraIcon in AuraIcons) { if (!auraIcon.Value) { Logger.LogErrorLine("{0}-{1}.png not Used!", iconName, auraIcon.Key); } } } } public void CheckUsage() { CheckUsage("HeroIcon"); CheckUsage("EquipIcon"); CheckUsage("HeroIcon"); CheckUsage("ItemIcon"); CheckUsage("MonsterIcon"); CheckUsage("PetIcon"); CheckUsage("RuneIcon"); CheckUsage("SkillIcon"); foreach (var uiImage in UIImages) { if (uiImage.Value!=null) { string str = uiImage.Value.FullName; str=str.Replace(PathManager.InputImagesPath.FullName, string.Empty); str=str.Replace("\\UI\\", string.Empty); Logger.LogErrorLine("\tUI image:{0} not used.", str); } } //foreach (var uiImage in ImagePacker.Images) //{ // if (!uiImage.Value) // { // Logger.LogErrorLine("\tUI image:{0} not used.", uiImage.Key.FileInfo.Name); // } //} } private void CopyImage(ImageFile imageFile) { /* var packageInfo = PackingInfo.GetPackingInfo(imageFile.OriginalFile.FileInfo.FullName); if (packageInfo.IsPackage(PublishTarget.Current)) { string tempFilePath = imageFile.OriginalFile.FileInfo.FullName; tempFilePath = tempFilePath.Replace(PathManager.InputPath, PathManager.TempPath); imageFile.ResultImage.Save(tempFilePath); ResourceMapGenerator.AddFileAndTag(imageFile, PublishTarget.Current); } */ } } }
using System; namespace ICSharpCode.SharpZipLib.Zip.Compression { /// <summary> /// This class is general purpose class for writing data to a buffer. /// /// It allows you to write bits as well as bytes /// Based on DeflaterPending.java /// /// author of the original java version : Jochen Hoenicke /// </summary> public class PendingBuffer { readonly #region Instance Fields /// <summary> /// Internal work buffer /// </summary> byte[] buffer_; int start; int end; uint bits; int bitCount; #endregion #region Constructors /// <summary> /// construct instance using default buffer size of 4096 /// </summary> public PendingBuffer() : this(4096) { } /// <summary> /// construct instance using specified buffer size /// </summary> /// <param name="bufferSize"> /// size to use for internal buffer /// </param> public PendingBuffer(int bufferSize) { buffer_ = new byte[bufferSize]; } #endregion /// <summary> /// Clear internal state/buffers /// </summary> public void Reset() { start = end = bitCount = 0; } /// <summary> /// Write a byte to buffer /// </summary> /// <param name="value"> /// The value to write /// </param> public void WriteByte(int value) { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (start != 0) ) { throw new SharpZipBaseException("Debug check: start != 0"); } #endif buffer_[end++] = unchecked((byte)value); } /// <summary> /// Write a short value to buffer LSB first /// </summary> /// <param name="value"> /// The value to write. /// </param> public void WriteShort(int value) { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (start != 0) ) { throw new SharpZipBaseException("Debug check: start != 0"); } #endif buffer_[end++] = unchecked((byte)value); buffer_[end++] = unchecked((byte)(value >> 8)); } /// <summary> /// write an integer LSB first /// </summary> /// <param name="value">The value to write.</param> public void WriteInt(int value) { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (start != 0) ) { throw new SharpZipBaseException("Debug check: start != 0"); } #endif buffer_[end++] = unchecked((byte)value); buffer_[end++] = unchecked((byte)(value >> 8)); buffer_[end++] = unchecked((byte)(value >> 16)); buffer_[end++] = unchecked((byte)(value >> 24)); } /// <summary> /// Write a block of data to buffer /// </summary> /// <param name="block">data to write</param> /// <param name="offset">offset of first byte to write</param> /// <param name="length">number of bytes to write</param> public void WriteBlock(byte[] block, int offset, int length) { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (start != 0) ) { throw new SharpZipBaseException("Debug check: start != 0"); } #endif System.Array.Copy(block, offset, buffer_, end, length); end += length; } /// <summary> /// The number of bits written to the buffer /// </summary> public int BitCount { get { return bitCount; } } /// <summary> /// Align internal buffer on a byte boundary /// </summary> public void AlignToByte() { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (start != 0) ) { throw new SharpZipBaseException("Debug check: start != 0"); } #endif if (bitCount > 0) { buffer_[end++] = unchecked((byte)bits); if (bitCount > 8) { buffer_[end++] = unchecked((byte)(bits >> 8)); } } bits = 0; bitCount = 0; } /// <summary> /// Write bits to internal buffer /// </summary> /// <param name="b">source of bits</param> /// <param name="count">number of bits to write</param> public void WriteBits(int b, int count) { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (start != 0) ) { throw new SharpZipBaseException("Debug check: start != 0"); } // if (DeflaterConstants.DEBUGGING) { // //Console.WriteLine("writeBits("+b+","+count+")"); // } #endif bits |= (uint)(b << bitCount); bitCount += count; if (bitCount >= 16) { buffer_[end++] = unchecked((byte)bits); buffer_[end++] = unchecked((byte)(bits >> 8)); bits >>= 16; bitCount -= 16; } } /// <summary> /// Write a short value to internal buffer most significant byte first /// </summary> /// <param name="s">value to write</param> public void WriteShortMSB(int s) { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (start != 0) ) { throw new SharpZipBaseException("Debug check: start != 0"); } #endif buffer_[end++] = unchecked((byte)(s >> 8)); buffer_[end++] = unchecked((byte)s); } /// <summary> /// Indicates if buffer has been flushed /// </summary> public bool IsFlushed { get { return end == 0; } } /// <summary> /// Flushes the pending buffer into the given output array. If the /// output array is to small, only a partial flush is done. /// </summary> /// <param name="output">The output array.</param> /// <param name="offset">The offset into output array.</param> /// <param name="length">The maximum number of bytes to store.</param> /// <returns>The number of bytes flushed.</returns> public int Flush(byte[] output, int offset, int length) { if (bitCount >= 8) { buffer_[end++] = unchecked((byte)bits); bits >>= 8; bitCount -= 8; } if (length > end - start) { length = end - start; System.Array.Copy(buffer_, start, output, offset, length); start = 0; end = 0; } else { System.Array.Copy(buffer_, start, output, offset, length); start += length; } return length; } /// <summary> /// Convert internal buffer to byte array. /// Buffer is empty on completion /// </summary> /// <returns> /// The internal buffer contents converted to a byte array. /// </returns> public byte[] ToByteArray() { byte[] result = new byte[end - start]; System.Array.Copy(buffer_, start, result, 0, result.Length); start = 0; end = 0; return result; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------ // </copyright> //------------------------------------------------------------------------------ using System.Xml.Extensions; namespace System.Xml.Serialization { internal class XmlSerializationPrimitiveWriter : System.Xml.Serialization.XmlSerializationWriter { internal void Write_string(object o) { WriteStartDocument(); if (o == null) { WriteNullTagLiteral(@"string", @""); return; } TopLevelElement(); WriteNullableStringLiteral(@"string", @"", ((System.String)o)); } internal void Write_int(object o) { WriteStartDocument(); if (o == null) { WriteEmptyTag(@"int", @""); return; } WriteElementStringRaw(@"int", @"", System.Xml.XmlConvert.ToString((System.Int32)((System.Int32)o))); } internal void Write_boolean(object o) { WriteStartDocument(); if (o == null) { WriteEmptyTag(@"boolean", @""); return; } WriteElementStringRaw(@"boolean", @"", System.Xml.XmlConvert.ToString((System.Boolean)((System.Boolean)o))); } internal void Write_short(object o) { WriteStartDocument(); if (o == null) { WriteEmptyTag(@"short", @""); return; } WriteElementStringRaw(@"short", @"", System.Xml.XmlConvert.ToString((System.Int16)((System.Int16)o))); } internal void Write_long(object o) { WriteStartDocument(); if (o == null) { WriteEmptyTag(@"long", @""); return; } WriteElementStringRaw(@"long", @"", System.Xml.XmlConvert.ToString((System.Int64)((System.Int64)o))); } internal void Write_float(object o) { WriteStartDocument(); if (o == null) { WriteEmptyTag(@"float", @""); return; } WriteElementStringRaw(@"float", @"", System.Xml.XmlConvert.ToString((System.Single)((System.Single)o))); } internal void Write_double(object o) { WriteStartDocument(); if (o == null) { WriteEmptyTag(@"double", @""); return; } WriteElementStringRaw(@"double", @"", System.Xml.XmlConvert.ToString((System.Double)((System.Double)o))); } internal void Write_decimal(object o) { WriteStartDocument(); if (o == null) { WriteEmptyTag(@"decimal", @""); return; } // Preventing inlining optimization which is causing issue for XmlConvert.ToString(Decimal) Decimal d = (System.Decimal)o; WriteElementStringRaw(@"decimal", @"", System.Xml.XmlConvert.ToString(d)); } internal void Write_dateTime(object o) { WriteStartDocument(); if (o == null) { WriteEmptyTag(@"dateTime", @""); return; } WriteElementStringRaw(@"dateTime", @"", FromDateTime(((System.DateTime)o))); } internal void Write_unsignedByte(object o) { WriteStartDocument(); if (o == null) { WriteEmptyTag(@"unsignedByte", @""); return; } WriteElementStringRaw(@"unsignedByte", @"", System.Xml.XmlConvert.ToString((System.Byte)((System.Byte)o))); } internal void Write_byte(object o) { WriteStartDocument(); if (o == null) { WriteEmptyTag(@"byte", @""); return; } WriteElementStringRaw(@"byte", @"", System.Xml.XmlConvert.ToString((System.SByte)((System.SByte)o))); } internal void Write_unsignedShort(object o) { WriteStartDocument(); if (o == null) { WriteEmptyTag(@"unsignedShort", @""); return; } WriteElementStringRaw(@"unsignedShort", @"", System.Xml.XmlConvert.ToString((System.UInt16)((System.UInt16)o))); } internal void Write_unsignedInt(object o) { WriteStartDocument(); if (o == null) { WriteEmptyTag(@"unsignedInt", @""); return; } WriteElementStringRaw(@"unsignedInt", @"", System.Xml.XmlConvert.ToString((System.UInt32)((System.UInt32)o))); } internal void Write_unsignedLong(object o) { WriteStartDocument(); if (o == null) { WriteEmptyTag(@"unsignedLong", @""); return; } WriteElementStringRaw(@"unsignedLong", @"", System.Xml.XmlConvert.ToString((System.UInt64)((System.UInt64)o))); } internal void Write_base64Binary(object o) { WriteStartDocument(); if (o == null) { WriteNullTagLiteral(@"base64Binary", @""); return; } TopLevelElement(); WriteNullableStringLiteralRaw(@"base64Binary", @"", FromByteArrayBase64(((System.Byte[])o))); } internal void Write_guid(object o) { WriteStartDocument(); if (o == null) { WriteEmptyTag(@"guid", @""); return; } // Preventing inlining optimization which is causing issue for XmlConvert.ToString(Guid) Guid guid = (Guid)o; WriteElementStringRaw(@"guid", @"", System.Xml.XmlConvert.ToString(guid)); } internal void Write_TimeSpan(object o) { WriteStartDocument(); if (o == null) { WriteEmptyTag(@"TimeSpan", @""); return; } TimeSpan timeSpan = (TimeSpan)o; WriteElementStringRaw(@"TimeSpan", @"", System.Xml.XmlConvert.ToString(timeSpan)); } internal void Write_char(object o) { WriteStartDocument(); if (o == null) { WriteEmptyTag(@"char", @""); return; } WriteElementString(@"char", @"", FromChar(((System.Char)o))); } internal void Write_QName(object o) { WriteStartDocument(); if (o == null) { WriteNullTagLiteral(@"QName", @""); return; } TopLevelElement(); WriteNullableQualifiedNameLiteral(@"QName", @"", ((global::System.Xml.XmlQualifiedName)o)); } protected override void InitCallbacks() { } } internal class XmlSerializationPrimitiveReader : System.Xml.Serialization.XmlSerializationReader { internal object Read_string() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id1_string && (object)Reader.NamespaceURI == (object)_id2_Item)) { if (ReadNull()) { o = null; } else { o = Reader.ReadElementString(); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } internal object Read_int() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id3_int && (object)Reader.NamespaceURI == (object)_id2_Item)) { { o = System.Xml.XmlConvert.ToInt32(Reader.ReadElementString()); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } internal object Read_boolean() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id4_boolean && (object)Reader.NamespaceURI == (object)_id2_Item)) { { o = System.Xml.XmlConvert.ToBoolean(Reader.ReadElementString()); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } internal object Read_short() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id5_short && (object)Reader.NamespaceURI == (object)_id2_Item)) { { o = System.Xml.XmlConvert.ToInt16(Reader.ReadElementString()); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } internal object Read_long() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id6_long && (object)Reader.NamespaceURI == (object)_id2_Item)) { { o = System.Xml.XmlConvert.ToInt64(Reader.ReadElementString()); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } internal object Read_float() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id7_float && (object)Reader.NamespaceURI == (object)_id2_Item)) { { o = System.Xml.XmlConvert.ToSingle(Reader.ReadElementString()); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } internal object Read_double() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id8_double && (object)Reader.NamespaceURI == (object)_id2_Item)) { { o = System.Xml.XmlConvert.ToDouble(Reader.ReadElementString()); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } internal object Read_decimal() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id9_decimal && (object)Reader.NamespaceURI == (object)_id2_Item)) { { o = System.Xml.XmlConvert.ToDecimal(Reader.ReadElementString()); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } internal object Read_dateTime() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id10_dateTime && (object)Reader.NamespaceURI == (object)_id2_Item)) { { o = ToDateTime(Reader.ReadElementString()); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } internal object Read_unsignedByte() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id11_unsignedByte && (object)Reader.NamespaceURI == (object)_id2_Item)) { { o = System.Xml.XmlConvert.ToByte(Reader.ReadElementString()); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } internal object Read_byte() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id12_byte && (object)Reader.NamespaceURI == (object)_id2_Item)) { { o = System.Xml.XmlConvert.ToSByte(Reader.ReadElementString()); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } internal object Read_unsignedShort() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id13_unsignedShort && (object)Reader.NamespaceURI == (object)_id2_Item)) { { o = System.Xml.XmlConvert.ToUInt16(Reader.ReadElementString()); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } internal object Read_unsignedInt() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id14_unsignedInt && (object)Reader.NamespaceURI == (object)_id2_Item)) { { o = System.Xml.XmlConvert.ToUInt32(Reader.ReadElementString()); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } internal object Read_unsignedLong() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id15_unsignedLong && (object)Reader.NamespaceURI == (object)_id2_Item)) { { o = System.Xml.XmlConvert.ToUInt64(Reader.ReadElementString()); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } internal object Read_base64Binary() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id16_base64Binary && (object)Reader.NamespaceURI == (object)_id2_Item)) { if (ReadNull()) { o = null; } else { o = ToByteArrayBase64(false); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } internal object Read_guid() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id17_guid && (object)Reader.NamespaceURI == (object)_id2_Item)) { { o = System.Xml.XmlConvert.ToGuid(Reader.ReadElementString()); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } internal object Read_TimeSpan() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id19_TimeSpan && (object)Reader.NamespaceURI == (object)_id2_Item)) { { o = System.Xml.XmlConvert.ToTimeSpan(Reader.ReadElementString()); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } internal object Read_char() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id18_char && (object)Reader.NamespaceURI == (object)_id2_Item)) { { o = ToChar(Reader.ReadElementString()); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } internal object Read_QName() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (((object)Reader.LocalName == (object)_id1_QName && (object)Reader.NamespaceURI == (object)_id2_Item)) { if (ReadNull()) { o = null; } else { o = ReadElementQualifiedName(); } } else { throw CreateUnknownNodeException(); } } else { UnknownNode(null); } return (object)o; } protected override void InitCallbacks() { } private System.String _id4_boolean; private System.String _id14_unsignedInt; private System.String _id15_unsignedLong; private System.String _id7_float; private System.String _id10_dateTime; private System.String _id6_long; private System.String _id9_decimal; private System.String _id8_double; private System.String _id17_guid; private System.String _id19_TimeSpan; private System.String _id2_Item; private System.String _id13_unsignedShort; private System.String _id18_char; private System.String _id3_int; private System.String _id12_byte; private System.String _id16_base64Binary; private System.String _id11_unsignedByte; private System.String _id5_short; private System.String _id1_string; private System.String _id1_QName; protected override void InitIDs() { _id4_boolean = Reader.NameTable.Add(@"boolean"); _id14_unsignedInt = Reader.NameTable.Add(@"unsignedInt"); _id15_unsignedLong = Reader.NameTable.Add(@"unsignedLong"); _id7_float = Reader.NameTable.Add(@"float"); _id10_dateTime = Reader.NameTable.Add(@"dateTime"); _id6_long = Reader.NameTable.Add(@"long"); _id9_decimal = Reader.NameTable.Add(@"decimal"); _id8_double = Reader.NameTable.Add(@"double"); _id17_guid = Reader.NameTable.Add(@"guid"); _id19_TimeSpan = Reader.NameTable.Add(@"TimeSpan"); _id2_Item = Reader.NameTable.Add(@""); _id13_unsignedShort = Reader.NameTable.Add(@"unsignedShort"); _id18_char = Reader.NameTable.Add(@"char"); _id3_int = Reader.NameTable.Add(@"int"); _id12_byte = Reader.NameTable.Add(@"byte"); _id16_base64Binary = Reader.NameTable.Add(@"base64Binary"); _id11_unsignedByte = Reader.NameTable.Add(@"unsignedByte"); _id5_short = Reader.NameTable.Add(@"short"); _id1_string = Reader.NameTable.Add(@"string"); _id1_QName = Reader.NameTable.Add(@"QName"); } } }
#region Using directives using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Windows.Markup; using System.Xml; using System.IO; using System.IO.Packaging; using System.Xml.Schema; using System.Net; using System.Resources; using System.Reflection; using System.Security; using MS.Internal; using MS.Internal.IO.Packaging; #endregion namespace System.Windows.Documents { internal class XpsValidatingLoader { internal XpsValidatingLoader() { } internal object Load(Stream stream, Uri parentUri, ParserContext pc, ContentType mimeType) { return Load(stream, parentUri, pc, mimeType, null); } internal void Validate(Stream stream, Uri parentUri, ParserContext pc, ContentType mimeType, string rootElement) { Load(stream, parentUri, pc, mimeType, rootElement); } /// <summary> /// rootElement == null: Load elements, validation of root element will occur in caller by checking object type or casting /// rootElement != null: Only perform validation, and expect rootElement at root of markup /// </summary> /// <param name="stream"></param> /// <param name="parentUri"></param> /// <param name="pc"></param> /// <param name="mimeType"></param> /// <param name="rootElement"></param> /// <returns></returns> /// <SecurityNote> /// Critical: Accesses a package from PreloadedPackages /// SecurityTreatAsSafe: No package instance or package related objects are handed out from this /// method except as SecurityCriticalData (to XpsSchema.ValidateRelationships) /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] private object Load(Stream stream, Uri parentUri, ParserContext pc, ContentType mimeType, string rootElement) { object obj = null; if (!DocumentMode) { // Loose XAML, just check against schema, don't check content type if (rootElement==null) { obj = XamlReader.Load(stream, pc); } } else { // inside an XPS Document. Perform maximum validation XpsSchema schema = XpsSchema.GetSchema(mimeType); Uri uri = pc.BaseUri; // Using PackUriHelper.ValidateAndGetPackUriComponents internal method // to get Package and Part Uri in one step Uri packageUri; Uri partUri; PackUriHelper.ValidateAndGetPackUriComponents(uri, out packageUri, out partUri); Package package = PreloadedPackages.GetPackage(packageUri); Uri parentPackageUri = null; if (parentUri != null) { parentPackageUri = PackUriHelper.GetPackageUri(parentUri); if (!parentPackageUri.Equals(packageUri)) { throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderUriNotInSamePackage)); } } schema.ValidateRelationships(new SecurityCriticalData<Package>(package), packageUri, partUri, mimeType); if (schema.AllowsMultipleReferencesToSameUri(mimeType)) { _uniqueUriRef = null; } else { _uniqueUriRef = new Hashtable(11); } Hashtable validResources = (_validResources.Count > 0 ? _validResources.Peek() : null); if (schema.HasRequiredResources(mimeType)) { validResources = new Hashtable(11); PackagePart part = package.GetPart(partUri); PackageRelationshipCollection requiredResources = part.GetRelationshipsByType(_requiredResourceRel); foreach (PackageRelationship relationShip in requiredResources) { Uri targetUri = PackUriHelper.ResolvePartUri(partUri, relationShip.TargetUri); Uri absTargetUri = PackUriHelper.Create(packageUri, targetUri); PackagePart targetPart = package.GetPart(targetUri); if (schema.IsValidRequiredResourceMimeType(targetPart.ValidatedContentType)) { if (!validResources.ContainsKey(absTargetUri)) { validResources.Add(absTargetUri, true); } } else { if (!validResources.ContainsKey(absTargetUri)) { validResources.Add(absTargetUri, false); } } } } XpsSchemaValidator xpsSchemaValidator = new XpsSchemaValidator(this, schema, mimeType, stream, packageUri, partUri); _validResources.Push(validResources); if (rootElement != null) { xpsSchemaValidator.XmlReader.MoveToContent(); if (!rootElement.Equals(xpsSchemaValidator.XmlReader.Name)) { throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderUnsupportedMimeType)); } while (xpsSchemaValidator.XmlReader.Read()) ; } else { obj = XamlReader.Load(xpsSchemaValidator.XmlReader, pc, XamlParseMode.Synchronous); } _validResources.Pop(); } return obj; } static internal bool DocumentMode { get { return _documentMode; } } static internal void AssertDocumentMode() { // Once switched to document mode, we stay there _documentMode = true; } internal void UriHitHandler(int node,Uri uri) { if (_uniqueUriRef != null) { if (_uniqueUriRef.Contains(uri)) { if ((int)_uniqueUriRef[uri] != node) { throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderDuplicateReference)); } } else { _uniqueUriRef.Add(uri, node); } } Hashtable validResources = _validResources.Peek(); if (validResources!=null) { if (!validResources.ContainsKey(uri)) { // The hashtable is case sensitive, packuris are not, so if we do not find in hashtable, // do true comparison and add when found for next time... bool found = false; foreach (Uri resUri in validResources.Keys) { if (PackUriHelper.ComparePackUri(resUri,uri) == 0) { validResources.Add(uri, validResources[resUri]); found = true; break; } } if (!found) { throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderUnlistedResource)); } } if (!(bool)validResources[uri]) { throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderUnsupportedMimeType)); } } } static private Stack<Hashtable> _validResources = new Stack<Hashtable>(); private Hashtable _uniqueUriRef; static private bool _documentMode = false; static private string _requiredResourceRel = "http://schemas.microsoft.com/xps/2005/06/required-resource"; static private XpsS0FixedPageSchema xpsS0FixedPageSchema = new XpsS0FixedPageSchema(); static private XpsS0ResourceDictionarySchema xpsS0ResourceDictionarySchema = new XpsS0ResourceDictionarySchema(); static private XpsDocStructSchema xpsDocStructSchema = new XpsDocStructSchema(); } }
using UnityEngine; using UnityEngine.UI; using UnityEngine.Events; using System; using System.Collections; using System.Collections.Generic; namespace Fungus { public struct PortraitState { public bool onScreen; public bool dimmed; public DisplayType display; public Sprite portrait; public RectTransform position; public FacingDirection facing; public Image portraitImage; } public enum DisplayType { None, Show, Hide, Replace, MoveToFront } public enum FacingDirection { None, Left, Right } public enum PositionOffset { None, OffsetLeft, OffsetRight } [CommandInfo("Narrative", "Portrait", "Controls a character portrait. ")] public class Portrait : Command { [Tooltip("Stage to display portrait on")] public Stage stage; [Tooltip("Display type")] public DisplayType display; [Tooltip("Character to display")] public Character character; [Tooltip("Character to swap with")] public Character replacedCharacter; [Tooltip("Portrait to display")] public Sprite portrait; [Tooltip("Move the portrait from/to this offset position")] public PositionOffset offset; [Tooltip("Move the portrait from this position")] public RectTransform fromPosition; [Tooltip("Move the portrait to this positoin")] public RectTransform toPosition; [Tooltip("Direction character is facing")] public FacingDirection facing; [Tooltip("Use Default Settings")] public bool useDefaultSettings = true; [Tooltip("Fade Duration")] public float fadeDuration = 0.5f; [Tooltip("Movement Duration")] public float moveDuration = 1f; [Tooltip("Shift Offset")] public Vector2 shiftOffset; [Tooltip("Move")] public bool move; [Tooltip("Start from offset")] public bool shiftIntoPlace; [Tooltip("Wait until the tween has finished before executing the next command")] public bool waitUntilFinished = false; // Timer for waitUntilFinished functionality protected float waitTimer; public override void OnEnter() { // If no display specified, do nothing if (display == DisplayType.None) { Continue(); return; } // If no character specified, do nothing if (character == null) { Continue(); return; } // If Replace and no replaced character specified, do nothing if (display == DisplayType.Replace && replacedCharacter == null) { Continue(); return; } // Selected "use default Portrait Stage" if (stage == null) // Default portrait stage selected { if (stage == null) // If no default specified, try to get any portrait stage in the scene { stage = GameObject.FindObjectOfType<Stage>(); } } // If portrait stage does not exist, do nothing if (stage == null) { Continue(); return; } // Use default settings if (useDefaultSettings) { fadeDuration = stage.fadeDuration; moveDuration = stage.moveDuration; shiftOffset = stage.shiftOffset; } if (character.state.portraitImage == null) { CreatePortraitObject(character, stage); } // if no previous portrait, use default portrait if (character.state.portrait == null) { character.state.portrait = character.profileSprite; } // Selected "use previous portrait" if (portrait == null) { portrait = character.state.portrait; } // if no previous position, use default position if (character.state.position == null) { character.state.position = stage.defaultPosition.rectTransform; } // Selected "use previous position" if (toPosition == null) { toPosition = character.state.position; } if (replacedCharacter != null) { // if no previous position, use default position if (replacedCharacter.state.position == null) { replacedCharacter.state.position = stage.defaultPosition.rectTransform; } } // If swapping, use replaced character's position if (display == DisplayType.Replace) { toPosition = replacedCharacter.state.position; } // Selected "use previous position" if (fromPosition == null) { fromPosition = character.state.position; } // if portrait not moving, use from position is same as to position if (!move) { fromPosition = toPosition; } if (display == DisplayType.Hide) { fromPosition = character.state.position; } // if no previous facing direction, use default facing direction if (character.state.facing == FacingDirection.None) { character.state.facing = character.portraitsFace; } // Selected "use previous facing direction" if (facing == FacingDirection.None) { facing = character.state.facing; } switch(display) { case (DisplayType.Show): Show(character, fromPosition, toPosition); character.state.onScreen = true; if (!stage.charactersOnStage.Contains(character)) { stage.charactersOnStage.Add(character); } break; case (DisplayType.Hide): Hide(character, fromPosition, toPosition); character.state.onScreen = false; stage.charactersOnStage.Remove(character); break; case (DisplayType.Replace): Show(character, fromPosition, toPosition); Hide(replacedCharacter, replacedCharacter.state.position, replacedCharacter.state.position); character.state.onScreen = true; replacedCharacter.state.onScreen = false; stage.charactersOnStage.Add(character); stage.charactersOnStage.Remove(replacedCharacter); break; case (DisplayType.MoveToFront): MoveToFront(character); break; } if (display == DisplayType.Replace) { character.state.display = DisplayType.Show; replacedCharacter.state.display = DisplayType.Hide; } else { character.state.display = display; } character.state.portrait = portrait; character.state.facing = facing; character.state.position = toPosition; waitTimer = 0f; if (!waitUntilFinished) { Continue(); } else { StartCoroutine(WaitUntilFinished(fadeDuration)); } } protected virtual IEnumerator WaitUntilFinished(float duration) { // Wait until the timer has expired // Any method can modify this timer variable to delay continuing. waitTimer = duration; while (waitTimer > 0f) { waitTimer -= Time.deltaTime; yield return null; } Continue(); } protected virtual void CreatePortraitObject(Character character, Stage stage) { // Create a new portrait object GameObject portraitObj = new GameObject(character.name, typeof(RectTransform), typeof(CanvasRenderer), typeof(Image)); // Set it to be a child of the stage portraitObj.transform.SetParent(stage.portraitCanvas.transform, true); // Configure the portrait image Image portraitImage = portraitObj.GetComponent<Image>(); portraitImage.preserveAspect = true; portraitImage.sprite = character.profileSprite; portraitImage.color = new Color(1f, 1f, 1f, 0f); // LeanTween doesn't handle 0 duration properly float duration = (fadeDuration > 0f) ? fadeDuration : float.Epsilon; // Fade in character image (first time) LeanTween.alpha(portraitImage.transform as RectTransform, 1f, duration).setEase(stage.fadeEaseType); // Tell character about portrait image character.state.portraitImage = portraitImage; } protected void SetupPortrait(Character character, RectTransform fromPosition) { SetRectTransform(character.state.portraitImage.rectTransform, fromPosition); if (character.state.facing != character.portraitsFace) { character.state.portraitImage.rectTransform.localScale = new Vector3(-1f, 1f, 1f); } else { character.state.portraitImage.rectTransform.localScale = new Vector3(1f, 1f, 1f); } if (facing != character.portraitsFace) { character.state.portraitImage.rectTransform.localScale = new Vector3(-1f, 1f, 1f); } else { character.state.portraitImage.rectTransform.localScale = new Vector3(1f, 1f, 1f); } } public static void SetRectTransform(RectTransform oldRectTransform, RectTransform newRectTransform) { oldRectTransform.eulerAngles = newRectTransform.eulerAngles; oldRectTransform.position = newRectTransform.position; oldRectTransform.rotation = newRectTransform.rotation; oldRectTransform.anchoredPosition = newRectTransform.anchoredPosition; oldRectTransform.sizeDelta = newRectTransform.sizeDelta; oldRectTransform.anchorMax = newRectTransform.anchorMax; oldRectTransform.anchorMin = newRectTransform.anchorMin; oldRectTransform.pivot = newRectTransform.pivot; oldRectTransform.localScale = newRectTransform.localScale; } protected void Show(Character character, RectTransform fromPosition, RectTransform toPosition) { if (shiftIntoPlace) { fromPosition = Instantiate(toPosition) as RectTransform; if (offset == PositionOffset.OffsetLeft) { fromPosition.anchoredPosition = new Vector2(fromPosition.anchoredPosition.x - Mathf.Abs(shiftOffset.x), fromPosition.anchoredPosition.y - Mathf.Abs(shiftOffset.y)); } else if (offset == PositionOffset.OffsetRight) { fromPosition.anchoredPosition = new Vector2(fromPosition.anchoredPosition.x + Mathf.Abs(shiftOffset.x), fromPosition.anchoredPosition.y + Mathf.Abs(shiftOffset.y)); } else { fromPosition.anchoredPosition = new Vector2(fromPosition.anchoredPosition.x, fromPosition.anchoredPosition.y); } } SetupPortrait(character, fromPosition); // LeanTween doesn't handle 0 duration properly float duration = (fadeDuration > 0f) ? fadeDuration : float.Epsilon; // Fade out a duplicate of the existing portrait image if (character.state.portraitImage != null) { GameObject tempGO = GameObject.Instantiate(character.state.portraitImage.gameObject); tempGO.transform.SetParent(character.state.portraitImage.transform, false); tempGO.transform.localPosition = Vector3.zero; Image tempImage = tempGO.GetComponent<Image>(); tempImage.sprite = character.state.portraitImage.sprite; tempImage.preserveAspect = true; tempImage.color = character.state.portraitImage.color; LeanTween.alpha(tempImage.rectTransform, 0f, duration).setEase(stage.fadeEaseType).setOnComplete(() => { Destroy(tempGO); }); } // Fade in the new sprite image character.state.portraitImage.sprite = portrait; character.state.portraitImage.color = new Color(1f, 1f, 1f, 0f); LeanTween.alpha(character.state.portraitImage.rectTransform, 1f, duration).setEase(stage.fadeEaseType); DoMoveTween(character, fromPosition, toPosition); } protected void Hide(Character character, RectTransform fromPosition, RectTransform toPosition) { if (character.state.display == DisplayType.None) { return; } SetupPortrait(character, fromPosition); // LeanTween doesn't handle 0 duration properly float duration = (fadeDuration > 0f) ? fadeDuration : float.Epsilon; LeanTween.alpha(character.state.portraitImage.rectTransform, 0f, duration).setEase(stage.fadeEaseType); DoMoveTween(character, fromPosition, toPosition); } protected void MoveToFront(Character character) { character.state.portraitImage.transform.SetSiblingIndex(character.state.portraitImage.transform.parent.childCount); } protected void DoMoveTween(Character character, RectTransform fromPosition, RectTransform toPosition) { // LeanTween doesn't handle 0 duration properly float duration = (moveDuration > 0f) ? moveDuration : float.Epsilon; // LeanTween.move uses the anchoredPosition, so all position images must have the same anchor position LeanTween.move(character.state.portraitImage.gameObject, toPosition.position, duration).setEase(stage.fadeEaseType); if (waitUntilFinished) { waitTimer = duration; } } public static void SetDimmed(Character character, Stage stage, bool dimmedState) { if (character.state.dimmed == dimmedState) { return; } character.state.dimmed = dimmedState; Color targetColor = dimmedState ? new Color(0.5f, 0.5f, 0.5f, 1f) : Color.white; // LeanTween doesn't handle 0 duration properly float duration = (stage.fadeDuration > 0f) ? stage.fadeDuration : float.Epsilon; LeanTween.color(character.state.portraitImage.rectTransform, targetColor, duration).setEase(stage.fadeEaseType); } public override string GetSummary() { if (display == DisplayType.None && character == null) { return "Error: No character or display selected"; } else if (display == DisplayType.None) { return "Error: No display selected"; } else if (character == null) { return "Error: No character selected"; } string displaySummary = ""; string characterSummary = ""; string fromPositionSummary = ""; string toPositionSummary = ""; string stageSummary = ""; string portraitSummary = ""; string facingSummary = ""; displaySummary = StringFormatter.SplitCamelCase(display.ToString()); if (display == DisplayType.Replace) { if (replacedCharacter != null) { displaySummary += " \"" + replacedCharacter.name + "\" with"; } } characterSummary = character.name; if (stage != null) { stageSummary = " on \"" + stage.name + "\""; } if (portrait != null) { portraitSummary = " " + portrait.name; } if (shiftIntoPlace) { if (offset != 0) { fromPositionSummary = offset.ToString(); fromPositionSummary = " from " + "\"" + fromPositionSummary + "\""; } } else if (fromPosition != null) { fromPositionSummary = " from " + "\"" + fromPosition.name + "\""; } if (toPosition != null) { string toPositionPrefixSummary = ""; if (move) { toPositionPrefixSummary = " to "; } else { toPositionPrefixSummary = " at "; } toPositionSummary = toPositionPrefixSummary + "\"" + toPosition.name + "\""; } if (facing != FacingDirection.None) { if (facing == FacingDirection.Left) { facingSummary = "<--"; } if (facing == FacingDirection.Right) { facingSummary = "-->"; } facingSummary = " facing \"" + facingSummary + "\""; } return displaySummary + " \"" + characterSummary + portraitSummary + "\"" + stageSummary + facingSummary + fromPositionSummary + toPositionSummary; } public override Color GetButtonColor() { return new Color32(230, 200, 250, 255); } public override void OnCommandAdded(Block parentBlock) { //Default to display type: show display = DisplayType.Show; } } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // using System; using System.IO; using DiscUtils.Streams; namespace DiscUtils.Ntfs { internal sealed class Bitmap : IDisposable { private BlockCacheStream _bitmap; private readonly long _maxIndex; private long _nextAvailable; private readonly Stream _stream; public Bitmap(Stream stream, long maxIndex) { _stream = stream; _maxIndex = maxIndex; _bitmap = new BlockCacheStream(SparseStream.FromStream(stream, Ownership.None), Ownership.None); } public void Dispose() { if (_bitmap != null) { _bitmap.Dispose(); _bitmap = null; } } public bool IsPresent(long index) { long byteIdx = index / 8; int mask = 1 << (int)(index % 8); return (GetByte(byteIdx) & mask) != 0; } public void MarkPresent(long index) { long byteIdx = index / 8; byte mask = (byte)(1 << (byte)(index % 8)); if (byteIdx >= _bitmap.Length) { _bitmap.Position = MathUtilities.RoundUp(byteIdx + 1, 8) - 1; _bitmap.WriteByte(0); } SetByte(byteIdx, (byte)(GetByte(byteIdx) | mask)); } public void MarkPresentRange(long index, long count) { if (count <= 0) { return; } long firstByte = index / 8; long lastByte = (index + count - 1) / 8; if (lastByte >= _bitmap.Length) { _bitmap.Position = MathUtilities.RoundUp(lastByte + 1, 8) - 1; _bitmap.WriteByte(0); } byte[] buffer = new byte[lastByte - firstByte + 1]; buffer[0] = GetByte(firstByte); if (buffer.Length != 1) { buffer[buffer.Length - 1] = GetByte(lastByte); } for (long i = index; i < index + count; ++i) { long byteIdx = i / 8 - firstByte; byte mask = (byte)(1 << (byte)(i % 8)); buffer[byteIdx] |= mask; } SetBytes(firstByte, buffer); } public void MarkAbsent(long index) { long byteIdx = index / 8; byte mask = (byte)(1 << (byte)(index % 8)); if (byteIdx < _stream.Length) { SetByte(byteIdx, (byte)(GetByte(byteIdx) & ~mask)); } if (index < _nextAvailable) { _nextAvailable = index; } } internal void MarkAbsentRange(long index, long count) { if (count <= 0) { return; } long firstByte = index / 8; long lastByte = (index + count - 1) / 8; if (lastByte >= _bitmap.Length) { _bitmap.Position = MathUtilities.RoundUp(lastByte + 1, 8) - 1; _bitmap.WriteByte(0); } byte[] buffer = new byte[lastByte - firstByte + 1]; buffer[0] = GetByte(firstByte); if (buffer.Length != 1) { buffer[buffer.Length - 1] = GetByte(lastByte); } for (long i = index; i < index + count; ++i) { long byteIdx = i / 8 - firstByte; byte mask = (byte)(1 << (byte)(i % 8)); buffer[byteIdx] &= (byte)~mask; } SetBytes(firstByte, buffer); if (index < _nextAvailable) { _nextAvailable = index; } } internal long AllocateFirstAvailable(long minValue) { long i = Math.Max(minValue, _nextAvailable); while (IsPresent(i) && i < _maxIndex) { ++i; } if (i < _maxIndex) { MarkPresent(i); _nextAvailable = i + 1; return i; } return -1; } internal long SetTotalEntries(long numEntries) { long length = MathUtilities.RoundUp(MathUtilities.Ceil(numEntries, 8), 8); _stream.SetLength(length); return length * 8; } internal long Size { get { return _bitmap.Length; } } internal byte GetByte(long index) { if (index >= _bitmap.Length) { return 0; } byte[] buffer = new byte[1]; _bitmap.Position = index; if (_bitmap.Read(buffer, 0, 1) != 0) { return buffer[0]; } return 0; } internal int GetBytes(long index, byte[] buffer, int offset, int count) { if (index + count >= _bitmap.Length) count = (int)(_bitmap.Length - index); if (count <= 0) return 0; _bitmap.Position = index; return _bitmap.Read(buffer, offset, count); } private void SetByte(long index, byte value) { byte[] buffer = { value }; _bitmap.Position = index; _bitmap.Write(buffer, 0, 1); _bitmap.Flush(); } private void SetBytes(long index, byte[] buffer) { _bitmap.Position = index; _bitmap.Write(buffer, 0, buffer.Length); _bitmap.Flush(); } } }
// // Mono.CSharp.Debugger/MonoSymbolTable.cs // // Author: // Martin Baulig (martin@ximian.com) // // (C) 2002 Ximian, Inc. http://www.ximian.com // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Security.Cryptography; using System.Collections.Generic; using System.Text; using System.IO; // // Parts which are actually written into the symbol file are marked with // // #region This is actually written to the symbol file // #endregion // // Please do not modify these regions without previously talking to me. // // All changes to the file format must be synchronized in several places: // // a) The fields in these regions (and their order) must match the actual // contents of the symbol file. // // This helps people to understand the symbol file format without reading // too much source code, ie. you look at the appropriate region and then // you know what's actually in the file. // // It is also required to help me enforce b). // // b) The regions must be kept in sync with the unmanaged code in // mono/metadata/debug-mono-symfile.h // // When making changes to the file format, you must also increase two version // numbers: // // i) OffsetTable.Version in this file. // ii) MONO_SYMBOL_FILE_VERSION in mono/metadata/debug-mono-symfile.h // // After doing so, recompile everything, including the debugger. Symbol files // with different versions are incompatible to each other and the debugger and // the runtime enfore this, so you need to recompile all your assemblies after // changing the file format. // namespace SquabPie.Mono.CompilerServices.SymbolWriter { public class OffsetTable { public const int MajorVersion = 50; public const int MinorVersion = 0; public const long Magic = 0x45e82623fd7fa614; #region This is actually written to the symbol file public int TotalFileSize; public int DataSectionOffset; public int DataSectionSize; public int CompileUnitCount; public int CompileUnitTableOffset; public int CompileUnitTableSize; public int SourceCount; public int SourceTableOffset; public int SourceTableSize; public int MethodCount; public int MethodTableOffset; public int MethodTableSize; public int TypeCount; public int AnonymousScopeCount; public int AnonymousScopeTableOffset; public int AnonymousScopeTableSize; [Flags] public enum Flags { IsAspxSource = 1, WindowsFileNames = 2 } public Flags FileFlags; public int LineNumberTable_LineBase = LineNumberTable.Default_LineBase; public int LineNumberTable_LineRange = LineNumberTable.Default_LineRange; public int LineNumberTable_OpcodeBase = LineNumberTable.Default_OpcodeBase; #endregion internal OffsetTable () { int platform = (int) Environment.OSVersion.Platform; if ((platform != 4) && (platform != 128)) FileFlags |= Flags.WindowsFileNames; } internal OffsetTable (BinaryReader reader, int major_version, int minor_version) { TotalFileSize = reader.ReadInt32 (); DataSectionOffset = reader.ReadInt32 (); DataSectionSize = reader.ReadInt32 (); CompileUnitCount = reader.ReadInt32 (); CompileUnitTableOffset = reader.ReadInt32 (); CompileUnitTableSize = reader.ReadInt32 (); SourceCount = reader.ReadInt32 (); SourceTableOffset = reader.ReadInt32 (); SourceTableSize = reader.ReadInt32 (); MethodCount = reader.ReadInt32 (); MethodTableOffset = reader.ReadInt32 (); MethodTableSize = reader.ReadInt32 (); TypeCount = reader.ReadInt32 (); AnonymousScopeCount = reader.ReadInt32 (); AnonymousScopeTableOffset = reader.ReadInt32 (); AnonymousScopeTableSize = reader.ReadInt32 (); LineNumberTable_LineBase = reader.ReadInt32 (); LineNumberTable_LineRange = reader.ReadInt32 (); LineNumberTable_OpcodeBase = reader.ReadInt32 (); FileFlags = (Flags) reader.ReadInt32 (); } internal void Write (BinaryWriter bw, int major_version, int minor_version) { bw.Write (TotalFileSize); bw.Write (DataSectionOffset); bw.Write (DataSectionSize); bw.Write (CompileUnitCount); bw.Write (CompileUnitTableOffset); bw.Write (CompileUnitTableSize); bw.Write (SourceCount); bw.Write (SourceTableOffset); bw.Write (SourceTableSize); bw.Write (MethodCount); bw.Write (MethodTableOffset); bw.Write (MethodTableSize); bw.Write (TypeCount); bw.Write (AnonymousScopeCount); bw.Write (AnonymousScopeTableOffset); bw.Write (AnonymousScopeTableSize); bw.Write (LineNumberTable_LineBase); bw.Write (LineNumberTable_LineRange); bw.Write (LineNumberTable_OpcodeBase); bw.Write ((int) FileFlags); } public override string ToString () { return String.Format ( "OffsetTable [{0} - {1}:{2} - {3}:{4}:{5} - {6}:{7}:{8} - {9}]", TotalFileSize, DataSectionOffset, DataSectionSize, SourceCount, SourceTableOffset, SourceTableSize, MethodCount, MethodTableOffset, MethodTableSize, TypeCount); } } public class LineNumberEntry { #region This is actually written to the symbol file public readonly int Row; public int Column; public int EndRow, EndColumn; public readonly int File; public readonly int Offset; public readonly bool IsHidden; // Obsolete is never used #endregion public sealed class LocationComparer : IComparer<LineNumberEntry> { public static readonly LocationComparer Default = new LocationComparer (); public int Compare (LineNumberEntry l1, LineNumberEntry l2) { return l1.Row == l2.Row ? l1.Column.CompareTo (l2.Column) : l1.Row.CompareTo (l2.Row); } } public static readonly LineNumberEntry Null = new LineNumberEntry (0, 0, 0, 0); public LineNumberEntry (int file, int row, int column, int offset) : this (file, row, column, offset, false) { } public LineNumberEntry (int file, int row, int offset) : this (file, row, -1, offset, false) { } public LineNumberEntry (int file, int row, int column, int offset, bool is_hidden) : this (file, row, column, -1, -1, offset, is_hidden) { } public LineNumberEntry (int file, int row, int column, int end_row, int end_column, int offset, bool is_hidden) { this.File = file; this.Row = row; this.Column = column; this.EndRow = end_row; this.EndColumn = end_column; this.Offset = offset; this.IsHidden = is_hidden; } public override string ToString () { return String.Format ("[Line {0}:{1,2}-{3,4}:{5}]", File, Row, Column, EndRow, EndColumn, Offset); } } public class CodeBlockEntry { public int Index; #region This is actually written to the symbol file public int Parent; public Type BlockType; public int StartOffset; public int EndOffset; #endregion public enum Type { Lexical = 1, CompilerGenerated = 2, IteratorBody = 3, IteratorDispatcher = 4 } public CodeBlockEntry (int index, int parent, Type type, int start_offset) { this.Index = index; this.Parent = parent; this.BlockType = type; this.StartOffset = start_offset; } internal CodeBlockEntry (int index, MyBinaryReader reader) { this.Index = index; int type_flag = reader.ReadLeb128 (); BlockType = (Type) (type_flag & 0x3f); this.Parent = reader.ReadLeb128 (); this.StartOffset = reader.ReadLeb128 (); this.EndOffset = reader.ReadLeb128 (); /* Reserved for future extensions. */ if ((type_flag & 0x40) != 0) { int data_size = reader.ReadInt16 (); reader.BaseStream.Position += data_size; } } public void Close (int end_offset) { this.EndOffset = end_offset; } internal void Write (MyBinaryWriter bw) { bw.WriteLeb128 ((int) BlockType); bw.WriteLeb128 (Parent); bw.WriteLeb128 (StartOffset); bw.WriteLeb128 (EndOffset); } public override string ToString () { return String.Format ("[CodeBlock {0}:{1}:{2}:{3}:{4}]", Index, Parent, BlockType, StartOffset, EndOffset); } } public struct LocalVariableEntry { #region This is actually written to the symbol file public readonly int Index; public readonly string Name; public readonly int BlockIndex; #endregion public LocalVariableEntry (int index, string name, int block) { this.Index = index; this.Name = name; this.BlockIndex = block; } internal LocalVariableEntry (MonoSymbolFile file, MyBinaryReader reader) { Index = reader.ReadLeb128 (); Name = reader.ReadString (); BlockIndex = reader.ReadLeb128 (); } internal void Write (MonoSymbolFile file, MyBinaryWriter bw) { bw.WriteLeb128 (Index); bw.Write (Name); bw.WriteLeb128 (BlockIndex); } public override string ToString () { return String.Format ("[LocalVariable {0}:{1}:{2}]", Name, Index, BlockIndex - 1); } } public struct CapturedVariable { #region This is actually written to the symbol file public readonly string Name; public readonly string CapturedName; public readonly CapturedKind Kind; #endregion public enum CapturedKind : byte { Local, Parameter, This } public CapturedVariable (string name, string captured_name, CapturedKind kind) { this.Name = name; this.CapturedName = captured_name; this.Kind = kind; } internal CapturedVariable (MyBinaryReader reader) { Name = reader.ReadString (); CapturedName = reader.ReadString (); Kind = (CapturedKind) reader.ReadByte (); } internal void Write (MyBinaryWriter bw) { bw.Write (Name); bw.Write (CapturedName); bw.Write ((byte) Kind); } public override string ToString () { return String.Format ("[CapturedVariable {0}:{1}:{2}]", Name, CapturedName, Kind); } } public struct CapturedScope { #region This is actually written to the symbol file public readonly int Scope; public readonly string CapturedName; #endregion public CapturedScope (int scope, string captured_name) { this.Scope = scope; this.CapturedName = captured_name; } internal CapturedScope (MyBinaryReader reader) { Scope = reader.ReadLeb128 (); CapturedName = reader.ReadString (); } internal void Write (MyBinaryWriter bw) { bw.WriteLeb128 (Scope); bw.Write (CapturedName); } public override string ToString () { return String.Format ("[CapturedScope {0}:{1}]", Scope, CapturedName); } } public struct ScopeVariable { #region This is actually written to the symbol file public readonly int Scope; public readonly int Index; #endregion public ScopeVariable (int scope, int index) { this.Scope = scope; this.Index = index; } internal ScopeVariable (MyBinaryReader reader) { Scope = reader.ReadLeb128 (); Index = reader.ReadLeb128 (); } internal void Write (MyBinaryWriter bw) { bw.WriteLeb128 (Scope); bw.WriteLeb128 (Index); } public override string ToString () { return String.Format ("[ScopeVariable {0}:{1}]", Scope, Index); } } public class AnonymousScopeEntry { #region This is actually written to the symbol file public readonly int ID; #endregion List<CapturedVariable> captured_vars = new List<CapturedVariable> (); List<CapturedScope> captured_scopes = new List<CapturedScope> (); public AnonymousScopeEntry (int id) { this.ID = id; } internal AnonymousScopeEntry (MyBinaryReader reader) { ID = reader.ReadLeb128 (); int num_captured_vars = reader.ReadLeb128 (); for (int i = 0; i < num_captured_vars; i++) captured_vars.Add (new CapturedVariable (reader)); int num_captured_scopes = reader.ReadLeb128 (); for (int i = 0; i < num_captured_scopes; i++) captured_scopes.Add (new CapturedScope (reader)); } internal void AddCapturedVariable (string name, string captured_name, CapturedVariable.CapturedKind kind) { captured_vars.Add (new CapturedVariable (name, captured_name, kind)); } public CapturedVariable[] CapturedVariables { get { CapturedVariable[] retval = new CapturedVariable [captured_vars.Count]; captured_vars.CopyTo (retval, 0); return retval; } } internal void AddCapturedScope (int scope, string captured_name) { captured_scopes.Add (new CapturedScope (scope, captured_name)); } public CapturedScope[] CapturedScopes { get { CapturedScope[] retval = new CapturedScope [captured_scopes.Count]; captured_scopes.CopyTo (retval, 0); return retval; } } internal void Write (MyBinaryWriter bw) { bw.WriteLeb128 (ID); bw.WriteLeb128 (captured_vars.Count); foreach (CapturedVariable cv in captured_vars) cv.Write (bw); bw.WriteLeb128 (captured_scopes.Count); foreach (CapturedScope cs in captured_scopes) cs.Write (bw); } public override string ToString () { return String.Format ("[AnonymousScope {0}]", ID); } } public class CompileUnitEntry : ICompileUnit { #region This is actually written to the symbol file public readonly int Index; int DataOffset; #endregion MonoSymbolFile file; SourceFileEntry source; List<SourceFileEntry> include_files; List<NamespaceEntry> namespaces; bool creating; public static int Size { get { return 8; } } CompileUnitEntry ICompileUnit.Entry { get { return this; } } public CompileUnitEntry (MonoSymbolFile file, SourceFileEntry source) { this.file = file; this.source = source; this.Index = file.AddCompileUnit (this); creating = true; namespaces = new List<NamespaceEntry> (); } public void AddFile (SourceFileEntry file) { if (!creating) throw new InvalidOperationException (); if (include_files == null) include_files = new List<SourceFileEntry> (); include_files.Add (file); } public SourceFileEntry SourceFile { get { if (creating) return source; ReadData (); return source; } } public int DefineNamespace (string name, string[] using_clauses, int parent) { if (!creating) throw new InvalidOperationException (); int index = file.GetNextNamespaceIndex (); NamespaceEntry ns = new NamespaceEntry (name, index, using_clauses, parent); namespaces.Add (ns); return index; } internal void WriteData (MyBinaryWriter bw) { DataOffset = (int) bw.BaseStream.Position; bw.WriteLeb128 (source.Index); int count_includes = include_files != null ? include_files.Count : 0; bw.WriteLeb128 (count_includes); if (include_files != null) { foreach (SourceFileEntry entry in include_files) bw.WriteLeb128 (entry.Index); } bw.WriteLeb128 (namespaces.Count); foreach (NamespaceEntry ns in namespaces) ns.Write (file, bw); } internal void Write (BinaryWriter bw) { bw.Write (Index); bw.Write (DataOffset); } internal CompileUnitEntry (MonoSymbolFile file, MyBinaryReader reader) { this.file = file; Index = reader.ReadInt32 (); DataOffset = reader.ReadInt32 (); } public void ReadAll () { ReadData (); } void ReadData () { if (creating) throw new InvalidOperationException (); lock (file) { if (namespaces != null) return; MyBinaryReader reader = file.BinaryReader; int old_pos = (int) reader.BaseStream.Position; reader.BaseStream.Position = DataOffset; int source_idx = reader.ReadLeb128 (); source = file.GetSourceFile (source_idx); int count_includes = reader.ReadLeb128 (); if (count_includes > 0) { include_files = new List<SourceFileEntry> (); for (int i = 0; i < count_includes; i++) include_files.Add (file.GetSourceFile (reader.ReadLeb128 ())); } int count_ns = reader.ReadLeb128 (); namespaces = new List<NamespaceEntry> (); for (int i = 0; i < count_ns; i ++) namespaces.Add (new NamespaceEntry (file, reader)); reader.BaseStream.Position = old_pos; } } public NamespaceEntry[] Namespaces { get { ReadData (); NamespaceEntry[] retval = new NamespaceEntry [namespaces.Count]; namespaces.CopyTo (retval, 0); return retval; } } public SourceFileEntry[] IncludeFiles { get { ReadData (); if (include_files == null) return new SourceFileEntry [0]; SourceFileEntry[] retval = new SourceFileEntry [include_files.Count]; include_files.CopyTo (retval, 0); return retval; } } } public class SourceFileEntry { #region This is actually written to the symbol file public readonly int Index; int DataOffset; #endregion MonoSymbolFile file; string file_name; byte[] guid; byte[] hash; bool creating; bool auto_generated; public static int Size { get { return 8; } } public SourceFileEntry (MonoSymbolFile file, string file_name) { this.file = file; this.file_name = file_name; this.Index = file.AddSource (this); creating = true; } public SourceFileEntry (MonoSymbolFile file, string file_name, byte[] guid, byte[] checksum) : this (file, file_name) { this.guid = guid; this.hash = checksum; } public byte[] Checksum { get { return hash; } } internal void WriteData (MyBinaryWriter bw) { DataOffset = (int) bw.BaseStream.Position; bw.Write (file_name); if (guid == null) guid = new byte[16]; if (hash == null) { try { using (FileStream fs = new FileStream (file_name, FileMode.Open, FileAccess.Read)) { MD5 md5 = MD5.Create (); hash = md5.ComputeHash (fs); } } catch { hash = new byte [16]; } } bw.Write (guid); bw.Write (hash); bw.Write ((byte) (auto_generated ? 1 : 0)); } internal void Write (BinaryWriter bw) { bw.Write (Index); bw.Write (DataOffset); } internal SourceFileEntry (MonoSymbolFile file, MyBinaryReader reader) { this.file = file; Index = reader.ReadInt32 (); DataOffset = reader.ReadInt32 (); int old_pos = (int) reader.BaseStream.Position; reader.BaseStream.Position = DataOffset; file_name = reader.ReadString (); guid = reader.ReadBytes (16); hash = reader.ReadBytes (16); auto_generated = reader.ReadByte () == 1; reader.BaseStream.Position = old_pos; } public string FileName { get { return file_name; } set { file_name = value; } } public bool AutoGenerated { get { return auto_generated; } } public void SetAutoGenerated () { if (!creating) throw new InvalidOperationException (); auto_generated = true; file.OffsetTable.FileFlags |= OffsetTable.Flags.IsAspxSource; } public bool CheckChecksum () { try { using (FileStream fs = new FileStream (file_name, FileMode.Open)) { MD5 md5 = MD5.Create (); byte[] data = md5.ComputeHash (fs); for (int i = 0; i < 16; i++) if (data [i] != hash [i]) return false; return true; } } catch { return false; } } public override string ToString () { return String.Format ("SourceFileEntry ({0}:{1})", Index, DataOffset); } } public class LineNumberTable { protected LineNumberEntry[] _line_numbers; public LineNumberEntry[] LineNumbers { get { return _line_numbers; } } public readonly int LineBase; public readonly int LineRange; public readonly byte OpcodeBase; public readonly int MaxAddressIncrement; #region Configurable constants public const int Default_LineBase = -1; public const int Default_LineRange = 8; public const byte Default_OpcodeBase = 9; #endregion public const byte DW_LNS_copy = 1; public const byte DW_LNS_advance_pc = 2; public const byte DW_LNS_advance_line = 3; public const byte DW_LNS_set_file = 4; public const byte DW_LNS_const_add_pc = 8; public const byte DW_LNE_end_sequence = 1; // MONO extensions. public const byte DW_LNE_MONO_negate_is_hidden = 0x40; internal const byte DW_LNE_MONO__extensions_start = 0x40; internal const byte DW_LNE_MONO__extensions_end = 0x7f; protected LineNumberTable (MonoSymbolFile file) { this.LineBase = file.OffsetTable.LineNumberTable_LineBase; this.LineRange = file.OffsetTable.LineNumberTable_LineRange; this.OpcodeBase = (byte) file.OffsetTable.LineNumberTable_OpcodeBase; this.MaxAddressIncrement = (255 - OpcodeBase) / LineRange; } internal LineNumberTable (MonoSymbolFile file, LineNumberEntry[] lines) : this (file) { this._line_numbers = lines; } internal void Write (MonoSymbolFile file, MyBinaryWriter bw, bool hasColumnsInfo, bool hasEndInfo) { int start = (int) bw.BaseStream.Position; bool last_is_hidden = false; int last_line = 1, last_offset = 0, last_file = 1; for (int i = 0; i < LineNumbers.Length; i++) { int line_inc = LineNumbers [i].Row - last_line; int offset_inc = LineNumbers [i].Offset - last_offset; if (LineNumbers [i].File != last_file) { bw.Write (DW_LNS_set_file); bw.WriteLeb128 (LineNumbers [i].File); last_file = LineNumbers [i].File; } if (LineNumbers [i].IsHidden != last_is_hidden) { bw.Write ((byte) 0); bw.Write ((byte) 1); bw.Write (DW_LNE_MONO_negate_is_hidden); last_is_hidden = LineNumbers [i].IsHidden; } if (offset_inc >= MaxAddressIncrement) { if (offset_inc < 2 * MaxAddressIncrement) { bw.Write (DW_LNS_const_add_pc); offset_inc -= MaxAddressIncrement; } else { bw.Write (DW_LNS_advance_pc); bw.WriteLeb128 (offset_inc); offset_inc = 0; } } if ((line_inc < LineBase) || (line_inc >= LineBase + LineRange)) { bw.Write (DW_LNS_advance_line); bw.WriteLeb128 (line_inc); if (offset_inc != 0) { bw.Write (DW_LNS_advance_pc); bw.WriteLeb128 (offset_inc); } bw.Write (DW_LNS_copy); } else { byte opcode; opcode = (byte) (line_inc - LineBase + (LineRange * offset_inc) + OpcodeBase); bw.Write (opcode); } last_line = LineNumbers [i].Row; last_offset = LineNumbers [i].Offset; } bw.Write ((byte) 0); bw.Write ((byte) 1); bw.Write (DW_LNE_end_sequence); if (hasColumnsInfo) { for (int i = 0; i < LineNumbers.Length; i++) { var ln = LineNumbers [i]; if (ln.Row >= 0) bw.WriteLeb128 (ln.Column); } } if (hasEndInfo) { for (int i = 0; i < LineNumbers.Length; i++) { var ln = LineNumbers [i]; if (ln.EndRow == -1 || ln.EndColumn == -1 || ln.Row > ln.EndRow) { bw.WriteLeb128 (0xffffff); } else { bw.WriteLeb128 (ln.EndRow - ln.Row); bw.WriteLeb128 (ln.EndColumn); } } } file.ExtendedLineNumberSize += (int) bw.BaseStream.Position - start; } internal static LineNumberTable Read (MonoSymbolFile file, MyBinaryReader br, bool readColumnsInfo, bool readEndInfo) { LineNumberTable lnt = new LineNumberTable (file); lnt.DoRead (file, br, readColumnsInfo, readEndInfo); return lnt; } void DoRead (MonoSymbolFile file, MyBinaryReader br, bool includesColumns, bool includesEnds) { var lines = new List<LineNumberEntry> (); bool is_hidden = false, modified = false; int stm_line = 1, stm_offset = 0, stm_file = 1; while (true) { byte opcode = br.ReadByte (); if (opcode == 0) { byte size = br.ReadByte (); long end_pos = br.BaseStream.Position + size; opcode = br.ReadByte (); if (opcode == DW_LNE_end_sequence) { if (modified) lines.Add (new LineNumberEntry ( stm_file, stm_line, -1, stm_offset, is_hidden)); break; } else if (opcode == DW_LNE_MONO_negate_is_hidden) { is_hidden = !is_hidden; modified = true; } else if ((opcode >= DW_LNE_MONO__extensions_start) && (opcode <= DW_LNE_MONO__extensions_end)) { ; // reserved for future extensions } else { throw new MonoSymbolFileException ("Unknown extended opcode {0:x}", opcode); } br.BaseStream.Position = end_pos; continue; } else if (opcode < OpcodeBase) { switch (opcode) { case DW_LNS_copy: lines.Add (new LineNumberEntry ( stm_file, stm_line, -1, stm_offset, is_hidden)); modified = false; break; case DW_LNS_advance_pc: stm_offset += br.ReadLeb128 (); modified = true; break; case DW_LNS_advance_line: stm_line += br.ReadLeb128 (); modified = true; break; case DW_LNS_set_file: stm_file = br.ReadLeb128 (); modified = true; break; case DW_LNS_const_add_pc: stm_offset += MaxAddressIncrement; modified = true; break; default: throw new MonoSymbolFileException ( "Unknown standard opcode {0:x} in LNT", opcode); } } else { opcode -= OpcodeBase; stm_offset += opcode / LineRange; stm_line += LineBase + (opcode % LineRange); lines.Add (new LineNumberEntry ( stm_file, stm_line, -1, stm_offset, is_hidden)); modified = false; } } _line_numbers = lines.ToArray (); if (includesColumns) { for (int i = 0; i < _line_numbers.Length; ++i) { var ln = _line_numbers[i]; if (ln.Row >= 0) ln.Column = br.ReadLeb128 (); } } if (includesEnds) { for (int i = 0; i < _line_numbers.Length; ++i) { var ln = _line_numbers[i]; int row = br.ReadLeb128 (); if (row == 0xffffff) { ln.EndRow = -1; ln.EndColumn = -1; } else { ln.EndRow = ln.Row + row; ln.EndColumn = br.ReadLeb128 (); } } } } public bool GetMethodBounds (out LineNumberEntry start, out LineNumberEntry end) { if (_line_numbers.Length > 1) { start = _line_numbers [0]; end = _line_numbers [_line_numbers.Length - 1]; return true; } start = LineNumberEntry.Null; end = LineNumberEntry.Null; return false; } } public class MethodEntry : IComparable { #region This is actually written to the symbol file public readonly int CompileUnitIndex; public readonly int Token; public readonly int NamespaceID; int DataOffset; int LocalVariableTableOffset; int LineNumberTableOffset; int CodeBlockTableOffset; int ScopeVariableTableOffset; int RealNameOffset; Flags flags; #endregion int index; public Flags MethodFlags { get { return flags; } } public readonly CompileUnitEntry CompileUnit; LocalVariableEntry[] locals; CodeBlockEntry[] code_blocks; ScopeVariable[] scope_vars; LineNumberTable lnt; string real_name; public readonly MonoSymbolFile SymbolFile; public int Index { get { return index; } set { index = value; } } [Flags] public enum Flags { LocalNamesAmbiguous = 1, ColumnsInfoIncluded = 1 << 1, EndInfoIncluded = 1 << 2 } public const int Size = 12; internal MethodEntry (MonoSymbolFile file, MyBinaryReader reader, int index) { this.SymbolFile = file; this.index = index; Token = reader.ReadInt32 (); DataOffset = reader.ReadInt32 (); LineNumberTableOffset = reader.ReadInt32 (); long old_pos = reader.BaseStream.Position; reader.BaseStream.Position = DataOffset; CompileUnitIndex = reader.ReadLeb128 (); LocalVariableTableOffset = reader.ReadLeb128 (); NamespaceID = reader.ReadLeb128 (); CodeBlockTableOffset = reader.ReadLeb128 (); ScopeVariableTableOffset = reader.ReadLeb128 (); RealNameOffset = reader.ReadLeb128 (); flags = (Flags) reader.ReadLeb128 (); reader.BaseStream.Position = old_pos; CompileUnit = file.GetCompileUnit (CompileUnitIndex); } internal MethodEntry (MonoSymbolFile file, CompileUnitEntry comp_unit, int token, ScopeVariable[] scope_vars, LocalVariableEntry[] locals, LineNumberEntry[] lines, CodeBlockEntry[] code_blocks, string real_name, Flags flags, int namespace_id) { this.SymbolFile = file; this.real_name = real_name; this.locals = locals; this.code_blocks = code_blocks; this.scope_vars = scope_vars; this.flags = flags; index = -1; Token = token; CompileUnitIndex = comp_unit.Index; CompileUnit = comp_unit; NamespaceID = namespace_id; CheckLineNumberTable (lines); lnt = new LineNumberTable (file, lines); file.NumLineNumbers += lines.Length; int num_locals = locals != null ? locals.Length : 0; if (num_locals <= 32) { // Most of the time, the O(n^2) factor is actually // less than the cost of allocating the hash table, // 32 is a rough number obtained through some testing. for (int i = 0; i < num_locals; i ++) { string nm = locals [i].Name; for (int j = i + 1; j < num_locals; j ++) { if (locals [j].Name == nm) { flags |= Flags.LocalNamesAmbiguous; goto locals_check_done; } } } locals_check_done : ; } else { var local_names = new Dictionary<string, LocalVariableEntry> (); foreach (LocalVariableEntry local in locals) { if (local_names.ContainsKey (local.Name)) { flags |= Flags.LocalNamesAmbiguous; break; } local_names.Add (local.Name, local); } } } static void CheckLineNumberTable (LineNumberEntry[] line_numbers) { int last_offset = -1; int last_row = -1; if (line_numbers == null) return; for (int i = 0; i < line_numbers.Length; i++) { LineNumberEntry line = line_numbers [i]; if (line.Equals (LineNumberEntry.Null)) throw new MonoSymbolFileException (); if (line.Offset < last_offset) throw new MonoSymbolFileException (); if (line.Offset > last_offset) { last_row = line.Row; last_offset = line.Offset; } else if (line.Row > last_row) { last_row = line.Row; } } } internal void Write (MyBinaryWriter bw) { if ((index <= 0) || (DataOffset == 0)) throw new InvalidOperationException (); bw.Write (Token); bw.Write (DataOffset); bw.Write (LineNumberTableOffset); } internal void WriteData (MonoSymbolFile file, MyBinaryWriter bw) { if (index <= 0) throw new InvalidOperationException (); LocalVariableTableOffset = (int) bw.BaseStream.Position; int num_locals = locals != null ? locals.Length : 0; bw.WriteLeb128 (num_locals); for (int i = 0; i < num_locals; i++) locals [i].Write (file, bw); file.LocalCount += num_locals; CodeBlockTableOffset = (int) bw.BaseStream.Position; int num_code_blocks = code_blocks != null ? code_blocks.Length : 0; bw.WriteLeb128 (num_code_blocks); for (int i = 0; i < num_code_blocks; i++) code_blocks [i].Write (bw); ScopeVariableTableOffset = (int) bw.BaseStream.Position; int num_scope_vars = scope_vars != null ? scope_vars.Length : 0; bw.WriteLeb128 (num_scope_vars); for (int i = 0; i < num_scope_vars; i++) scope_vars [i].Write (bw); if (real_name != null) { RealNameOffset = (int) bw.BaseStream.Position; bw.Write (real_name); } foreach (var lne in lnt.LineNumbers) { if (lne.EndRow != -1 || lne.EndColumn != -1) flags |= Flags.EndInfoIncluded; } LineNumberTableOffset = (int) bw.BaseStream.Position; lnt.Write (file, bw, (flags & Flags.ColumnsInfoIncluded) != 0, (flags & Flags.EndInfoIncluded) != 0); DataOffset = (int) bw.BaseStream.Position; bw.WriteLeb128 (CompileUnitIndex); bw.WriteLeb128 (LocalVariableTableOffset); bw.WriteLeb128 (NamespaceID); bw.WriteLeb128 (CodeBlockTableOffset); bw.WriteLeb128 (ScopeVariableTableOffset); bw.WriteLeb128 (RealNameOffset); bw.WriteLeb128 ((int) flags); } public void ReadAll () { GetLineNumberTable (); GetLocals (); GetCodeBlocks (); GetScopeVariables (); GetRealName (); } public LineNumberTable GetLineNumberTable () { lock (SymbolFile) { if (lnt != null) return lnt; if (LineNumberTableOffset == 0) return null; MyBinaryReader reader = SymbolFile.BinaryReader; long old_pos = reader.BaseStream.Position; reader.BaseStream.Position = LineNumberTableOffset; lnt = LineNumberTable.Read (SymbolFile, reader, (flags & Flags.ColumnsInfoIncluded) != 0, (flags & Flags.EndInfoIncluded) != 0); reader.BaseStream.Position = old_pos; return lnt; } } public LocalVariableEntry[] GetLocals () { lock (SymbolFile) { if (locals != null) return locals; if (LocalVariableTableOffset == 0) return null; MyBinaryReader reader = SymbolFile.BinaryReader; long old_pos = reader.BaseStream.Position; reader.BaseStream.Position = LocalVariableTableOffset; int num_locals = reader.ReadLeb128 (); locals = new LocalVariableEntry [num_locals]; for (int i = 0; i < num_locals; i++) locals [i] = new LocalVariableEntry (SymbolFile, reader); reader.BaseStream.Position = old_pos; return locals; } } public CodeBlockEntry[] GetCodeBlocks () { lock (SymbolFile) { if (code_blocks != null) return code_blocks; if (CodeBlockTableOffset == 0) return null; MyBinaryReader reader = SymbolFile.BinaryReader; long old_pos = reader.BaseStream.Position; reader.BaseStream.Position = CodeBlockTableOffset; int num_code_blocks = reader.ReadLeb128 (); code_blocks = new CodeBlockEntry [num_code_blocks]; for (int i = 0; i < num_code_blocks; i++) code_blocks [i] = new CodeBlockEntry (i, reader); reader.BaseStream.Position = old_pos; return code_blocks; } } public ScopeVariable[] GetScopeVariables () { lock (SymbolFile) { if (scope_vars != null) return scope_vars; if (ScopeVariableTableOffset == 0) return null; MyBinaryReader reader = SymbolFile.BinaryReader; long old_pos = reader.BaseStream.Position; reader.BaseStream.Position = ScopeVariableTableOffset; int num_scope_vars = reader.ReadLeb128 (); scope_vars = new ScopeVariable [num_scope_vars]; for (int i = 0; i < num_scope_vars; i++) scope_vars [i] = new ScopeVariable (reader); reader.BaseStream.Position = old_pos; return scope_vars; } } public string GetRealName () { lock (SymbolFile) { if (real_name != null) return real_name; if (RealNameOffset == 0) return null; real_name = SymbolFile.BinaryReader.ReadString (RealNameOffset); return real_name; } } public int CompareTo (object obj) { MethodEntry method = (MethodEntry) obj; if (method.Token < Token) return 1; else if (method.Token > Token) return -1; else return 0; } public override string ToString () { return String.Format ("[Method {0}:{1:x}:{2}:{3}]", index, Token, CompileUnitIndex, CompileUnit); } } public struct NamespaceEntry { #region This is actually written to the symbol file public readonly string Name; public readonly int Index; public readonly int Parent; public readonly string[] UsingClauses; #endregion public NamespaceEntry (string name, int index, string[] using_clauses, int parent) { this.Name = name; this.Index = index; this.Parent = parent; this.UsingClauses = using_clauses != null ? using_clauses : new string [0]; } internal NamespaceEntry (MonoSymbolFile file, MyBinaryReader reader) { Name = reader.ReadString (); Index = reader.ReadLeb128 (); Parent = reader.ReadLeb128 (); int count = reader.ReadLeb128 (); UsingClauses = new string [count]; for (int i = 0; i < count; i++) UsingClauses [i] = reader.ReadString (); } internal void Write (MonoSymbolFile file, MyBinaryWriter bw) { bw.Write (Name); bw.WriteLeb128 (Index); bw.WriteLeb128 (Parent); bw.WriteLeb128 (UsingClauses.Length); foreach (string uc in UsingClauses) bw.Write (uc); } public override string ToString () { return String.Format ("[Namespace {0}:{1}:{2}]", Name, Index, Parent); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using Microsoft.Research.AbstractDomains; using System.Collections.Generic; using Microsoft.Research.DataStructures; using Microsoft.Research.AbstractDomains.Numerical; using System.Diagnostics.Contracts; using Microsoft.Research.CodeAnalysis; using System.Diagnostics.CodeAnalysis; namespace Microsoft.Research.CodeAnalysis { public static partial class AnalysisWrapper { public static partial class TypeBindings<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable> where Variable : IEquatable<Variable> where Expression : IEquatable<Expression> where Type : IEquatable<Type> { /// <summary> /// Analysis that determines which array elements have tested (or not tested). /// It is used to infer preconditions for array contents /// </summary> [ContractVerification(true)] public class ArrayElementsCheckedAnalysisPlugin : GenericPlugInAnalysisForComposedAnalysis { #region Invariant [ContractInvariantMethod] void ObjectInvariant() { Contract.Invariant(this.Id >= 0); } #endregion #region Constants static public readonly FlatAbstractDomainOfBoolsWithRenaming<BoxedVariable<Variable>> CHECKED = new FlatAbstractDomainOfBoolsWithRenaming<BoxedVariable<Variable>>(true, "checked"); // Thread-safe static public readonly FlatAbstractDomainOfBoolsWithRenaming<BoxedVariable<Variable>> UNCHECKED = new FlatAbstractDomainOfBoolsWithRenaming<BoxedVariable<Variable>>(false, "not-checked"); // Thread-safe #endregion #region Constructor public ArrayElementsCheckedAnalysisPlugin( int id, string methodName, IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, ILogOptions> mdriver, ILogOptions options, Predicate<APC> cachePCs ) : base(id, methodName, mdriver, new PlugInAnalysisOptions(options), cachePCs) { } #endregion #region Override public override IFactQuery<BoxedExpression, Variable> FactQuery(IFixpointInfo<APC, ArrayState> fixpoint) { return null; } public override ArrayState.AdditionalStates Kind { get { return ArrayState.AdditionalStates.ArrayChecked; } } public override IAbstractDomainForEnvironments<BoxedVariable<Variable>, BoxedExpression> InitialState { get { return new ArraySegmentationEnvironment<FlatAbstractDomainOfBoolsWithRenaming<BoxedVariable<Variable>>, BoxedVariable<Variable>, BoxedExpression>( this.ExpressionManager); } } public override IAbstractDomainForEnvironments<BoxedVariable<Variable>, BoxedExpression> AssignInParallel(Dictionary<BoxedVariable<Variable>, FList<BoxedVariable<Variable>>> refinedMap, Converter<BoxedVariable<Variable>, BoxedExpression> convert, List<Pair<NormalizedExpression<BoxedVariable<Variable>>, NormalizedExpression<BoxedVariable<Variable>>>> equalities, ArrayState state) { Contract.Assume(state != null); Contract.Assume(refinedMap != null); Contract.Assume(convert != null); var result = Select(state); result.AssignInParallel(refinedMap, convert); foreach(var pair in equalities) { Contract.Assume(pair.One != null); Contract.Assume(pair.Two != null); var tmp = result.TestTrueEqualAsymmetric(pair.One, pair.Two); result = result.TestTrueEqualAsymmetric(pair.One.PlusOne(), pair.Two.PlusOne()); } return result; } #endregion #region Select public ArraySegmentationEnvironment<FlatAbstractDomainOfBoolsWithRenaming<BoxedVariable<Variable>>, BoxedVariable<Variable>, BoxedExpression> Select(ArrayState state) { Contract.Requires(state != null); Contract.Requires(this.Id < state.PluginsCount); Contract.Ensures( Contract.Result< ArraySegmentationEnvironment< FlatAbstractDomainOfBoolsWithRenaming<BoxedVariable<Variable>>, BoxedVariable<Variable>, BoxedExpression>>() != null); var subState = state.PluginAbstractStateAt(this.Id) as ArraySegmentationEnvironment<FlatAbstractDomainOfBoolsWithRenaming<BoxedVariable<Variable>>, BoxedVariable<Variable>, BoxedExpression>; Contract.Assume(subState != null); return subState; } #endregion #region Transfer functions #region Entry public override ArrayState Entry(APC pc, Method method, ArrayState data) { Contract.Assume(data != null); var mySubState = Select(data); // We materialize all the arrays in the parameters... foreach (var param in this.DecoderForMetaData.Parameters(method).Enumerate()) { Variable symb; var postPC = Context.MethodContext.CFG.Post(pc); if ( this.Context.ValueContext.TryParameterValue(postPC, param, out symb)) { if (this.DecoderForMetaData.IsArray(DecoderForMetaData.ParameterType(param))) { var dummy = MaterializeArray( postPC, mySubState, data.Numerical.CheckIfNonZero, symb, UNCHECKED, new FlatAbstractDomainOfBoolsWithRenaming<BoxedVariable<Variable>>(FlatAbstractDomain<bool>.State.Bottom)); } else { var paramType = this.DecoderForMetaData.ParameterType(param); foreach (var intf in this.DecoderForMetaData.Interfaces(paramType)) { if (this.DecoderForMetaData.Name(intf).AssumeNotNull().Contains("IEnumerable")) { var dummy = MaterializeEnumerable(postPC, mySubState, symb, UNCHECKED); } } } } } return data.UpdatePluginAt(this.Id, mySubState); } #endregion #region Assert public override ArrayState Assert(APC pc, string tag, Variable condition, object provenance, ArrayState data) { Contract.Ensures(Contract.Result<ArrayState>() != null); Contract.Assume(data != null); var conditionExp = ToBoxedExpression(pc, condition); if(conditionExp == null) { return data; } // We first check (x == nul) == 0 BoxedExpression checkedExp; Variable var1, var2; if (conditionExp.IsCheckExpNotNotNull(out checkedExp) && checkedExp.TryGetFrameworkVariable(out var1)) { return AssumeCheckOfAnArrayElement(pc, var1, data); } else if (conditionExp.IsCheckExp1EqExp2(out var1, out var2)) { var refined = Select(data).TestTrueEqual(new BoxedVariable<Variable>(var1), new BoxedVariable<Variable>(var2)); return data.UpdatePluginAt(this.Id, refined); } else { var t1 = Select(data); // Otherwise see if "assert refined.One[refined.Two] return AssumeCheckOfAnArrayElement(pc, condition, data); } } private ArrayState AssumeCheckOfAnArrayElement(APC pc, Variable var, ArrayState data) { Contract.Requires(data != null); Contract.Ensures(Contract.Result<ArrayState>() != null); Pair<BoxedVariable<Variable>, BoxedVariable<Variable>> refined; if (data.CanRefineToArrayLoad(new BoxedVariable<Variable>(var), out refined)) { var mySubState = Select(data); ArraySegmentation< FlatAbstractDomainOfBoolsWithRenaming<BoxedVariable<Variable>>, BoxedVariable<Variable>, BoxedExpression> segmentation; Contract.Assume(refined.One != null); Contract.Assume(refined.Two != null); // Do we have a segmentation? foreach (var arr in GetEquals(pc, refined.One, data)) { if (mySubState.TryGetValue(arr, out segmentation)) { // Is it unmodified? if (data.IsUnmodifiedArrayElementFromEntry(arr, ToBoxedExpression(pc, refined.Two))) { var norm = ToBoxedExpression(pc, refined.Two).ToNormalizedExpression<Variable>(); if (norm != null && segmentation.TrySetAbstractValue(norm, CHECKED, data.Numerical, out segmentation)) { mySubState.Update(arr, segmentation); } else { mySubState.RemoveElement(arr); } data = data.UpdatePluginAt(this.Id, mySubState); } } } } return data; } IEnumerable<BoxedVariable<Variable>> GetEquals(APC pc, BoxedVariable<Variable> arr, ArrayState state) { yield return arr; foreach (var x in new List<BoxedVariable<Variable>>(Select(state).Keys)) { if (state.Numerical.CheckIfEqual(ToBoxedExpression(pc, arr), ToBoxedExpression(pc, x)).IsTrue()) { yield return x; } } } #endregion #region Assume public override ArrayState Assume(APC pc, string tag, Variable source, object provenance, ArrayState data) { Contract.Assume(data != null); if (tag != "false") { data = this.Assert(pc, "assume", source, provenance, data); Contract.Assert(data != null); var convertedExp = ToBoxedExpression(pc, source); if(convertedExp == null) { // abort return data; } Variable v1, v2; BoxedExpression bLeft, bRight, x; int k; if (convertedExp.IsCheckExp1EqExp2(out bLeft, out bRight) // bLeft == bRight && bRight.IsCheckExp1EqConst(out x, out k) // bRight == x + 1 && bLeft.TryGetFrameworkVariable(out v1) && x.TryGetFrameworkVariable(out v2) ) { var vNormExp = NormalizedExpression<BoxedVariable<Variable>>.For(new BoxedVariable<Variable>(v1)); var sumNormExp = NormalizedExpression<BoxedVariable<Variable>>.For(new BoxedVariable<Variable>(v2), k); var mySubState = Select(data); mySubState = mySubState.TestTrueEqualAsymmetric(vNormExp, sumNormExp); mySubState = mySubState.TestTrueEqualAsymmetric(sumNormExp, vNormExp); data = data.UpdatePluginAt(this.Id, mySubState); } } return data.UpdatePluginAt(this.Id, Select(data).ReduceWith(data.Numerical)); } #endregion #region Call public override ArrayState Call<TypeList, ArgList>(APC pc, Method method, bool tail, bool virt, TypeList extraVarargs, Variable dest, ArgList args, ArrayState data) { Contract.Assume(data != null); if (!this.DecoderForContracts.IsPure(method)) { var mySubState = Select(data); // Havoc all the arrays in the arguments that are not marked as pure for (var pos = this.DecoderForMetaData.IsStatic(method) ? 0 : 1; pos < args.Count; pos++) { Variable arrayValue, index; // An array is passed. Havoc the content if (mySubState.ContainsKey(new BoxedVariable<Variable>(args[pos])) && !this.DecoderForMetaData.IsPure(method, pos)) { mySubState.RemoveVariable(new BoxedVariable<Variable>(args[pos])); } // an array is passed by ref: Havoc the array else if (this.Context.ValueContext.TryGetArrayFromElementAddress(pc, args[pos], out arrayValue, out index)) { mySubState.RemoveVariable(new BoxedVariable<Variable>(arrayValue)); } } data = data.UpdatePluginAt(this.Id, mySubState); } if (!this.DecoderForMetaData.IsStatic(method)) { Contract.Assume(args.Count > 0); return AssumeCheckOfAnArrayElement(pc, args[0], data); } else { return data; } } #endregion #region Binary public override ArrayState Binary(APC pc, BinaryOperator op, Variable dest, Variable s1, Variable s2, ArrayState data) { Variable var; int k; if (TryMatchVariableConstant(pc, op, Strip(pc, s1), Strip(pc, s2), data.Numerical, out var, out k) && k != Int32.MinValue) { var mySubState = Select(data); var normExpression = NormalizedExpression<BoxedVariable<Variable>>.For(new BoxedVariable<Variable>(var), k); var normVariable = NormalizedExpression<BoxedVariable<Variable>>.For(new BoxedVariable<Variable>(dest)); var array = mySubState.TestTrueEqualAsymmetric(normVariable, normExpression); normExpression = NormalizedExpression<BoxedVariable<Variable>>.For(new BoxedVariable<Variable>(dest), -k); normVariable = NormalizedExpression<BoxedVariable<Variable>>.For(new BoxedVariable<Variable>(var)); return data.UpdatePluginAt(this.Id, mySubState.TestTrueEqualAsymmetric(normExpression, normVariable)); } return data; } #endregion #region StLoc public override ArrayState Stloc(APC pc, Local local, Variable source, ArrayState data) { var resultState = base.Stloc(pc, local, source, data); Contract.Assume(resultState != null); return resultState.UpdatePluginAt(this.Id, ArrayCounterInitialization(pc, local, source, resultState, Select(resultState))); } #endregion #region Collect not-null assertions public override ArrayState Ldelem(APC pc, Type type, Variable dest, Variable array, Variable index, ArrayState data) { Contract.Assume(data != null); return AssumeCheckOfAnArrayElement(pc, array, data); } public override ArrayState Ldelema(APC pc, Type type, bool @readonly, Variable dest, Variable array, Variable index, ArrayState data) { Contract.Assume(data != null); return AssumeCheckOfAnArrayElement(pc, array, data); } public override ArrayState Ldfld(APC pc, Field field, bool @volatile, Variable dest, Variable obj, ArrayState data) { Contract.Assume(data != null); return AssumeCheckOfAnArrayElement(pc, obj, data); } #endregion #endregion #region Precondition suggestion public override void SuggestPrecondition(ContractInferenceManager inferenceManager, IFixpointInfo<APC, ArrayState> fixpointInfo) { Contract.Assume(inferenceManager != null); ArrayState postState; var pc = this.Context.MethodContext.CFG.NormalExit; if (PreState(pc, fixpointInfo, out postState)) { Contract.Assume(postState != null); var mySubState = Select(postState); if (mySubState.IsNormal()) { foreach (var segmentation in mySubState.Elements) { Contract.Assume(segmentation.Key != null); Contract.Assume(segmentation.Value != null); if (segmentation.Value.IsNormal()) { foreach (var pre in GetForAllVisibleOutsideOfTheMethod(segmentation.Key, segmentation.Value)) { var pcAfterRequires = this.Context.MethodContext.CFG.EntryAfterRequires; inferenceManager.AddPreconditionOrAssume(new EmptyProofObligation(pcAfterRequires), new List<BoxedExpression>() { pre }, ProofOutcome.Top); } } } } } } private List<BoxedExpression> GetForAllVisibleOutsideOfTheMethod( BoxedVariable<Variable> array, ArraySegmentation<FlatAbstractDomainOfBoolsWithRenaming<BoxedVariable<Variable>>, BoxedVariable<Variable>, BoxedExpression> segmentation) { Contract.Requires(array != null); Contract.Requires(segmentation != null); var result = new List<BoxedExpression>(); var arrayBE = ReadVariableInPreStateForRequires(this.Context.MethodContext.CFG.EntryAfterRequires, array); if (arrayBE != null) { var boundVar = BoxedExpression.Var("i"); var arrayindex = new BoxedExpression.ArrayIndexExpression<Type>(arrayBE, boundVar, this.DecoderForMetaData.System_Object); var factory = new BoxedExpressionFactory<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Variable>( boundVar, arrayindex, (v => ReadVariableInPreStateForRequires(this.Context.MethodContext.CFG.EntryAfterRequires, v)), this.DecoderForMetaData, null); var formula = segmentation.To(factory); if (formula != null) { result.AddRange(factory.SplitAnd(formula)); } } return result; } public string PrettyPrint(string arrayName, FlatAbstractDomainOfBoolsWithRenaming<BoxedVariable<Variable>> aState) { Contract.Requires(arrayName != null); Contract.Requires(aState != null); if (aState.IsBottom) { return "false"; } #if false // Verbose if (aState.IsTop) { return "maybe checked"; } if (!aState.BoxedElement) { return "never checked"; } #else if (aState.IsTop /*|| !aState.BoxedElement*/) { return null; } #endif if (aState.BoxedElement) { return string.Format("{0}[i] != null", arrayName); } // Should be unreachable return null; } #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 NUnit.Framework; using StandardAnalyzer = Lucene.Net.Analysis.Standard.StandardAnalyzer; using Document = Lucene.Net.Documents.Document; using Field = Lucene.Net.Documents.Field; using MapFieldSelector = Lucene.Net.Documents.MapFieldSelector; using Directory = Lucene.Net.Store.Directory; using MockRAMDirectory = Lucene.Net.Store.MockRAMDirectory; using RAMDirectory = Lucene.Net.Store.RAMDirectory; using BooleanQuery = Lucene.Net.Search.BooleanQuery; using IndexSearcher = Lucene.Net.Search.IndexSearcher; using Query = Lucene.Net.Search.Query; using ScoreDoc = Lucene.Net.Search.ScoreDoc; using Searcher = Lucene.Net.Search.Searcher; using TermQuery = Lucene.Net.Search.TermQuery; using Occur = Lucene.Net.Search.BooleanClause.Occur; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; namespace Lucene.Net.Index { [TestFixture] public class TestParallelReader:LuceneTestCase { private Searcher parallel; private Searcher single; [SetUp] public override void SetUp() { base.SetUp(); single = Single(); parallel = Parallel(); } [Test] public virtual void TestQueries() { QueryTest(new TermQuery(new Term("f1", "v1"))); QueryTest(new TermQuery(new Term("f1", "v2"))); QueryTest(new TermQuery(new Term("f2", "v1"))); QueryTest(new TermQuery(new Term("f2", "v2"))); QueryTest(new TermQuery(new Term("f3", "v1"))); QueryTest(new TermQuery(new Term("f3", "v2"))); QueryTest(new TermQuery(new Term("f4", "v1"))); QueryTest(new TermQuery(new Term("f4", "v2"))); BooleanQuery bq1 = new BooleanQuery(); bq1.Add(new TermQuery(new Term("f1", "v1")), Occur.MUST); bq1.Add(new TermQuery(new Term("f4", "v1")), Occur.MUST); QueryTest(bq1); } [Test] public virtual void TestFieldNames() { Directory dir1 = GetDir1(); Directory dir2 = GetDir2(); ParallelReader pr = new ParallelReader(); pr.Add(IndexReader.Open(dir1)); pr.Add(IndexReader.Open(dir2)); System.Collections.Generic.ICollection<string> fieldNames = pr.GetFieldNames(IndexReader.FieldOption.ALL); Assert.AreEqual(4, fieldNames.Count); Assert.IsTrue(SupportClass.CollectionsHelper.Contains(fieldNames, "f1")); Assert.IsTrue(SupportClass.CollectionsHelper.Contains(fieldNames, "f2")); Assert.IsTrue(SupportClass.CollectionsHelper.Contains(fieldNames, "f3")); Assert.IsTrue(SupportClass.CollectionsHelper.Contains(fieldNames, "f4")); } [Test] public virtual void TestDocument() { Directory dir1 = GetDir1(); Directory dir2 = GetDir2(); ParallelReader pr = new ParallelReader(); pr.Add(IndexReader.Open(dir1)); pr.Add(IndexReader.Open(dir2)); Document doc11 = pr.Document(0, new MapFieldSelector(new System.String[]{"f1"})); Document doc24 = pr.Document(1, new MapFieldSelector(new System.Collections.ArrayList(new System.String[]{"f4"}))); Document doc223 = pr.Document(1, new MapFieldSelector(new System.String[]{"f2", "f3"})); Assert.AreEqual(1, doc11.GetFields().Count); Assert.AreEqual(1, doc24.GetFields().Count); Assert.AreEqual(2, doc223.GetFields().Count); Assert.AreEqual("v1", doc11.Get("f1")); Assert.AreEqual("v2", doc24.Get("f4")); Assert.AreEqual("v2", doc223.Get("f2")); Assert.AreEqual("v2", doc223.Get("f3")); } [Test] public virtual void TestIncompatibleIndexes() { // two documents: Directory dir1 = GetDir1(); // one document only: Directory dir2 = new MockRAMDirectory(); IndexWriter w2 = new IndexWriter(dir2, new StandardAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED); Document d3 = new Document(); d3.Add(new Field("f3", "v1", Field.Store.YES, Field.Index.ANALYZED)); w2.AddDocument(d3); w2.Close(); ParallelReader pr = new ParallelReader(); pr.Add(IndexReader.Open(dir1)); try { pr.Add(IndexReader.Open(dir2)); Assert.Fail("didn't get exptected exception: indexes don't have same number of documents"); } catch (System.ArgumentException e) { // expected exception } } [Test] public virtual void TestIsCurrent() { Directory dir1 = GetDir1(); Directory dir2 = GetDir2(); ParallelReader pr = new ParallelReader(); pr.Add(IndexReader.Open(dir1)); pr.Add(IndexReader.Open(dir2)); Assert.IsTrue(pr.IsCurrent()); IndexReader modifier = IndexReader.Open(dir1); modifier.SetNorm(0, "f1", 100); modifier.Close(); // one of the two IndexReaders which ParallelReader is using // is not current anymore Assert.IsFalse(pr.IsCurrent()); modifier = IndexReader.Open(dir2); modifier.SetNorm(0, "f3", 100); modifier.Close(); // now both are not current anymore Assert.IsFalse(pr.IsCurrent()); } [Test] public virtual void TestIsOptimized() { Directory dir1 = GetDir1(); Directory dir2 = GetDir2(); // add another document to ensure that the indexes are not optimized IndexWriter modifier = new IndexWriter(dir1, new StandardAnalyzer(), IndexWriter.MaxFieldLength.LIMITED); Document d = new Document(); d.Add(new Field("f1", "v1", Field.Store.YES, Field.Index.ANALYZED)); modifier.AddDocument(d); modifier.Close(); modifier = new IndexWriter(dir2, new StandardAnalyzer(), IndexWriter.MaxFieldLength.LIMITED); d = new Document(); d.Add(new Field("f2", "v2", Field.Store.YES, Field.Index.ANALYZED)); modifier.AddDocument(d); modifier.Close(); ParallelReader pr = new ParallelReader(); pr.Add(IndexReader.Open(dir1)); pr.Add(IndexReader.Open(dir2)); Assert.IsFalse(pr.IsOptimized()); pr.Close(); modifier = new IndexWriter(dir1, new StandardAnalyzer(), IndexWriter.MaxFieldLength.LIMITED); modifier.Optimize(); modifier.Close(); pr = new ParallelReader(); pr.Add(IndexReader.Open(dir1)); pr.Add(IndexReader.Open(dir2)); // just one of the two indexes are optimized Assert.IsFalse(pr.IsOptimized()); pr.Close(); modifier = new IndexWriter(dir2, new StandardAnalyzer(), IndexWriter.MaxFieldLength.LIMITED); modifier.Optimize(); modifier.Close(); pr = new ParallelReader(); pr.Add(IndexReader.Open(dir1)); pr.Add(IndexReader.Open(dir2)); // now both indexes are optimized Assert.IsTrue(pr.IsOptimized()); pr.Close(); } [Test] public virtual void TestAllTermDocs() { Directory dir1 = GetDir1(); Directory dir2 = GetDir2(); ParallelReader pr = new ParallelReader(); pr.Add(IndexReader.Open(dir1)); pr.Add(IndexReader.Open(dir2)); int NUM_DOCS = 2; TermDocs td = pr.TermDocs(null); for (int i = 0; i < NUM_DOCS; i++) { Assert.IsTrue(td.Next()); Assert.AreEqual(i, td.Doc()); Assert.AreEqual(1, td.Freq()); } td.Close(); pr.Close(); dir1.Close(); dir2.Close(); } private void QueryTest(Query query) { ScoreDoc[] parallelHits = parallel.Search(query, null, 1000).ScoreDocs; ScoreDoc[] singleHits = single.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(parallelHits.Length, singleHits.Length); for (int i = 0; i < parallelHits.Length; i++) { Assert.AreEqual(parallelHits[i].score, singleHits[i].score, 0.001f); Document docParallel = parallel.Doc(parallelHits[i].doc); Document docSingle = single.Doc(singleHits[i].doc); Assert.AreEqual(docParallel.Get("f1"), docSingle.Get("f1")); Assert.AreEqual(docParallel.Get("f2"), docSingle.Get("f2")); Assert.AreEqual(docParallel.Get("f3"), docSingle.Get("f3")); Assert.AreEqual(docParallel.Get("f4"), docSingle.Get("f4")); } } // Fields 1-4 indexed together: private Searcher Single() { Directory dir = new MockRAMDirectory(); IndexWriter w = new IndexWriter(dir, new StandardAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED); Document d1 = new Document(); d1.Add(new Field("f1", "v1", Field.Store.YES, Field.Index.ANALYZED)); d1.Add(new Field("f2", "v1", Field.Store.YES, Field.Index.ANALYZED)); d1.Add(new Field("f3", "v1", Field.Store.YES, Field.Index.ANALYZED)); d1.Add(new Field("f4", "v1", Field.Store.YES, Field.Index.ANALYZED)); w.AddDocument(d1); Document d2 = new Document(); d2.Add(new Field("f1", "v2", Field.Store.YES, Field.Index.ANALYZED)); d2.Add(new Field("f2", "v2", Field.Store.YES, Field.Index.ANALYZED)); d2.Add(new Field("f3", "v2", Field.Store.YES, Field.Index.ANALYZED)); d2.Add(new Field("f4", "v2", Field.Store.YES, Field.Index.ANALYZED)); w.AddDocument(d2); w.Close(); return new IndexSearcher(dir); } // Fields 1 & 2 in one index, 3 & 4 in other, with ParallelReader: private Searcher Parallel() { Directory dir1 = GetDir1(); Directory dir2 = GetDir2(); ParallelReader pr = new ParallelReader(); pr.Add(IndexReader.Open(dir1)); pr.Add(IndexReader.Open(dir2)); return new IndexSearcher(pr); } private Directory GetDir1() { Directory dir1 = new MockRAMDirectory(); IndexWriter w1 = new IndexWriter(dir1, new StandardAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED); Document d1 = new Document(); d1.Add(new Field("f1", "v1", Field.Store.YES, Field.Index.ANALYZED)); d1.Add(new Field("f2", "v1", Field.Store.YES, Field.Index.ANALYZED)); w1.AddDocument(d1); Document d2 = new Document(); d2.Add(new Field("f1", "v2", Field.Store.YES, Field.Index.ANALYZED)); d2.Add(new Field("f2", "v2", Field.Store.YES, Field.Index.ANALYZED)); w1.AddDocument(d2); w1.Close(); return dir1; } private Directory GetDir2() { Directory dir2 = new RAMDirectory(); IndexWriter w2 = new IndexWriter(dir2, new StandardAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED); Document d3 = new Document(); d3.Add(new Field("f3", "v1", Field.Store.YES, Field.Index.ANALYZED)); d3.Add(new Field("f4", "v1", Field.Store.YES, Field.Index.ANALYZED)); w2.AddDocument(d3); Document d4 = new Document(); d4.Add(new Field("f3", "v2", Field.Store.YES, Field.Index.ANALYZED)); d4.Add(new Field("f4", "v2", Field.Store.YES, Field.Index.ANALYZED)); w2.AddDocument(d4); w2.Close(); return dir2; } } }
// 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.V9.Resources; using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V9.Resources { /// <summary>Resource name for the <c>CustomConversionGoal</c> resource.</summary> public sealed partial class CustomConversionGoalName : gax::IResourceName, sys::IEquatable<CustomConversionGoalName> { /// <summary>The possible contents of <see cref="CustomConversionGoalName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>customers/{customer_id}/customConversionGoals/{goal_id}</c>. /// </summary> CustomerGoal = 1, } private static gax::PathTemplate s_customerGoal = new gax::PathTemplate("customers/{customer_id}/customConversionGoals/{goal_id}"); /// <summary>Creates a <see cref="CustomConversionGoalName"/> 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="CustomConversionGoalName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static CustomConversionGoalName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new CustomConversionGoalName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="CustomConversionGoalName"/> with the pattern /// <c>customers/{customer_id}/customConversionGoals/{goal_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="goalId">The <c>Goal</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// A new instance of <see cref="CustomConversionGoalName"/> constructed from the provided ids. /// </returns> public static CustomConversionGoalName FromCustomerGoal(string customerId, string goalId) => new CustomConversionGoalName(ResourceNameType.CustomerGoal, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), goalId: gax::GaxPreconditions.CheckNotNullOrEmpty(goalId, nameof(goalId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="CustomConversionGoalName"/> with pattern /// <c>customers/{customer_id}/customConversionGoals/{goal_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="goalId">The <c>Goal</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CustomConversionGoalName"/> with pattern /// <c>customers/{customer_id}/customConversionGoals/{goal_id}</c>. /// </returns> public static string Format(string customerId, string goalId) => FormatCustomerGoal(customerId, goalId); /// <summary> /// Formats the IDs into the string representation of this <see cref="CustomConversionGoalName"/> with pattern /// <c>customers/{customer_id}/customConversionGoals/{goal_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="goalId">The <c>Goal</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CustomConversionGoalName"/> with pattern /// <c>customers/{customer_id}/customConversionGoals/{goal_id}</c>. /// </returns> public static string FormatCustomerGoal(string customerId, string goalId) => s_customerGoal.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(goalId, nameof(goalId))); /// <summary> /// Parses the given resource name string into a new <see cref="CustomConversionGoalName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/customConversionGoals/{goal_id}</c></description></item> /// </list> /// </remarks> /// <param name="customConversionGoalName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="CustomConversionGoalName"/> if successful.</returns> public static CustomConversionGoalName Parse(string customConversionGoalName) => Parse(customConversionGoalName, false); /// <summary> /// Parses the given resource name string into a new <see cref="CustomConversionGoalName"/> 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>customers/{customer_id}/customConversionGoals/{goal_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="customConversionGoalName">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="CustomConversionGoalName"/> if successful.</returns> public static CustomConversionGoalName Parse(string customConversionGoalName, bool allowUnparsed) => TryParse(customConversionGoalName, allowUnparsed, out CustomConversionGoalName 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="CustomConversionGoalName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/customConversionGoals/{goal_id}</c></description></item> /// </list> /// </remarks> /// <param name="customConversionGoalName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="CustomConversionGoalName"/>, 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 customConversionGoalName, out CustomConversionGoalName result) => TryParse(customConversionGoalName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CustomConversionGoalName"/> 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>customers/{customer_id}/customConversionGoals/{goal_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="customConversionGoalName">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="CustomConversionGoalName"/>, 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 customConversionGoalName, bool allowUnparsed, out CustomConversionGoalName result) { gax::GaxPreconditions.CheckNotNull(customConversionGoalName, nameof(customConversionGoalName)); gax::TemplatedResourceName resourceName; if (s_customerGoal.TryParseName(customConversionGoalName, out resourceName)) { result = FromCustomerGoal(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(customConversionGoalName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private CustomConversionGoalName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string goalId = null) { Type = type; UnparsedResource = unparsedResourceName; CustomerId = customerId; GoalId = goalId; } /// <summary> /// Constructs a new instance of a <see cref="CustomConversionGoalName"/> class from the component parts of /// pattern <c>customers/{customer_id}/customConversionGoals/{goal_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="goalId">The <c>Goal</c> ID. Must not be <c>null</c> or empty.</param> public CustomConversionGoalName(string customerId, string goalId) : this(ResourceNameType.CustomerGoal, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), goalId: gax::GaxPreconditions.CheckNotNullOrEmpty(goalId, nameof(goalId))) { } /// <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>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>Goal</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string GoalId { 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.CustomerGoal: return s_customerGoal.Expand(CustomerId, GoalId); 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 CustomConversionGoalName); /// <inheritdoc/> public bool Equals(CustomConversionGoalName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(CustomConversionGoalName a, CustomConversionGoalName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(CustomConversionGoalName a, CustomConversionGoalName b) => !(a == b); } public partial class CustomConversionGoal { /// <summary> /// <see cref="gagvr::CustomConversionGoalName"/>-typed view over the <see cref="ResourceName"/> resource name /// property. /// </summary> internal CustomConversionGoalName ResourceNameAsCustomConversionGoalName { get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::CustomConversionGoalName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagvr::CustomConversionGoalName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> internal CustomConversionGoalName CustomConversionGoalName { get => string.IsNullOrEmpty(Name) ? null : gagvr::CustomConversionGoalName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary> /// <see cref="ConversionActionName"/>-typed view over the <see cref="ConversionActions"/> resource name /// property. /// </summary> internal gax::ResourceNameList<ConversionActionName> ConversionActionsAsConversionActionNames { get => new gax::ResourceNameList<ConversionActionName>(ConversionActions, s => string.IsNullOrEmpty(s) ? null : ConversionActionName.Parse(s, allowUnparsed: true)); } } }
// 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.Globalization; using System.Runtime.Tests.Common; using Xunit; public static class DoubleTests { [Fact] public static void TestCtorEmpty() { double i = new double(); Assert.Equal(0, i); } [Fact] public static void TestCtorValue() { double i = 41; Assert.Equal(41, i); i = 41.3; Assert.Equal(41.3, i); } [Fact] public static void TestMaxValue() { Assert.Equal((double)1.7976931348623157E+308, double.MaxValue); } [Fact] public static void TestMinValue() { Assert.Equal((double)(-1.7976931348623157E+308), double.MinValue); } [Fact] public static void TestEpsilon() { Assert.Equal((double)4.9406564584124654E-324, double.Epsilon); } [Fact] public static void TestIsInfinity() { Assert.True(double.IsInfinity(double.NegativeInfinity)); Assert.True(double.IsInfinity(double.PositiveInfinity)); } [Fact] public static void TestNaN() { Assert.Equal((double)0.0 / (double)0.0, double.NaN); } [Fact] public static void TestIsNaN() { Assert.True(double.IsNaN(double.NaN)); } [Fact] public static void TestNegativeInfinity() { Assert.Equal((double)(-1.0) / (double)0.0, double.NegativeInfinity); } [Fact] public static void TestIsNegativeInfinity() { Assert.True(double.IsNegativeInfinity(double.NegativeInfinity)); } [Fact] public static void TestPositiveInfinity() { Assert.Equal((double)1.0 / (double)0.0, double.PositiveInfinity); } [Fact] public static void TestIsPositiveInfinity() { Assert.True(double.IsPositiveInfinity(double.PositiveInfinity)); } [Theory] [InlineData((double)234, (double)234, 0)] [InlineData((double)234, double.MinValue, 1)] [InlineData((double)234, (double)(-123), 1)] [InlineData((double)234, (double)0, 1)] [InlineData((double)234, (double)123, 1)] [InlineData((double)234, (double)456, -1)] [InlineData((double)234, double.MaxValue, -1)] [InlineData((double)234, double.NaN, 1)] [InlineData(double.NaN, double.NaN, 0)] [InlineData(double.NaN, 0, -1)] public static void TestCompareTo(double i, double value, int expected) { int result = CompareHelper.NormalizeCompare(i.CompareTo(value)); Assert.Equal(expected, result); } [Theory] [InlineData(null, 1)] [InlineData((double)234, 0)] [InlineData(double.MinValue, 1)] [InlineData((double)(-123), 1)] [InlineData((double)0, 1)] [InlineData((double)123, 1)] [InlineData((double)456, -1)] [InlineData(double.MaxValue, -1)] public static void TestCompareToObject(object obj, int expected) { IComparable comparable = (double)234; int i = CompareHelper.NormalizeCompare(comparable.CompareTo(obj)); Assert.Equal(expected, i); } [Fact] public static void TestCompareToObjectInvalid() { IComparable comparable = (double)234; Assert.Throws<ArgumentException>(null, () => comparable.CompareTo("a")); //Obj is not a double } [Theory] [InlineData((double)789, true)] [InlineData((double)(-789), false)] [InlineData((double)0, false)] public static void TestEqualsObject(object obj, bool expected) { double i = 789; Assert.Equal(expected, i.Equals(obj)); } [Theory] [InlineData((double)789, (double)789, true)] [InlineData((double)789, (double)(-789), false)] [InlineData((double)789, (double)0, false)] [InlineData(double.NaN, double.NaN, true)] public static void TestEquals(double i1, double i2, bool expected) { Assert.Equal(expected, i1.Equals(i2)); } [Fact] public static void TestGetHashCode() { double i1 = 123; double i2 = 654; Assert.NotEqual(0, i1.GetHashCode()); Assert.NotEqual(i1.GetHashCode(), i2.GetHashCode()); } [Fact] public static void TestToString() { double i1 = 6310; Assert.Equal("6310", i1.ToString()); double i2 = -8249; Assert.Equal("-8249", i2.ToString()); } [Fact] public static void TestToStringFormatProvider() { var numberFormat = new NumberFormatInfo(); double i1 = 6310; Assert.Equal("6310", i1.ToString(numberFormat)); double i2 = -8249; Assert.Equal("-8249", i2.ToString(numberFormat)); double i3 = -2468; // Changing the negative pattern doesn't do anything without also passing in a format string numberFormat.NumberNegativePattern = 0; Assert.Equal("-2468", i3.ToString(numberFormat)); Assert.Equal("NaN", double.NaN.ToString(NumberFormatInfo.InvariantInfo)); Assert.Equal("Infinity", double.PositiveInfinity.ToString(NumberFormatInfo.InvariantInfo)); Assert.Equal("-Infinity", double.NegativeInfinity.ToString(NumberFormatInfo.InvariantInfo)); } [Fact] public static void TestToStringFormat() { double i1 = 6310; Assert.Equal("6310", i1.ToString("G")); double i2 = -8249; Assert.Equal("-8249", i2.ToString("g")); double i3 = -2468; Assert.Equal(string.Format("{0:N}", -2468.00), i3.ToString("N")); } [Fact] public static void TestToStringFormatFormatProvider() { var numberFormat = new NumberFormatInfo(); double i1 = 6310; Assert.Equal("6310", i1.ToString("G", numberFormat)); double i2 = -8249; Assert.Equal("-8249", i2.ToString("g", numberFormat)); numberFormat.NegativeSign = "xx"; // setting it to trash to make sure it doesn't show up numberFormat.NumberGroupSeparator = "*"; numberFormat.NumberNegativePattern = 0; double i3 = -2468; Assert.Equal("(2*468.00)", i3.ToString("N", numberFormat)); } [Fact] public static void TestParse() { Assert.Equal(123, double.Parse("123")); Assert.Equal(-123, double.Parse("-123")); //TODO: Negative tests once we get better exceptions } [Fact] public static void TestParseNumberStyle() { Assert.Equal((double)123.1, double.Parse(string.Format("{0}", 123.1), NumberStyles.AllowDecimalPoint)); Assert.Equal(1000, double.Parse(string.Format("{0}", 1000), NumberStyles.AllowThousands)); //TODO: Negative tests once we get better exceptions } [Fact] public static void TestParseFormatProvider() { var nfi = new NumberFormatInfo(); Assert.Equal(123, double.Parse("123", nfi)); Assert.Equal(-123, double.Parse("-123", nfi)); //TODO: Negative tests once we get better exceptions } [Fact] public static void TestParseNumberStyleFormatProvider() { var nfi = new NumberFormatInfo(); nfi.NumberDecimalSeparator = "."; Assert.Equal((double)123.123, double.Parse("123.123", NumberStyles.Float, nfi)); nfi.CurrencySymbol = "$"; nfi.CurrencyGroupSeparator = ","; Assert.Equal(1000, double.Parse("$1,000", NumberStyles.Currency, nfi)); //TODO: Negative tests once we get better exception support } [Fact] public static void TestTryParse() { // Defaults AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowDecimalPoint | AllowExponent | AllowThousands double i; Assert.True(double.TryParse("123", out i)); // Simple Assert.Equal(123, i); Assert.True(double.TryParse("-385", out i)); // LeadingSign Assert.Equal(-385, i); Assert.True(double.TryParse(" 678 ", out i)); // Leading/Trailing whitespace Assert.Equal(678, i); Assert.True(double.TryParse((678.90).ToString("F2"), out i)); // Decimal Assert.Equal((double)678.90, i); Assert.True(double.TryParse("1E23", out i)); // Exponent Assert.Equal((double)1E23, i); Assert.True(double.TryParse((1000).ToString("N0"), out i)); // Thousands Assert.Equal(1000, i); var nfi = new NumberFormatInfo() { CurrencyGroupSeparator = "" }; Assert.False(double.TryParse((1000).ToString("C0", nfi), out i)); // Currency Assert.False(double.TryParse("abc", out i)); // Hex digits Assert.False(double.TryParse("(135)", out i)); // Parentheses } [Fact] public static void TestTryParseNumberStyleFormatProvider() { double i; var nfi = new NumberFormatInfo(); nfi.NumberDecimalSeparator = "."; Assert.True(double.TryParse("123.123", NumberStyles.Any, nfi, out i)); // Simple positive Assert.Equal((double)123.123, i); Assert.True(double.TryParse("123", NumberStyles.Float, nfi, out i)); // Simple Hex Assert.Equal(123, i); nfi.CurrencySymbol = "$"; nfi.CurrencyGroupSeparator = ","; Assert.True(double.TryParse("$1,000", NumberStyles.Currency, nfi, out i)); // Currency/Thousands positive Assert.Equal(1000, i); Assert.False(double.TryParse("abc", NumberStyles.None, nfi, out i)); // Hex Number negative Assert.False(double.TryParse("678.90", NumberStyles.Integer, nfi, out i)); // Decimal Assert.False(double.TryParse(" 678 ", NumberStyles.None, nfi, out i)); // Trailing/Leading whitespace negative Assert.True(double.TryParse("(135)", NumberStyles.AllowParentheses, nfi, out i)); // Parentheses positive Assert.Equal(-135, i); Assert.True(double.TryParse("Infinity", NumberStyles.Any, NumberFormatInfo.InvariantInfo, out i)); Assert.True(double.IsPositiveInfinity(i)); Assert.True(double.TryParse("-Infinity", NumberStyles.Any, NumberFormatInfo.InvariantInfo, out i)); Assert.True(double.IsNegativeInfinity(i)); Assert.True(double.TryParse("NaN", NumberStyles.Any, NumberFormatInfo.InvariantInfo, out i)); Assert.True(double.IsNaN(i)); } }
using System; using System.Collections.Generic; using StructureMap.Graph; using StructureMap.Interceptors; using StructureMap.Pipeline; namespace StructureMap.Configuration.DSL.Expressions { /// <summary> /// Expression Builder that has grammars for defining policies at the /// PluginType level /// </summary> public class CreatePluginFamilyExpression<TPluginType> { private readonly List<Action<PluginFamily>> _alterations = new List<Action<PluginFamily>>(); private readonly List<Action<PluginGraph>> _children = new List<Action<PluginGraph>>(); private readonly Type _pluginType; public CreatePluginFamilyExpression(Registry registry, ILifecycle scope) { _pluginType = typeof (TPluginType); registry.alter = graph => { PluginFamily family = graph.Families[_pluginType]; _children.Each(action => action(graph)); _alterations.Each(action => action(family)); }; if (scope != null) { _alterations.Add(family => family.SetScopeTo(scope)); } } public InstanceExpression<TPluginType> MissingNamedInstanceIs { get { return new InstanceExpression<TPluginType>(i => _alterations.Add(family => family.MissingInstance = i)); } } /// <summary> /// Add multiple Instance's to this PluginType /// </summary> /// <param name="action"></param> /// <returns></returns> public CreatePluginFamilyExpression<TPluginType> AddInstances(Action<IInstanceExpression<TPluginType>> action) { var list = new List<Instance>(); var child = new InstanceExpression<TPluginType>(list.Add); action(child); return alterAndContinue(family => { foreach (Instance instance in list) { family.AddInstance(instance); } }); } /// <summary> /// Access to all of the uncommon Instance types /// </summary> /// <param name="configure"></param> /// <returns></returns> public CreatePluginFamilyExpression<TPluginType> UseSpecial(Action<IInstanceExpression<TPluginType>> configure) { var expression = new InstanceExpression<TPluginType>(Use); configure(expression); return this; } /// <summary> /// Access to all of the uncommon Instance types /// </summary> /// <param name="configure"></param> /// <returns></returns> public CreatePluginFamilyExpression<TPluginType> AddSpecial(Action<IInstanceExpression<TPluginType>> configure) { var expression = new InstanceExpression<TPluginType>(Add); configure(expression); return this; } private CreatePluginFamilyExpression<TPluginType> alterAndContinue(Action<PluginFamily> action) { _alterations.Add(action); return this; } /// <summary> /// Shorthand way of saying Use<> /// </summary> /// <typeparam name="TConcreteType"></typeparam> /// <returns></returns> public SmartInstance<TConcreteType> Use<TConcreteType>() where TConcreteType : TPluginType { // This is *my* team's naming convention for generic parameters // I know you may not like it, but it's my article so there var instance = new SmartInstance<TConcreteType>(); registerDefault(instance); return instance; } /// <summary> /// Use a lambda using the IContext to construct the default instance of the Plugin type /// /// </summary> /// <param name="func"></param> /// <returns></returns> public LambdaInstance<TPluginType> Use(Func<IContext, TPluginType> func) { var instance = new LambdaInstance<TPluginType>(func); registerDefault(instance); return instance; } /// <summary> /// Use a lambda to construct the default instance of the Plugin type /// </summary> /// <param name="func"></param> /// <returns></returns> public LambdaInstance<TPluginType> Use(Func<TPluginType> func) { var instance = new LambdaInstance<TPluginType>(func); registerDefault(instance); return instance; } /// <summary> /// Makes the supplied instance the default Instance for /// TPluginType /// </summary> /// <param name="instance"></param> public void Use(Instance instance) { registerDefault(instance); } /// <summary> /// Shorthand to say TheDefault.IsThis(@object) /// </summary> /// <param name="object"></param> /// <returns></returns> public ObjectInstance Use(TPluginType @object) { var instance = new ObjectInstance(@object); registerDefault(instance); return instance; } /// <summary> /// Makes the default instance of TPluginType the named /// instance /// </summary> /// <param name="instanceName"></param> /// <returns></returns> public ReferencedInstance Use(string instanceName) { var instance = new ReferencedInstance(instanceName); Use(instance); return instance; } /// <summary> /// Convenience method to mark a PluginFamily as a Singleton /// </summary> /// <returns></returns> public CreatePluginFamilyExpression<TPluginType> Singleton() { return lifecycleIs(Lifecycles.Singleton); } /// <summary> /// Convenience method to mark a PluginFamily as a Transient /// </summary> /// <returns></returns> public CreatePluginFamilyExpression<TPluginType> Transient() { return lifecycleIs(Lifecycles.Transient); } private CreatePluginFamilyExpression<TPluginType> lifecycleIs(ILifecycle lifecycle) { _alterations.Add(family => family.SetScopeTo(lifecycle)); return this; } /// <summary> /// Register an Action to run against any object of this PluginType immediately after /// it is created, but before the new object is passed back to the caller /// </summary> /// <param name="handler"></param> /// <returns></returns> public CreatePluginFamilyExpression<TPluginType> OnCreationForAll(Action<TPluginType> handler) { _children.Add( graph => { var interceptor = new PluginTypeInterceptor(typeof(TPluginType), (c, o) => { handler((TPluginType)o); return o; }); graph.InterceptorLibrary.AddInterceptor(interceptor); }); return this; } /// <summary> /// Adds an Interceptor to only this PluginType /// </summary> /// <param name="interceptor"></param> /// <returns></returns> public CreatePluginFamilyExpression<TPluginType> InterceptWith(InstanceInterceptor interceptor) { _children.Add( graph => { var typeInterceptor = new PluginTypeInterceptor(typeof (TPluginType), (c, o) => interceptor.Process(o, c)); graph.InterceptorLibrary.AddInterceptor(typeInterceptor); }); return this; } /// <summary> /// Register an Action to run against any object of this PluginType immediately after /// it is created, but before the new object is passed back to the caller /// </summary> /// <param name="handler"></param> /// <returns></returns> public CreatePluginFamilyExpression<TPluginType> OnCreationForAll(Action<IContext, TPluginType> handler) { _children.Add( graph => { Func<IContext, object, object> function = (c, o) => { handler(c, (TPluginType)o); return o; }; var interceptor = new PluginTypeInterceptor(typeof(TPluginType), function); graph.InterceptorLibrary.AddInterceptor(interceptor); }); return this; } /// <summary> /// Register a Func to run against any object of this PluginType immediately after it is created, /// but before the new object is passed back to the caller. Unlike <see cref="OnCreation(Action{TPluginType})">OnCreationForAll()</see>, /// EnrichAllWith() gives the the ability to return a different object. Use this method for runtime AOP /// scenarios or to return a decorator. /// </summary> /// <param name="handler"></param> /// <returns></returns> public CreatePluginFamilyExpression<TPluginType> EnrichAllWith(EnrichmentHandler<TPluginType> handler) { _children.Add( graph => { Func<IContext, object, object> function = (context, target) => handler((TPluginType)target); var interceptor = new PluginTypeInterceptor(typeof(TPluginType), function); graph.InterceptorLibrary.AddInterceptor(interceptor); }); return this; } /// <summary> /// Register a Func to run against any object of this PluginType immediately after it is created, /// but before the new object is passed back to the caller. Unlike <see cref="OnCreation(Action{IContext,TPluginType})">OnCreationForAll()</see>, /// EnrichAllWith() gives the the ability to return a different object. Use this method for runtime AOP /// scenarios or to return a decorator. /// </summary> /// <param name="handler"></param> /// <returns></returns> public CreatePluginFamilyExpression<TPluginType> EnrichAllWith(ContextEnrichmentHandler<TPluginType> handler) { _children.Add( graph => { var interceptor = new PluginTypeInterceptor(typeof(TPluginType), (c, o) => handler(c, (TPluginType)o)); graph.InterceptorLibrary.AddInterceptor(interceptor); }); return this; } /// <summary> /// Registers an ILifecycle for this Plugin Type that executes before /// any object of this PluginType is created. ILifecycle's can be /// used to create a custom scope /// </summary> /// <param name="lifecycle"></param> /// <returns></returns> public CreatePluginFamilyExpression<TPluginType> LifecycleIs(ILifecycle lifecycle) { _alterations.Add(family => family.SetScopeTo(lifecycle)); return this; } private void registerDefault(Instance instance) { _alterations.Add(family => family.SetDefault(instance)); } /// <summary> /// Forces StructureMap to always use a unique instance to /// stop the "BuildSession" caching /// </summary> /// <returns></returns> public CreatePluginFamilyExpression<TPluginType> AlwaysUnique() { return LifecycleIs(new UniquePerRequestLifecycle()); } /// <summary> /// Adds the object to to the TPluginType /// </summary> /// <param name="object"></param> /// <returns></returns> public ObjectInstance Add(TPluginType @object) { var instance = new ObjectInstance(@object); Add(instance); return instance; } public SmartInstance<TPluggedType> Add<TPluggedType>() { var instance = new SmartInstance<TPluggedType>(); Add(instance); return instance; } /// <summary> /// Add an Instance to this type created by a Lambda /// </summary> /// <param name="func"></param> /// <returns></returns> public LambdaInstance<TPluginType> Add(Func<IContext, TPluginType> func) { var instance = new LambdaInstance<TPluginType>(func); Add(instance); return instance; } public void Add(Instance instance) { _alterations.Add(f => f.AddInstance(instance)); } } }
//--------------------------------------------------------------------------- // // <copyright file=TextServicesContext.cs company=Microsoft> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: Manages Text Services Framework state. // // History: // 07/16/2003 : [....] - Ported from .net tree. // //--------------------------------------------------------------------------- using System; using System.Runtime.InteropServices; using System.Threading; using System.Windows.Threading; using System.Security; using System.Security.Permissions; using System.Diagnostics; using System.Collections; using MS.Utility; using MS.Win32; using MS.Internal; using MS.Internal.PresentationCore; // SecurityHelper namespace System.Windows.Input { //------------------------------------------------------ // // TextServicesContext class // //------------------------------------------------------ /// <summary> /// This class manages the ITfThreadMgr, EmptyDim and the reference to /// the default TextStore. /// The instance of TextServicesContext class is created per Dispatcher. /// </summary> /// <remarks> /// </remarks> internal class TextServicesContext { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ #region Constructors /// <summary> /// Instantiates a TextServicesContext. /// </summary> /// <SecurityNote> /// Critical - accesses AppDomain.DomainUnload event. /// SecurityTreatAsSafe - does not accept or reveal any information. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] private TextServicesContext() { Debug.Assert(Thread.CurrentThread.GetApartmentState() == ApartmentState.STA, "SetDispatcherThreaad on MTA thread"); // We will clean up Cicero's resource when Dispatcher is terminated or // when AppDomain is unloaded. TextServicesContextShutDownListener listener = new TextServicesContextShutDownListener(this, ShutDownEvents.DispatcherShutdown | ShutDownEvents.DomainUnload); } #endregion Constructors //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods /// <summary> /// Releases all unmanaged resources allocated by the /// TextServicesContext. /// </summary> /// <remarks> /// if appDomainShutdown == false, this method must be called on the /// Dispatcher thread. Otherwise, the caller is an AppDomain.Shutdown /// listener, and is calling from a worker thread. /// </remarks> /// <SecurityNote> /// Critical - access thread manager directly /// TreatAsSafe - uninitializing would only result in input being dead for the app /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] internal void Uninitialize(bool appDomainShutdown) { // Unregister DefaultTextStore. if (_defaultTextStore != null) { StopTransitoryExtension(); if (_defaultTextStore.DocumentManager != null) { _defaultTextStore.DocumentManager.Pop(UnsafeNativeMethods.PopFlags.TF_POPF_ALL); Marshal.ReleaseComObject(_defaultTextStore.DocumentManager); _defaultTextStore.DocumentManager = null; } // We can't use tls during AppDomainShutdown -- we're called on // a worker thread. But we don't need to cleanup in that case // either. if (!appDomainShutdown) { InputMethod.Current.DefaultTextStore = null; } _defaultTextStore = null; } // Free up any remaining textstores. if (_istimactivated == true) { // Shut down the thread manager when the last TextStore goes away. // On XP, if we're called on a worker thread (during AppDomain shutdown) // we can't call call any methods on _threadManager. The problem is // that there's no proxy registered for ITfThreadMgr on OS versions // previous to Vista. Not calling Deactivate will leak the IMEs, but // in practice (1) they're singletons, so it's not unbounded; and (2) // most applications will share the thread with other AppDomains that // have a UI, in which case the IME won't be released until the process // shuts down in any case. In theory we could also work around this // problem by creating our own XP proxy/stub implementation, which would // be added to WPF setup.... if (!appDomainShutdown || System.Environment.OSVersion.Version.Major >= 6) { _threadManager.Value.Deactivate(); } _istimactivated = false; } // Release the empty dim. if (_dimEmpty != null) { if (_dimEmpty.Value != null) { Marshal.ReleaseComObject(_dimEmpty.Value); } _dimEmpty = null; } // Release the ThreadManager. // We don't do this in UnregisterTextStore because someone may have // called get_ThreadManager after the last TextStore was unregistered. if (_threadManager != null) { if (_threadManager.Value != null) { Marshal.ReleaseComObject(_threadManager.Value); } _threadManager = null; } } /// <summary> /// Feeds a keystroke to the Text Services Framework, wrapper for /// ITfKeystrokeMgr::TestKeyUp/TestKeyDown/KeyUp/KeyDown. /// </summary> /// <remarks> /// Must be called on the main dispatcher thread. /// </remarks> /// <returns> /// true if the keystroke will be eaten by the Text Services Framework, /// false otherwise. /// Callers should stop further processing of the keystroke on true, /// continue otherwise. /// </returns> /// <SecurityNote> /// Critical - directly access thread manager, and pushes keystrokes into the input pipeline /// </SecurityNote> [SecurityCritical] internal bool Keystroke(int wParam, int lParam, KeyOp op) { bool fConsume; UnsafeNativeMethods.ITfKeystrokeMgr keystrokeMgr; // We delay load cicero until someone creates an ITextStore. // Or this thread may not have a ThreadMgr. if ((_threadManager == null) || (_threadManager.Value == null)) return false; keystrokeMgr = _threadManager.Value as UnsafeNativeMethods.ITfKeystrokeMgr; switch (op) { case KeyOp.TestUp: keystrokeMgr.TestKeyUp(wParam, lParam, out fConsume); break; case KeyOp.TestDown: keystrokeMgr.TestKeyDown(wParam, lParam, out fConsume); break; case KeyOp.Up: keystrokeMgr.KeyUp(wParam, lParam, out fConsume); break; case KeyOp.Down: keystrokeMgr.KeyDown(wParam, lParam, out fConsume); break; default: fConsume = false; break; } return fConsume; } // Called by framework's TextStore class. This method registers a // document with TSF. The TextServicesContext must maintain this list // to ensure all native resources are released after gc or uninitialization. /// <SecurityNote> /// Critical - directly manipulates input/message pump It also calls into Cicero /// to extract ThreadManager, clientID and DocumentManager all of which are not safe to /// expose. /// </SecurityNote> [SecurityCritical] internal void RegisterTextStore(DefaultTextStore defaultTextStore) { // We must cache the DefaultTextStore because we'll need it from // a worker thread if the AppDomain is torn down before the Dispatcher // is shutdown. _defaultTextStore = defaultTextStore; UnsafeNativeMethods.ITfThreadMgr threadManager = ThreadManager; if (threadManager != null) { UnsafeNativeMethods.ITfDocumentMgr doc; UnsafeNativeMethods.ITfContext context; int editCookie = UnsafeNativeMethods.TF_INVALID_COOKIE; // Activate TSF on this thread if this is the first TextStore. if (_istimactivated == false) { //temp variable created to retrieve the value // which is then stored in the critical data. int clientIdTemp; threadManager.Activate(out clientIdTemp); _clientId = new SecurityCriticalData<int>(clientIdTemp); _istimactivated = true; } // Create a TSF document. threadManager.CreateDocumentMgr(out doc); doc.CreateContext(_clientId.Value, 0 /* flags */, _defaultTextStore, out context, out editCookie); doc.Push(context); // Release any native resources we're done with. Marshal.ReleaseComObject(context); // Same DocumentManager and EditCookie in _defaultTextStore. _defaultTextStore.DocumentManager = doc; _defaultTextStore.EditCookie = editCookie; // Start the transitory extenstion so we can have Level 1 composition window from Cicero. StartTransitoryExtension(); } } // Cal ITfThreadMgr.SetFocus() with the dim for the default text store /// <SecurityNote> /// Critical - access DocumentManager of the current DefaultTextStore. /// TreatAsSafe - This is a safe since it does not expose ITfDocumentMgr. /// </SecurityNote> [SecurityCritical,SecurityTreatAsSafe] internal void SetFocusOnDefaultTextStore() { SetFocusOnDim(DefaultTextStore.Current.DocumentManager); } // Cal ITfThreadMgr.SetFocus() with the empty dim. /// <SecurityNote> /// Critical - access ITfDocumentMgr for empty dim. /// TreatAsSafe - This is a safe since it does not expose ITfDocumentMgr. /// </SecurityNote> [SecurityCritical,SecurityTreatAsSafe] internal void SetFocusOnEmptyDim() { SetFocusOnDim(EmptyDocumentManager); } #endregion Internal Methods //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ // Get TextServicesContext that is linked to the current Dispatcher. // return NULL if the default text store is not registered yet. internal static TextServicesContext DispatcherCurrent { get { // Create TextServicesContext on demand. if (InputMethod.Current.TextServicesContext == null) { InputMethod.Current.TextServicesContext = new TextServicesContext(); } return InputMethod.Current.TextServicesContext; } } /// <summary> /// This is an internal, link demand protected method. /// </summary> /// <SecurityNote> /// Critical - returns the thread manager (input and message pump) /// </SecurityNote> internal UnsafeNativeMethods.ITfThreadMgr ThreadManager { // The ITfThreadMgr for this thread. [SecurityCritical] get { if (_threadManager == null) { _threadManager = new SecurityCriticalDataClass<UnsafeNativeMethods.ITfThreadMgr>(TextServicesLoader.Load()); } return _threadManager.Value; } } //------------------------------------------------------ // // Internal Events // //------------------------------------------------------ //------------------------------------------------------ // // Internal Enums // //------------------------------------------------------ #region Internal Enums /// <summary> /// Specifies the type of keystroke operation to perform in the /// TextServicesContext.Keystroke method. /// </summary> internal enum KeyOp { /// <summary> /// ITfKeystrokeMgr::TestKeyUp /// </summary> TestUp, /// <summary> /// ITfKeystrokeMgr::TestKeyDown /// </summary> TestDown, /// <summary> /// ITfKeystrokeMgr::KeyUp /// </summary> Up, /// <summary> /// ITfKeystrokeMgr::KeyDown /// </summary> Down }; #endregion Internal Enums //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ // Cal ITfThreadMgr.SetFocus() with dim /// <SecurityNote> /// Critical: This code calls into critical code threadmgr.SetFocus /// TreatAsSafe: This does not expose any critical data and SetFocus is safe to expose /// </SecurityNote> [SecurityCritical,SecurityTreatAsSafe] private void SetFocusOnDim(UnsafeNativeMethods.ITfDocumentMgr dim) { UnsafeNativeMethods.ITfThreadMgr threadmgr = ThreadManager; if (threadmgr != null) { threadmgr.SetFocus(dim); } } // Start the transitory extestion for Cicero Level1/Level2 composition window support. /// <SecurityNote> /// Critical: Accesses unmanaged pointers (DocumentManager, CompartmentMgr,Compartment, Source) /// </SecurityNote> [SecurityCritical] private void StartTransitoryExtension() { Guid guid; Object var; UnsafeNativeMethods.ITfCompartmentMgr compmgr; UnsafeNativeMethods.ITfCompartment comp; UnsafeNativeMethods.ITfSource source; int transitoryExtensionSinkCookie; // Start TransitryExtension compmgr = _defaultTextStore.DocumentManager as UnsafeNativeMethods.ITfCompartmentMgr; // Set GUID_COMPARTMENT_TRANSITORYEXTENSION guid = UnsafeNativeMethods.GUID_COMPARTMENT_TRANSITORYEXTENSION; compmgr.GetCompartment(ref guid, out comp); var = (int)1; comp.SetValue(0, ref var); // Advise TransitoryExtension Sink and store the cookie. guid = UnsafeNativeMethods.IID_ITfTransitoryExtensionSink; source = _defaultTextStore.DocumentManager as UnsafeNativeMethods.ITfSource; if (source != null) { // DocumentManager only supports ITfSource on Longhorn, XP does not support it source.AdviseSink(ref guid, _defaultTextStore, out transitoryExtensionSinkCookie); _defaultTextStore.TransitoryExtensionSinkCookie = transitoryExtensionSinkCookie; } Marshal.ReleaseComObject(comp); } // Stop TransitoryExtesion /// <SecurityNote> /// Critical: This code calls into ITfCompartmentMgr, ITfCompartment and ITfSource all /// COM interop pointers /// TreatAsSafe: This does not expose any critical data. /// Stopping the transitory extenstion is a safe operation. /// </SecurityNote> [SecurityCritical,SecurityTreatAsSafe] private void StopTransitoryExtension() { // Unadvice the transitory extension sink. if (_defaultTextStore.TransitoryExtensionSinkCookie != UnsafeNativeMethods.TF_INVALID_COOKIE) { UnsafeNativeMethods.ITfSource source; source = _defaultTextStore.DocumentManager as UnsafeNativeMethods.ITfSource; if (source != null) { // DocumentManager only supports ITfSource on Longhorn, XP does not support it source.UnadviseSink(_defaultTextStore.TransitoryExtensionSinkCookie); } _defaultTextStore.TransitoryExtensionSinkCookie = UnsafeNativeMethods.TF_INVALID_COOKIE; } // Reset GUID_COMPARTMENT_TRANSITORYEXTENSION UnsafeNativeMethods.ITfCompartmentMgr compmgr; compmgr = _defaultTextStore.DocumentManager as UnsafeNativeMethods.ITfCompartmentMgr; if (compmgr != null) { Guid guid; Object var; UnsafeNativeMethods.ITfCompartment comp; guid = UnsafeNativeMethods.GUID_COMPARTMENT_TRANSITORYEXTENSION; compmgr.GetCompartment(ref guid, out comp); if (comp != null) { var = (int)0; comp.SetValue(0, ref var); Marshal.ReleaseComObject(comp); } } } //------------------------------------------------------ // // Private Properties // //------------------------------------------------------ // Create an empty dim on demand. /// <SecurityNote> /// Critical - directly manipulates thread manager and expose ITfDocumentMgr /// </SecurityNote> private UnsafeNativeMethods.ITfDocumentMgr EmptyDocumentManager { [SecurityCritical] get { if (_dimEmpty == null) { UnsafeNativeMethods.ITfThreadMgr threadManager = ThreadManager; if (threadManager == null) { return null; } //creating temp variable to retrieve from call and store in security critical data UnsafeNativeMethods.ITfDocumentMgr dimEmptyTemp; // Create a TSF document. threadManager.CreateDocumentMgr(out dimEmptyTemp); _dimEmpty = new SecurityCriticalDataClass<UnsafeNativeMethods.ITfDocumentMgr>(dimEmptyTemp); } return _dimEmpty.Value; } } //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Fields // Cached Dispatcher default text store. // We must cache the DefaultTextStore because we sometimes need it from // a worker thread if the AppDomain is torn down before the Dispatcher // is shutdown. private DefaultTextStore _defaultTextStore; // This is true if thread manager is activated. private bool _istimactivated; // The root TSF object, created on demand. /// <SecurityNote> /// Critical: UnsafeNativeMethods.ITfThreadMgr has methods with SuppressUnmanagedCodeSecurity. /// </SecurityNote> [SecurityCritical] private SecurityCriticalDataClass<UnsafeNativeMethods.ITfThreadMgr> _threadManager; // TSF ClientId from Activate call. /// <SecurityNote> /// Critical: _clientId is an identifier for Cicero. /// </SecurityNote> [SecurityCritical] private SecurityCriticalData<int> _clientId; // The empty dim for this thread. Created on demand. /// <SecurityNote> /// Critical: UnsafeNativeMethods.ITfDocumentMgr has methods with SuppressUnmanagedCodeSecurity. /// </SecurityNote> [SecurityCritical] private SecurityCriticalDataClass<UnsafeNativeMethods.ITfDocumentMgr> _dimEmpty; #endregion Private Fields #region WeakEventTableShutDownListener private sealed class TextServicesContextShutDownListener : ShutDownListener { /// <SecurityNote> /// Critical: accesses AppDomain.DomainUnload event /// TreatAsSafe: This code does not take any parameter or return state. /// It simply attaches private callbacks. /// </SecurityNote> [SecurityCritical,SecurityTreatAsSafe] public TextServicesContextShutDownListener(TextServicesContext target, ShutDownEvents events) : base(target, events) { } internal override void OnShutDown(object target, object sender, EventArgs e) { TextServicesContext textServicesContext = (TextServicesContext)target; textServicesContext.Uninitialize(!(sender is Dispatcher) /*appDomainShutdown*/); } } #endregion TextServicesContextShutDownListener } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Config { using System; using System.Globalization; using System.Threading; using NLog.Config; using NLog.LayoutRenderers; using NLog.Targets; using Xunit; public class CultureInfoTests : NLogTestBase { [Fact] public void WhenInvariantCultureDefinedThenDefaultCultureIsInvariantCulture() { var configuration = XmlLoggingConfiguration.CreateFromXmlString("<nlog useInvariantCulture='true'></nlog>"); Assert.Equal(CultureInfo.InvariantCulture, configuration.DefaultCultureInfo); } [Fact] public void DifferentConfigurations_UseDifferentDefaultCulture() { var currentCulture = CultureInfo.CurrentCulture; try { // set the current thread culture to be definitely different from the InvariantCulture Thread.CurrentThread.CurrentCulture = GetCultureInfo("de-DE"); var configurationTemplate = @"<nlog useInvariantCulture='{0}'> <targets> <target name='debug' type='Debug' layout='${{message}}' /> </targets> <rules> <logger name='*' writeTo='debug'/> </rules> </nlog>"; // configuration with current culture var logFactory1 = new LogFactory(); var configuration1 = XmlLoggingConfiguration.CreateFromXmlString(string.Format(configurationTemplate, false), logFactory1); Assert.Null(configuration1.DefaultCultureInfo); logFactory1.Configuration = configuration1; // configuration with invariant culture var logFactory2 = new LogFactory(); var configuration2 = XmlLoggingConfiguration.CreateFromXmlString(string.Format(configurationTemplate, true), logFactory2); Assert.Equal(CultureInfo.InvariantCulture, configuration2.DefaultCultureInfo); logFactory2.Configuration = configuration2; Assert.NotEqual(configuration1.DefaultCultureInfo, configuration2.DefaultCultureInfo); var testNumber = 3.14; var testDate = DateTime.Now; const string formatString = "{0},{1:d}"; AssertMessageFormattedWithCulture(logFactory1, CultureInfo.CurrentCulture, formatString, testNumber, testDate); AssertMessageFormattedWithCulture(logFactory2, CultureInfo.InvariantCulture, formatString, testNumber, testDate); } finally { // restore current thread culture Thread.CurrentThread.CurrentCulture = currentCulture; } } private void AssertMessageFormattedWithCulture(LogFactory logFactory, CultureInfo culture, string formatString, params object[] parameters) { var expected = string.Format(culture, formatString, parameters); var logger = logFactory.GetLogger("test"); logger.Debug(formatString, parameters); Assert.Equal(expected, GetDebugLastMessage("debug", logFactory.Configuration)); } [Fact] public void EventPropRendererCultureTest() { string cultureName = "de-DE"; string expected = "1,23"; // with decimal comma var logEventInfo = CreateLogEventInfo(cultureName); logEventInfo.Properties["ADouble"] = 1.23; var renderer = new EventPropertiesLayoutRenderer(); renderer.Item = "ADouble"; string output = renderer.Render(logEventInfo); Assert.Equal(expected, output); } [Fact] public void ProcessInfoLayoutRendererCultureTest() { string cultureName = "de-DE"; string expected = "."; // dot as date separator (01.10.2008) string output = string.Empty; var logEventInfo = CreateLogEventInfo(cultureName); if (IsLinux()) { Console.WriteLine("[SKIP] CultureInfoTests.ProcessInfoLayoutRendererCultureTest because we are running in Travis"); } else { var renderer = new ProcessInfoLayoutRenderer(); renderer.Property = ProcessInfoProperty.StartTime; renderer.Format = "d"; output = renderer.Render(logEventInfo); Assert.Contains(expected, output); Assert.DoesNotContain("/", output); Assert.DoesNotContain("-", output); } var renderer2 = new ProcessInfoLayoutRenderer(); renderer2.Property = ProcessInfoProperty.PriorityClass; renderer2.Format = "d"; output = renderer2.Render(logEventInfo); Assert.True(output.Length >= 1); Assert.True("012345678".IndexOf(output[0]) > 0); } [Fact] public void AllEventPropRendererCultureTest() { string cultureName = "de-DE"; string expected = "ADouble=1,23"; // with decimal comma var logEventInfo = CreateLogEventInfo(cultureName); logEventInfo.Properties["ADouble"] = 1.23; var renderer = new AllEventPropertiesLayoutRenderer(); string output = renderer.Render(logEventInfo); Assert.Equal(expected, output); } private static LogEventInfo CreateLogEventInfo(string cultureName) { var logEventInfo = new LogEventInfo( LogLevel.Info, "SomeName", CultureInfo.GetCultureInfo(cultureName), "SomeMessage", null); return logEventInfo; } /// <summary> /// expected: exactly the same exception message + stack trace regardless of the CurrentUICulture /// </summary> [Fact] public void ExceptionTest() { var target = new MemoryTarget { Layout = @"${exception:format=tostring}" }; SimpleConfigurator.ConfigureForTargetLogging(target); var logger = LogManager.GetCurrentClassLogger(); try { throw new InvalidOperationException(); } catch (Exception ex) { Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US", false); Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US", false); logger.Error(ex, ""); #if !NETSTANDARD Thread.CurrentThread.CurrentUICulture = new CultureInfo("de-DE", false); Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE", false); #endif logger.Error(ex, ""); Assert.Equal(2, target.Logs.Count); Assert.NotNull(target.Logs[0]); Assert.NotNull(target.Logs[1]); Assert.Equal(target.Logs[0], target.Logs[1]); } } } }
/* * Copyright (c) 2014 All Rights Reserved by the SDL Group. * * 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.Management.Automation; using Trisoft.ISHRemote.Objects; using Trisoft.ISHRemote.Objects.Public; using Trisoft.ISHRemote.Exceptions; using Trisoft.ISHRemote.HelperClasses; using System.Linq; namespace Trisoft.ISHRemote.Cmdlets.BackgroundTask { /// <summary> /// <para type="synopsis">Gets BackgroundTask entries with filtering options.</para> /// <para type="description">Uses BackgroundTask25 API to retrieve backgroundtasks showing their status, lease, etc from the virtual queue.</para> /// <para type="description">This table oriented API maps straight through to database column names regarding ishfield usage.</para> /// </summary> /// <example> /// <code> /// New-IshSession -WsBaseUrl "https://example.com/ISHWS/" -PSCredential "Admin" /// Get-IshBackgroundTask /// </code> /// <para>New-IshSession will submit into SessionState, so it can be reused by this cmdlet. Returns the full denormalized task/history entries limited to only Basic fields, for All users and the last 24 hours.</para> /// </example> /// <example> /// <code> /// $allMetadata = Set-IshRequestedMetadataField -IshSession $ishSession -Level Task -Name CREATIONDATE | /// Set-IshRequestedMetadataField -IshSession $ishSession -Level Task -Name CURRENTATTEMPT | /// Set-IshRequestedMetadataField -IshSession $ishSession -Level Task -Name EVENTTYPE | /// Set-IshRequestedMetadataField -IshSession $ishSession -Level Task -Name EXECUTEAFTERDATE | /// Set-IshRequestedMetadataField -IshSession $ishSession -Level Task -Name HASHID | /// Set-IshRequestedMetadataField -IshSession $ishSession -Level Task -Name INPUTDATAID | /// Set-IshRequestedMetadataField -IshSession $ishSession -Level Task -Name LEASEDBY | /// Set-IshRequestedMetadataField -IshSession $ishSession -Level Task -Name LEASEDON | /// Set-IshRequestedMetadataField -IshSession $ishSession -Level Task -Name MODIFICATIONDATE | /// Set-IshRequestedMetadataField -IshSession $ishSession -Level Task -Name OUTPUTDATAID | /// Set-IshRequestedMetadataField -IshSession $ishSession -Level Task -Name PROGRESSID | /// Set-IshRequestedMetadataField -IshSession $ishSession -Level Task -Name STATUS -ValueType Value | /// Set-IshRequestedMetadataField -IshSession $ishSession -Level Task -Name STATUS -ValueType Element | /// Set-IshRequestedMetadataField -IshSession $ishSession -Level Task -Name TASKID | /// Set-IshRequestedMetadataField -IshSession $ishSession -Level Task -Name TRACKINGID | /// Set-IshRequestedMetadataField -IshSession $ishSession -Level Task -Name USERID -ValueType All | /// Set-IshRequestedMetadataField -IshSession $ishSession -Level History -Name ENDDATE | /// Set-IshRequestedMetadataField -IshSession $ishSession -Level History -Name ERROR | /// Set-IshRequestedMetadataField -IshSession $ishSession -Level History -Name ERRORNUMBER | /// Set-IshRequestedMetadataField -IshSession $ishSession -Level History -Name EXITCODE | /// Set-IshRequestedMetadataField -IshSession $ishSession -Level History -Name HISTORYID | /// Set-IshRequestedMetadataField -IshSession $ishSession -Level History -Name HOSTNAME | /// Set-IshRequestedMetadataField -IshSession $ishSession -Level History -Name OUTPUT | /// Set-IshRequestedMetadataField -IshSession $ishSession -Level History -Name STARTDATE /// Get-IshBackgroundTask -IshSession $ishSession -RequestedMetadata $allMetadata /// </code> /// <para>Returns the full denormalized task/history entries limited to All users and the last 24 hours.</para> /// </example> /// <example> /// <code> /// Get-IshBackgroundTask -IshSession $ishSession -ModifiedSince ((Get-Date).AddSeconds(-10)) -UserFilter Current /// </code> /// <para>Returns the full denormalized task/history entries limited to only Basic fields, the current user and limited to 10 seconds ago of activity.</para> /// </example> /// <example> /// <code> /// $filterMetadata = Set-IshMetadataFilterField -IshSession $ishSession -Level Task -Name EVENTTYPE -FilterOperator In -Value "CREATETRANSLATIONS, CREATETRANSLATIONFROMLIST" | /// Set-IshMetadataFilterField -IshSession $ishSession -Level Task -Name TASKID -Value $taskId /// Get-IshBackgroundTask -IshSession $ishSession -MetadataFilter $filterMetadata /// </code> /// <para>Returns the full denormalized task/history entries limited to only Basic fields, for All users and the last 24 hours.</para> /// </example> /// <example> /// <code> /// $metadata = Set-IshRequestedMetadataField -IshSession $ishSession -Level Task -Name STATUS /// Get-IshBackgroundTask -IshSession $ishSession -RequestedMetadata $metadata | Group-Object -Property status /// </code> /// <para>Returns the group-by count by status, for All users and the last 24 hours.</para> /// </example> [Cmdlet(VerbsCommon.Get, "IshBackgroundTask", SupportsShouldProcess = false)] [OutputType(typeof(IshBackgroundTask))] public sealed class GetIshBackgroundTask : BackgroundTaskCmdlet { /// <summary> /// <para type="description">The IshSession variable holds the authentication and contract information. This object can be initialized using the New-IshSession cmdlet.</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshBackgroundTasksGroup")] [ValidateNotNullOrEmpty] public IshSession IshSession { get; set; } /// <summary> /// <para type="description">Enumeration indicating if only events of the current user or all events must be retrieved</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup")] [ValidateNotNullOrEmpty] public Enumerations.UserFilter UserFilter { private get { return Enumerations.UserFilter.All; } // required otherwise XmlDoc2CmdletDoc crashes with 'System.ArgumentException: Property Get method was not found.' set { _userFilter = EnumConverter.ToUserFilter<BackgroundTask25ServiceReference.eUserFilter>(value); } } /// <summary> /// <para type="description">A date limiting the events that will be retrieved based on the last modification date of the events</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup")] [ValidateNotNullOrEmpty] public DateTime ModifiedSince { get { return _modifiedSince; } set { _modifiedSince = value; } } /// <summary> /// <para type="description">Filter on metadata to limit the objects on which metadata has to be returned</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshBackgroundTasksGroup")] [ValidateNotNullOrEmpty] public IshField[] MetadataFilter { get; set; } /// <summary> /// <para type="description">XML structure indicating which metadata has to be retrieved.</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshBackgroundTasksGroup")] [ValidateNotNullOrEmpty] public IshField[] RequestedMetadata { get; set; } /// <summary> /// <para type="description">The <see cref="IshBackgroundTask"/>s that need to be handled.</para> /// </summary> [Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = "IshBackgroundTasksGroup")] public IshBackgroundTask[] IshBackgroundTask { get; set; } #region Private fields private DateTime _modifiedSince = DateTime.Today.AddDays(-1); //private BackgroundTask25ServiceReference.B _progressStatusFilter = BackgroundTask25ServiceReference.ProgressStatusFilter.All; private BackgroundTask25ServiceReference.eUserFilter _userFilter = BackgroundTask25ServiceReference.eUserFilter.All; private readonly List<IshBackgroundTask> _retrievedIshBackgroundTask = new List<IshBackgroundTask>(); #endregion protected override void BeginProcessing() { if (IshSession == null) { IshSession = (IshSession)SessionState.PSVariable.GetValue(ISHRemoteSessionStateIshSession); } if (IshSession == null) { throw new ArgumentException(ISHRemoteSessionStateIshSessionException); } WriteDebug($"Using IshSession[{IshSession.Name}] from SessionState.{ISHRemoteSessionStateIshSession}"); if ((IshSession.ServerIshVersion.MajorVersion < 13) || ((IshSession.ServerIshVersion.MajorVersion == 13) && (IshSession.ServerIshVersion.RevisionVersion < 2))) { throw new PlatformNotSupportedException($"Get-IshBackgroundTask requires server-side BackgroundTask API which only available starting from 13SP2/13.0.2 and up. ServerIshVersion[{IshSession.ServerVersion}]"); } base.BeginProcessing(); } /// <summary> /// Process the cmdlet. /// </summary> protected override void ProcessRecord() { try { if (IshBackgroundTask != null) { foreach(IshBackgroundTask ishBackgroundTask in IshBackgroundTask) { _retrievedIshBackgroundTask.Add(ishBackgroundTask); } } } catch (TrisoftAutomationException trisoftAutomationException) { ThrowTerminatingError(new ErrorRecord(trisoftAutomationException, base.GetType().Name, ErrorCategory.InvalidOperation, null)); } catch (Exception exception) { ThrowTerminatingError(new ErrorRecord(exception, base.GetType().Name, ErrorCategory.NotSpecified, null)); } } /// <summary> /// Process the cmdlet. /// </summary> /// <exception cref="TrisoftAutomationException"></exception> /// <exception cref="Exception"></exception> /// <remarks>Writes <see cref="IshEvent"/> to the pipeline.</remarks> protected override void EndProcessing() { try { IshFields metadataFilter = new IshFields(MetadataFilter); IshFields requestedMetadata = IshSession.IshTypeFieldSetup.ToIshRequestedMetadataFields(IshSession.DefaultRequestedMetadata, ISHType, new IshFields(RequestedMetadata), Enumerations.ActionMode.Find); string xmlIshBackgroundTasks; if (_retrievedIshBackgroundTask.Count != 0) { var backgroundTaskIds = _retrievedIshBackgroundTask.Select(ishBackgroundTask => Convert.ToInt64(ishBackgroundTask.TaskRef)).ToList(); if (backgroundTaskIds.Count != 0) { var backgroundTaskIdsAsString = string.Join(", ", backgroundTaskIds.ToArray()); metadataFilter.AddOrUpdateField(new IshMetadataFilterField("TASKID", Enumerations.Level.Task, Enumerations.FilterOperator.In, backgroundTaskIdsAsString, Enumerations.ValueType.Value), Enumerations.ActionMode.Find); } } WriteDebug($"Finding UserFilter[{_userFilter}] MetadataFilter.length[{metadataFilter.ToXml().Length}] RequestedMetadata.length[{requestedMetadata.ToXml().Length}]"); xmlIshBackgroundTasks = IshSession.BackgroundTask25.Find( ModifiedSince, _userFilter, metadataFilter.ToXml(), requestedMetadata.ToXml()); List<IshBackgroundTask> returnIshBackgroundTasks = new IshBackgroundTasks(xmlIshBackgroundTasks).BackgroundTasks; WriteVerbose("returned object count[" + returnIshBackgroundTasks.Count + "]"); WriteObject(IshSession, ISHType, returnIshBackgroundTasks.ConvertAll(x => (IshBaseObject)x), true); } catch (TrisoftAutomationException trisoftAutomationException) { ThrowTerminatingError(new ErrorRecord(trisoftAutomationException, base.GetType().Name, ErrorCategory.InvalidOperation, null)); } catch (Exception exception) { ThrowTerminatingError(new ErrorRecord(exception, base.GetType().Name, ErrorCategory.NotSpecified, null)); } finally { base.EndProcessing(); } } } }
/* * 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. */ // to build without references to System.Drawing, comment this out #define SYSTEM_DRAWING using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using BitmapProcessing; #if SYSTEM_DRAWING namespace PrimMesher { public class SculptMap { public byte[] blueBytes; public byte[] greenBytes; public int height; public byte[] redBytes; public int width; public SculptMap() { } public SculptMap(Bitmap bm, int lod) { int bmW = bm.Width; int bmH = bm.Height; if (bmW == 0 || bmH == 0) throw new Exception("SculptMap: bitmap has no data"); int numLodPixels = lod*2*lod*2; // (32 * 2)^2 = 64^2 pixels for default sculpt map image bool needsScaling = false; bool smallMap = bmW*bmH <= lod*lod; width = bmW; height = bmH; while (width*height > numLodPixels) { width >>= 1; height >>= 1; needsScaling = true; } try { if (needsScaling) bm = ScaleImage(bm, width, height, InterpolationMode.NearestNeighbor); } catch (Exception e) { throw new Exception("Exception in ScaleImage(): e: " + e); } if (width*height > lod*lod) { width >>= 1; height >>= 1; } int numBytes = (width + 1)*(height + 1); redBytes = new byte[numBytes]; greenBytes = new byte[numBytes]; blueBytes = new byte[numBytes]; /* FastBitmap unsafeBMP = new FastBitmap(bm); unsafeBMP.LockBitmap(); //Lock the bitmap for the unsafe operation */ int byteNdx = 0; try { for (int y = 0; y <= height; y++) { for (int x = 0; x <= width; x++) { Color pixel; if (smallMap) // pixel = unsafeBMP.GetPixel(x < width ? x : x - 1, pixel = bm.GetPixel(x < width ? x : x - 1, y < height ? y : y - 1); else pixel = bm.GetPixel(x < width ? x : x - 1, // pixel = unsafeBMP.GetPixel(x < width ? x*2 : x*2 - 1, y < height ? y*2 : y*2 - 1); redBytes[byteNdx] = pixel.R; greenBytes[byteNdx] = pixel.G; blueBytes[byteNdx] = pixel.B; ++byteNdx; } } } catch (Exception e) { throw new Exception("Caught exception processing byte arrays in SculptMap(): e: " + e); } //All done, unlock // unsafeBMP.UnlockBitmap(); width++; height++; } public List<List<Coord>> ToRows(bool mirror) { int numRows = height; int numCols = width; List<List<Coord>> rows = new List<List<Coord>>(numRows); float pixScale = 1.0f/255; int rowNdx, colNdx; int smNdx = 0; for (rowNdx = 0; rowNdx < numRows; rowNdx++) { List<Coord> row = new List<Coord>(numCols); for (colNdx = 0; colNdx < numCols; colNdx++) { if (mirror) row.Add(new Coord(-(redBytes[smNdx]*pixScale - 0.5f), (greenBytes[smNdx]*pixScale - 0.5f), blueBytes[smNdx]*pixScale - 0.5f)); else row.Add(new Coord(redBytes[smNdx]*pixScale - 0.5f, greenBytes[smNdx]*pixScale - 0.5f, blueBytes[smNdx]*pixScale - 0.5f)); ++smNdx; } rows.Add(row); } return rows; } private Bitmap ScaleImage(Bitmap srcImage, int destWidth, int destHeight, InterpolationMode interpMode) { Bitmap scaledImage = new Bitmap(destWidth, destHeight, PixelFormat.Format24bppRgb); Color c; float xscale = srcImage.Width / destWidth; float yscale = srcImage.Height / destHeight; float sy = 0.5f; for (int y = 0; y < destHeight; y++) { float sx = 0.5f; for (int x = 0; x < destWidth; x++) { try { c = srcImage.GetPixel((int)(sx), (int)(sy)); scaledImage.SetPixel(x, y, Color.FromArgb(c.R, c.G, c.B)); } catch (IndexOutOfRangeException) { } sx += xscale; } sy += yscale; } srcImage.Dispose(); return scaledImage; /* Bitmap scaledImage = new Bitmap(srcImage, destWidth, destHeight); scaledImage.SetResolution(96.0f, 96.0f); Graphics grPhoto = Graphics.FromImage(scaledImage); grPhoto.InterpolationMode = interpMode; grPhoto.DrawImage(srcImage, new Rectangle(0, 0, destWidth, destHeight), new Rectangle(0, 0, srcImage.Width, srcImage.Height), GraphicsUnit.Pixel); grPhoto.Dispose(); return scaledImage; */ } } } #endif
using System; using System.Collections; using System.Linq; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using Prism.Regions; using Prism.Regions.Behaviors; using Prism.Wpf.Tests.Mocks; using Xunit; namespace Prism.Wpf.Tests.Regions.Behaviors { public class SelectorItemsSourceSyncRegionBehaviorFixture { [StaFact] public void CanAttachToSelector() { SelectorItemsSourceSyncBehavior behavior = CreateBehavior(); behavior.Attach(); Assert.True(behavior.IsAttached); } [StaFact] public void AttachSetsItemsSourceOfSelector() { SelectorItemsSourceSyncBehavior behavior = CreateBehavior(); var v1 = new Button(); var v2 = new Button(); behavior.Region.Add(v1); behavior.Region.Add(v2); behavior.Attach(); Assert.Equal(2, (behavior.HostControl as Selector).Items.Count); } [StaFact] public void IfViewsHaveSortHintThenViewsAreProperlySorted() { SelectorItemsSourceSyncBehavior behavior = CreateBehavior(); var v1 = new MockSortableView1(); var v2 = new MockSortableView2(); var v3 = new MockSortableView3(); behavior.Attach(); behavior.Region.Add(v3); behavior.Region.Add(v2); behavior.Region.Add(v1); Assert.Equal(3, (behavior.HostControl as Selector).Items.Count); Assert.Same(v1, (behavior.HostControl as Selector).Items[0]); Assert.Same(v2, (behavior.HostControl as Selector).Items[1]); Assert.Same(v3, (behavior.HostControl as Selector).Items[2]); } [StaFact] public void SelectionChangedShouldChangeActiveViews() { SelectorItemsSourceSyncBehavior behavior = CreateBehavior(); var v1 = new Button(); var v2 = new Button(); behavior.Region.Add(v1); behavior.Region.Add(v2); behavior.Attach(); (behavior.HostControl as Selector).SelectedItem = v1; var activeViews = behavior.Region.ActiveViews; Assert.Single(activeViews); Assert.Equal(v1, activeViews.First()); (behavior.HostControl as Selector).SelectedItem = v2; Assert.Single(activeViews); Assert.Equal(v2, activeViews.First()); } [StaFact] public void ActiveViewChangedShouldChangeSelectedItem() { SelectorItemsSourceSyncBehavior behavior = CreateBehavior(); var v1 = new Button(); var v2 = new Button(); behavior.Region.Add(v1); behavior.Region.Add(v2); behavior.Attach(); behavior.Region.Activate(v1); Assert.Equal(v1, (behavior.HostControl as Selector).SelectedItem); behavior.Region.Activate(v2); Assert.Equal(v2, (behavior.HostControl as Selector).SelectedItem); } [StaFact] public void ItemsSourceSetThrows() { var ex = Assert.Throws<InvalidOperationException>(() => { SelectorItemsSourceSyncBehavior behavior = CreateBehavior(); (behavior.HostControl as Selector).ItemsSource = new[] { new Button() }; behavior.Attach(); }); } [StaFact] public void ControlWithExistingBindingOnItemsSourceWithNullValueThrows() { var behavor = CreateBehavior(); Binding binding = new Binding("Enumerable"); binding.Source = new SimpleModel() { Enumerable = null }; (behavor.HostControl as Selector).SetBinding(ItemsControl.ItemsSourceProperty, binding); try { behavor.Attach(); } catch (Exception ex) { Assert.IsType<InvalidOperationException>(ex); Assert.Contains("ItemsControl's ItemsSource property is not empty.", ex.Message); } } [StaFact] public void AddingViewToTwoRegionsThrows() { var ex = Assert.Throws<InvalidOperationException>(() => { var behavior1 = CreateBehavior(); var behavior2 = CreateBehavior(); behavior1.Attach(); behavior2.Attach(); var v1 = new Button(); behavior1.Region.Add(v1); behavior2.Region.Add(v1); }); } [StaFact] public void ReactivatingViewAddsViewToTab() { var behavior1 = CreateBehavior(); behavior1.Attach(); var v1 = new Button(); var v2 = new Button(); behavior1.Region.Add(v1); behavior1.Region.Add(v2); behavior1.Region.Activate(v1); Assert.True(behavior1.Region.ActiveViews.First() == v1); behavior1.Region.Activate(v2); Assert.True(behavior1.Region.ActiveViews.First() == v2); behavior1.Region.Activate(v1); Assert.True(behavior1.Region.ActiveViews.First() == v1); } [StaFact] public void ShouldAllowMultipleSelectedItemsForListBox() { var behavior1 = CreateBehavior(); ListBox listBox = new ListBox(); listBox.SelectionMode = SelectionMode.Multiple; behavior1.HostControl = listBox; behavior1.Attach(); var v1 = new Button(); var v2 = new Button(); behavior1.Region.Add(v1); behavior1.Region.Add(v2); listBox.SelectedItems.Add(v1); listBox.SelectedItems.Add(v2); Assert.True(behavior1.Region.ActiveViews.Contains(v1)); Assert.True(behavior1.Region.ActiveViews.Contains(v2)); } private SelectorItemsSourceSyncBehavior CreateBehavior() { Region region = new Region(); Selector selector = new TabControl(); var behavior = new SelectorItemsSourceSyncBehavior(); behavior.HostControl = selector; behavior.Region = region; return behavior; } private class SimpleModel { public IEnumerable Enumerable { get; set; } } } }
// 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; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class SetKeywordRecommenderTests : KeywordRecommenderTests { [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAtRoot_Interactive() { VerifyAbsence(SourceCodeKind.Script, @"$$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterClass_Interactive() { VerifyAbsence(SourceCodeKind.Script, @"class C { } $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterGlobalStatement_Interactive() { VerifyAbsence(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterGlobalVariableDeclaration_Interactive() { VerifyAbsence(SourceCodeKind.Script, @"int i = 0; $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInUsingAlias() { VerifyAbsence( @"using Foo = $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInEmptyStatement() { VerifyAbsence(AddInsideMethod( @"$$")); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterProperty() { VerifyKeyword( @"class C { int Foo { $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterPropertyPrivate() { VerifyKeyword( @"class C { int Foo { private $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterPropertyAttribute() { VerifyKeyword( @"class C { int Foo { [Bar] $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterPropertyAttributeAndPrivate() { VerifyKeyword( @"class C { int Foo { [Bar] private $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterPropertyGet() { VerifyKeyword( @"class C { int Foo { get; $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterPropertyGetAndPrivate() { VerifyKeyword( @"class C { int Foo { get; private $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterPropertyGetAndAttribute() { VerifyKeyword( @"class C { int Foo { get; [Bar] $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterPropertyGetAndAttributeAndPrivate() { VerifyKeyword( @"class C { int Foo { get; [Bar] private $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterGetAccessorBlock() { VerifyKeyword( @"class C { int Foo { get { } $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterGetAccessorBlockAndPrivate() { VerifyKeyword( @"class C { int Foo { get { } private $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterGetAccessorBlockAndAttribute() { VerifyKeyword( @"class C { int Foo { get { } [Bar] $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterGetAccessorBlockAndAttributeAndPrivate() { VerifyKeyword( @"class C { int Foo { get { } [Bar] private $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterPropertySetKeyword() { VerifyAbsence( @"class C { int Foo { set $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterPropertySetAccessor() { VerifyAbsence( @"class C { int Foo { set; $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInEvent() { VerifyAbsence( @"class C { event Foo E { $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterIndexer() { VerifyKeyword( @"class C { int this[int i] { $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterIndexerPrivate() { VerifyKeyword( @"class C { int this[int i] { private $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterIndexerAttribute() { VerifyKeyword( @"class C { int this[int i] { [Bar] $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterIndexerAttributeAndPrivate() { VerifyKeyword( @"class C { int this[int i] { [Bar] private $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterIndexerGet() { VerifyKeyword( @"class C { int this[int i] { get; $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterIndexerGetAndPrivate() { VerifyKeyword( @"class C { int this[int i] { get; private $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterIndexerGetAndAttribute() { VerifyKeyword( @"class C { int this[int i] { get; [Bar] $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterIndexerGetAndAttributeAndPrivate() { VerifyKeyword( @"class C { int this[int i] { get; [Bar] private $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterIndexerGetBlock() { VerifyKeyword( @"class C { int this[int i] { get { } $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterIndexerGetBlockAndPrivate() { VerifyKeyword( @"class C { int this[int i] { get { } private $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterIndexerGetBlockAndAttribute() { VerifyKeyword( @"class C { int this[int i] { get { } [Bar] $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterIndexerGetBlockAndAttributeAndPrivate() { VerifyKeyword( @"class C { int this[int i] { get { } [Bar] private $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterIndexerSetKeyword() { VerifyAbsence( @"class C { int this[int i] { set $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterIndexerSetAccessor() { VerifyAbsence( @"class C { int this[int i] { set; $$"); } } }
#region license // Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) // 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 Ayende Rahien nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections.Generic; using Rhino.Mocks.Constraints; using Rhino.Mocks.Exceptions; using Xunit; namespace Rhino.Mocks.Tests { // Interface to create mocks for public interface ITestInterface { event EventHandler<EventArgs> AnEvent; void RefOut(string str, out int i, string str2, ref int j, string str3); void VoidList(List<string> list); void VoidObject(object obj); } public class ArgConstraintTests { private IDemo demoMock; ITestInterface testMock; private delegate string StringDelegateWithParams(int a, string b); public ArgConstraintTests() { demoMock = MockRepository.GenerateStrictMock<IDemo>(); testMock = MockRepository.GenerateStrictMock<ITestInterface>(); } [Fact] public void ThreeArgs_Pass() { demoMock.Expect(x => x.VoidThreeArgs( Arg<int>.Is.Anything, Arg.Text.Contains("eine"), Arg<float>.Is.LessThan(2.5f))); demoMock.VoidThreeArgs(3, "Steinegger", 2.4f); demoMock.VerifyAllExpectations(); testMock.VerifyAllExpectations(); } [Fact] public void ThreeArgs_Fail() { demoMock.Expect(x => x.VoidThreeArgs( Arg<int>.Is.Anything, Arg.Text.Contains("eine"), Arg<float>.Is.LessThan(2.5f))); Assert.Throws<ExpectationViolationException>(() => demoMock.VoidThreeArgs(2, "Steinegger", 2.6f)); } [Fact] public void Matches() { demoMock.Expect(x => x.VoidStringArg(Arg<string>.Matches(Is.Equal("hallo") || Text.EndsWith("b")))).Repeat.Times(3); demoMock.VoidStringArg("hallo"); demoMock.VoidStringArg("ab"); demoMock.VoidStringArg("bb"); demoMock.VerifyAllExpectations(); testMock.VerifyAllExpectations(); } [Fact] public void ConstraintsThatWerentCallCauseVerifyFailure() { this.demoMock.Expect(x => x.VoidStringArg(Arg.Text.Contains("World"))); var ex = Assert.Throws<ExpectationViolationException>(() => this.demoMock.VerifyAllExpectations()); Assert.Equal("IDemo.VoidStringArg(contains \"World\"); Expected #1, Actual #0.", ex.Message); } [Fact] public void RefAndOutArgs() { testMock.Expect(x => x.RefOut( Arg<string>.Is.Anything, out Arg<int>.Out(3).Dummy, Arg<string>.Is.Equal("Steinegger"), ref Arg<int>.Ref(Is.Equal(2), 7).Dummy, Arg<string>.Is.NotNull )); int iout = 0; int iref = 2; testMock.RefOut("hallo", out iout, "Steinegger", ref iref, "notnull"); Assert.Equal(3, iout); Assert.Equal(7, iref); demoMock.VerifyAllExpectations(); testMock.VerifyAllExpectations(); } [Fact] public void Event() { ITestInterface eventMock = MockRepository.GenerateStrictMock<ITestInterface>(); eventMock.Expect(x => x.AnEvent += Arg<EventHandler<EventArgs>>.Is.Anything); eventMock.AnEvent += handler; demoMock.VerifyAllExpectations(); testMock.VerifyAllExpectations(); eventMock.VerifyAllExpectations(); } [Fact] public void ListTest() { ITestInterface testMock = MockRepository.GenerateStrictMock<ITestInterface>(); testMock.Expect(x => x.VoidList(Arg<List<string>>.List.Count(Is.GreaterThan(3)))); testMock.Expect(x => x.VoidList(Arg<List<string>>.List.IsIn("hello"))); testMock.VoidList(new List<string>(new string[] { "1", "2", "4", "5" })); var ex = Assert.Throws<ExpectationViolationException>(() => testMock.VoidList(new List<string>(new string[] { "1", "3" }))); Assert.Equal("ITestInterface.VoidList(System.Collections.Generic.List`1[System.String]); Expected #0, Actual #1.", ex.Message); } [Fact] public void ConstraintWithTooFewArguments_ThrowsException() { var ex = Assert.Throws<InvalidOperationException>(() => this.demoMock.Expect(x => x.VoidThreeArgs( Arg<int>.Is.Equal(4), Arg.Text.Contains("World"), 3.14f))); Assert.Equal("When using Arg<T>, all arguments must be defined using Arg<T>.Is, Arg<T>.Text, Arg<T>.List, Arg<T>.Ref or Arg<T>.Out. 3 arguments expected, 2 have been defined.", ex.Message); } [Fact] public void ConstraintToManyArgs_ThrowsException() { Arg<int>.Is.Equal(4); var ex = Assert.Throws<InvalidOperationException>(() => this.demoMock.Expect(x => x.VoidThreeArgs(Arg<int>.Is.Equal(4), Arg.Text.Contains("World"), Arg<float>.Is.Equal(3.14f)))); Assert.Equal("Use Arg<T> ONLY within a mock method call while recording. 3 arguments expected, 4 have been defined.", ex.Message); } [Fact] public void MockRepositoryClearsArgData() { Arg<int>.Is.Equal(4); Arg<int>.Is.Equal(4); // create new MockRepository to see if the Arg data has been cleared demoMock = MockRepository.GenerateStrictMock<IDemo>(); demoMock.Expect(x => x.VoidThreeArgs(Arg<int>.Is.Equal(4), Arg.Text.Contains("World"), Arg<float>.Is.Equal(3.14f))); } [Fact] public void TooFewOutArgs() { int iout = 2; var ex = Assert.Throws<InvalidOperationException>(() => this.testMock.Expect(x => x.RefOut( Arg<string>.Is.Anything, out iout, Arg.Text.Contains("Steinegger"), ref Arg<int>.Ref(Is.Equal(2), 7).Dummy, Arg<string>.Is.NotNull))); Assert.Equal("When using Arg<T>, all arguments must be defined using Arg<T>.Is, Arg<T>.Text, Arg<T>.List, Arg<T>.Ref or Arg<T>.Out. 5 arguments expected, 4 have been defined.", ex.Message); } [Fact] public void RefInsteadOfOutArg() { var ex = Assert.Throws<InvalidOperationException>(() => this.testMock.Expect(x => x.RefOut( Arg<string>.Is.Anything, out Arg<int>.Ref(Is.Equal(2), 7).Dummy, Arg.Text.Contains("Steinegger"), ref Arg<int>.Ref(Is.Equal(2), 7).Dummy, Arg<string>.Is.NotNull))); Assert.Equal("Argument 1 must be defined as: out Arg<T>.Out(returnvalue).Dummy", ex.Message); } [Fact] public void OutInsteadOfRefArg() { var ex = Assert.Throws<InvalidOperationException>(() => this.testMock.Expect(x => x.RefOut( Arg<string>.Is.Anything, out Arg<int>.Out(7).Dummy, Arg.Text.Contains("Steinegger"), ref Arg<int>.Out(7).Dummy, Arg<string>.Is.NotNull))); Assert.Equal("Argument 3 must be defined as: ref Arg<T>.Ref(constraint, returnvalue).Dummy", ex.Message); } [Fact] public void OutInsteadOfInArg() { var ex = Assert.Throws<InvalidOperationException>(() => this.testMock.Expect(x => x.VoidObject(Arg<object>.Out(null)))); Assert.Equal("Argument 0 must be defined using: Arg<T>.Is, Arg<T>.Text or Arg<T>.List", ex.Message); } [Fact] public void Is_EqualsThrowsException() { var ex = Assert.Throws<InvalidOperationException>(() => Arg<object>.Is.Equals(null)); Assert.Equal("Don't use Equals() to define constraints, use Equal() instead", ex.Message); } [Fact] public void List_EqualsThrowsException() { var ex = Assert.Throws<InvalidOperationException>(() => Arg<object>.List.Equals(null)); Assert.Equal("Don't use Equals() to define constraints, use Equal() instead", ex.Message); } [Fact] public void Text_EqualsThrowsException() { var ex = Assert.Throws<InvalidOperationException>(() => Arg.Text.Equals(null)); Assert.Equal("Don't use Equals() to define constraints, use Equal() instead", ex.Message); } /// <summary> /// Adapted from MockingDelegatesTests.MockStringDelegateWithParams /// </summary> [Fact] public void MockStringDelegateWithParams() { StringDelegateWithParams d = (StringDelegateWithParams)MockRepository.GenerateStrictMock(typeof(StringDelegateWithParams), null, null); d.Expect(x => x(Arg<int>.Is.Equal(1), Arg<string>.Is.Equal("111"))).Return("abc"); d.Expect(x => x(Arg<int>.Is.Equal(2), Arg<string>.Is.Equal("222"))).Return("def"); Assert.Equal("abc", d(1, "111")); Assert.Equal("def", d(2, "222")); Assert.Throws<ExpectationViolationException>(() => d(3, "333")); } private void handler(object o, EventArgs e) { } [Fact] public void Mock_object_using_ExpectMethod_with_ArgConstraints_allow_for_multiple_calls_as_default_behavior() { // Arrange var mock = MockRepository.GenerateMock<IDemo>(); mock.Expect(x => x.StringArgString(Arg<string>.Is.Equal("input"))).Return("output"); // Act var firstCallResult = mock.StringArgString("input"); var secondCallResult = mock.StringArgString("input"); // Assert Assert.Equal("output", firstCallResult); Assert.Equal(firstCallResult, secondCallResult); } [Fact] public void Stub_object_using_ExpectMethod_with_ArgConstraints_allow_for_multiple_calls_as_default_behavior() { // Arrange var mock = MockRepository.GenerateStub<IDemo>(); mock.Expect(x => x.StringArgString(Arg<string>.Is.Equal("input"))).Return("output"); // Act var firstCallResult = mock.StringArgString("input"); var secondCallResult = mock.StringArgString("input"); // Assert Assert.Equal("output", firstCallResult); Assert.Equal(firstCallResult, secondCallResult); } [Fact] public void Stub_object_using_StubMethod_with_ArgConstraints_allow_for_multiple_calls_as_default_behavior() { // Arrange var stub = MockRepository.GenerateStub<IDemo>(); stub.Stub(x => x.StringArgString(Arg<string>.Is.Equal("input"))).Return("output"); // Act var firstCallResult = stub.StringArgString("input"); var secondCallResult = stub.StringArgString("input"); // Assert Assert.Equal("output", firstCallResult); Assert.Equal(firstCallResult, secondCallResult); } [Fact] public void Mock_object_using_StubMethod_with_ArgConstraints_allow_for_multiple_calls_as_default_behavior() { // Arrange var mock = MockRepository.GenerateMock<IDemo>(); mock.Stub(x => x.StringArgString(Arg<string>.Is.Equal("input"))).Return("output"); // Act var firstCallResult = mock.StringArgString("input"); var secondCallResult = mock.StringArgString("input"); // Assert Assert.Equal("output", firstCallResult); Assert.Equal(firstCallResult, secondCallResult); } [Fact] public void ImplicitlyConverted_parameter_is_properly_compared_when_using_IsEqual() { // Arrange var stub = MockRepository.GenerateStub<ITestService>(); stub.Stub(x => x.GetUser(Arg<long>.Is.Equal(1))).Return("test"); // 1 is inferred as Int32 (not Int64) // Assert Assert.Equal(null, stub.GetUser(0)); Assert.Equal("test", stub.GetUser(1)); } [Fact] public void ImplicitlyConverted_parameter_is_properly_compared_when_using_IsNotEqual() { // Arrange var stub = MockRepository.GenerateStub<ITestService>(); stub.Stub(x => x.GetUser(Arg<long>.Is.NotEqual(1))).Return("test"); // 1 is inferred as Int32 (not Int64) var actual = stub.GetUser(0); // Assert Assert.Equal("test", actual); Assert.Equal(null, stub.GetUser(1)); } [Fact] public void ImplicitlyConverted_parameter_is_properly_compared_when_using_IsGreaterThan() { // Arrange var stub = MockRepository.GenerateStub<ITestService>(); stub.Stub(x => x.GetUser(Arg<long>.Is.GreaterThan(1))).Return("test"); // 1 is inferred as Int32 (not Int64) // Assert Assert.Equal(null, stub.GetUser(0)); Assert.Equal(null, stub.GetUser(1)); Assert.Equal("test", stub.GetUser(2)); } [Fact] public void ImplicitlyConverted_parameter_is_properly_compared_when_using_IsGreaterThanOrEqual() { // Arrange var stub = MockRepository.GenerateStub<ITestService>(); stub.Stub(x => x.GetUser(Arg<long>.Is.GreaterThanOrEqual(2))).Return("test"); // 1 is inferred as Int32 (not Int64) // Assert Assert.Equal(null, stub.GetUser(1)); Assert.Equal("test", stub.GetUser(2)); Assert.Equal("test", stub.GetUser(3)); } [Fact] public void ImplicitlyConverted_parameter_is_properly_compared_when_using_IsLessThan() { // Arrange var stub = MockRepository.GenerateStub<ITestService>(); stub.Stub(x => x.GetUser(Arg<long>.Is.LessThan(2))).Return("test"); // 1 is inferred as Int32 (not Int64) // Assert Assert.Equal("test", stub.GetUser(1)); Assert.Equal(null, stub.GetUser(2)); Assert.Equal(null, stub.GetUser(3)); } [Fact] public void ImplicitlyConverted_parameter_is_properly_compared_when_using_IsLessThanOrEqual() { // Arrange var stub = MockRepository.GenerateStub<ITestService>(); stub.Stub(x => x.GetUser(Arg<long>.Is.LessThanOrEqual(2))).Return("test"); // 1 is inferred as Int32 (not Int64) // Assert Assert.Equal("test", stub.GetUser(1)); Assert.Equal("test", stub.GetUser(2)); Assert.Equal(null, stub.GetUser(3)); } public interface ITestService { string GetUser(long id); int GetUserId(string firstName, string lastName); } } public class ArgConstraintTests2 { [Fact] public void Can_use_partial_constraints_API() { // Arrange var stub = MockRepository.GenerateStub<ITestService>(); //stub.Stub(x => x.GetUser(1)).Return("tim").Repeat.Once(); stub.Stub(x => x.GetUser(Arg<int>.Is.Anything)).Return("barcz"); Console.WriteLine(stub.GetUser(1)); Console.WriteLine(stub.GetUser(1)); // stub.Stub(x => x.GetUserId("Tim", "Barcz")).Return(12); //stub.Stub(x => // x.GetUserId( // Arg<string>.Is.Equal("Tim"), // "Barcz")) // .Return(12); // Act & Assert //Assert.Equal(12, stub.GetUserId("Tim","Barcz")); //Assert.NotNull(stub); } public interface ITestService { string GetUser(long id); int GetUserId(string firstName, string lastName); } } }
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace CmsEngine.Data.Entities { public static class ModelConfiguration { public static void ConfigureWebsite(EntityTypeBuilder<Website> b) { // Fields b.HasKey(model => model.Id); b.Property(model => model.Name) .HasMaxLength(200) .IsRequired(); b.Property(model => model.Tagline) .HasMaxLength(200); b.Property(model => model.Culture) .HasMaxLength(5) .IsRequired(); b.Property(model => model.UrlFormat) .HasMaxLength(100) .IsRequired(); b.Property(model => model.DateFormat) .HasMaxLength(10) .IsRequired(); b.Property(model => model.SiteUrl) .HasMaxLength(250) .IsRequired(); b.Property(model => model.ArticleLimit) .IsRequired(); b.Property(model => model.Address) .HasMaxLength(250); b.Property(model => model.Phone) .HasMaxLength(20); b.Property(model => model.Email) .HasMaxLength(250); b.Property(model => model.Facebook) .HasMaxLength(20); b.Property(model => model.Twitter) .HasMaxLength(20); b.Property(model => model.Instagram) .HasMaxLength(20); b.Property(model => model.LinkedIn) .HasMaxLength(20); b.Property(model => model.FacebookAppId) .HasMaxLength(30); b.Property(model => model.FacebookApiVersion) .HasMaxLength(10); b.Property(model => model.VanityId) .ValueGeneratedOnAdd() .HasDefaultValueSql("newid()"); AddPropertiesForAuditing(b); // Relationships b.HasMany(model => model.Posts); b.HasMany(model => model.Pages); b.HasMany(model => model.Tags); b.HasMany(model => model.Categories); } public static void ConfigurePage(EntityTypeBuilder<Page> b) { // Fields b.HasKey(model => model.Id); b.Property(model => model.Title) .HasMaxLength(100) .IsRequired(); b.Property(model => model.Slug) .HasMaxLength(100) .IsRequired(); b.Property(model => model.Description) .HasMaxLength(150) .IsRequired(); //b.Property(model => model.DocumentContent) // .IsRequired(); b.Property(model => model.PublishedOn) .IsRequired(); b.Property(model => model.VanityId) .ValueGeneratedOnAdd() .HasDefaultValueSql("newid()"); AddPropertiesForAuditing(b); // Relationships b.HasOne(model => model.Website) .WithMany(model => model.Pages); } public static void ConfigurePost(EntityTypeBuilder<Post> b) { // Fields b.HasKey(model => model.Id); b.Property(model => model.Title) .HasMaxLength(100) .IsRequired(); b.Property(model => model.Slug) .HasMaxLength(100) .IsRequired(); b.Property(model => model.Description) .HasMaxLength(150) .IsRequired(); //b.Property(model => model.DocumentContent) // .IsRequired(); b.Property(model => model.PublishedOn) .IsRequired(); b.Property(model => model.VanityId) .ValueGeneratedOnAdd() .HasDefaultValueSql("newid()"); AddPropertiesForAuditing(b); // Relationships b.HasOne(model => model.Website) .WithMany(model => model.Posts); } public static void ConfigureCategory(EntityTypeBuilder<Category> b) { // Fields b.HasKey(model => model.Id); b.Property(model => model.Name) .HasMaxLength(35) .IsRequired(); b.Property(model => model.Slug) .HasMaxLength(35) .IsRequired(); b.Property(model => model.Description) .HasMaxLength(200); b.Property(model => model.VanityId) .ValueGeneratedOnAdd() .HasDefaultValueSql("newid()"); AddPropertiesForAuditing(b); } public static void ConfigureTag(EntityTypeBuilder<Tag> b) { // Fields b.HasKey(model => model.Id); b.Property(model => model.Name) .HasMaxLength(25) .IsRequired(); b.Property(model => model.Slug) .HasMaxLength(25) .IsRequired(); b.Property(model => model.VanityId) .ValueGeneratedOnAdd() .HasDefaultValueSql("newid()"); AddPropertiesForAuditing(b); } public static void ConfigureEmail(EntityTypeBuilder<Email> b) { // Fields b.HasKey(model => model.Id); b.Property(model => model.Subject) .HasMaxLength(150) .IsRequired(); b.Property(model => model.Message) .HasMaxLength(500) .IsRequired(); b.Property(model => model.VanityId) .ValueGeneratedOnAdd() .HasDefaultValueSql("newid()"); AddPropertiesForAuditing(b); } // Many to many public static void ConfigurePostCategory(EntityTypeBuilder<PostCategory> b) { b.HasKey(model => new { model.PostId, model.CategoryId }); } public static void ConfigurePostTag(EntityTypeBuilder<PostTag> b) { b.HasKey(model => new { model.PostId, model.TagId }); b.HasOne(model => model.Post) .WithMany(p => p.PostTags) .HasForeignKey(model => model.PostId); b.HasOne(model => model.Tag) .WithMany(c => c.PostTags) .HasForeignKey(model => model.TagId); } public static void ConfigurePostApplicationUser(EntityTypeBuilder<PostApplicationUser> b) { b.HasKey(model => new { model.PostId, model.ApplicationUserId }); b.HasOne(model => model.Post) .WithMany(p => p.PostApplicationUsers) .HasForeignKey(model => model.PostId); b.HasOne(model => model.ApplicationUser) .WithMany(c => c.PostApplicationUsers) .HasForeignKey(model => model.ApplicationUserId); } public static void ConfigurePageApplicationUser(EntityTypeBuilder<PageApplicationUser> b) { b.HasKey(model => new { model.PageId, model.ApplicationUserId }); b.HasOne(model => model.Page) .WithMany(p => p.PageApplicationUsers) .HasForeignKey(model => model.PageId); b.HasOne(model => model.ApplicationUser) .WithMany(c => c.PageApplicationUsers) .HasForeignKey(model => model.ApplicationUserId); } private static void AddPropertiesForAuditing<T>(EntityTypeBuilder<T> b) where T : BaseEntity { b.Property<DateTime>("DateCreated"); b.Property<DateTime>("DateModified"); b.Property<string>("UserCreated").HasMaxLength(50); b.Property<string>("UserModified").HasMaxLength(50); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class DelegateKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Foo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCompilationUnit() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterExtern() { await VerifyKeywordAsync( @"extern alias Foo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing() { await VerifyKeywordAsync( @"using Foo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync( @"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeDeclaration() { await VerifyKeywordAsync( @"class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateDeclaration() { await VerifyKeywordAsync( @"delegate void Foo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Foo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ using Foo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ using Foo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAssemblyAttribute() { await VerifyKeywordAsync( @"[assembly: foo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRootAttribute() { await VerifyKeywordAsync( @"[foo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [foo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInsideInterface() { await VerifyAbsenceAsync(@"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() { await VerifyAbsenceAsync(@"partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAbstract() { await VerifyAbsenceAsync(@"abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternal() { await VerifyKeywordAsync( @"internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic() { await VerifyKeywordAsync( @"public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate() { await VerifyKeywordAsync( @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProtected() { await VerifyKeywordAsync( @"protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSealed() { await VerifyAbsenceAsync(@"sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStatic() { await VerifyAbsenceAsync(@"static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticPublic() { await VerifyAbsenceAsync(@"static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegate() { await VerifyAbsenceAsync(@"delegate $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestDelegateAsArgument() { await VerifyKeywordAsync(AddInsideMethod( @"Assert.Throws<InvalidOperationException>($$")); } [WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInConstMemberInitializer1() { await VerifyAbsenceAsync( @"class E { const int a = $$ }"); } [WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEnumMemberInitializer1() { await VerifyAbsenceAsync( @"enum E { a = $$ }"); } [WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInConstLocalInitializer1() { await VerifyAbsenceAsync( @"class E { void Foo() { const int a = $$ } }"); } [WorkItem(538264, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538264")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInMemberInitializer1() { await VerifyKeywordAsync( @"class E { int a = $$ }"); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInTypeOf() { await VerifyAbsenceAsync(AddInsideMethod( @"typeof($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInDefault() { await VerifyAbsenceAsync(AddInsideMethod( @"default($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInSizeOf() { await VerifyAbsenceAsync(AddInsideMethod( @"sizeof($$")); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInObjectInitializerMemberContext() { await VerifyAbsenceAsync(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$"); } [WorkItem(607197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/607197")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAsyncInMethodBody() { await VerifyKeywordAsync(@" using System; class C { void M() { Action a = async $$"); } [WorkItem(607197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/607197")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAsyncInMemberDeclaration() { await VerifyAbsenceAsync(@" using System; class C { async $$"); } } }
using System; using System.Collections; using AppUtil; using Vim25Api; using System.Net; namespace GetVirtualDiskFiles { class GetVirtualDiskFilesV25 { static VimService _service; static ServiceContent _sic; private static AppUtil.AppUtil ecb = null; public static OptionSpec[] constructOptions() { OptionSpec[] useroptions = new OptionSpec[1]; useroptions[0] = new OptionSpec("hostip", "String", 1 , "IP of the host" , null); return useroptions; } /// <summary> /// The main entry point for the application. /// </summary> public static void Main(String[] args) { GetVirtualDiskFilesV25 obj = new GetVirtualDiskFilesV25(); ecb = AppUtil.AppUtil.initialize("GetVirtualDiskFilesV25" , GetVirtualDiskFilesV25.constructOptions() , args); ecb.connect(); obj.GetVirtualDiskFilesForHost(); ecb.disConnect(); Console.WriteLine("Press any key to exit: "); Console.Read(); } public static Object getObjectProperty(ManagedObjectReference moRef, String propertyName) { return getProperties(moRef, new String[] { propertyName })[0]; } /* * getProperties -- * * Retrieves the specified set of properties for the given managed object * reference into an array of result objects (returned in the same oder * as the property list). */ public static Object[] getProperties(ManagedObjectReference moRef, String[] properties) { // PropertySpec specifies what properties to // retrieve and from type of Managed Object PropertySpec pSpec = new PropertySpec(); pSpec.type = moRef.type; pSpec.pathSet = properties; // ObjectSpec specifies the starting object and // any TraversalSpecs used to specify other objects // for consideration ObjectSpec oSpec = new ObjectSpec(); oSpec.obj = moRef; // PropertyFilterSpec is used to hold the ObjectSpec and // PropertySpec for the call PropertyFilterSpec pfSpec = new PropertyFilterSpec(); pfSpec.propSet = new PropertySpec[] { pSpec }; pfSpec.objectSet = new ObjectSpec[] { oSpec }; // retrieveProperties() returns the properties // selected from the PropertyFilterSpec ObjectContent[] ocs = new ObjectContent[20]; ocs = ecb._svcUtil.retrievePropertiesEx(_sic.propertyCollector, new PropertyFilterSpec[] { pfSpec }); // Return value, one object for each property specified Object[] ret = new Object[properties.Length]; if (ocs != null) { for (int i = 0; i < ocs.Length; ++i) { ObjectContent oc = ocs[i]; DynamicProperty[] dps = oc.propSet; if (dps != null) { for (int j = 0; j < dps.Length; ++j) { DynamicProperty dp = dps[j]; // find property path index for (int p = 0; p < ret.Length; ++p) { if (properties[p].Equals(dp.name)) { ret[p] = dp.val; } } } } } } return ret; } public void GetVirtualDiskFilesForHost() { try { _service = ecb.getConnection().Service; _sic = ecb.getConnection().ServiceContent; ArrayList supportedVersions = VersionUtil.getSupportedVersions(ecb.get_option("url")); ManagedObjectReference hmor = _service.FindByIp(ecb.getConnection().ServiceContent.searchIndex, null, ecb.get_option("hostip"), false); if (hmor == null) { Console.WriteLine("Unable to find host with IP : " + ecb.get_option("hostip") + " in Inventory"); } else { if (VersionUtil.isApiVersionSupported(supportedVersions, "2.5")) { Object[] datastores = getProperties(hmor, new String[] { "datastore" }); Console.WriteLine("Searching The Datastores"); ManagedObjectReference[] dstoreArr = datastores[0] as ManagedObjectReference[]; foreach (ManagedObjectReference dstore in dstoreArr) { ManagedObjectReference dsBrowser = ecb.getServiceUtil().GetMoRefProp(dstore, "browser"); ObjectContent[] objary = ecb.getServiceUtil().GetObjectProperties(_sic.propertyCollector, dstore, new String[] { "summary" }); DatastoreSummary ds = objary[0].propSet[0].val as DatastoreSummary; String dsName = ds.name; Console.WriteLine(""); Console.WriteLine("Searching The Datastore " + dsName); VmDiskFileQueryFilter vdiskFilter = new VmDiskFileQueryFilter(); String[] type = { "VirtualIDEController" }; vdiskFilter.controllerType = type; Boolean flag = VersionUtil.isApiVersionSupported(supportedVersions, "4.0"); if (flag) { vdiskFilter.thin = true; } VmDiskFileQuery fQuery = new VmDiskFileQuery(); fQuery.filter = vdiskFilter; HostDatastoreBrowserSearchSpec searchSpec = new HostDatastoreBrowserSearchSpec(); FileQuery[] arr = { fQuery }; searchSpec.query = arr; //searchSpec.setMatchPattern(matchPattern); ManagedObjectReference taskmor = _service.SearchDatastoreSubFolders_Task(dsBrowser, "[" + dsName + "]", searchSpec); object[] result = ecb.getServiceUtil().WaitForValues(taskmor, new string[] { "info.state", "info.result" }, new string[] { "state" }, // info has a property - state for state of the task new object[][] { new object[] { TaskInfoState.success, TaskInfoState.error } } ); // Wait till the task completes. if (result[0].Equals(TaskInfoState.success)) { ObjectContent[] objTaskInfo = ecb.getServiceUtil().GetObjectProperties(_sic.propertyCollector, taskmor, new String[] { "info" }); TaskInfo tInfo = (TaskInfo)objTaskInfo[0].propSet[0].val; ; HostDatastoreBrowserSearchResults[] searchResult = (HostDatastoreBrowserSearchResults[])tInfo.result; int len = searchResult.Length; for (int j = 0; j < len; j++) { HostDatastoreBrowserSearchResults sres = searchResult[j]; FileInfo[] fileArray = sres.file; if (fileArray != null) { for (int z = 0; z < fileArray.Length; z++) { Console.WriteLine("Virtual Disks Files " + fileArray[z].path); } } else { Console.WriteLine("No Thin-provisioned Virtual Disks Files found"); } } } else { Console.WriteLine("SearchDatastoreSubFolders Task couldn't be completed successfully"); } } } else { Object[] datastores = getProperties(hmor, new String[] { "datastore" }); Console.WriteLine("Searching The Datastores"); ManagedObjectReference[] dstoreArr = datastores[0] as ManagedObjectReference[]; foreach (ManagedObjectReference dstore in dstoreArr) { ManagedObjectReference dsBrowser = (ManagedObjectReference) ecb.getServiceUtil().GetMoRefProp(dstore, "browser"); ObjectContent[] objary = ecb.getServiceUtil().GetObjectProperties(_sic.propertyCollector, dstore, new String[] { "summary" }); DatastoreSummary ds = objary[0].propSet[0].val as DatastoreSummary; String dsName = ds.name; Console.WriteLine(""); Console.WriteLine("Searching The Datastore " + dsName); HostDatastoreBrowserSearchSpec searchSpec = new HostDatastoreBrowserSearchSpec(); ManagedObjectReference taskmor = _service.SearchDatastoreSubFolders_Task(dsBrowser, "[" + dsName + "]", searchSpec); object[] result = ecb.getServiceUtil().WaitForValues(taskmor, new string[] { "info.state", "info.result" }, new string[] { "state" }, // info has a property - state for state of the task new object[][] { new object[] { TaskInfoState.success, TaskInfoState.error } } ); // Wait till the task completes. if (result[0].Equals(TaskInfoState.success)) { ObjectContent[] objTaskInfo = ecb.getServiceUtil().GetObjectProperties(_sic.propertyCollector, taskmor, new String[] { "info" }); TaskInfo tInfo = (TaskInfo)objTaskInfo[0].propSet[0].val; ; HostDatastoreBrowserSearchResults[] searchResult = (HostDatastoreBrowserSearchResults[])tInfo.result; int len = searchResult.Length; for (int j = 0; j < len; j++) { HostDatastoreBrowserSearchResults sres = searchResult[j]; FileInfo[] fileArray = sres.file; for (int z = 0; z < fileArray.Length; z++) { Console.WriteLine("Virtual Disks Files " + fileArray[z].path); } } } else { Console.WriteLine("SearchDatastoreSubFolders Task couldn't be completed successfully"); } } } } } catch (Exception e) { ecb.log.LogLine("VirtualDiskFiles : Failed Connect"); throw e; } finally { ecb.log.LogLine("Ended VirtualDiskFiles"); ecb.log.Close(); } } } }
/* * 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.Data; using System.Reflection; using System.Collections.Generic; using log4net; #if CSharpSqlite using Community.CsharpSqlite.Sqlite; #else using Mono.Data.Sqlite; #endif using OpenMetaverse; using OpenSim.Framework; namespace OpenSim.Data.SQLite { /// <summary> /// An asset storage interface for the SQLite database system /// </summary> public class SQLiteAssetData : AssetDataBase { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private const string SelectAssetSQL = "select * from assets where UUID=:UUID"; private const string SelectAssetMetadataSQL = "select Name, Description, Type, Temporary, asset_flags, UUID, CreatorID from assets limit :start, :count"; private const string DeleteAssetSQL = "delete from assets where UUID=:UUID"; private const string InsertAssetSQL = "insert into assets(UUID, Name, Description, Type, Local, Temporary, asset_flags, CreatorID, Data) values(:UUID, :Name, :Description, :Type, :Local, :Temporary, :Flags, :CreatorID, :Data)"; private const string UpdateAssetSQL = "update assets set Name=:Name, Description=:Description, Type=:Type, Local=:Local, Temporary=:Temporary, asset_flags=:Flags, CreatorID=:CreatorID, Data=:Data where UUID=:UUID"; private const string assetSelect = "select * from assets"; private SqliteConnection m_conn; override public void Dispose() { if (m_conn != null) { m_conn.Close(); m_conn = null; } } /// <summary> /// <list type="bullet"> /// <item>Initialises AssetData interface</item> /// <item>Loads and initialises a new SQLite connection and maintains it.</item> /// <item>use default URI if connect string is empty.</item> /// </list> /// </summary> /// <param name="dbconnect">connect string</param> override public void Initialise(string dbconnect) { if (dbconnect == string.Empty) { dbconnect = "URI=file:Asset.db,version=3"; } m_conn = new SqliteConnection(dbconnect); m_conn.Open(); Assembly assem = GetType().Assembly; Migration m = new Migration(m_conn, assem, "AssetStore"); m.Update(); return; } /// <summary> /// Fetch Asset /// </summary> /// <param name="uuid">UUID of ... ?</param> /// <returns>Asset base</returns> override public AssetBase GetAsset(UUID uuid) { lock (this) { using (SqliteCommand cmd = new SqliteCommand(SelectAssetSQL, m_conn)) { cmd.Parameters.Add(new SqliteParameter(":UUID", uuid.ToString())); using (IDataReader reader = cmd.ExecuteReader()) { if (reader.Read()) { AssetBase asset = buildAsset(reader); reader.Close(); return asset; } else { reader.Close(); return null; } } } } } /// <summary> /// Create an asset /// </summary> /// <param name="asset">Asset Base</param> override public void StoreAsset(AssetBase asset) { //m_log.Info("[ASSET DB]: Creating Asset " + asset.FullID.ToString()); if (ExistsAsset(asset.FullID)) { //LogAssetLoad(asset); lock (this) { using (SqliteCommand cmd = new SqliteCommand(UpdateAssetSQL, m_conn)) { cmd.Parameters.Add(new SqliteParameter(":UUID", asset.FullID.ToString())); cmd.Parameters.Add(new SqliteParameter(":Name", asset.Name)); cmd.Parameters.Add(new SqliteParameter(":Description", asset.Description)); cmd.Parameters.Add(new SqliteParameter(":Type", asset.Type)); cmd.Parameters.Add(new SqliteParameter(":Local", asset.Local)); cmd.Parameters.Add(new SqliteParameter(":Temporary", asset.Temporary)); cmd.Parameters.Add(new SqliteParameter(":Flags", asset.Flags)); cmd.Parameters.Add(new SqliteParameter(":CreatorID", asset.Metadata.CreatorID)); cmd.Parameters.Add(new SqliteParameter(":Data", asset.Data)); cmd.ExecuteNonQuery(); } } } else { lock (this) { using (SqliteCommand cmd = new SqliteCommand(InsertAssetSQL, m_conn)) { cmd.Parameters.Add(new SqliteParameter(":UUID", asset.FullID.ToString())); cmd.Parameters.Add(new SqliteParameter(":Name", asset.Name)); cmd.Parameters.Add(new SqliteParameter(":Description", asset.Description)); cmd.Parameters.Add(new SqliteParameter(":Type", asset.Type)); cmd.Parameters.Add(new SqliteParameter(":Local", asset.Local)); cmd.Parameters.Add(new SqliteParameter(":Temporary", asset.Temporary)); cmd.Parameters.Add(new SqliteParameter(":Flags", asset.Flags)); cmd.Parameters.Add(new SqliteParameter(":CreatorID", asset.Metadata.CreatorID)); cmd.Parameters.Add(new SqliteParameter(":Data", asset.Data)); cmd.ExecuteNonQuery(); } } } } // /// <summary> // /// Some... logging functionnality // /// </summary> // /// <param name="asset"></param> // private static void LogAssetLoad(AssetBase asset) // { // string temporary = asset.Temporary ? "Temporary" : "Stored"; // string local = asset.Local ? "Local" : "Remote"; // // int assetLength = (asset.Data != null) ? asset.Data.Length : 0; // // m_log.Debug("[ASSET DB]: " + // string.Format("Loaded {5} {4} Asset: [{0}][{3}] \"{1}\":{2} ({6} bytes)", // asset.FullID, asset.Name, asset.Description, asset.Type, // temporary, local, assetLength)); // } /// <summary> /// Check if an asset exist in database /// </summary> /// <param name="uuid">The asset UUID</param> /// <returns>True if exist, or false.</returns> override public bool ExistsAsset(UUID uuid) { lock (this) { using (SqliteCommand cmd = new SqliteCommand(SelectAssetSQL, m_conn)) { cmd.Parameters.Add(new SqliteParameter(":UUID", uuid.ToString())); using (IDataReader reader = cmd.ExecuteReader()) { if (reader.Read()) { reader.Close(); return true; } else { reader.Close(); return false; } } } } } /// <summary> /// /// </summary> /// <param name="row"></param> /// <returns></returns> private static AssetBase buildAsset(IDataReader row) { // TODO: this doesn't work yet because something more // interesting has to be done to actually get these values // back out. Not enough time to figure it out yet. AssetBase asset = new AssetBase( new UUID((String)row["UUID"]), (String)row["Name"], Convert.ToSByte(row["Type"]), (String)row["CreatorID"] ); asset.Description = (String) row["Description"]; asset.Local = Convert.ToBoolean(row["Local"]); asset.Temporary = Convert.ToBoolean(row["Temporary"]); asset.Flags = (AssetFlags)Convert.ToInt32(row["asset_flags"]); asset.Data = (byte[])row["Data"]; return asset; } private static AssetMetadata buildAssetMetadata(IDataReader row) { AssetMetadata metadata = new AssetMetadata(); metadata.FullID = new UUID((string) row["UUID"]); metadata.Name = (string) row["Name"]; metadata.Description = (string) row["Description"]; metadata.Type = Convert.ToSByte(row["Type"]); metadata.Temporary = Convert.ToBoolean(row["Temporary"]); // Not sure if this is correct. metadata.Flags = (AssetFlags)Convert.ToInt32(row["asset_flags"]); metadata.CreatorID = row["CreatorID"].ToString(); // Current SHA1s are not stored/computed. metadata.SHA1 = new byte[] {}; return metadata; } /// <summary> /// Returns a list of AssetMetadata objects. The list is a subset of /// the entire data set offset by <paramref name="start" /> containing /// <paramref name="count" /> elements. /// </summary> /// <param name="start">The number of results to discard from the total data set.</param> /// <param name="count">The number of rows the returned list should contain.</param> /// <returns>A list of AssetMetadata objects.</returns> public override List<AssetMetadata> FetchAssetMetadataSet(int start, int count) { List<AssetMetadata> retList = new List<AssetMetadata>(count); lock (this) { using (SqliteCommand cmd = new SqliteCommand(SelectAssetMetadataSQL, m_conn)) { cmd.Parameters.Add(new SqliteParameter(":start", start)); cmd.Parameters.Add(new SqliteParameter(":count", count)); using (IDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { AssetMetadata metadata = buildAssetMetadata(reader); retList.Add(metadata); } } } } return retList; } /*********************************************************************** * * Database Binding functions * * These will be db specific due to typing, and minor differences * in databases. * **********************************************************************/ #region IPlugin interface /// <summary> /// /// </summary> override public string Version { get { Module module = GetType().Module; // string dllName = module.Assembly.ManifestModule.Name; Version dllVersion = module.Assembly.GetName().Version; return string.Format("{0}.{1}.{2}.{3}", dllVersion.Major, dllVersion.Minor, dllVersion.Build, dllVersion.Revision); } } /// <summary> /// Initialise the AssetData interface using default URI /// </summary> override public void Initialise() { Initialise("URI=file:Asset.db,version=3"); } /// <summary> /// Name of this DB provider /// </summary> override public string Name { get { return "SQLite Asset storage engine"; } } // TODO: (AlexRa): one of these is to be removed eventually (?) /// <summary> /// Delete an asset from database /// </summary> /// <param name="uuid"></param> public bool DeleteAsset(UUID uuid) { lock (this) { using (SqliteCommand cmd = new SqliteCommand(DeleteAssetSQL, m_conn)) { cmd.Parameters.Add(new SqliteParameter(":UUID", uuid.ToString())); cmd.ExecuteNonQuery(); } } return true; } public override bool Delete(string id) { UUID assetID; if (!UUID.TryParse(id, out assetID)) return false; return DeleteAsset(assetID); } #endregion } }
// // Created by Ian Copland on 2015-11-10 // // The MIT License (MIT) // // Copyright (c) 2015 Tag Games Limited // // 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; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Text.RegularExpressions; using SdkCore.MiniJSON; using UnityEngine; using UnityEngine.Networking; namespace SdkCore { /// <summary> /// <para>Provides a means to make both GET and POST requests to the given /// web-server. Requests can be both HTTP and HTTPS.</para> /// /// <para>This is thread-safe.</para> /// </summary> public sealed class HttpSystem { private TaskScheduler m_taskScheduler; /// <summary> /// Initializes a new instance of the HTTP system with the given task /// scheduler. /// </summary> /// /// <param name="taskScheduler">The task scheduler.</param> public HttpSystem(TaskScheduler taskScheduler) { ReleaseAssert.IsTrue(taskScheduler != null, "The task scheduler in a HTTP request system must not be null."); m_taskScheduler = taskScheduler; } /// <summary> /// Makes a HTTP GET request with the given request object. This is /// performed asynchronously, with the callback block run on a background /// thread. /// </summary> /// /// <param name="request">The GET HTTP request.</param> /// <param name="callback">The callback which will provide the response from the server. /// The callback will be made on a background thread.</param> public void SendRequest(HttpGetRequest request, Action<HttpGetRequest, HttpResponse> callback) { ReleaseAssert.IsTrue(request != null, "The HTTP GET request must not be null when sending a request."); ReleaseAssert.IsTrue(callback != null, "The callback must not be null when sending a request."); SendRequest(request.Url, request.Headers, null, (HttpResponse response) => { callback(request, response); }); } /// <summary> /// Makes a HTTP POST request with the given request object. This is /// performed asynchronously, with the callback block run on a background /// thread. /// </summary> /// /// <param name="request">The POST HTTP request.</param> /// <param name="callback">The callback which will provide the response from the server. /// The callback will be made on a background thread.</param> public void SendRequest(HttpPostRequest request, Action<HttpPostRequest, HttpResponse> callback) { ReleaseAssert.IsTrue(request != null, "The HTTP POST request must not be null when sending a request."); ReleaseAssert.IsTrue(callback != null, "The callback must not be null when sending a request."); var headers = new Dictionary<string, string>(request.Headers); if (request.ContentType != null) { headers.Add("Content-Type", request.ContentType); } SendRequest(request.Url, headers, request.Body, (HttpResponse response) => { callback(request, response); }); } /// <summary> /// Provides the means to send both GET and POST requests depending on the /// input data. /// </summary> /// /// <param name="url">The URL that the request is targetting.</param> /// <param name="headers">The headers for the HTTP request.</param> /// <param name="body">The body of the request. If null, a GET request will be sent.</param> /// <param name="callback">The callback providing the response from the server.</param> private void SendRequest(String url, IDictionary<string, string> headers, byte[] body, Action<HttpResponse> callback) { ReleaseAssert.IsTrue(url != null, "The URL must not be null when sending a request."); ReleaseAssert.IsTrue(headers != null, "The headers must not be null when sending a request."); ReleaseAssert.IsTrue(callback != null, "The callback must not be null when sending a request."); m_taskScheduler.ScheduleMainThreadTask(() => { // Create the web request var webRequest = new UnityWebRequest(url); webRequest.method = UnityWebRequest.kHttpVerbPOST; // Set the headers foreach(var pair in headers) { webRequest.SetRequestHeader(pair.Key, pair.Value); } // Handlers webRequest.uploadHandler = new UploadHandlerRaw(body); webRequest.downloadHandler = new DownloadHandlerBuffer(); m_taskScheduler.StartCoroutine(ProcessRequest(webRequest, callback)); }); } /// <summary> /// <para>The coroutine for processing the HTTP request. This will yield until the /// request has completed then get the data from the Web Request object.</para> /// </summary> /// /// <returns>The coroutine enumerator.</returns> /// /// <param name="webRequest">The Web Request object.</param> /// <param name="callback">The callback providing the response from the server.</param> private IEnumerator ProcessRequest(UnityWebRequest webRequest, Action<HttpResponse> callback) { ReleaseAssert.IsTrue(webRequest != null, "The webRequest must not be null when sending a request."); ReleaseAssert.IsTrue(callback != null, "The callback must not be null when sending a request."); yield return webRequest.Send(); HttpResponseDesc desc = null; int responseCode = (int)webRequest.responseCode; if(webRequest.isError) { // Print error UnityEngine.Debug.LogErrorFormat("error = {0}", webRequest.error); } if(responseCode == 0) { desc = new HttpResponseDesc(HttpResult.CouldNotConnect); } else { desc = new HttpResponseDesc(HttpResult.Success); } // Populate the request response if(webRequest.GetResponseHeaders() == null) { desc.Headers = new Dictionary<string, string>(); } else { desc.Headers = new Dictionary<string, string>(webRequest.GetResponseHeaders()); } desc.HttpResponseCode = responseCode; // Fill the response data if (webRequest.downloadedBytes > 0) { desc.Body = webRequest.downloadHandler.data; } HttpResponse response = new HttpResponse(desc); m_taskScheduler.ScheduleBackgroundTask(() => { callback(response); }); } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using NSubstitute; using NSubstitute.ExceptionExtensions; using NUnit.Framework; using System; using System.Collections.Generic; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Rest.Trusthub.V1; namespace Twilio.Tests.Rest.Trusthub.V1 { [TestFixture] public class SupportingDocumentTest : TwilioTest { [Test] public void TestCreateRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Post, Twilio.Rest.Domain.Trusthub, "/v1/SupportingDocuments", "" ); request.AddPostParam("FriendlyName", Serialize("friendly_name")); request.AddPostParam("Type", Serialize("type")); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { SupportingDocumentResource.Create("friendly_name", "type", client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestCreateResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.Created, "{\"status\": \"draft\",\"date_updated\": \"2021-02-11T17:23:00Z\",\"friendly_name\": \"Business-profile-physical-address\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"url\": \"https://trusthub.twilio.com/v1/SupportingDocuments/RDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"date_created\": \"2021-02-11T17:23:00Z\",\"sid\": \"RDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"attributes\": {\"address_sids\": \"ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"type\": \"customer_profile_address\",\"mime_type\": null}" )); var response = SupportingDocumentResource.Create("friendly_name", "type", client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestReadRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Get, Twilio.Rest.Domain.Trusthub, "/v1/SupportingDocuments", "" ); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { SupportingDocumentResource.Read(client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestReadEmptyResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"results\": [],\"meta\": {\"page\": 0,\"page_size\": 50,\"first_page_url\": \"https://trusthub.twilio.com/v1/SupportingDocuments?PageSize=50&Page=0\",\"previous_page_url\": null,\"url\": \"https://trusthub.twilio.com/v1/SupportingDocuments?PageSize=50&Page=0\",\"next_page_url\": null,\"key\": \"results\"}}" )); var response = SupportingDocumentResource.Read(client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestReadFullResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"results\": [{\"status\": \"draft\",\"date_updated\": \"2021-02-11T17:23:00Z\",\"friendly_name\": \"Business-profile-physical-address\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"url\": \"https://trusthub.twilio.com/v1/SupportingDocuments/RDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"date_created\": \"2021-02-11T17:23:00Z\",\"sid\": \"RDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"attributes\": {\"address_sids\": \"ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"type\": \"customer_profile_address\",\"mime_type\": null}],\"meta\": {\"page\": 0,\"page_size\": 50,\"first_page_url\": \"https://trusthub.twilio.com/v1/SupportingDocuments?PageSize=50&Page=0\",\"previous_page_url\": null,\"url\": \"https://trusthub.twilio.com/v1/SupportingDocuments?PageSize=50&Page=0\",\"next_page_url\": null,\"key\": \"results\"}}" )); var response = SupportingDocumentResource.Read(client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestFetchRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Get, Twilio.Rest.Domain.Trusthub, "/v1/SupportingDocuments/RDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "" ); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { SupportingDocumentResource.Fetch("RDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestFetchResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"status\": \"draft\",\"date_updated\": \"2021-02-11T17:23:00Z\",\"friendly_name\": \"Business-profile-physical-address\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"url\": \"https://trusthub.twilio.com/v1/SupportingDocuments/RDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"date_created\": \"2021-02-11T17:23:00Z\",\"sid\": \"RDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"attributes\": {\"address_sids\": \"ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"type\": \"customer_profile_address\",\"mime_type\": null}" )); var response = SupportingDocumentResource.Fetch("RDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestUpdateRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Post, Twilio.Rest.Domain.Trusthub, "/v1/SupportingDocuments/RDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "" ); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { SupportingDocumentResource.Update("RDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestUpdateResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"status\": \"draft\",\"date_updated\": \"2021-02-11T17:23:00Z\",\"friendly_name\": \"friendly_name\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"url\": \"https://trusthub.twilio.com/v1/SupportingDocuments/RDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"date_created\": \"2021-02-11T17:23:00Z\",\"sid\": \"RDaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"attributes\": {\"address_sids\": \"ADaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"},\"type\": \"customer_profile_address\",\"mime_type\": null}" )); var response = SupportingDocumentResource.Update("RDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestDeleteRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Delete, Twilio.Rest.Domain.Trusthub, "/v1/SupportingDocuments/RDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "" ); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { SupportingDocumentResource.Delete("RDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestDeleteResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.NoContent, "null" )); var response = SupportingDocumentResource.Delete("RDXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.NotNull(response); } } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Xaml.Xaml File: OptionDesk.xaml.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Xaml { using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Windows.Data; using System.Windows.Media; using Ecng.Common; using Ecng.ComponentModel; using Ecng.Serialization; using Ecng.Xaml.Grids; using MoreLinq; using StockSharp.Algo; using StockSharp.Algo.Derivatives; using StockSharp.BusinessEntities; using StockSharp.Messages; using StockSharp.Localization; /// <summary> /// Options board. /// </summary> public partial class OptionDesk { private bool _updateSource = true; /// <summary> /// Initializes a new instance of the <see cref="OptionDesk"/>. /// </summary> public OptionDesk() { InitializeComponent(); #region Format rules var callColor = Color.FromArgb(255, 190, 224, 189); var putColor = Color.FromArgb(255, 255, 190, 189); FormatRules.Add(CallRho, new FormatRule { Condition = ComparisonOperator.Any, Background = new SolidColorBrush(callColor), }); FormatRules.Add(CallTheta, new FormatRule { Condition = ComparisonOperator.Any, Background = new SolidColorBrush(callColor), }); FormatRules.Add(CallVega, new FormatRule { Condition = ComparisonOperator.Any, Background = new SolidColorBrush(callColor), }); FormatRules.Add(CallGamma, new FormatRule { Condition = ComparisonOperator.Any, Background = new SolidColorBrush(callColor), }); FormatRules.Add(CallDelta, new FormatRule { Condition = ComparisonOperator.Any, Background = new SolidColorBrush(callColor), }); FormatRules.Add(CallBid, new FormatRule { Condition = ComparisonOperator.Any, Background = new SolidColorBrush(callColor), }); FormatRules.Add(CallAsk, new FormatRule { Condition = ComparisonOperator.Any, Background = new SolidColorBrush(callColor), }); FormatRules.Add(CallTheorPrice, new FormatRule { Condition = ComparisonOperator.Any, Background = new SolidColorBrush(callColor), }); FormatRules.Add(CallVolume, new FormatRule { Condition = ComparisonOperator.Any, Background = new SolidColorBrush(callColor), }); FormatRules.Add(CallOpenInterest, new FormatRule { Condition = ComparisonOperator.Any, Background = new SolidColorBrush(callColor), }); FormatRules.Add(CallSecCode, new FormatRule { Condition = ComparisonOperator.Any, Background = new SolidColorBrush(callColor), }); FormatRules.Add(Strike, new FormatRule { Condition = ComparisonOperator.Any, Background = Brushes.LightGray, Font = { Weight = System.Windows.FontWeights.Bold } }); FormatRules.Add(ImpliedVolatility, new FormatRule { Condition = ComparisonOperator.Any, Background = Brushes.LightGray, }); FormatRules.Add(HistoricalVolatility, new FormatRule { Condition = ComparisonOperator.Any, Background = Brushes.LightGray, }); FormatRules.Add(PnL, new FormatRule { Condition = ComparisonOperator.Any, Background = Brushes.LightGray, }); FormatRules.Add(PutSecCode, new FormatRule { Condition = ComparisonOperator.Any, Background = new SolidColorBrush(putColor), }); FormatRules.Add(PutOpenInterest, new FormatRule { Condition = ComparisonOperator.Any, Background = new SolidColorBrush(putColor), }); FormatRules.Add(PutVolume, new FormatRule { Condition = ComparisonOperator.Any, Background = new SolidColorBrush(putColor), }); FormatRules.Add(PutTheorPrice, new FormatRule { Condition = ComparisonOperator.Any, Background = new SolidColorBrush(putColor), }); FormatRules.Add(PutBid, new FormatRule { Condition = ComparisonOperator.Any, Background = new SolidColorBrush(putColor), }); FormatRules.Add(PutAsk, new FormatRule { Condition = ComparisonOperator.Any, Background = new SolidColorBrush(putColor), }); FormatRules.Add(PutDelta, new FormatRule { Condition = ComparisonOperator.Any, Background = new SolidColorBrush(putColor), }); FormatRules.Add(PutGamma, new FormatRule { Condition = ComparisonOperator.Any, Background = new SolidColorBrush(putColor), }); FormatRules.Add(PutVega, new FormatRule { Condition = ComparisonOperator.Any, Background = new SolidColorBrush(putColor), }); FormatRules.Add(PutTheta, new FormatRule { Condition = ComparisonOperator.Any, Background = new SolidColorBrush(putColor), }); FormatRules.Add(PutRho, new FormatRule { Condition = ComparisonOperator.Any, Background = new SolidColorBrush(putColor), }); #endregion Options = Enumerable.Empty<Security>(); } /// <summary> /// The provider of information about instruments. /// </summary> public ISecurityProvider SecurityProvider { get; set; } /// <summary> /// The market data provider. /// </summary> public IMarketDataProvider MarketDataProvider { get; set; } /// <summary> /// Current time. If it is set, then <see cref="IBlackScholes"/> uses this time. /// </summary> public DateTimeOffset? CurrentTime { get; set; } /// <summary> /// The current price of the underlying asset. If it is set, then <see cref="IBlackScholes"/> uses this price. /// </summary> public decimal? AssetPrice { get; set; } private bool _useBlackModel; /// <summary> /// To use the model <see cref="Black"/> instead of <see cref="IBlackScholes"/> model. The default is off. /// </summary> public bool UseBlackModel { get { return _useBlackModel; } set { if (_useBlackModel == value) return; _useBlackModel = value; ((OptionDeskRow[])ItemsSource).ForEach(r => { r.Call?.ApplyModel(); r.Put?.ApplyModel(); }); } } private IEnumerable<Security> _options; /// <summary> /// Strike options. /// </summary> public IEnumerable<Security> Options { get { return _options; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var group = value.GroupBy(o => o.GetUnderlyingAsset(SecurityProvider)); if (group.Count() > 1) throw new ArgumentException(LocalizedStrings.Str1524); _options = value; _updateSource = true; } } /// <summary> /// To update the board values. /// </summary> public void RefreshOptions() { if (_updateSource) { ItemsSource = _options.GroupBy(o => o.Strike).Select(g => new OptionDeskRow(this, g.FirstOrDefault(o => o.OptionType == OptionTypes.Call), g.FirstOrDefault(o => o.OptionType == OptionTypes.Put))) .ToArray(); _updateSource = false; } var rows = (OptionDeskRow[])ItemsSource; if (MarketDataProvider == null || SecurityProvider == null) return; decimal maxIV = 0; decimal maxHV = 0; decimal maxPnL = 0; decimal maxCallVolume = 0; decimal maxPutVolume = 0; decimal maxCallOI = 0; decimal maxPutOI = 0; var now = CurrentTime ?? TimeHelper.NowWithOffset; foreach (var row in rows) { var call = row.Call; if (call != null) { decimal? iv, hv, oi, volume; Update(call, now, out iv, out hv, out oi, out volume); maxIV = maxIV.Max(iv ?? 0m); maxHV = maxHV.Max(hv ?? 0m); maxCallVolume = maxCallVolume.Max(volume ?? 0m); maxCallOI = maxCallOI.Max(oi ?? 0m); } var put = row.Put; if (put != null) { decimal? iv, hv, oi, volume; Update(put, now, out iv, out hv, out oi, out volume); maxIV = maxIV.Max(iv ?? 0m); maxHV = maxHV.Max(hv ?? 0m); maxPutVolume = maxPutVolume.Max(volume ?? 0m); maxPutOI = maxPutOI.Max(oi ?? 0m); } maxPnL = maxPnL.Max(row.PnL ?? 0); } rows.ForEach(row => { row.MaxImpliedVolatility = maxIV; row.MaxHistoricalVolatility = maxHV; row.MaxPnL = maxPnL; if (row.Call != null) { row.Call.MaxOpenInterest = maxCallOI; row.Call.MaxVolume = maxCallVolume; } if (row.Put != null) { row.Put.MaxOpenInterest = maxPutOI; row.Put.MaxVolume = maxPutVolume; } row.Notify("ImpliedVolatility"); row.Notify("MaxHistoricalVolatility"); row.Notify("HistoricalVolatility"); row.Notify("MaxHistoricalVolatility"); row.Notify("MaxPnL"); row.Notify("Call"); row.Notify("Put"); }); } //private void MarketDataProviderOnValuesChanged(Security security, IEnumerable<KeyValuePair<Level1Fields, object>> changes, DateTime serverTime, DateTime localTime) //{ // var item = _optionDeskRowSides.TryGetValue(security); // if (item == null) // return; // Update(item, changes); //} private void Update(OptionDeskRow.OptionDeskRowSide side, DateTimeOffset now, out decimal? iv, out decimal? hv, out decimal? oi, out decimal? volume) { iv = hv = oi = volume = null; var option = side.Option; var changes = MarketDataProvider.GetSecurityValues(option); if (changes == null) return; foreach (var change in changes) { switch (change.Key) { case Level1Fields.BestAskPrice: side.BestAskPrice = (decimal)change.Value; break; case Level1Fields.BestBidPrice: side.BestBidPrice = (decimal)change.Value; break; case Level1Fields.Volume: volume = side.Volume = (decimal)change.Value; break; case Level1Fields.OpenInterest: oi = side.OpenInterest = (decimal)change.Value; break; case Level1Fields.ImpliedVolatility: iv = (decimal)change.Value; break; case Level1Fields.HistoricalVolatility: hv = (decimal)change.Value; break; } } var bs = side.Model; side.TheorPrice = Round(now, bs.Premium); side.Delta = Round(now, bs.Delta); side.Gamma = Round(now, bs.Gamma); side.Theta = Round(now, bs.Theta); side.Vega = Round(now, bs.Vega); side.Rho = Round(now, bs.Rho); var assetPrice = bs.GetAssetPrice(AssetPrice); if (assetPrice == 0) side.PnL = 0; else { side.PnL = (option.OptionType == OptionTypes.Call ? 1 : -1) * (assetPrice - option.Strike); if (side.PnL < 0) side.PnL = 0; } } private decimal? Round(DateTimeOffset now, Func<DateTimeOffset, decimal?, decimal?, decimal?> func) { const int round = 2; var value = func(now, null, AssetPrice); return value == null ? (decimal?)null : decimal.Round(value.Value, round); } /// <summary> /// Save settings. /// </summary> /// <param name="storage">Settings storage.</param> public override void Save(SettingsStorage storage) { base.Save(storage); storage.SetValue(nameof(UseBlackModel), UseBlackModel); } /// <summary> /// Load settings. /// </summary> /// <param name="storage">Settings storage.</param> public override void Load(SettingsStorage storage) { base.Load(storage); UseBlackModel = storage.GetValue<bool>(nameof(UseBlackModel)); } } sealed class NullableDecimalValueConverter : IValueConverter { object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture) { return value ?? 0m; } object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException(); } } }
namespace Cvdm.Scheduler.Tests { using System; using System.Threading; using Cvdm.Scheduler.Helpers; using Moq; using NUnit.Framework; [TestFixture] public sealed class SchedulerTests { private Mock<ITimerFactory> timerFactory; private Mock<ITimeProvider> timeProvider; private Scheduler scheduler; [SetUp] public void SetUp() { this.timerFactory = new Mock<ITimerFactory>(); this.timeProvider = new Mock<ITimeProvider>(); this.scheduler = new Scheduler( this.timerFactory.Object, this.timeProvider.Object); } [Test] public void ScheduleRecurringWithStateAndStartTime_Should_CreateCorrectTimer() { // Arrange var currentTime = new DateTimeOffset(2000, 1, 1, 0, 0, 0, TimeSpan.Zero); this.timeProvider.Setup(_ => _.Now).Returns(currentTime); var callback = new TimerCallback(_ => { }); var state = new object(); var startTime = new DateTimeOffset(2001, 2, 3, 4, 5, 6, TimeSpan.Zero); var interval = new TimeSpan(1, 2, 3); // Act this.scheduler.ScheduleRecurring(callback, state, startTime, interval); // Assert this.timerFactory.Verify(_ => _.Create(callback, state, startTime - currentTime, interval)); } [Test] public void ScheduleRecurringWithStateAndDelay_Should_CreateCorrectTimer() { // Arrange var callback = new TimerCallback(_ => { }); var state = new object(); var startAfter = new TimeSpan(2, 3, 4); var interval = new TimeSpan(1, 2, 3); // Act this.scheduler.ScheduleRecurring(callback, state, startAfter, interval); // Assert this.timerFactory.Verify(_ => _.Create(callback, state, startAfter, interval)); } [Test] public void ScheduleRecurringWithStateAndStartTime_When_CallbackIsNull_Should_Throw() { // Act/Assert Assert.That( () => this.scheduler.ScheduleRecurring(null, new object(), DateTimeOffset.Now.AddDays(1), TimeSpan.FromDays(1)), Throws.ArgumentNullException); } [Test] public void ScheduleRecurringWithStateAndDelay_When_CallbackIsNull_Should_Throw() { // Act/Assert Assert.That( () => this.scheduler.ScheduleRecurring(null, new object(), TimeSpan.Zero, TimeSpan.FromDays(1)), Throws.ArgumentNullException); } [Test] public void ScheduleRecurringWithStateAndStartTime_When_StateIsNull_Should_Throw() { // Act/Assert Assert.That( () => this.scheduler.ScheduleRecurring(_ => { }, null, DateTimeOffset.Now.AddDays(1), TimeSpan.FromDays(1)), Throws.ArgumentNullException); } [Test] public void ScheduleRecurringWithStateAndDelay_When_StateIsNull_Should_Throw() { // Act/Assert Assert.That( () => this.scheduler.ScheduleRecurring(_ => { }, null, TimeSpan.Zero, TimeSpan.FromDays(1)), Throws.ArgumentNullException); } [Test] public void ScheduleRecurringWithStateAndStartTime_When_StartTimeIsPast_Should_Throw() { // Arrange var currentTime = new DateTimeOffset(2000, 1, 1, 0, 0, 0, TimeSpan.Zero); this.timeProvider.Setup(_ => _.Now).Returns(currentTime); DateTimeOffset startTime = currentTime.AddSeconds(-1); // Act/Assert Assert.That( () => this.scheduler.ScheduleRecurring(_ => { }, new object(), startTime, TimeSpan.FromDays(1)), Throws.TypeOf<ArgumentOutOfRangeException>()); } [Test] public void ScheduleRecurringWithStateAndDelay_When_DelayIsNegative_Should_Throw() { // Act/Assert Assert.That( () => this.scheduler.ScheduleRecurring( _ => { }, new object(), TimeSpan.FromMilliseconds(-1), TimeSpan.FromDays(1)), Throws.TypeOf<ArgumentOutOfRangeException>()); } [Test] public void ScheduleRecurringWithStateAndStartTime_When_IntervalIsNotPositive_Should_Throw() { // Act/Assert Assert.That( () => this.scheduler.ScheduleRecurring( _ => { }, new object(), DateTimeOffset.Now.AddDays(1), TimeSpan.Zero), Throws.TypeOf<ArgumentOutOfRangeException>()); } [Test] public void ScheduleRecurringWithStateAndDelay_When_IntervalIsNotPositive_Should_Throw() { // Act/Assert Assert.That( () => this.scheduler.ScheduleRecurring(_ => { }, new object(), TimeSpan.Zero, TimeSpan.Zero), Throws.TypeOf<ArgumentOutOfRangeException>()); } [Test] public void ScheduleRecurringWithoutStateAndStartTime_Should_CreateCorrectTimer() { // Arrange var currentTime = new DateTimeOffset(2000, 1, 1, 0, 0, 0, TimeSpan.Zero); this.timeProvider.Setup(_ => _.Now).Returns(currentTime); var actionWasCalled = false; var callback = new Action(() => actionWasCalled = true); var startTime = new DateTimeOffset(2001, 2, 3, 4, 5, 6, TimeSpan.Zero); var interval = new TimeSpan(1, 2, 3); this.timerFactory.Setup(_ => _.Create(It.IsAny<TimerCallback>(), null, startTime - currentTime, interval)) .Callback((TimerCallback cb, object _, TimeSpan __, TimeSpan ___) => cb(null)); // Act this.scheduler.ScheduleRecurring(callback, startTime, interval); // Assert this.timerFactory.Verify(_ => _.Create(It.IsAny<TimerCallback>(), null, startTime - currentTime, interval)); Assert.That(actionWasCalled); } [Test] public void ScheduleRecurringWithoutStateAndWithDelay_Should_CreateCorrectTimer() { // Arrange var actionWasCalled = false; var callback = new Action(() => actionWasCalled = true); var startAfter = new TimeSpan(2, 3, 4); var interval = new TimeSpan(1, 2, 3); this.timerFactory.Setup(_ => _.Create(It.IsAny<TimerCallback>(), null, startAfter, interval)) .Callback((TimerCallback cb, object _, TimeSpan __, TimeSpan ___) => cb(null)); // Act this.scheduler.ScheduleRecurring(callback, startAfter, interval); // Assert this.timerFactory.Verify(_ => _.Create(It.IsAny<TimerCallback>(), null, startAfter, interval)); Assert.That(actionWasCalled); } [Test] public void ScheduleRecurringWithoutStateAndWithStartTime_When_CallbackIsNull_Should_Throw() { // Act/Assert Assert.That( () => this.scheduler.ScheduleRecurring(null, DateTimeOffset.Now.AddDays(1), TimeSpan.FromDays(1)), Throws.ArgumentNullException); } [Test] public void ScheduleRecurringWithoutStateAndWithDelay_When_CallbackIsNull_Should_Throw() { // Act/Assert Assert.That( () => this.scheduler.ScheduleRecurring(null, TimeSpan.Zero, TimeSpan.FromDays(1)), Throws.ArgumentNullException); } [Test] public void ScheduleRecurringWithoutStateAndWithStartTime_When_StartTimeIsPast_Should_Throw() { // Arrange var currentTime = new DateTimeOffset(2000, 1, 1, 0, 0, 0, TimeSpan.Zero); this.timeProvider.Setup(_ => _.Now).Returns(currentTime); DateTimeOffset startTime = currentTime.AddSeconds(-1); // Act/Assert Assert.That( () => this.scheduler.ScheduleRecurring(() => { }, startTime, TimeSpan.FromDays(1)), Throws.TypeOf<ArgumentOutOfRangeException>()); } [Test] public void ScheduleRecurringWithoutStateAndWithStartTime_When_DelayIsNegative_Should_Throw() { // Act/Assert Assert.That( () => this.scheduler.ScheduleRecurring( () => { }, TimeSpan.FromMilliseconds(-1), TimeSpan.FromDays(1)), Throws.TypeOf<ArgumentOutOfRangeException>()); } [Test] public void ScheduleRecurringWithoutStateAndWithStartTime_When_IntervalIsNotPositive_Should_Throw() { // Act/Assert Assert.That( () => this.scheduler.ScheduleRecurring( () => { }, DateTimeOffset.Now.AddDays(1), TimeSpan.Zero), Throws.TypeOf<ArgumentOutOfRangeException>()); } [Test] public void ScheduleRecurringWithoutStateAndWithDelay_When_IntervalIsNotPositive_Should_Throw() { // Act/Assert Assert.That( () => this.scheduler.ScheduleRecurring( () => { }, TimeSpan.Zero, TimeSpan.Zero), Throws.TypeOf<ArgumentOutOfRangeException>()); } [Test] public void ScheduleOneTimeWithStateAndStartTime_Should_CreateCorrectTimer() { // Arrange var currentTime = new DateTimeOffset(2000, 1, 1, 0, 0, 0, TimeSpan.Zero); this.timeProvider.Setup(_ => _.Now).Returns(currentTime); var callback = new TimerCallback(_ => { }); var state = new object(); var startTime = new DateTimeOffset(2001, 2, 3, 4, 5, 6, TimeSpan.Zero); // Act this.scheduler.ScheduleOneTime(callback, state, startTime); // Assert this.timerFactory.Verify(_ => _.Create(callback, state, startTime - currentTime, TimeSpan.FromMilliseconds(-1))); } [Test] public void ScheduleOneTimeWithStateAndDelay_Should_CreateCorrectTimer() { // Arrange var callback = new TimerCallback(_ => { }); var state = new object(); var startAfter = new TimeSpan(1, 2, 3); // Act this.scheduler.ScheduleOneTime(callback, state, startAfter); // Assert this.timerFactory.Verify(_ => _.Create(callback, state, startAfter, TimeSpan.FromMilliseconds(-1))); } [Test] public void ScheduleOneTimeWithStateAndStartTime_When_CallbackIsNull_Should_Throw() { // Act/Assert Assert.That( () => this.scheduler.ScheduleOneTime(null, new object(), DateTimeOffset.Now.AddDays(1)), Throws.ArgumentNullException); } [Test] public void ScheduleOneTimeWithStateAndDelay_When_CallbackIsNull_Should_Throw() { // Act/Assert Assert.That( () => this.scheduler.ScheduleOneTime(null, new object(), TimeSpan.Zero), Throws.ArgumentNullException); } [Test] public void ScheduleOneTimeWithStateAndStartTime_When_StateIsNull_Should_Throw() { // Act/Assert Assert.That( () => this.scheduler.ScheduleOneTime(_ => { }, null, DateTimeOffset.Now.AddDays(1)), Throws.ArgumentNullException); } [Test] public void ScheduleOneTimeWithStateAndDelay_When_StateIsNull_Should_Throw() { // Act/Assert Assert.That( () => this.scheduler.ScheduleOneTime(_ => { }, null, TimeSpan.Zero), Throws.ArgumentNullException); } [Test] public void ScheduleOneTimeWithStateAndStartTime_When_StartTimeIsPast_Should_Throw() { // Arrange var currentTime = new DateTimeOffset(2000, 1, 1, 0, 0, 0, TimeSpan.Zero); this.timeProvider.Setup(_ => _.Now).Returns(currentTime); DateTimeOffset startTime = currentTime.AddSeconds(-1); // Act/Assert Assert.That( () => this.scheduler.ScheduleOneTime(_ => { }, new object(), startTime), Throws.TypeOf<ArgumentOutOfRangeException>()); } [Test] public void ScheduleOneTimeWithStateAndDelay_When_DelayIsNegative_Should_Throw() { // Act/Assert Assert.That( () => this.scheduler.ScheduleOneTime( _ => { }, new object(), TimeSpan.FromMilliseconds(-1)), Throws.TypeOf<ArgumentOutOfRangeException>()); } [Test] public void ScheduleOneTimeWithoutStateAndWithStartTime_Should_CreateCorrectTimer() { // Arrange var currentTime = new DateTimeOffset(2000, 1, 1, 0, 0, 0, TimeSpan.Zero); this.timeProvider.Setup(_ => _.Now).Returns(currentTime); var actionWasCalled = false; var callback = new Action(() => actionWasCalled = true); var startTime = new DateTimeOffset(2001, 2, 3, 4, 5, 6, TimeSpan.Zero); this.timerFactory.Setup( _ => _.Create(It.IsAny<TimerCallback>(), null, startTime - currentTime, TimeSpan.FromMilliseconds(-1))) .Callback((TimerCallback cb, object _, TimeSpan __, TimeSpan ___) => cb(null)); // Act this.scheduler.ScheduleOneTime(callback, startTime); // Assert this.timerFactory.Verify( _ => _.Create(It.IsAny<TimerCallback>(), null, startTime - currentTime, TimeSpan.FromMilliseconds(-1))); Assert.That(actionWasCalled); } [Test] public void ScheduleOneTimeWithoutStateAndWithDelay_Should_CreateCorrectTimer() { // Arrange var actionWasCalled = false; var callback = new Action(() => actionWasCalled = true); var startAfter = new TimeSpan(1, 2, 3); this.timerFactory.Setup(_ => _.Create(It.IsAny<TimerCallback>(), null, startAfter, TimeSpan.FromMilliseconds(-1))) .Callback((TimerCallback cb, object _, TimeSpan __, TimeSpan ___) => cb(null)); // Act this.scheduler.ScheduleOneTime(callback, startAfter); // Assert this.timerFactory.Verify(_ => _.Create(It.IsAny<TimerCallback>(), null, startAfter, TimeSpan.FromMilliseconds(-1))); Assert.That(actionWasCalled); } [Test] public void ScheduleOneTimeWithoutStateAndWithStartTime_When_CallbackIsNull_Should_Throw() { // Act/Assert Assert.That( () => this.scheduler.ScheduleOneTime(null, DateTimeOffset.Now.AddDays(1)), Throws.ArgumentNullException); } [Test] public void ScheduleOneTimeWithoutStateAndWithDelay_When_CallbackIsNull_Should_Throw() { // Act/Assert Assert.That( () => this.scheduler.ScheduleOneTime(null, TimeSpan.Zero), Throws.ArgumentNullException); } [Test] public void ScheduleOneTimeWithoutStateAndWithStartTime_When_StartTimeIsPast_Should_Throw() { // Arrange var currentTime = new DateTimeOffset(2000, 1, 1, 0, 0, 0, TimeSpan.Zero); this.timeProvider.Setup(_ => _.Now).Returns(currentTime); DateTimeOffset startTime = currentTime.AddSeconds(-1); // Act/Assert Assert.That( () => this.scheduler.ScheduleOneTime(() => { }, startTime), Throws.TypeOf<ArgumentOutOfRangeException>()); } [Test] public void ScheduleOneTimeWithoutStateAndWithDelay_When_DelayIsNegative_Should_Throw() { // Act/Assert Assert.That( () => this.scheduler.ScheduleOneTime( () => { }, TimeSpan.FromMilliseconds(-1)), Throws.TypeOf<ArgumentOutOfRangeException>()); } [Test] public void Test_Default_Constructor() { // Arrange var actionWasRaised = true; // Act var realScheduler = new Scheduler(); realScheduler.ScheduleOneTime(() => actionWasRaised = true, TimeSpan.Zero); // Assert Assert.That(actionWasRaised, Is.True.After(1000, 10)); } } }
/* Project Orleans Cloud Service SDK ver. 1.0 Copyright (c) Microsoft Corporation All rights reserved. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Linq; using System.Collections.Generic; namespace Orleans.Runtime.ConsistentRing { /// <summary> /// We use the 'backward/clockwise' definition to assign responsibilities on the ring. /// E.g. in a ring of nodes {5, 10, 15} the responsible for key 7 is 10 (the node is responsible for its predecessing range). /// The backwards/clockwise approach is consistent with many overlays, e.g., Chord, Cassandra, etc. /// Note: MembershipOracle uses 'forward/counter-clockwise' definition to assign responsibilities. /// E.g. in a ring of nodes {5, 10, 15}, the responsible of key 7 is node 5 (the node is responsible for its sucessing range).. /// </summary> internal class VirtualBucketsRingProvider : MarshalByRefObject, IConsistentRingProvider, ISiloStatusListener { private readonly List<IRingRangeListener> statusListeners; private readonly SortedDictionary<uint, SiloAddress> bucketsMap; private List<Tuple<uint, SiloAddress>> sortedBucketsList; // flattened sorted bucket list for fast lock-free calculation of CalculateTargetSilo private readonly TraceLogger logger; private readonly SiloAddress myAddress; private readonly int numBucketsPerSilo; private readonly object lockable; private bool running; private IRingRange myRange; internal VirtualBucketsRingProvider(SiloAddress siloAddr, int nBucketsPerSilo) { if (nBucketsPerSilo <= 0 ) throw new IndexOutOfRangeException("numBucketsPerSilo is out of the range. numBucketsPerSilo = " + nBucketsPerSilo); logger = TraceLogger.GetLogger(typeof(VirtualBucketsRingProvider).Name); statusListeners = new List<IRingRangeListener>(); bucketsMap = new SortedDictionary<uint, SiloAddress>(); sortedBucketsList = new List<Tuple<uint, SiloAddress>>(); myAddress = siloAddr; numBucketsPerSilo = nBucketsPerSilo; lockable = new object(); running = true; myRange = RangeFactory.CreateFullRange(); logger.Info("Starting {0} on silo {1}.", typeof(VirtualBucketsRingProvider).Name, siloAddr.ToStringWithHashCode()); StringValueStatistic.FindOrCreate(StatisticNames.CONSISTENTRING_RING, ToString); IntValueStatistic.FindOrCreate(StatisticNames.CONSISTENTRING_RINGSIZE, () => GetRingSize()); StringValueStatistic.FindOrCreate(StatisticNames.CONSISTENTRING_MYRANGE_RINGDISTANCE, () => String.Format("x{0,8:X8}", ((IRingRangeInternal)myRange).RangeSize())); FloatValueStatistic.FindOrCreate(StatisticNames.CONSISTENTRING_MYRANGE_RINGPERCENTAGE, () => (float)((IRingRangeInternal)myRange).RangePercentage()); FloatValueStatistic.FindOrCreate(StatisticNames.CONSISTENTRING_AVERAGERINGPERCENTAGE, () => { int size = GetRingSize(); return size == 0 ? 0 : ((float)100.0/(float) size); }); // add myself to the list of members AddServer(myAddress); } private void Stop() { running = false; } public IRingRange GetMyRange() { return myRange; } private int GetRingSize() { lock (lockable) { return bucketsMap.Values.Distinct().Count(); } } public bool SubscribeToRangeChangeEvents(IRingRangeListener observer) { lock (statusListeners) { if (statusListeners.Contains(observer)) return false; statusListeners.Add(observer); return true; } } public bool UnSubscribeFromRangeChangeEvents(IRingRangeListener observer) { lock (statusListeners) { return statusListeners.Contains(observer) && statusListeners.Remove(observer); } } private void NotifyLocalRangeSubscribers(IRingRange old, IRingRange now, bool increased) { logger.Info(ErrorCode.CRP_Notify, "-NotifyLocalRangeSubscribers about old {0} new {1} increased? {2}", old.ToString(), now.ToString(), increased); List<IRingRangeListener> copy; lock (statusListeners) { copy = statusListeners.ToList(); } foreach (IRingRangeListener listener in copy) { try { listener.RangeChangeNotification(old, now, increased); } catch (Exception exc) { logger.Error(ErrorCode.CRP_Local_Subscriber_Exception, String.Format("Local IRangeChangeListener {0} has thrown an exception when was notified about RangeChangeNotification about old {1} new {2} increased? {3}", listener.GetType().FullName, old, now, increased), exc); } } } private void AddServer(SiloAddress silo) { lock (lockable) { List<uint> hashes = silo.GetUniformHashCodes(numBucketsPerSilo); foreach (var hash in hashes) { if (bucketsMap.ContainsKey(hash)) { var other = bucketsMap[hash]; // If two silos conflict, take the lesser of the two (usually the older one; that is, the lower epoch) if (silo.CompareTo(other) > 0) continue; } bucketsMap[hash] = silo; } var myOldRange = myRange; var bucketsList = bucketsMap.Select(pair => new Tuple<uint, SiloAddress>(pair.Key, pair.Value)).ToList(); var myNewRange = CalculateRange(bucketsList, myAddress); // capture my range and sortedBucketsList for later lock-free access. myRange = myNewRange; sortedBucketsList = bucketsList; logger.Info(ErrorCode.CRP_Added_Silo, "Added Server {0}. Current view: {1}", silo.ToStringWithHashCode(), this.ToString()); NotifyLocalRangeSubscribers(myOldRange, myNewRange, true); } } internal void RemoveServer(SiloAddress silo) { lock (lockable) { if (!bucketsMap.ContainsValue(silo)) return; // we have already removed this silo List<uint> hashes = silo.GetUniformHashCodes(numBucketsPerSilo); foreach (var hash in hashes) { bucketsMap.Remove(hash); } var myOldRange = this.myRange; var bucketsList = bucketsMap.Select(pair => new Tuple<uint, SiloAddress>(pair.Key, pair.Value)).ToList(); var myNewRange = CalculateRange(bucketsList, myAddress); // capture my range and sortedBucketsList for later lock-free access. myRange = myNewRange; sortedBucketsList = bucketsList; logger.Info(ErrorCode.CRP_Removed_Silo, "Removed Server {0}. Current view: {1}", silo.ToStringWithHashCode(), this.ToString()); NotifyLocalRangeSubscribers(myOldRange, myNewRange, true); } } private static IRingRange CalculateRange(List<Tuple<uint, SiloAddress>> list, SiloAddress silo) { var ranges = new List<IRingRange>(); for (int i = 0; i < list.Count; i++) { var curr = list[i]; var next = list[(i + 1) % list.Count]; // 'backward/clockwise' definition to assign responsibilities on the ring. if (next.Item2.Equals(silo)) { IRingRange range = RangeFactory.CreateRange(curr.Item1, next.Item1); ranges.Add(range); } } return RangeFactory.CreateRange(ranges); } // just for debugging public override string ToString() { Dictionary<SiloAddress, IRingRangeInternal> ranges = GetRanges(); List<KeyValuePair<SiloAddress, IRingRangeInternal>> sortedList = ranges.AsEnumerable().ToList(); sortedList.Sort((t1, t2) => t1.Value.RangePercentage().CompareTo(t2.Value.RangePercentage())); return Utils.EnumerableToString(sortedList, kv => String.Format("{0} -> {1}", kv.Key, kv.Value.ToString())); } // Internal: for testing only! internal Dictionary<SiloAddress, IRingRangeInternal> GetRanges() { List<SiloAddress> silos; List<Tuple<uint, SiloAddress>> snapshotBucketsList; lock (lockable) { silos = bucketsMap.Values.Distinct().ToList(); snapshotBucketsList = sortedBucketsList; } var ranges = new Dictionary<SiloAddress, IRingRangeInternal>(); foreach (var silo in silos) { var range = (IRingRangeInternal)CalculateRange(snapshotBucketsList, silo); ranges.Add(silo, range); } return ranges; } public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status) { // This silo's status has changed if (updatedSilo.Equals(myAddress)) { if (status.IsTerminating()) { Stop(); } } else // Status change for some other silo { if (status.IsTerminating()) { RemoveServer(updatedSilo); } else if (status.Equals(SiloStatus.Active)) // do not do anything with SiloStatus.Created or SiloStatus.Joining -- wait until it actually becomes active { AddServer(updatedSilo); } } } public SiloAddress GetPrimaryTargetSilo(uint key) { return CalculateTargetSilo(key); } /// <summary> /// Finds the silo that owns the given hash value. /// This routine will always return a non-null silo address unless the excludeThisSiloIfStopping parameter is true, /// this is the only silo known, and this silo is stopping. /// </summary> /// <param name="hash"></param> /// <param name="excludeThisSiloIfStopping"></param> /// <returns></returns> private SiloAddress CalculateTargetSilo(uint hash, bool excludeThisSiloIfStopping = true) { // put a private reference to point to sortedBucketsList, // so if someone is changing the sortedBucketsList reference, we won't get it changed in the middle of our operation. // The tricks of writing lock-free code! var snapshotBucketsList = sortedBucketsList; // excludeMySelf from being a TargetSilo if we're not running and the excludeThisSIloIfStopping flag is true. see the comment in the Stop method. bool excludeMySelf = excludeThisSiloIfStopping && !running; if (snapshotBucketsList.Count == 0) { // If the membership ring is empty, then we're the owner by default unless we're stopping. return excludeMySelf ? null : myAddress; } // use clockwise ... current code in membershipOracle.CalculateTargetSilo() does counter-clockwise ... // if you want to stick to counter-clockwise, change the responsibility definition in 'In()' method & responsibility defs in OrleansReminderMemory // need to implement a binary search, but for now simply traverse the list of silos sorted by their hashes Tuple<uint, SiloAddress> s = snapshotBucketsList.Find(tuple => (tuple.Item1 >= hash) && // <= hash for counter-clockwise responsibilities (!tuple.Item2.Equals(myAddress) || !excludeMySelf)); if (s == null) { // if not found in traversal, then first silo should be returned (we are on a ring) // if you go back to their counter-clockwise policy, then change the 'In()' method in OrleansReminderMemory s = snapshotBucketsList[0]; // vs [membershipRingList.Count - 1]; for counter-clockwise policy // Make sure it's not us... if (s.Item2.Equals(myAddress) && excludeMySelf) { // vs [membershipRingList.Count - 2]; for counter-clockwise policy s = snapshotBucketsList.Count > 1 ? snapshotBucketsList[1] : null; } } if (logger.IsVerbose2) logger.Verbose2("Calculated ring partition owner silo {0} for key {1}: {2} --> {3}", s.Item2, hash, hash, s.Item1); return s.Item2; } } }
using System.Text; namespace UnityEngine.EventSystems { [AddComponentMenu("Event/Touch Input Module")] public class TouchInputModule : PointerInputModule { protected TouchInputModule() { } private Vector2 m_LastMousePosition; private Vector2 m_MousePosition; [SerializeField] private bool m_AllowActivationOnStandalone; public bool allowActivationOnStandalone { get { return m_AllowActivationOnStandalone; } set { m_AllowActivationOnStandalone = value; } } public override void UpdateModule() { m_LastMousePosition = m_MousePosition; m_MousePosition = Input.mousePosition; } public override bool IsModuleSupported() { return m_AllowActivationOnStandalone || Input.touchSupported; } public override bool ShouldActivateModule() { if (!base.ShouldActivateModule()) return false; if (UseFakeInput()) { bool wantsEnable = Input.GetMouseButtonDown(0); wantsEnable |= (m_MousePosition - m_LastMousePosition).sqrMagnitude > 0.0f; return wantsEnable; } for (int i = 0; i < Input.touchCount; ++i) { Touch input = Input.GetTouch(i); if (input.phase == TouchPhase.Began || input.phase == TouchPhase.Moved || input.phase == TouchPhase.Stationary) return true; } return false; } private bool UseFakeInput() { return !Input.touchSupported; } public override void Process() { if (UseFakeInput()) FakeTouches(); else ProcessTouchEvents(); } /// <summary> /// For debugging touch-based devices using the mouse. /// </summary> private void FakeTouches() { var pointerData = GetMousePointerEventData(); var leftPressData = pointerData.GetButtonState(PointerEventData.InputButton.Left).eventData; // fake touches... on press clear delta if (leftPressData.PressedThisFrame()) leftPressData.buttonData.delta = Vector2.zero; ProcessTouchPress(leftPressData.buttonData, leftPressData.PressedThisFrame(), leftPressData.ReleasedThisFrame()); // only process move if we are pressed... if (Input.GetMouseButton(0)) { ProcessMove(leftPressData.buttonData); ProcessDrag(leftPressData.buttonData); } } /// <summary> /// Process all touch events. /// </summary> private void ProcessTouchEvents() { for (int i = 0; i < Input.touchCount; ++i) { Touch input = Input.GetTouch(i); bool released; bool pressed; var pointer = GetTouchPointerEventData(input, out pressed, out released); ProcessTouchPress(pointer, pressed, released); if (!released) { ProcessMove(pointer); ProcessDrag(pointer); } else RemovePointerData(pointer); } } private void ProcessTouchPress(PointerEventData pointerEvent, bool pressed, bool released) { var currentOverGo = pointerEvent.pointerCurrentRaycast.gameObject; // PointerDown notification if (pressed) { pointerEvent.eligibleForClick = true; pointerEvent.delta = Vector2.zero; pointerEvent.dragging = false; pointerEvent.useDragThreshold = true; pointerEvent.pressPosition = pointerEvent.position; pointerEvent.pointerPressRaycast = pointerEvent.pointerCurrentRaycast; DeselectIfSelectionChanged(currentOverGo, pointerEvent); if (pointerEvent.pointerEnter != currentOverGo) { // send a pointer enter to the touched element if it isn't the one to select... HandlePointerExitAndEnter(pointerEvent, currentOverGo); pointerEvent.pointerEnter = currentOverGo; } // search for the control that will receive the press // if we can't find a press handler set the press // handler to be what would receive a click. var newPressed = ExecuteEvents.ExecuteHierarchy(currentOverGo, pointerEvent, ExecuteEvents.pointerDownHandler); // didnt find a press handler... search for a click handler if (newPressed == null) newPressed = ExecuteEvents.GetEventHandler<IPointerClickHandler>(currentOverGo); // Debug.Log("Pressed: " + newPressed); float time = Time.unscaledTime; if (newPressed == pointerEvent.lastPress) { var diffTime = time - pointerEvent.clickTime; if (diffTime < 0.3f) ++pointerEvent.clickCount; else pointerEvent.clickCount = 1; pointerEvent.clickTime = time; } else { pointerEvent.clickCount = 1; } pointerEvent.pointerPress = newPressed; pointerEvent.rawPointerPress = currentOverGo; pointerEvent.clickTime = time; // Save the drag handler as well pointerEvent.pointerDrag = ExecuteEvents.GetEventHandler<IDragHandler>(currentOverGo); if (pointerEvent.pointerDrag != null) ExecuteEvents.Execute(pointerEvent.pointerDrag, pointerEvent, ExecuteEvents.initializePotentialDrag); } // PointerUp notification if (released) { // Debug.Log("Executing pressup on: " + pointer.pointerPress); ExecuteEvents.Execute(pointerEvent.pointerPress, pointerEvent, ExecuteEvents.pointerUpHandler); // Debug.Log("KeyCode: " + pointer.eventData.keyCode); // see if we mouse up on the same element that we clicked on... var pointerUpHandler = ExecuteEvents.GetEventHandler<IPointerClickHandler>(currentOverGo); // PointerClick and Drop events if (pointerEvent.pointerPress == pointerUpHandler && pointerEvent.eligibleForClick) { ExecuteEvents.Execute(pointerEvent.pointerPress, pointerEvent, ExecuteEvents.pointerClickHandler); } else if (pointerEvent.pointerDrag != null) { ExecuteEvents.ExecuteHierarchy(currentOverGo, pointerEvent, ExecuteEvents.dropHandler); } pointerEvent.eligibleForClick = false; pointerEvent.pointerPress = null; pointerEvent.rawPointerPress = null; if (pointerEvent.pointerDrag != null && pointerEvent.dragging) ExecuteEvents.Execute(pointerEvent.pointerDrag, pointerEvent, ExecuteEvents.endDragHandler); pointerEvent.dragging = false; pointerEvent.pointerDrag = null; if (pointerEvent.pointerDrag != null) ExecuteEvents.Execute(pointerEvent.pointerDrag, pointerEvent, ExecuteEvents.endDragHandler); pointerEvent.pointerDrag = null; // send exit events as we need to simulate this on touch up on touch device ExecuteEvents.ExecuteHierarchy(pointerEvent.pointerEnter, pointerEvent, ExecuteEvents.pointerExitHandler); pointerEvent.pointerEnter = null; } } public override void DeactivateModule() { base.DeactivateModule(); ClearSelection(); } public override string ToString() { var sb = new StringBuilder(); sb.AppendLine(UseFakeInput() ? "Input: Faked" : "Input: Touch"); if (UseFakeInput()) { var pointerData = GetLastPointerEventData(kMouseLeftId); if (pointerData != null) sb.AppendLine(pointerData.ToString()); } else { foreach (var pointerEventData in m_PointerData) sb.AppendLine(pointerEventData.ToString()); } return sb.ToString(); } } }
using System; using System.Collections.Generic; using System.Text; using System.Reflection; using System.Reflection.Emit; using System.Threading; using System.IO; namespace BitDiffer.Common.Utility { // Based from MSDN blog post http://blogs.msdn.com/haibo_luo/archive/2005/10/04/476242.aspx internal class MethodStreamer { private byte[] _bytes; private int _position; private MethodBase _method; private BinaryWriter _writer; static OpCode[] s_OneByteOpCodes = new OpCode[0x100]; static OpCode[] s_TwoByteOpCodes = new OpCode[0x100]; Byte ReadByte() { return (Byte)_bytes[_position++]; } SByte ReadSByte() { return (SByte)ReadByte(); } UInt16 ReadUInt16() { _position += 2; return BitConverter.ToUInt16(_bytes, _position - 2); } UInt32 ReadUInt32() { _position += 4; return BitConverter.ToUInt32(_bytes, _position - 4); } UInt64 ReadUInt64() { _position += 8; return BitConverter.ToUInt64(_bytes, _position - 8); } Int32 ReadInt32() { _position += 4; return BitConverter.ToInt32(_bytes, _position - 4); } Int64 ReadInt64() { _position += 8; return BitConverter.ToInt64(_bytes, _position - 8); } Single ReadSingle() { _position += 4; return BitConverter.ToSingle(_bytes, _position - 4); } Double ReadDouble() { _position += 8; return BitConverter.ToDouble(_bytes, _position - 8); } static MethodStreamer() { foreach (FieldInfo fi in typeof(OpCodes).GetFields(BindingFlags.Public | BindingFlags.Static)) { OpCode opCode = (OpCode)fi.GetValue(null); UInt16 value = (UInt16)opCode.Value; if (value < 0x100) s_OneByteOpCodes[value] = opCode; else if ((value & 0xff00) == 0xfe00) s_TwoByteOpCodes[value & 0xff] = opCode; } } internal MethodStreamer(MethodBase method) { _method = method; } internal void WriteImplementationToStream(Stream stream) { _position = 0; _writer = new BinaryWriter(stream, Encoding.Unicode); _bytes = _method.GetMethodBody().GetILAsByteArray(); WriteImplementationToStream(); } private void WriteImplementationToStream() { OpCode opcode = OpCodes.Nop; while (_position < _bytes.Length) { byte op = ReadByte(); _writer.Write(op); if (op != 0xFE) { opcode = s_OneByteOpCodes[op]; } else { op = ReadByte(); _writer.Write(op); opcode = s_TwoByteOpCodes[op]; } switch (opcode.OperandType) { case OperandType.InlineBrTarget: _writer.Write(ReadInt32()); break; case OperandType.InlineField: _writer.Write(GetNameForField(ReadInt32())); break; case OperandType.InlineMethod: _writer.Write(GetNameForMethod(ReadInt32())); break; case OperandType.InlineSig: _writer.Write(_method.Module.ResolveSignature(ReadInt32())); break; case OperandType.InlineTok: _writer.Write(GetNameForTok(ReadInt32())); break; case OperandType.InlineType: _writer.Write(GetNameForType(ReadInt32())); break; case OperandType.InlineI: _writer.Write(ReadInt32()); break; case OperandType.InlineI8: _writer.Write(ReadInt64()); break; case OperandType.InlineNone: break; case OperandType.InlineR: _writer.Write(ReadDouble()); break; case OperandType.InlineString: int value = ReadInt32(); _writer.Write(_method.Module.ResolveString(value)); break; case OperandType.InlineSwitch: int count = ReadInt32(); _writer.Write(count); for (int i = 0; i < count; i++) { _writer.Write(ReadInt32()); } break; case OperandType.InlineVar: _writer.Write(ReadUInt16()); break; case OperandType.ShortInlineBrTarget: _writer.Write(ReadSByte()); break; case OperandType.ShortInlineI: _writer.Write(ReadSByte()); break; case OperandType.ShortInlineR: _writer.Write(ReadSingle()); break; case OperandType.ShortInlineVar: _writer.Write(ReadByte()); break; default: throw new InvalidProgramException("Unknown IL instruction"); } } } private string GetNameForField(int token) { if (_method is ConstructorInfo) { return GetNameForField(_method.Module.ResolveField(token, _method.DeclaringType.GetGenericArguments(), null)); } else { return GetNameForField(_method.Module.ResolveField(token, _method.DeclaringType.GetGenericArguments(), _method.GetGenericArguments())); } } private string GetNameForMethod(int token) { try { if (_method is ConstructorInfo) { return GetNameForMethod(_method.Module.ResolveMethod(token, _method.DeclaringType.GetGenericArguments(), null)); } else { return GetNameForMethod(_method.Module.ResolveMethod(token, _method.DeclaringType.GetGenericArguments(), _method.GetGenericArguments())); } } catch { if (_method is ConstructorInfo) { return GetNameForMember(_method.Module.ResolveMember(token, _method.DeclaringType.GetGenericArguments(), null)); } else { return GetNameForMember(_method.Module.ResolveMember(token, _method.DeclaringType.GetGenericArguments(), _method.GetGenericArguments())); } } } private string GetNameForTok(int token) { try { return GetNameForType(token); } catch { } try { return GetNameForMethod(token); } catch { } try { return GetNameForField(token); } catch { } throw new ArgumentException("Unable to parse inline tok " + token.ToString()); } private string GetNameForType(int token) { if (_method is MethodInfo) { return GetNameForType(_method.Module.ResolveType(token, _method.DeclaringType.GetGenericArguments(), _method.GetGenericArguments())); } else if (_method is ConstructorInfo) { return GetNameForType(_method.Module.ResolveType(token, _method.DeclaringType.GetGenericArguments(), null)); } else { return GetNameForType(_method.Module.ResolveType(token)); } } private string GetNameForField(FieldInfo fi) { return (fi == null) ? "" : fi.Name; } private string GetNameForMethod(MethodBase mb) { return (mb == null) ? "" : mb.Name; } private string GetNameForMember(MemberInfo mi) { return (mi == null) ? "" : mi.Name; } private string GetNameForType(Type type) { // Dont use FullName... for generics it includes a version number in referenced types, and if that referenced version changes // the output changes when it should not. if ((type.IsGenericType) && (type.DeclaringType != null)) { return type.Name + ":" + type.DeclaringType.Name; } else { return type.Name; } } } }
/* ==================================================================== */ 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 System.Globalization; namespace Oranikle.ReportDesigner { /// <summary> /// Control supports the properties for DataSet/Rows elements. This is an extension to /// the RDL specification allowing data to be defined within a report. /// </summary> internal class DataSetRowsCtl : Oranikle.ReportDesigner.Base.BaseControl, IProperty { private DesignXmlDraw _Draw; private DataSetValues _dsv; private XmlNode _dsNode; private DataTable _DataTable; private Oranikle.Studio.Controls.StyledButton bDelete; private System.Windows.Forms.DataGridTableStyle dgTableStyle; private Oranikle.Studio.Controls.StyledButton bUp; private Oranikle.Studio.Controls.StyledButton bDown; private Oranikle.Studio.Controls.StyledCheckBox chkRowsFile; private Oranikle.Studio.Controls.StyledButton bRowsFile; private System.Windows.Forms.DataGrid dgRows; private Oranikle.Studio.Controls.CustomTextControl tbRowsFile; private System.Windows.Forms.Label label1; private Oranikle.Studio.Controls.StyledButton bLoad; private Oranikle.Studio.Controls.StyledButton bClear; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; internal DataSetRowsCtl(DesignXmlDraw dxDraw, XmlNode dsNode, DataSetValues dsv) { _Draw = dxDraw; _dsv = dsv; _dsNode = dsNode; // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // Initialize form using the style node values InitValues(); } private void InitValues() { CreateDataTable(); // create data table based on the existing fields XmlNode rows = _Draw.GetNamedChildNode(_dsNode, "Rows"); if (rows == null) rows = _Draw.GetNamedChildNode(_dsNode, "fyi:Rows"); string file=null; if (rows != null) { file = _Draw.GetElementAttribute(rows, "File", null); PopulateRows(rows); } this.dgRows.DataSource = _DataTable; if (file != null) { tbRowsFile.Text = file; this.chkRowsFile.Checked = true; } chkRowsFile_CheckedChanged(this, new EventArgs()); } private void CreateDataTable() { _DataTable = new DataTable(); dgTableStyle.GridColumnStyles.Clear(); // reset the grid column styles foreach (DataRow dr in _dsv.Fields.Rows) { if (dr[0] == DBNull.Value) continue; if (dr[2] == DBNull.Value) {} else if (((string) dr[2]).Length > 0) continue; string name = (string) dr[0]; DataGridTextBoxColumn dgc = new DataGridTextBoxColumn(); dgTableStyle.GridColumnStyles.Add(dgc); dgc.HeaderText = name; dgc.MappingName = name; dgc.Width = 75; string type = dr["TypeName"] as string; Type t = type == null || type.Length == 0? typeof(string): Oranikle.Report.Engine.DataType.GetStyleType(type); _DataTable.Columns.Add(new DataColumn(name,t)); } } private void PopulateRows(XmlNode rows) { object[] rowValues = new object[_DataTable.Columns.Count]; bool bSkipMsg = false; foreach (XmlNode rNode in rows.ChildNodes) { if (rNode.Name != "Row") continue; int col=0; bool bBuiltRow=false; // if all columns will be null we won't add the row foreach (DataColumn dc in _DataTable.Columns) { XmlNode dNode = _Draw.GetNamedChildNode(rNode, dc.ColumnName); if (dNode != null) bBuiltRow = true; if (dNode == null) rowValues[col] = null; else if (dc.DataType == typeof(string)) rowValues[col] = dNode.InnerText; else { object box; try { if (dc.DataType == typeof(int)) box = Convert.ToInt32(dNode.InnerText, NumberFormatInfo.InvariantInfo); else if (dc.DataType == typeof(decimal)) box = Convert.ToDecimal(dNode.InnerText, NumberFormatInfo.InvariantInfo); else if (dc.DataType == typeof(long)) box = Convert.ToInt64(dNode.InnerText, NumberFormatInfo.InvariantInfo); else if (DesignerUtility.IsNumeric(dc.DataType)) // catch all numeric box = Convert.ToDouble(dNode.InnerText, NumberFormatInfo.InvariantInfo); else if (dc.DataType == typeof(DateTime)) { box = Convert.ToDateTime(dNode.InnerText, System.Globalization.DateTimeFormatInfo.InvariantInfo); } else { box = dNode.InnerText; } rowValues[col] = box; } catch (Exception e) { if (!bSkipMsg) { if (MessageBox.Show(string.Format("Unable to convert {1} to {0}: {2}", dc.DataType.ToString(), dNode.InnerText, e.Message) + Environment.NewLine + "Do you want to see any more errors?", "Error Reading Data Rows", MessageBoxButtons.YesNo) == DialogResult.No) bSkipMsg = true; } rowValues[col] = dNode.InnerText; } } col++; } if (bBuiltRow) _DataTable.Rows.Add(rowValues); } } /// <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.dgRows = new System.Windows.Forms.DataGrid(); this.dgTableStyle = new System.Windows.Forms.DataGridTableStyle(); this.bDelete = new Oranikle.Studio.Controls.StyledButton(); this.bUp = new Oranikle.Studio.Controls.StyledButton(); this.bDown = new Oranikle.Studio.Controls.StyledButton(); this.chkRowsFile = new Oranikle.Studio.Controls.StyledCheckBox(); this.tbRowsFile = new Oranikle.Studio.Controls.CustomTextControl(); this.bRowsFile = new Oranikle.Studio.Controls.StyledButton(); this.label1 = new System.Windows.Forms.Label(); this.bLoad = new Oranikle.Studio.Controls.StyledButton(); this.bClear = new Oranikle.Studio.Controls.StyledButton(); ((System.ComponentModel.ISupportInitialize)(this.dgRows)).BeginInit(); this.SuspendLayout(); // // dgRows // this.dgRows.CaptionVisible = false; this.dgRows.DataMember = ""; this.dgRows.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.dgRows.Location = new System.Drawing.Point(8, 48); this.dgRows.Name = "dgRows"; this.dgRows.Size = new System.Drawing.Size(376, 200); this.dgRows.TabIndex = 2; this.dgRows.TableStyles.AddRange(new System.Windows.Forms.DataGridTableStyle[] { this.dgTableStyle}); // // dgTableStyle // this.dgTableStyle.AllowSorting = false; this.dgTableStyle.DataGrid = this.dgRows; this.dgTableStyle.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.dgTableStyle.MappingName = ""; // // bDelete // this.bDelete.Location = new System.Drawing.Point(392, 48); this.bDelete.Name = "bDelete"; this.bDelete.Size = new System.Drawing.Size(48, 23); this.bDelete.TabIndex = 1; this.bDelete.Text = "Delete"; this.bDelete.Click += new System.EventHandler(this.bDelete_Click); // // bUp // this.bUp.Location = new System.Drawing.Point(392, 80); this.bUp.Name = "bUp"; this.bUp.Size = new System.Drawing.Size(48, 23); this.bUp.TabIndex = 3; this.bUp.Text = "Up"; this.bUp.Click += new System.EventHandler(this.bUp_Click); // // bDown // this.bDown.Location = new System.Drawing.Point(392, 112); this.bDown.Name = "bDown"; this.bDown.Size = new System.Drawing.Size(48, 23); this.bDown.TabIndex = 4; this.bDown.Text = "Down"; this.bDown.Click += new System.EventHandler(this.bDown_Click); // // chkRowsFile // this.chkRowsFile.Location = new System.Drawing.Point(8, 8); this.chkRowsFile.Name = "chkRowsFile"; this.chkRowsFile.Size = new System.Drawing.Size(136, 24); this.chkRowsFile.TabIndex = 5; this.chkRowsFile.Text = "Use XML file for data"; this.chkRowsFile.CheckedChanged += new System.EventHandler(this.chkRowsFile_CheckedChanged); // // tbRowsFile // this.tbRowsFile.Location = new System.Drawing.Point(144, 8); this.tbRowsFile.Name = "tbRowsFile"; this.tbRowsFile.Size = new System.Drawing.Size(240, 20); this.tbRowsFile.TabIndex = 6; this.tbRowsFile.Text = ""; // // bRowsFile // this.bRowsFile.Location = new System.Drawing.Point(392, 8); this.bRowsFile.Name = "bRowsFile"; this.bRowsFile.Size = new System.Drawing.Size(24, 23); this.bRowsFile.TabIndex = 7; this.bRowsFile.Text = "..."; this.bRowsFile.Click += new System.EventHandler(this.bRowsFile_Click); // // label1 // this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 6F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.label1.Location = new System.Drawing.Point(16, 256); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(368, 23); this.label1.TabIndex = 8; this.label1.Text = "Warning: this panel supports an extension to the RDL specification. This informa" + "tion will be ignored in RDL processors other than in Oranikle Reporting."; // // bLoad // this.bLoad.Location = new System.Drawing.Point(392, 184); this.bLoad.Name = "bLoad"; this.bLoad.Size = new System.Drawing.Size(48, 48); this.bLoad.TabIndex = 9; this.bLoad.Text = "Load From SQL"; this.bLoad.Click += new System.EventHandler(this.bLoad_Click); // // bClear // this.bClear.Location = new System.Drawing.Point(392, 141); this.bClear.Name = "bClear"; this.bClear.Size = new System.Drawing.Size(48, 23); this.bClear.TabIndex = 10; this.bClear.Text = "Clear"; this.bClear.Click += new System.EventHandler(this.bClear_Click); // // DataSetRowsCtl // this.Controls.Add(this.bClear); this.Controls.Add(this.bLoad); this.Controls.Add(this.label1); this.Controls.Add(this.bRowsFile); this.Controls.Add(this.tbRowsFile); this.Controls.Add(this.chkRowsFile); this.Controls.Add(this.bDown); this.Controls.Add(this.bUp); this.Controls.Add(this.bDelete); this.Controls.Add(this.dgRows); this.Name = "DataSetRowsCtl"; this.Size = new System.Drawing.Size(488, 304); this.VisibleChanged += new System.EventHandler(this.DataSetRowsCtl_VisibleChanged); ((System.ComponentModel.ISupportInitialize)(this.dgRows)).EndInit(); this.ResumeLayout(false); } #endregion public bool IsValid() { if (this.chkRowsFile.Checked && this.tbRowsFile.Text.Length == 0) { MessageBox.Show("File name required when 'Use XML file for data checked'"); return false; } return true; } public void Apply() { // Remove the old row XmlNode rows = _Draw.GetNamedChildNode(this._dsNode, "Rows"); if (rows == null) rows = _Draw.GetNamedChildNode(this._dsNode, "fyi:Rows"); if (rows != null) _dsNode.RemoveChild(rows); // different result if we just want the file if (this.chkRowsFile.Checked) { rows = _Draw.GetCreateNamedChildNode(_dsNode, "fyi:Rows"); _Draw.SetElementAttribute(rows, "File", this.tbRowsFile.Text); } else { rows = GetXmlData(); if (rows.HasChildNodes) _dsNode.AppendChild(rows); } } private void bDelete_Click(object sender, System.EventArgs e) { this._DataTable.Rows.RemoveAt(this.dgRows.CurrentRowIndex); } private void bUp_Click(object sender, System.EventArgs e) { int cr = dgRows.CurrentRowIndex; if (cr <= 0) // already at the top return; SwapRow(_DataTable.Rows[cr-1], _DataTable.Rows[cr]); dgRows.CurrentRowIndex = cr-1; } private void bDown_Click(object sender, System.EventArgs e) { int cr = dgRows.CurrentRowIndex; if (cr < 0) // invalid index return; if (cr + 1 >= _DataTable.Rows.Count) return; // already at end SwapRow(_DataTable.Rows[cr+1], _DataTable.Rows[cr]); dgRows.CurrentRowIndex = cr+1; } private void SwapRow(DataRow tdr, DataRow fdr) { // Loop thru all the columns in a row and swap the data for (int ci=0; ci < _DataTable.Columns.Count; ci++) { object save = tdr[ci]; tdr[ci] = fdr[ci]; fdr[ci] = save; } return; } private void chkRowsFile_CheckedChanged(object sender, System.EventArgs e) { this.tbRowsFile.Enabled = chkRowsFile.Checked; this.bRowsFile.Enabled = chkRowsFile.Checked; this.bDelete.Enabled = !chkRowsFile.Checked; this.bUp.Enabled = !chkRowsFile.Checked; this.bDown.Enabled = !chkRowsFile.Checked; this.dgRows.Enabled = !chkRowsFile.Checked; } private void bRowsFile_Click(object sender, System.EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "XML files (*.xml)|*.xml" + "|All files (*.*)|*.*"; ofd.FilterIndex = 1; ofd.FileName = "*.xml"; ofd.Title = "Specify XML File Name"; ofd.DefaultExt = "xml"; ofd.AddExtension = true; try { if (ofd.ShowDialog() == DialogResult.OK) { string file = Path.GetFileName(ofd.FileName); this.tbRowsFile.Text = file; } } finally { ofd.Dispose(); } } private bool DidFieldsChange() { int col=0; foreach (DataRow dr in _dsv.Fields.Rows) { if (col >= _DataTable.Columns.Count) return true; if (dr[0] == DBNull.Value) continue; if (dr[2] == DBNull.Value) {} else if (((string) dr[2]).Length > 0) continue; string name = (string) (dr[1] == DBNull.Value? dr[0]: dr[1]); if (_DataTable.Columns[col].ColumnName != name) return true; col++; } if (col == _DataTable.Columns.Count) return false; else return true; } private XmlNode GetXmlData() { XmlDocumentFragment fDoc = _Draw.ReportDocument.CreateDocumentFragment(); XmlNode rows = _Draw.CreateElement(fDoc, "fyi:Rows", null); foreach (DataRow dr in _DataTable.Rows) { XmlNode row = _Draw.CreateElement(rows, "Row", null); bool bRowBuilt=false; foreach (DataColumn dc in _DataTable.Columns) { if (dr[dc] == DBNull.Value) continue; string val; if (dc.DataType == typeof(DateTime)) { val = Convert.ToString(dr[dc], System.Globalization.DateTimeFormatInfo.InvariantInfo); } else { val = Convert.ToString(dr[dc], NumberFormatInfo.InvariantInfo); } if (val == null) continue; _Draw.CreateElement(row, dc.ColumnName, val); bRowBuilt = true; // we've populated at least one column; so keep row } if (!bRowBuilt) rows.RemoveChild(row); } return rows; } private void DataSetRowsCtl_VisibleChanged(object sender, System.EventArgs e) { if (!DidFieldsChange()) // did the structure of the fields change return; // Need to reset the data; this assumes that some of the data rows are similar XmlNode rows = GetXmlData(); // get old data CreateDataTable(); // this recreates the datatable PopulateRows(rows); // repopulate the datatable this.dgRows.DataSource = _DataTable; // this recreates the datatable so reset grid } private void bClear_Click(object sender, System.EventArgs e) { this._DataTable.Rows.Clear(); } private void bLoad_Click(object sender, System.EventArgs e) { // Load the data from the SQL; we append the data to what already exists try { // Obtain the connection information XmlNode rNode = _Draw.GetReportNode(); XmlNode dsNode = _Draw.GetNamedChildNode(rNode, "DataSources"); if (dsNode == null) return; XmlNode datasource=null; foreach (XmlNode dNode in dsNode) { if (dNode.Name != "DataSource") continue; XmlAttribute nAttr = dNode.Attributes["Name"]; if (nAttr == null) // shouldn't really happen continue; if (nAttr.Value != _dsv.DataSourceName) continue; datasource = dNode; break; } if (datasource == null) { MessageBox.Show(string.Format("Datasource '{0}' not found.", _dsv.DataSourceName), "Load Failed"); return; } // get the connection information string connection = ""; string dataProvider = ""; string dataSourceReference = _Draw.GetElementValue(datasource, "DataSourceReference", null); if (dataSourceReference != null) { // This is not very pretty code since it is assuming the structure of the windows parenting. // But there isn't any other way to get this information from here. Control p = _Draw; MDIChild mc = null; while (p != null && !(p is RdlDesigner)) { if (p is MDIChild) mc = (MDIChild)p; p = p.Parent; } if (p == null || mc == null || mc.SourceFile == null) { MessageBox.Show("Unable to locate DataSource Shared file. Try saving report first"); return; } string filename = Path.GetDirectoryName(mc.SourceFile) + Path.DirectorySeparatorChar + dataSourceReference; if (!DesignerUtility.GetSharedConnectionInfo((DesignerForm) p, filename, out dataProvider, out connection)) return; } else { XmlNode cpNode = DesignXmlDraw.FindNextInHierarchy(datasource, "ConnectionProperties", "ConnectString"); connection = cpNode == null ? "" : cpNode.InnerText; XmlNode datap = DesignXmlDraw.FindNextInHierarchy(datasource, "ConnectionProperties", "DataProvider"); dataProvider = datap == null ? "" : datap.InnerText; } // Populate the data table DesignerUtility.GetSqlData(dataProvider, connection, _dsv.CommandText, null, _DataTable); } catch (Exception ex) { MessageBox.Show(ex.Message, "Load Failed"); } } } }
using Microsoft.Extensions.Logging; using System; using System.Threading.Tasks; namespace DaaSDemo.Provisioning.Provisioners { using DatabaseProxy.Client; using Exceptions; using Models.Data; using Models.DatabaseProxy; /// <summary> /// Provisioner for <see cref="DatabaseInstance"/>s hosted in SQL Server. /// </summary> public sealed class SqlServerDatabaseProvisioner : DatabaseProvisioner { /// <summary> /// Create a new <see cref="SqlServerDatabaseProvisioner"/>. /// </summary> /// <param name="logger"> /// The provisioner's logger. /// </param> /// <param name="databaseProxyClient"> /// The <see cref="DatabaseProxyApiClient"/> used to communicate with the Database Proxy API. /// </param> public SqlServerDatabaseProvisioner(ILogger<DatabaseProvisioner> logger, DatabaseProxyApiClient databaseProxyClient) : base(logger) { if (databaseProxyClient == null) throw new ArgumentNullException(nameof(databaseProxyClient)); DatabaseProxyClient = databaseProxyClient; } /// <summary> /// The <see cref="DatabaseProxyApiClient"/> used to communicate with the Database Proxy API. /// </summary> DatabaseProxyApiClient DatabaseProxyClient { get; } /// <summary> /// Determine whether the provisioner supports the specified server type. /// </summary> /// <param name="serverKind"> /// A <see cref="DatabaseServerKind"/> value representing the server type. /// </param> /// <returns> /// <c>true</c>, if the provisioner supports databases hosted in the specified server type; otherwise, <c>false</c>. /// </returns> public override bool SupportsServerKind(DatabaseServerKind serverKind) => serverKind == DatabaseServerKind.SqlServer; /// <summary> /// Check if the target database exists. /// </summary> /// <returns> /// <c>true</c>, if the database exists; otherwise, <c>false</c>. /// </returns> public override async Task<bool> DoesDatabaseExist() { RequireState(); QueryResult result = await DatabaseProxyClient.ExecuteQuery( serverId: State.ServerId, databaseId: DatabaseProxyApiClient.MasterDatabaseId, sql: ManagementSql.CheckDatabaseExists(), parameters: ManagementSql.Parameters.CheckDatabaseExists( databaseName: State.Name ), executeAsAdminUser: true, stopOnError: true ); return result.ResultSets[0].Rows.Count == 1; } /// <summary> /// Create the database. /// </summary> /// <returns> /// A <see cref="Task"/> representing the operation. /// </returns> public override async Task CreateDatabase() { RequireState(); Log.LogInformation("Creating database {DatabaseName} (Id:{DatabaseId}) on server {ServerId}...", State.Name, State.Id, State.ServerId ); CommandResult commandResult = await DatabaseProxyClient.ExecuteCommand( serverId: State.ServerId, databaseId: DatabaseProxyApiClient.MasterDatabaseId, sql: ManagementSql.CreateDatabase( State.Name, State.DatabaseUser, State.DatabasePassword, maxPrimaryFileSizeMB: State.Storage.SizeMB, maxLogFileSizeMB: (int)(0.2 * State.Storage.SizeMB) // Reserve an additional 20% of storage for transaction logs. ), executeAsAdminUser: true, stopOnError: true ); for (int messageIndex = 0; messageIndex < commandResult.Messages.Count; messageIndex++) { Log.LogInformation("T-SQL message [{MessageIndex}] from server {ServerId}: {TSqlMessage}", messageIndex, State.ServerId, commandResult.Messages[messageIndex] ); } if (!commandResult.Success) { foreach (SqlError error in commandResult.Errors) { Log.LogWarning("Error encountered while creating database {DatabaseId} ({DatabaseName}) on server {ServerId} ({ErrorKind}: {ErrorMessage})", State.Id, State.Name, State.ServerId, error.Kind, error.Message ); } throw new SqlExecutionException($"Failed to create database '{State.Name}' (Id:{State.Id}) on server {State.ServerId}.", serverId: State.ServerId, databaseId: State.Id, sqlMessages: commandResult.Messages, sqlErrors: commandResult.Errors ); } Log.LogInformation("Created database {DatabaseName} (Id:{DatabaseId}) on server {ServerId}.", State.Name, State.Id, State.ServerId ); } /// <summary> /// Drop the database. /// </summary> public override async Task DropDatabase() { RequireState(); Log.LogInformation("Dropping database {DatabaseName} (Id:{DatabaseId}) on server {ServerId}...", State.Name, State.Id, State.ServerId ); CommandResult commandResult = await DatabaseProxyClient.ExecuteCommand( serverId: State.ServerId, databaseId: DatabaseProxyApiClient.MasterDatabaseId, sql: ManagementSql.DropDatabase(State.Name), executeAsAdminUser: true, stopOnError: true ); for (int messageIndex = 0; messageIndex < commandResult.Messages.Count; messageIndex++) { Log.LogInformation("T-SQL message [{MessageIndex}] from server {ServerId}: {TSqlMessage}", messageIndex, State.ServerId, commandResult.Messages[messageIndex] ); } if (!commandResult.Success) { foreach (SqlError error in commandResult.Errors) { Log.LogWarning("Error encountered while dropping database {DatabaseId} ({DatabaseName}) on server {ServerId} ({ErrorKind}: {ErrorMessage})", State.Id, State.Name, State.ServerId, error.Kind, error.Message ); } throw new SqlExecutionException($"Failed to drop database '{State.Name}' (Id:{State.Id}) on server {State.ServerId}.", serverId: State.ServerId, databaseId: State.Id, sqlMessages: commandResult.Messages, sqlErrors: commandResult.Errors ); } Log.LogInformation("Dropped database {DatabaseName} (Id:{DatabaseId}) on server {ServerId}.", State.Name, State.Id, State.ServerId ); } } }